#!/bin/sh
###############################################################################
#                                                                             #
# This script preprocesses ice fields for the ocean wave models.              #
# It is run as a child scipt by the corresponding preprocessig script.        #
#                                                                             #
# Remarks :                                                                   #
# - This script runs in the work directory designated in the mother script in #
#   which it generates its own sub-directory 'ice'.                           #
# - Because this script is not essential for the running for the wave model   #
#   (as long as it runs every now and then) the error exit codes are set to   #
#   0. The main program script will then not find the file ice.ww3 and send   #
#   a message to the wave.log file.                                           #
# - See section 0.b for variables that need to be set.                        #
#                                                                             #
#  Update record :                                                            #
#                                                                             #
# - Origination:                                               01-Mar-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

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

  cd ice
  ln -s ../postmsg .

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

  set +x
  echo ' '
  echo '+--------------------------------+'
  echo '!         Make ice fields        |'
  echo '+--------------------------------+'
  echo "   Model ID        : $modID"
  echo "   Ice grid ID     : $iceID"
  echo ' '
  [[ "$LOUD" = YES ]] && set -x
  postmsg "$jlogfile" "Making ice fields."

  if [ -z "$YMDH" ] || [ -z "$date" ] || [ -z "$cycle" ] || \
     [ -z "$COMOUT" ] || [ -z "$EXECcode" ] || \
     [ -z "$modID" ] || [ -z "$iceID" ] || [ -z "$SENDCOM" ] || \
     [ -z "$COMICE" ] || [ -z "$SENDDBN" ]
  then
    set +x
    echo ' '
    echo '**************************************************'
    echo '*** EXPORTED VARIABLES IN preprocessor NOT SET ***'
    echo '**************************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "NON-FATAL ERROR - EXPORTED VARIABLES IN preprocessor NOT SET"
    exit 0
  fi

# 0.c Links to working directory

  ln -s ../mod_def.$iceID mod_def.ww3

# --------------------------------------------------------------------------- #
# 1.  Get the necessary files
# 1.a Copy the ice data file

  if [ "$cycle" = 't00z' ]  || [ "$cycle" = 't06z' ]
  then
    timeID="`$utilexec/ndate -24 $YMDH | cut -c3-8`00"
    YMD="`$utilexec/ndate -24 $YMDH | cut -c1-8`"
  else
    timeID="`echo $YMDH | cut -c 3-8`00"
    YMD="`echo $YMDH | cut -c 1-8`"
  fi

  file=$COMICE/sice.$YMD/seaice.t00z.5min.grb

  if [ -f $file ]
  then
    cp $file ice.grib
  fi

  if [ -f ice.grib ]
  then
    set +x
    echo ' '
    echo "   ice.grib copied ($file)."
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
  else
    set +x
    echo ' '
    echo '************************************** '
    echo '*** ERROR : NO ICE FILE (GFS GRIB) *** '
    echo '************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "NON-FATAL ERROR - NO ICE FILE (GFS GRIB)"
    exit 0
  fi

# --------------------------------------------------------------------------- #
# 2.  Process the GRIB packed ice file
# 2.a Make an index file

  set +x
  echo ' '
  echo '   Making GRIB index file ...'
  echo ' '
  [[ "$LOUD" = YES ]] && set -x

  $utilexec/wgrib ice.grib > ice.index

# 2.b Check valid time in index file

  set +x
  echo ' '
  echo "   Time ID of ice field : $timeID"
  echo ' '
  [[ "$LOUD" = YES ]] && set -x

  if [ -z "`grep $timeID ice.index`" ]
  then
    set +x
    echo ' '
    echo '********************************************** '
    echo '*** ERROR : ICE FIELD WITH UNEXPECTED DATE *** '
    echo '********************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "NON-FATAL ERROR - ICE FIELD WITH UNEXPECTED DATE"
    exit 0
  fi

# 2.c Unpack data

  set +x
  echo ' '
  echo '   Extracting data from ice.grib ...'
  echo ' '
  [[ "$LOUD" = YES ]] && set -x

  grep $timeID ice.index | \
           $utilexec/wgrib ice.grib -i -text -o ice.raw 2>&1 > wgrib.out

  err=$?

  if [ "$err" != '0' ]
  then
    cat wgrib.out
    set +x
    echo ' '
    echo '**************************************** '
    echo '*** ERROR IN UNPACKING GRIB ICE FILE *** '
    echo '**************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "NON-FATAL ERROR IN UNPACKING GRIB ICE FILE."
    exit 0
  fi

  rm -f wgrib.out
  rm -f ice.grib 
  rm -f ice.index

# 2.d Run through preprocessor wave_prep

  set +x
  echo ' '
  echo '   Executing $EXECcode/multiwaveprep ...'
  echo ' '
  [[ "$LOUD" = YES ]] && set -x

  sed "s/YYYYMMDD/$YMD/g" ../multiwaveprep.$iceID.tmpl > multiwaveprep.inp

  ln -s ../$iceID.$cycle.ice ice.ww3
  $EXECcode/multiwaveprep  2>&1 > multiwaveprep.out
  err=$?

  if [ "$err" != '0' ]
  then
    cat waveprep.out
    set +x
    echo ' '
    echo '************************* '
    echo '*** ERROR IN waveprep *** '
    echo '************************* '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "NON-FATAL ERROR IN waveprep."
    exit 0
  fi

  rm -f multiwaveprep.out
  rm -f multiwaveprep.inp
  rm -f ice.raw
  rm -f ice.ww3
  rm -f mod_def.ww3

# --------------------------------------------------------------------------- #
# 3.  Save the ice file

  if [ "$SENDCOM" = 'YES' ]
  then
    set +x
    echo ' '
    echo "   Saving ice.ww3 as $COMOUT/${modID}.$iceID.$cycle.ice.${model_ver}"
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    cp ../$iceID.$cycle.ice $COMOUT/${modID}.$iceID.$cycle.ice.${model_ver}
  fi 

  if [ "$SENDDBN" = 'YES' ]
  then
    # 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_BINARY${DBNtag} $job $COMOUT/${modID}.$iceID.$cycle.ice.${model_ver}
  fi

# --------------------------------------------------------------------------- #
# 4.  Clean up the directory

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

  cd ..
  rm -rf ice

  set +x
  echo ' '
  echo 'End of multiwaveice.sh at'
  date

# End of multiwaveice.sh ---------------------------------------------------- #
