#!/bin/sh
###############################################################################
#                                                                             #
# This script preprocesses SST fields for the ocean wave models.              #
# It is run as a child scipt by the corresponding preprocessing script.       #
#                                                                             #
# Remarks :                                                                   #
# - Shell script variables controling time, directories etc. are set in the   #
#   mother script.                                                            #
# - This script runs in the work directory designated in the mother script,   #
#   under which it creates a directory 'sst'                                  #
# - 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 sst
  mkdir sst
  err=$?
  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '***************************************************************************** '
    echo '*** FATAL ERROR : ERROR IN multiwavesst (COULD NOT CREATE TEMP DIRECTORY) *** '
    echo '***************************************************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavesst (Could not create temp directory)"
    exit 1
  fi

  cd sst
  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 sst fields        |'
  echo '+--------------------------------+'
  echo "   Model ID        : $modID"
  echo "   Wind grid ID    : $wndID"
  echo ' '
  [[ "$LOUD" = YES ]] && set -x
  postmsg "$jlogfile" "Making SST Fields."

  if [ -z "$YMDH" ] || [ -z "$date" ] || [ -z "$cycle" ] || \
     [ -z "$COMOUT" ] || [ -z "$comdirIn" ] || [ -z "$EXECwave" ] || \
     [ -z "$modID" ] || [ -z "$wndID" ] || [ -z "$SENDCOM" ] || \
     [ -z "$COMGFS" ]
  then
    set +x
    echo ' '
    echo '**************************************************'
    echo '*** EXPORTED VARIABLES IN preprocessor NOT SET ***'
    echo '**************************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "FATAL ERROR - EXPORTED VARIABLES IN preprocessor NOT SET."
    exit 1
  fi

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

  file=$COMGFS/gfs.$cycle.sstgrb

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

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

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

    set +x
    echo '   Making GRIB index file ...'
    [[ "$LOUD" = YES ]] && set -x
    $utilexec/wgrib sst.grib > sst.index

# 2.b Extract data from GRIB file

    echo '   Extracting data from sst.grib ...'

    grep TMP sst.index | \
           $utilexec/wgrib sst.grib -i -o sst.raw 2>&1 > wgrib.out
    err=$?

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

# 2.c Convert to wave model grid

      set +x
      echo '   Convert to wave model grid ...'
      [[ "$LOUD" = YES ]] && set -x

      ln -s ../sst.ww3 .
      $EXECwave/multiwave_${wndID}_sst
      err=$?

      if [ "$err" != '0' ]
      then
        set +x
        echo ' '
        echo '************************************** '
        echo "*** ERROR IN multiwave_${wndID}_sst *** "
        echo '************************************** '
        echo ' '
        [[ "$LOUD" = YES ]] && set -x
        postmsg "$jlogfile" "NON-FATAL ERROR IN multiwave_${wndID}_sst"
      fi
    fi
  fi

# 2.d Clean up

  rm -f sst.grib
  rm -f sst.index
  rm -f sst.raw
  rm -f sst.ww3
  rm -f wgrib.out

# --------------------------------------------------------------------------- #
# 3.  Error fallback : copy file of previous cycle if necessary
# 3.a Get old file if none there

  if [ ! -f ../sst.ww3 ]
  then
    ymdh="`$utilexec/ndate -6 $YMDH`"
    pdate=`echo $ymdh | cut -c1-8`
    pcycle=t`echo $ymdh | cut -c9-10`z
    file=$comdirIn/wave.$pdate/$wndID.$pcycle.sst

    if [ -f $file ]
    then
      cp $file ../sst.ww3
      set +x
      echo ' '
      echo '   SST data taken from previous run.'
      [[ "$LOUD" = YES ]] && set -x
      echo "$modID prep $date $cycle : SST taken from previous run" >> $wavelog
    fi
  fi

# 3.b exit with error code if still none there

  if [ ! -f ../sst.ww3 ]
  then
    set +x
    echo ' '
    echo '*************************************************** '
    echo '*** FATAL ERROR : NO SST FILE CREATED OR COPIED *** '
    echo '*************************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "FATAL ERROR - NO SST FILE CREATED OR COPIED."
    exit 2
  fi

# --------------------------------------------------------------------------- #
# 4.  Save the sst file for fallback option in section 3.

  if [ "$SENDCOM" = 'YES' ]
  then
    set +x
    echo ' '
    echo "   Saving sst.ww3 as $COMOUT/$modID.$cycle.sst."
    [[ "$LOUD" = YES ]] && set -x
    cp ../sst.ww3 $COMOUT/$wndID.$cycle.sst
  fi 

# --------------------------------------------------------------------------- #
# 5.  Clean up the directory

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

  cd ..
  rm -rf sst

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

# End of multiwavesst.sh ---------------------------------------------------- #
