#!/bin/sh
###############################################################################
#                                                                             #
# This script generates the GRIB2 file for the MWW3 forecast model            #
# It is run as a child scipt interactively by the postprocessor.              #
#                                                                             #
# Remarks :                                                                   #
# - The necessary files are retrieved by the mother script.                   #
# - This script generates it own sub-directory 'grib_*'.                      # 
# - See section 0.b for variables that need to be set.                        # 
#                                                                             #
#                                                                July, 2007   #
# 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

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

  grdID=$1  
  ymdh_now=$2
  rm -rf grib_${grdID}_$ymdh_now
  mkdir grib_${grdID}_$ymdh_now
  err=$?
  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '************************************************************************************** '
    echo '*** FATAL ERROR : ERROR IN multiwavegrib2_single (COULD NOT CREATE TEMP DIRECTORY) *** '
    echo '************************************************************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2_single (Could not create temp directory)"
    exit 1
  fi

  cd grib_${grdID}_$ymdh_now

# 0.b Define directories and the search path.
#     The tested variables should be exported by the postprocessor script.

  ymdh_start=$3
  GRIDNR=$4
  MODNR=$5

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

  if [ -z "$cycle" ] || [ -z "$EXECwave" ] || [ -z "$EXECcode" ] || [ -z "$GRIBFLAGS" ] || \
     [ -z "$COMOUT" ] || [ -z "$modID" ] || [ -z "$SENDCOM" ] || \
     [ -z "$GRIDNR" ] || [ -z "$MODNR" ] || [ -z "$SENDDBN" ] || \
     [ -z "$PCOM" ]
  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 Times for output

  tstart="`echo $ymdh_start | cut -c1-8` `echo $ymdh_start | cut -c9-10`0000"
  tnow="`echo $ymdh_now | cut -c1-8` `echo $ymdh_now | cut -c9-10`0000"

  typeset -Z3 hr=`$utilexec/nhour $ymdh_now $ymdh_start`

# 0.d Links to working directory

  ln -s ../mod_def.$grdID mod_def.ww3
  ln -s ../out_grd.$grdID  out_grd.ww3 

# --------------------------------------------------------------------------- #
# 1.  Generate GRIB file with all data
# 1.a Generate input file for multiwavegrib2
#     Template copied in mother script ...

  set +x
  echo "   Generate input file for multiwavegrib2"
  [[ "$LOUD" = YES ]] && set -x

  if [ ! -f ../multiwavegrib2_single.inp.tmpl ]; then
     cp $FIXwave/multiwavegrib2_single.inp.tmpl ../.
  fi
  sed -e "s/STIME/$tstart/g" \
      -e "s/TIME/$tnow/g" \
      -e "s/GRIDNR/$GRIDNR/g" \
      -e "s/MODNR/$MODNR/g" \
      -e "s/FLAGS/$GRIBFLAGS/g" \
                               ../multiwavegrib2_single.inp.tmpl > multiwavegrib2.inp

# 1.b Run GRIB packing program

  set +x
  echo "   Run multiwavegrib2"
  echo "     Executing $EXECcode/multiwavegrib2"
  [[ "$LOUD" = YES ]] && set -x

  ln -s ../$modID.$grdID.$cycle.f${hr}.grib2 gribfile
  $EXECcode/multiwavegrib2
  err=$?

  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '**************************************************** '
    echo '*** FATAL ERROR : ERROR IN multiwavegrib2_single *** '
    echo '**************************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2_single"
    err_chk
    exit 3
  fi

# 1.c Clean up

  rm -f multiwavegrib2.inp
  rm -f mod_def.ww3
  rm -f out_grd.ww3

# 1.d Create a wave steepness grib2 file

# 1.d.i Create grib2 index file

  $utilexec/grb2index gribfile gribfile_indx
  $utilexec/wgrib2 -s gribfile > gribfile.idx

# 1.d.ii Run wave steepness executable

  export XLFUNIT_10="gribfile"
  export XLFUNIT_11="gribfile_indx"
  export XLFUNIT_20="wsteep.grib2"

  timex $EXECwave/multiwavesteepgrb2 1> ft06 2> errfile
  err=$?

  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '************************************************* '
    echo '*** FATAL ERROR : ERROR IN multiwavesteepgrb2 *** '
    echo '************************************************* '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavesteepgrb2"
    err_chk
    exit 4
  fi

  $utilexec/wgrib2 -s wsteep.grib2 > wsteep.grib2.idx

# 1.e Save in /com

  if [ "$SENDCOM" = 'YES' ]
  then
    set +x
    echo "   Saving GRIB file as $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2"
    echo "   Saving wave steepness file as $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2"
    [[ "$LOUD" = YES ]] && set -x
    cp gribfile $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2
    cp gribfile.idx $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2.idx
    cp wsteep.grib2 $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2
    cp wsteep.grib2.idx $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2.idx

    if [ ! -f $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2 ]
    then
      echo ' '
      echo '********************************************* '
      echo '*** FATAL ERROR : ERROR IN multiwavegrib2 *** '
      echo '********************************************* '
      echo ' '
      echo " Error in moving grib file $modID.$grdID.$cycle.f${hr}.grib2 to com"
      echo ' '
      [[ "$LOUD" = YES ]] && set -x
      ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2"
      exit 4
    fi

    if [ ! -f $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2 ]
    then
      echo ' '
      echo '********************************************* '
      echo '*** FATAL ERROR : ERROR IN multiwavegrib2 *** '
      echo '********************************************* '
      echo ' '
      echo " Error in moving grib file $modID.$grdID.wstp.$cycle.f${hr}.grib2 to com"
      echo ' '
      [[ "$LOUD" = YES ]] && set -x
      ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2"
      exit 4
    fi

    if [ "$SENDDBN" = 'YES' ]
    then
      set +x
      echo "   Alerting GRIB file as $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2"
#      echo "   Alerting GRIB steepness file as $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2"
      [[ "$LOUD" = YES ]] && set -x
      # add optional tag to dbn_alert subtyp (to distinguish from standard prod alerts)
      if [ "$envir" = 'prod' ]; then
        DBNtag=${DBNtag:-""}
      else
        DBNtag=${DBNtag:="_PARA"}  # '=' used instead of '-' to ensure to use the non-prod alert type for non-prod jobs
      fi
      $DBNROOT/bin/dbn_alert MODEL WAVE_GRIB_GB2${DBNtag} $job $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2
      $DBNROOT/bin/dbn_alert MODEL WAVE_GRIB_GB2_WIDX${DBNtag} $job $COMOUT/$modID.$grdID.$cycle.f${hr}.grib2.idx
# According to dataflow, WAVE_STEEPNESS* alerts are not in table, so commenting out.
#      $DBNROOT/bin/dbn_alert MODEL WAVE_STEEPNESS_GRIB_GB2${DBNtag} $job $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2
#      $DBNROOT/bin/dbn_alert MODEL WAVE_STEEPNESS_GRIB_GB2_WIDX${DBNtag} $job $COMOUT/$modID.wstp.$grdID.$cycle.f${hr}.grib2.idx
    fi
  fi 

# --------------------------------------------------------------------------- #
# 2.  Generate AWIPS File 
# AWIPS headers are created for all grids except the arctic grid and the 
# original global grid. Instead the interpolated extended global grid
# is passed via AWIPS using the global grid headers

  if [ "$grdID" != 'ao_30m' ] && [ "$grdID" != 'glo_30m' ]
  then

    if [ "$grdID" = 'glo_30mext' ]
    then
      grdID_parm='glo_30m'
    else
      grdID_parm=$grdID
    fi

# 2.a.i AWIPS Headers for grib2 file

    if [ ! -f "../grib2_awips_${modID}_fh${hr}.$grdID_parm" ]
    then
      cp $PARMwave/grib2_awips_${modID}_fh${hr}.$grdID_parm ../.
    fi

    if [ -f "../grib2_awips_${modID}_fh${hr}.$grdID_parm" ]
    then
      set +x
      echo ' '
      echo ' Generating AWIPS Headers for GRIB2 file '
      echo '-----------------------------------------'
      echo "  using : grib2_awips_${modID}_fh${hr}.$grdID_parm"
      [[ "$LOUD" = YES ]] && set -x

      rm -f awipsparm
      ln -s ../grib2_awips_${modID}_fh${hr}.$grdID_parm awipsparm

      set +x
      echo "   Run tocgrib2"
      [[ "$LOUD" = YES ]] && set -x

      export pgm=tocgrib2
      export pgmout=tocgrib2.out
      #. ../prep_step

      rm -f AWIPSGRIB

      export XLFUNIT_11="gribfile"
      export XLFUNIT_31="gribfile_indx"
      export XLFUNIT_51="AWIPSGRB"

      $utilexec/tocgrib2 < awipsparm parm='KWBJ' > tocgrib2.out 2>&1
      OK=$?

      if [ "$OK" != '0' ]
      then
        cat tocgrib2.out
        msg="ABNORMAL EXIT: ERROR IN tocgrib2"
        postmsg "$jlogfile" "$msg"
        set +x
        echo ' '
        echo '*************************************** '
        echo '*** FATAL ERROR : ERROR IN tocgrib2 *** '
        echo '*************************************** '
        echo ' '
        echo "$modID grib2 $date $cycle : error in tocgrib2." >> $wavelog
        echo $msg
        [[ "$LOUD" = YES ]] && set -x
        exit 5
      fi

      set +x
      echo "   Get awips GRIB bulletins out ..."
      [[ "$LOUD" = YES ]] && set -x

      if [ "$SENDCOM" = 'YES' ]
      then
        echo "      Saving AWIPSGRB as grib2.$cycle.f${hr}.awipsww3_${grdID_parm}"
        echo "          in $PCOM"
        cp AWIPSGRB $PCOM/grib2.$cycle.f${hr}.awipsww3_${grdID_parm}
      fi

      if [ "$SENDDBN_NTC" = 'YES' ]
      then
        echo "      Sending AWIPSGRB to DBNET."
        $DBNROOT/bin/dbn_alert GRIB_LOW $NET $job $PCOM/grib2.$cycle.f${hr}.awipsww3_${grdID_parm}
      fi

      rm -f AWIPSGRB tocgrib2.out 
 
    fi

# 2.a.ii AWIPS Headers for Wave Steepness grib2 file
 
    if [ -f "../grib2_awips_wstp_${modID}_fh${hr}.$grdID_parm" ]
    then

      set +x
      echo ' '
      echo ' Generating AWIPS Headers for Wave Steepness GRIB2 file '
      echo '--------------------------------------------------------'
      echo "  using : grib2_awips_wstp_${modID}_fh${hr}.$grdID_parm"
      [[ "$LOUD" = YES ]] && set -x

      rm -f awipsparm
      ln -s ../grib2_awips_wstp_${modID}_fh${hr}.$grdID_parm awipsparm

      set +x
      echo "   Generating grib2 index file"
      [[ "$LOUD" = YES ]] && set -x

      $utilexec/grb2index wsteep.grib2 wsteep_indx

      set +x
      echo "   Run tocgrib2"
      [[ "$LOUD" = YES ]] && set -x

      export pgm=tocgrib2
      export pgmout=tocgrib2.out
      #. ../prep_step

      rm -f AWIPSGRIB

      export XLFUNIT_11="wsteep.grib2"
      export XLFUNIT_31="wsteep_indx"
      export XLFUNIT_51="AWIPSGRB"

      $utilexec/tocgrib2 < awipsparm parm='KWBJ' > tocgrib2.out 2>&1
      OK=$?

      if [ "$OK" != '0' ]
      then
        cat tocgrib2.out
        msg="ABNORMAL EXIT: ERROR IN tocgrib2"
        postmsg "$jlogfile" "$msg"
        set +x
        echo ' '
        echo '*************************************** '
        echo '*** FATAL ERROR : ERROR IN tocgrib2 *** '
        echo '*************************************** '
        echo ' '
        echo "$modID grib2 $date $cycle : error in tocgrib2." >> $wavelog
        echo $msg
        [[ "$LOUD" = YES ]] && set -x
        exit 6
      fi

      set +x
      echo "   Get awips wave steepness GRIB bulletins out ..."
      [[ "$LOUD" = YES ]] && set -x

      if [ "$SENDCOM" = 'YES' ]
      then
        echo "      Saving AWIPSGRB as grib2.wstp.$cycle.f${hr}.awipsww3_${grdID_parm}"
        echo "          in $PCOM"
        cp AWIPSGRB $PCOM/grib2.wstp.$cycle.f${hr}.awipsww3_${grdID_parm}
      fi

      if [ "$SENDDBN_NTC" = 'YES' ]
      then
        echo "      Sending AWIPSGRB to DBNET."
        $DBNROOT/bin/dbn_alert GRIB_LOW $NET $job $PCOM/grib2.wstp.$cycle.f${hr}.awipsww3_${grdID_parm}
      fi

      rm -f AWIPSGRB tocgrib2.out  
 
    fi
  fi
# --------------------------------------------------------------------------- #
# 3.  Touch success file and Clean up the directory


  touch ../gribdone.$ymdh_now.$grdID

  rm -f gribfile gribfile_indx wsteep.grib2 wsteep_indx
  set +x
  echo "   Removing work directory after success."
  [[ "$LOUD" = YES ]] && set -x

  cd ..
  rm -rf grib_${grdID}_$ymdh_now

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

# End of multiwavegrib2_single.sh ------------------------------------------- #
