#!/bin/sh
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# This script is the ensemble postprocessor for the global ens wave model.  It +
# packs ensemble mean and spread in grib form.  It runs in serial mode and in  +
# its own directory. The output are copied to the output directory.            +
#                                                                              +
# For non-fatal errors output is witten to the ens.log file.                   +
#                                                                              +
# Feb, 2008                                                                    +
#                                                                              +
#                            ************************                          +
# Modified for NCEP and FNMOC ensemble wave models combined in grib2 form.     +
# June 2011                                                                    +
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# 0.  Preparations
# 0.a Basic modes of operation
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
  seton='-xa'
  setoff='+xa'

  set $setoff
  echo ' '
  echo '                   ******************************************'
  echo '                   *** WAVE ENSEMBLE POSTPROCESSOR SCRIPT ***'
  echo '                   ******************************************'
  echo ' '
  echo "Starting at : `date`"
  set $seton

  export wgrib2=$utilexec/wgrib2
#
# 0.b Date and time stuff
#
  export YMD=$PDY
  export YMDH=${PDY}${cyc}
  export tcycz=t${cyc}z

  export grdID='glo_60m'
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# 1. Get Buoy files.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
# buoy input files exist?
#
  if [ -f $FIXwave/wave_ens_buoy.data ] ; then
    cp  $FIXwave/wave_ens_buoy.data  buoy_file.data
    echo " $FIXwave/wave_ens_buoy.data copied to buoy_file.data."
  else
    msg="ABNORMAL EXIT: ERR in copying wave_ens_buoy.data."
    postmsg "$jlogfile" "$msg"
    set $setoff
    echo ' '
    echo '***************************************************** '
    echo "*** ERROR : No $FIXwave/wave_ens_buoy.data  copied. *** "
    echo '***************************************************** '
    echo ' '
    echo "$FIXwave/wave_ens_buoy.data  missing." >> $ensemb_log
    set $seton
    err=1;export err;err_chk
  fi
#
  if [ -f $FIXwave/wave_ens_buoy.ratio ] ; then
    cp  $FIXwave/wave_ens_buoy.ratio  buoy_ratio.data
    echo " $FIXwave/wave_ens_buoy.ratio copied to buoy_ratio.data."
  else
    msg="ABNORMAL EXIT: ERR in copying wave_ens_buoy.ratio."
    postmsg "$jlogfile" "$msg"
    set $setoff
    echo ' '
    echo '***************************************************** '
    echo "*** ERROR : No $FIXwave/wave_ens_buoy.ratio  copied.*** "
    echo '***************************************************** '
    echo ' '
    echo "$FIXwave/wave_ens_buoy.ratio  missing." >> $ensemb_log
    set $seton
    err=1;export err;err_chk
  fi
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
    end_hour=${END_HOUR}
    echo "end_hour=${END_HOUR}"
    dh='6'

   para='HTSGW'  

#Beaufort Wind Scale, from Force 2 t 10.  And corresponding wave heights.
  uscale='3.60 5.65 8.74 11.31 14.39 17.48 21.07 24.67'
  hscale='0.60 1.00 2.00  3.00  4.00  5.50  7.00  9.00'
  tpscale='5.0 7.0 9.0 11.0 13.0 15.0 17.0 19.0'
  tmscale=''
  tsscale=''
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# 2. Get NCEP files.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
# get data for specified members

  membn='00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20' 
  nmembn=`echo ${membn} | wc -w`
  for me in $membn
  do
    if [ $me = '00' ] ; then
      if [ -f $COMIN/$ctlID.$grdID.t${cyc}z.grib2 ] ; then
        cp  $COMIN/$ctlID.$grdID.t${cyc}z.grib2  $me.grib2
      else
        msg="ABNORMAL EXIT: ERR in copying $ctlID.$grdID.t${cyc}z.grib2."
        postmsg "$jlogfile" "$msg"
        set $setoff
        echo '******************************************************* '
        echo "*** ERROR : No $COMIN/$ctlID.$grdID.t${cyc}z.grib2 copied ** "
        echo '******************************************************* '
        echo "$COMIN/$ctlID.$grdID.t${cyc}z.grib2 missing." >> $ensemb_log
        set $seton
        err=1;export err;err_chk
      fi
    else
      if [ -f $COMIN/${ensID}${me}.$grdID.t${cyc}z.grib2 ] ; then
        cp  $COMIN/${ensID}${me}.$grdID.t${cyc}z.grib2  $me.grib2
      else
        msg="ABNORMAL EXIT: ERR in copying ${ensID}$me.$grdID.t${cyc}z.grib2."
        postmsg "$jlogfile" "$msg"
        set $setoff
        echo ' '
        echo '******************************************************* '
        echo "*** ERR : No $COMIN/${ensID}$me.$grdID.t${cyc}z.grib2 copied. *** "
        echo '******************************************************* '
        echo ' '
        echo "$COMIN/${ensID}$me.$grdID.t${cyc}z.grib2 missing." >> $ensemb_log
        set $seton
        err=1;export err;err_chk
      fi
    fi
#
# get data for specified forecast hour for specified parameter.
#
    fhour=0
#
    while [ "$fhour" -le "$end_hour" ]
    do
#
      if [ $fhour -eq 0 ] ; then
        ihr='anl'
        hhh='000'
      elif [ $fhour -lt 10 ] ; then
        ihr=${fhour}' hour'
        hhh='00'$fhour
      elif [ $fhour -lt 100 ] ; then
        ihr=${fhour}' hour'
        hhh='0'$fhour
      elif [ $fhour -ge 100 ] ; then
        ihr=${fhour}' hour'
        hhh=$fhour
      fi

      for ip in $para
      do
        $wgrib2 $me.grib2 -s | grep ":${ip}:surface:${ihr}" | $wgrib2 -i $me.grib2  -grib ${ip}_${me}.${hhh}.grib2 
#       ls -la ${ip}_${me}.${hhh}.grib2
        ok1=$?
        if [ $ok1 -ne 0 ] ; then
          echo " *** ERROR : ip=$ip, im=$me, ok1=$ok1"
          exit
        fi
        echo " got from NCEP's ${me}.t${cyc}z: ${ip}_${me}.${hhh}.grib2."
        $wgrib2 ${ip}_${me}.${hhh}.grib2 -append -grib  ${ip}_${me}.t${cyc}z.grib2
      done
      fhour=`expr $fhour + $dh`
    done
    rm -f $me.grib2
  done
  nlast=$me
  echo "last NCEP member is $nlast"
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# 3. Get FNMOC files.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#

  chkFNMOC=YES
  for chkmemb in $(seq 1 $me)
  do
     if [ $chkmemb -lt 10 ]
     then
        chkmemb='0'${chkmemb}
     fi
     for chkhr in $(seq 0 $dh $end_hour)
     do
        if [ $chkhr -lt 10 ]
        then
           chkhr='00'${chkhr}
        elif [ $chkhr -lt 100 ]
        then
           chkhr='0'${chkhr}
        fi
        chkfile=$COMFN/${fnmID}_et0${chkmemb}.${chkhr}.${YMDH}
        if [ ! -f ${chkfile} ]
        then
           chkFNMOC=NO
        fi
     done
  done
#  chkfile=$COMFN/${fnmID}_et0${me}.${end_hour}.${YMDH}

  foundFN='no'

  if [ ${chkFNMOC} = 'NO' -o ${RUN_FNMOC} = 'NO' ]
  then
# FNMOC files for all forecast times are not available, go without FNMOC data
    
    membf=0
    nmembf=0

  else
# FNMOC file for last forecast time found
    foundFN='yes' 

    membf='01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20'
    nmembf=`echo ${membf} | wc -w`
#
# forecast hour loop.
#
    fhour=0
#
    while [ "$fhour" -le "$end_hour" ]
    do
#
      if [ $fhour -eq 0 ] ; then
        ihr='anl'
        hhh='000'
      elif [ $fhour -lt 10 ] ; then
        ihr=${fhour}' hour'
        hhh='00'$fhour
      elif [ $fhour -lt 100 ] ; then
        ihr=${fhour}' hour'
        hhh='0'$fhour
      elif [ $fhour -ge 100 ] ; then
        ihr=${fhour}' hour'
        hhh=$fhour
      fi
#
# member loop
#
      for me in $membf
      do
        ie=` expr $nlast + $me `
        if [ -f $COMFN/${fnmID}_et0${me}.${hhh}.${YMDH} ] ; then
          cp  $COMFN/${fnmID}_et0${me}.${hhh}.${YMDH}  ${ie}.${hhh}.grib2
        else
           msg="ABNORMAL EXIT: ERR in copying $fnmID_et0$me.$hhh.$YMDH"
           postmsg "$jlogfile" "$msg"
           set $setoff
           echo ' '
           echo '******************************************************* '
           echo "*** ERR : No $COMFN/${fnmID}_et0${me}.${hhh}.${YMDH} copied. *** "
           echo '******************************************************* '
           echo ' '
           echo "$COMFN/${fnmID}_et0${me}.${hhh}.${YMDH} missing." >> $ensemb_log
           set $seton
           err=1;export err;err_chk
        fi
# Parameter loop
        for ip in $para
        do
          infile=${ie}.${hhh}.grib2  
          $wgrib2 $infile -s | grep "${ip}:surface:${ihr}" | $wgrib2 -i $infile -grib  ${ip}_${ie}.${hhh}.grib2
           ok1=$?
           if [ $ok1 -ne 0 ] ; then
             echo " *** ERROR : ip=$ip, me=${me}, ok1=$ok1"
             exit
           fi
          echo " got from FNMOC's et0${me}.${hhh}.${YMDH}: ${ip}_${ie}.${hhh}.grib2."
          $wgrib2 ${ip}_${ie}.${hhh}.grib2 -append -grib  ${ip}_${ie}.t${cyc}z.grib2
        done
      done
      fhour=`expr $fhour + $dh`
    done
  fi
#
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# 4. Output to what_{modID}_used
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
  if [ "$foundFN" = 'no' ]
  then
    msg="COULD NOT FIND FNMOC ENSEMBLES DATA, USING ONLY NCEP ENSEMBLES"
    postmsg "$jlogfile" "$msg"
    echo ' ' >> warning
    echo '******************************************************' >> warning
    echo '*** WARNING !! COULD NOT FIND FNMOC ENSEMBLES DATA ***' >> warning
    echo '***         (USING ONLY NCEP ENSEMBLES)            ***' >> warning
    echo '******************************************************' >> warning
    echo ' ' >> warning
    echo "${chkfile} : FNMOC file(s) missing (using only NCEP)" >> $wavelog
    echo 'NCEP-FNMOC COMBINED WAVE ENSEMBLE WILL RUN WITH ONLY NCEP MEMBERS' >> warning

    #send email to NCO and EMC developer
    mail -v -s "Missing FNMOC Ensemble Data" -c "Henrique.Alves@noaa.gov" sdm@noaa.gov<warning
  fi

  echo "NCEP ${nmembn}" > what_wave${modID}_used.t${cyc}z
  if [ "$foundFN" == 'yes' ]
  then
    echo "FNMOC ${nmembf}" >> what_wave${modID}_used.t${cyc}z
  fi
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# 5. Compute mean, spread and probability of exceedence 
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
# set $seton

  rm -f mean.t${cyc}z.grib spread.t${cyc}z.grib probab.t${cyc}z.grib

  nmemb=`expr ${nmembn} + ${nmembf}`
  nmembm1=`expr ${nmemb} - 1`
#
# Create list of combined ensemble member numbers (starting from 00 = NCEP control run)
#
  memb=`seq -w 0 ${nmembm1}`
#
# forecast hour loop.
#
  fhour=0
#
  while [ "$fhour" -le "$end_hour" ]
  do
#
    if [ $fhour -eq 0 ] ; then
      ihr='anl'
      hhh='000'
    elif [ $fhour -lt 10 ] ; then
      ihr=${fhour}' hour'
      hhh='00'$fhour
    elif [ $fhour -lt 100 ] ; then
      ihr=${fhour}' hour'
      hhh='0'$fhour
    elif [ $fhour -ge 100 ] ; then
      ihr=${fhour}' hour'
      hhh=$fhour
    fi
#
    for ip in $para
    do
#
      scale='     '
      case $ip in
        HTSGW)   scale=$hscale ; id_para='10,0,3'  ;;
        *)       scale=$tsscale; id_para='   '  ;;
      esac
#
      rm -f fname_input data_* 
#
      echo $YMDH $hhh $ip $id_para  > fname_input
      echo ${nmemb}                 >> fname_input
      echo $memb                    >> fname_input
      echo $scale | wc -w           >> fname_input
      echo $scale                   >> fname_input
#
#      for im in $memb
      nme=0
      while [ ${nme} -lt ${nmemb} ]
      do

      im=${nme}
      if [ ${nme} -lt 10 ]
      then
        im='0'${nme}
      fi
 
        infile=${ip}_${im}.${hhh}.grib2
           $wgrib2 $infile -s \
           | grep "${ip}:surface:${ihr}" | \
           $wgrib2 -i $infile -bin data_${im}
#       ls -la data_${im}
        ok1=$?
        if [ $ok1 -ne 0 ] ; then
          echo " *** ERROR : ip=$ip, im=$im, ok1=$ok1"
          exit
        fi
        echo data_$im       >> fname_input
        cp fname_input ${ip}_fname_input.${hhh}

      nme=`expr ${nme} + 1`

      done
#
# execute ensemb.x
# and create grib2 files
#
      rm -f station_out mean_out spread_out probab_out test_out
#
   export pgm=nfcombwave_ensemble
   . prep_step

      startmsg
      $EXECwave/nfcombwave_ensemble  < fname_input >>$pgmout 2>errfile
      export err=$?; err_chk 
#
      cat station_out >> ${ip}_station.t${cyc}z.text

      cp mean_out    ${ip}_mean.$hhh.grib2
      cp spread_out  ${ip}_spread.$hhh.grib2
      cp probab_out  ${ip}_probab.$hhh.grib2
      $wgrib2  mean_out  -append -grib ${ip}_mean.t${cyc}z.grib2
      $wgrib2  spread_out -append -grib ${ip}_spread.t${cyc}z.grib2
      $wgrib2  probab_out -append -grib ${ip}_probab.t${cyc}z.grib2
#
    done
    fhour=`expr $fhour + $dh`
  done
#
  cp  *station.t${cyc}z.text $COMOUT/.
  cp  *.t${cyc}z.grib2    $COMOUT/.
#
  compress $COMOUT/*station.t${cyc}z.text
#
  cp what_wave${modID}_used.${cycle} ${COMOUT}/.

#

  if [ "$SENDDBN" = 'YES' ]
  then
    for dbmemb in $memb    
    do
       $DBNROOT/bin/dbn_alert MODEL NFC_WAVEENS $job $COMOUT/HTSGW_${dbmemb}.t${cyc}z.grib2
    done
       $DBNROOT/bin/dbn_alert MODEL NFC_WAVEENS $job $COMOUT/HTSGW_mean.t${cyc}z.grib2
       $DBNROOT/bin/dbn_alert MODEL NFC_WAVEENS $job $COMOUT/HTSGW_spread.t${cyc}z.grib2
       $DBNROOT/bin/dbn_alert MODEL NFC_WAVEENS $job $COMOUT/HTSGW_probab.t${cyc}z.grib2
       $DBNROOT/bin/dbn_alert MODEL NFC_WAVEENS $job $COMOUT/HTSGW_station.t${cyc}z.text.Z
       $DBNROOT/bin/dbn_alert MODEL NFC_WAVEENS $job $COMOUT/what_wave${modID}_used.${cycle}
  fi 

#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
# END OF WAVE ENSEMBLE POSTPROCESSOR SCRIPT
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --+ + + ++
#
