#!/bin/sh
# 5/2018                                   Wesley Ebisuzaki
#
# fast grib2 average
#   ref: https://www.cpc.ncep.noaa.gov/products/wesley/wgrib2/fcst_ave.html
#
# note: this is the normal averge such as averaging several analyses
#       this is not the fcst average .. one forecast and many forecast times
#
# 9/2020: rm $tmp" -> rm $tmp (Leigh Zhang)
#         ref: http://www....  -> https://www....
#
if [ "$#" -le 3 ] ; then
   echo "$0 output dt (list of grib2 files)"
   echo "output = grib2 file with the average"
   echo "dt = (integer)(unit)    unit=hr, dy, mo, yr  (GrADS time units)"
   exit 8
fi

set -x
out=$1
dt=$2
shift 2

if [ "$2" == '' ] ; then
  echo "only one file!"
  cp $1 $out
  exit 0
fi

tmp=/tmp/tmp$$
wgrib2 $1 -match_inv | cut -f4- -d: | sort -u | sed -e 's/:n=.*//' >$tmp
cmd="cat $* | wgrib2 - -set_grib_type c3 "

# old   cmd="$cmd -if '$line' -ave $dt $out "
# new   cmd="$cmd -if_fs '$line' -ave $dt $out "

while read line
do
   cmd="$cmd -if_fs '$line' -ave $dt $out "
done <$tmp
rm $tmp
echo "cmd=$cmd"
eval $cmd
