#!/bin/sh
###############################################################################
#                                                                             #
# This is the master script to generates GRIB2 file for the MWW3 forecast     #
#  model as the output is generated. The script is called from the master     #
#  script that starts the model run and is completed when the grib2 file      #
#  for the last step is generated or when the abort signal from the master    #
#  script is sent out. It runs a child script to generate grib2 files for     #
#  individual steps                                                           #
#                                                                             #
# Remarks :                                                                   #
# - The necessary files are retrieved by the mother script.                   #
# - See section 0.b for variables that need to be set.                        # 
#                                                                             #
#                                                                Jan, 2009    #
# Last update : 02-29-2012                                                    #
#                                                                             #
###############################################################################

#
# --------------------------------------------------------------------------- #
# 0.  Preparations
# 0.a Basic modes of operation

  # set execution trace prompt.  ${0##*/} adds the script's basename
  PS4=" \${SECONDS} ${0##*/} L\${LINENO} + "
  set -x

  # Use LOUD variable to turn on/off trace.  Defaults to YES (on).
  export LOUD=${LOUD:-YES}; [[ $LOUD = yes ]] && export LOUD=YES
  [[ "$LOUD" != YES ]] && set +x

  MODNR=${MODNR:?}  # exit with error msg if not set 

  grdID=$1
  ymdh_end=$2

  cd $DATA
#  postmsg "$jlogfile" "Making GRIB2 Files."   # commented to reduce unnecessary output to jlogfile

  set +x
  echo ' '
  echo '+--------------------------------+'
  echo '!         Make GRIB files        |'
  echo '+--------------------------------+'
  echo "   Model ID        : $modID"
  echo "   Grid ID         : $grdID"
  [[ "$LOUD" = YES ]] && set -x

  if [ -z "$YMDH" ] || [ -z "$cycle" ] || \
     [ -z "$COMOUT" ] || [ -z "$modID" ] || [ -z "$SENDCOM" ] || \
     [ -z "$dtgrib" ] || [ -z "$GRIBFLAGS" ] || [ -z "$grdID" ] || \
     [ -z "$SENDDBN" ]
  then
    set +x
    echo ' '
    echo '***************************************************'
    echo '*** EXPORTED VARIABLES IN postprocessor NOT SET ***'
    echo '***************************************************'
    echo ' '
    postmsg "$jlogfile" "EXPORTED VARIABLES IN postprocessor NOT SET"
    exit 1
    [[ "$LOUD" = YES ]] && set -x
  fi

# 0.c Starting time for output

  ymdh=$YMDH
  tstart="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
  tend="`echo $ymdh_end | cut -c1-8` `echo $ymdh_end | cut -c9-10`0000"

  dtgribh=`expr $dtgrib / 3600`
  set +x
  echo "   Starting time           : $tstart"
  echo "   Ending time             : $tend"
  echo "   Time step (in hours)    : $dtgribh"
  echo "   GRIB field flags        : $GRIBFLAGS"
  echo ' '
  [[ "$LOUD" = YES ]] && set -x


# --------------------------------------------------------------------------- #
# 1.  Set up control loop

  while [ -f "grib2.$grdID.lock" ]
  do

    gribdone='yes'
    ymdh=$YMDH

    while [ "$ymdh" -le "$ymdh_end" ]
    do

      if [ ! -f "gribdone.$ymdh.$grdID" ]
      then

        if [ -f "Field_done.$ymdh.$grdID" ] || [ "$INDRUN" = 'yes' ]
        then
          set +x
          echo ' '
          echo "  Generating grib file for $grdID at $ymdh ... "
          [[ "$LOUD" = YES ]] && set -x

          case $grdID in
            glo_30m ) GRIDNR=11 ;;
            ao_30m  ) GRIDNR=255 ;;
            at_10m  ) GRIDNR=12 ;;
            wc_10m  ) GRIDNR=13 ;;
            ep_10m  ) GRIDNR=14 ;;
            ak_10m  ) GRIDNR=15 ;;
            ak_4m   ) GRIDNR=16 ;;
            wc_4m   ) GRIDNR=17 ;;
            at_4m   ) GRIDNR=18 ;;
          esac

          $USHwave/multiwavegrib2_single.sh $grdID $ymdh $YMDH $GRIDNR $MODNR  > grib2out_${grdID}_${ymdh}.out

          if [ -d "grib_${grdID}_${ymdh}" ]
          then
            set +x
            echo ' '
            echo '************************************'
            echo '***ERROR IN GENERATING GRIB FILES***'
            echo '************************************'
            postmsg "$jlogfile" "GRIB2 Files not generated for $grdID and $ymdh"
            sed "s/^/grib2out_${grdID}_${ymdh}.out :/g" grib2out_${grdID}_${ymdh}.out
            rm -f grib2out_${grdID}_${ymdh}.out
            gribdone='no'
            rm -f gribdone.$ymdh.$grdID 
            [[ "$LOUD" = YES ]] && set -x
          else
            rm -f grib2out_${grdID}_${ymdh}.out
          fi 

          typeset -Z3 hr=`$utilexec/nhour $ymdh $YMDH`

          if [ ! -f "$modID.$grdID.$cycle.f${hr}.grib2" ]
          then
            set +x
            echo ' '
            echo '************************************'
            echo '***ERROR IN GENERATING GRIB FILES***'
            echo '************************************'
            postmsg "$jlogfile" "GRIB2 Files not generated for $grdID and forecast hour $hr"
            rm -f gribdone.$ymdh.$grdID 
            gribdone='no'
          fi
        else
          gribdone='no'
        fi  

      fi 


      ymdh=`$utilexec/ndate $dtgribh $ymdh`

    done

    if [ "$gribdone" = 'yes' ]
    then
      rm -f grib2.$grdID.lock
    else
      sleep 30
    fi

  done 

# --------------------------------------------------------------------------- #
# 2.  Check to see if script completed cleanly

  if [ "$gribdone" = 'yes' ]
  then
    set +x
    echo ' '
    echo " Grib2 files for $grdID generated cleanly "
    [[ "$LOUD" = YES ]] && set -x
    touch grib2.$grdID.complete
  else 
    set +x
    echo ' '
    echo '************************************************************ '
    echo '*** FATAL ERROR : multiwavegrib2_sbs did not end cleanly *** '
    echo '************************************************************ '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2"
  fi

  set +x
  echo ' '
  echo "End of multiwavegrib2_sbs.sh at"
  date

# End of multiwavegrib2_sbs.sh -------------------------------------------------- #
