#!/bin/sh
#  Public Domain 8.2025 Wesley Ebisuzaki
#
# make mean, use daily min/max values
#
# uses $out.* as temp files
#
# Usage: mk_core_mean.sh output_file DHR (list of files)
# DHR = 3hr or 6hr
#
# v1.0 8/2025 Wesley Ebisuzaki

set -x
if [ $# -lt 3  ] ; then
   echo "$0 output-file dhr (list of grib files)"
   echo "  dhr = 3hr or 6hr"
   echo " list of grib files need to be chronological order"
   echo " grib files need have the fields in identical order"
   echo "found $*"
   exit 8
fi
out=$1
dhr=$2

shift 2
wgrib2=${wgrib2:-wgrib2}

# See if need to do special processing for min/max fields
do_max=`$wgrib2 $1 | egrep -c ' (min|max) fcst:'`

# make means for non max/min fields
gmerge - $* | $wgrib2 - -not ' (max|min) fcst:' -set_grib_type c3 -ave ${dhr} $out

# add daily means of min/max fields
if [ "$do_max" -ge 1 ] ; then
    rm $out.tmp.*
    dhr_val=`echo $dhr | sed 's/[a-z]//g'`
    N_perday=`expr 24 / $dhr_val`
    N_days=`expr $# / $N_perday`
    n=1
 
    while [ $n -le $N_days ]
    do
       n=`printf "%03d" $n`
       if [ $dhr == 3hr ] ; then
          gmerge - $1 $2 $3 $4 $5 $6 $7 $8 | $wgrib2 - -match ' (min|max) fcst:' \
             -set_grib_type c3  \
             -if " max fcst:" -time_processing 2 1 3hr $out.tmp.$n -endif \
             -if " min fcst:" -time_processing 3 1 3hr $out.tmp.$n -endif
          shift 8
       fi
       if [ $dhr == 6hr ] ; then
          gmerge - $1 $2 $3 $4 | $wgrib2 - -match ' (min|max) fcst:' \
             -set_grib_type c3 \
             -if " max fcst:" -time_processing 2 1 6hr $out.tmp.$n -endif \
             -if " min fcst:" -time_processing 3 1 6hr $out.tmp.$n -endif
          shift 4
       fi
       n=`expr $n + 1`
    done
    if [ $N_days -eq 1 ] ; then
       cat $out.tmp.001 >> $out
    else
       gmerge - $out.tmp.* | $wgrib2 - -append -ave 1dy $out
    fi
    rm $out.tmp.*
fi

exit 0
