#!/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                                                    #
#                                                                             #
###############################################################################

#
# ... Define directories
#
#
# --------------------------------------------------------------------------- #
# 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  
  rm -rf grib_$grdID
  mkdir grib_$grdID
  err=$?
  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '******************************************************************************* '
    echo '*** FATAL ERROR : ERROR IN multiwavegrib2 (COULD NOT CREATE TEMP DIRECTORY) *** '
    echo '******************************************************************************* '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2 (Could not create temp directory)"
    exit 1
  fi

  cd grib_$grdID

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

  dtgrib=$2
  ngrib=$3
  GRIDNR=$4
  MODNR=$5
  gribflags=$6

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

  if [ -z "$YMDH" ] || [ -z "$cycle" ] || [ -z "$EXECwave" ] || [ -z "$EXECcode" ] || \
     [ -z "$COMOUT" ] || [ -z "$modID" ] || [ -z "$SENDCOM" ] || \
     [ -z "$dtgrib" ] || [ -z "$ngrib" ] || [ -z "$gribflags" ] || [ -z "$utilexec" ] || \
     [ -z "$GRIDNR" ] || [ -z "$MODNR" ] || [ -z "$SENDDBN" ]
  then
    set +x
    echo ' '
    echo '***************************************************'
    echo '*** EXPORTED VARIABLES IN postprocessor NOT SET ***'
    echo '***************************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "EXPORTED VARIABLES IN postprocessor NOT SET"
    exit 1
  fi

# 0.c Starting time for output

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

  set +x
  echo "   Starting time    : $tstart"
  echo "   Time step        : $dtgrib"
  echo "   Number of times  : $ngrib"
  echo "   GRIB field flags : $gribflags"
  echo ' '
  [[ "$LOUD" = YES ]] && set -x

# 0.d sync important files

#  $utilexec/fsync_file ${DATA}/mod_def.$grdID
#  $utilexec/fsync_file ${DATA}/out_grd.$grdID
#  $utilexec/fsync_file ${DATA}/multiwavesgrib2.inp.tmpl

# 0.e 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

  sed -e "s/TIME/$tstart/g" \
      -e "s/DT/$dtgrib/g" \
      -e "s/NT/$ngrib/g" \
      -e "s/GRIDNR/$GRIDNR/g" \
      -e "s/MODNR/$MODNR/g" \
      -e "s/FLAGS/$gribflags/g" \
                               ../multiwavegrib2.inp.tmpl > multiwavegrib2.inp

# 1.b Run GRIB packing program

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

  ln -sf ../$modID.$grdID.$cycle.grib2 gribfile
  $EXECcode/multiwavegrib2
  err=$?

  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '********************************************* '
    echo '*** FATAL ERROR : ERROR IN multiwavegrib2 *** '
    echo '********************************************* '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2"
    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
  err=$?
  echo "err from grib2index = $err"

# 1.d.ii Run wave steepness executable

#  ls -l gribfile
#  export XLFUNIT_10="gribfile"
#  export XLFUNIT_11="gribfile_indx"
#  export XLFUNIT_20="wsteep.grib2"

#  timex $EXECwave/multiwavesteepgrb2 1> ft06 2> errfile
#  err=$?
#  echo "err from steep = $err"
#  cp ft06 sav.ft06

# 1.e Save in /com

  if [ "$SENDCOM" = 'YES' ]
  then
    set +x
    echo "   Saving GRIB file as $COMOUT/$modID.$grdID.$cycle.grib2"
#    echo "   Saving wave steepness file as $COMOUT/$modID.wstp.$grdID.$cycle.grib2"
    [[ "$LOUD" = YES ]] && set -x
    cp gribfile $COMOUT/$modID.$grdID.$cycle.grib2
    
    if [ ! -f $COMOUT/$modID.$grdID.$cycle.grib2 ]
    then
      echo ' '
      echo '********************************************* '
      echo '*** FATAL ERROR : ERROR IN multiwavegrib2 *** '
      echo '********************************************* '
      echo ' '
      echo " Error in moving grib file $modID.$grdID.$cycle.grib2 to com"
      echo ' '
      [[ "$LOUD" = YES ]] && set -x
      ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib2"
      exit 4
    fi

#    cp wsteep.grib2 $COMOUT/$modID.wstp.$grdID.$cycle.grib2
    echo "   Creating wgrib index of $COMOUT/$modID.$grdID.$cycle.grib2"
    $utilexec/wgrib2 -s $COMOUT/$modID.$grdID.$cycle.grib2 > $COMOUT/$modID.$grdID.$cycle.grib2.idx
#    echo "   Creating wgrib index of $COMOUT/$modID.wstp.$grdID.$cycle.grib2"
#    $utilexec/wgrib2 -s $COMOUT/$modID.wstp.$grdID.$cycle.grib2 > $COMOUT/$modID.wstp.$grdID.$cycle.grib2.idx

    if [ "$SENDDBN" = 'YES' ]
    then
      set +x
      echo "   Alerting GRIB file as $COMOUT/$modID.$grdID.$cycle.grib2"
      echo "   Alerting GRIB index file as $COMOUT/$modID.$grdID.$cycle.grib2.idx"
#      echo "   Alerting GRIB steepness file as $COMOUT/$modID.wstp.$grdID.$cycle.grib2"
#      echo "   Alerting GRIB steepness index file as $COMOUT/$modID.wstp.$grdID.$cycle.grib2.idx"
      [[ "$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.grib2
      $DBNROOT/bin/dbn_alert MODEL WAVE_GRIB_GB2_WIDX${DBNtag} $job $COMOUT/$modID.$grdID.$cycle.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.grib2
#      $DBNROOT/bin/dbn_alert MODEL WAVE_STEEPNESS_GRIB_GB2_WIDX${DBNtag} $job $COMOUT/$modID.wstp.$grdID.$cycle.grib2.idx
    fi
  fi 

 
# --------------------------------------------------------------------------- #
# 3.  Clean up the directory

  set +x
  echo "   Removing work directory after success."
  [[ "$LOUD" = YES ]] && set -x

  cd ..
  rm -rf grib_$grdID

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

# End of multiwavegrib2.sh -------------------------------------------------- #
