#!/bin/csh -f

# Usage example: Pipe data on standard input to:
#   total '$13' Enr
# to total data in field $13 (default awk delimiter) and call it Enr

set noglob

set awkcommands = ""

while ($#argv > 0)
  if ("$1" == "-p") then
     set awkcommands = "$awkcommands"' {print $0}'
  else
     set awkcommands = "$awkcommands {if (strtonum($1)>0) {total["\""$2"\""] += $1; count["\""$2"\""] += 1}}"
     if ($#argv > 1) shift
  endif
  shift
end

if ("$awkcommands" == "") set awkcommands = '{total[""] += 1; count[""] += 1}'

awk "$awkcommands"' END {for (fieldname in total)\
    {print fieldname, " Total", total[fieldname], " Count", count[fieldname], " Avg", total[fieldname]/count[fieldname] }}'\
    |& grep -v 'awk: total is not an array'
