#!/bin/sh
###############################################################################
#                                                                             #
# This script finds and copies a sigma file for the wave model, and converts  #
# then to gridded fields.                                                     #
#                                                                             #
# Remarks :                                                                   #
# - This script runs in the work directory designated in the mother script in #
#   which it generates its own sub-directory 'sig_yyyymmddhh'. If all is well #
#   the derectory is removed at the end of the script.                        #
# - The time group yyyymmddhh is the first parameter passed to the script.    #
# - See section 0.c 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 sig_$1
  mkdir sig_$1
  err=$?
  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '***************************************************************************** '
    echo '*** FATAL ERROR : ERROR IN multiwavesig (COULD NOT CREATE TEMP DIRECTORY) *** '
    echo '***************************************************************************** '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavesig (Could not create temp directory)"
    exit 1
  fi

  cd sig_$1

  ln -sf ../postmsg .

  set +x
  echo ' '
  echo '+-----------------------------------+'
  echo '!   Find and process sigma files    |'
  echo '+-----------------------------------+'
  [[ "$LOUD" = YES ]] && set -x

# 0.b Check if time set

  if [ "$#" -lt '1' ]
  then
    set +x
    echo ' '
    echo '***************************************'
    echo '*** TIME IN multiwavesig.sh NOT SET ***'
    echo '***************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" " TIME IN multiwavesig.sh NOT SET"
    exit 1
  else
    ymdh=$1
    set +x
    echo "   Time            : $ymdh"
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
  fi

# 0.c The tested variables should be exported by the calling script.

  if [ -z "$utilscript" ] || [ -z "$EXECwave" ] || [ -z "$COMGFS" ] || [ -z "$PDY" ] \
     || [ -z "$cyc" ] || [ -z "$cycle" ]
  then
    set +x
    echo ' '
    echo '**********************************'
    echo '*** EXPORTED VARIABLES NOT SET ***'
    echo '**********************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" " EXPORTED VARIABLES NOT SET."
    exit 1
  fi

# --------------------------------------------------------------------------- #
# 1.  Run getges.sh for hindcast or copy from GFS directory for forecast

  if [ "$ymdh" -le "${PDY}${cyc}" ]
  then

   $utilscript/getges.sh -q -t sigcur -r any -v $ymdh -e $GETGES_envr > getges.out 2> getges.err
    err=$?

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

    spec_file=`cat getges.out | awk '{ print $1 }'`
    rm -f getges.out getges.err
    specfile_ready='yes'

  else

    fcsth=`$utilexec/nhour $ymdh ${PDY}${cyc}`
    spec_file=$COMGFS/gfs.$cycle.sf$fcsth
    file_size=`ls -l $spec_file | awk '{print $5}'`

    if [ -f "$COMGFS/gfs.$cycle.logf$fcsth" ] && [ "$file_size" -gt '500000000' ]
    then
      specfile_ready='yes'
    else
      specfile_ready='no'
    fi

  fi

# --------------------------------------------------------------------------- #
# 2.  Copy file

  set +x
  echo "   File for ${ymdh} : ${spec_file}"
  echo "      File ready ?  : $specfile_ready"
  [[ "$LOUD" = YES ]] && set -x
  if [ -f $spec_file ] && [ "$specfile_ready" = 'yes' ]
  then

    cp $spec_file swnd.$ymdh
    err=$?
    if [ "$err" != '0' ]
    then
      set +x
      echo ' '
      echo '********************************************'
      echo '*** FATAL ERROR IN COPYING SPECTRAL FILE ***'
      echo '********************************************'
      echo ' '
      [[ "$LOUD" = YES ]] && set -x
      postmsg "$jlogfile" "ERROR IN COPYING SPECTRAL FILE FOR $ymdh."
      exit 3
    fi

  else

    set +x
    echo ' '
    echo "File $spec_file not found"
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    exit 4

  fi

# --------------------------------------------------------------------------- #
# 4.  Wait for SST file to be there

  set +x
  echo "      Checking for sst file."
  [[ "$LOUD" = YES ]] && set -x

  ntry=1
  ntry_max=150

  until [ -s ../sst.ww3 ] || [ "$ntry" -gt "$ntry_max" ]
  do
    ntry=`expr $ntry + 1`
    sleep 1
  done

  if [ ! -s ../sst.ww3 ]
  then
    set +x
    echo ' '
    echo '***************************************'
    echo '*** FATAL ERROR IN FINDING SST FILE ***'
    echo '***************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    postmsg "$jlogfile" "ERROR IN FINDING SST FILE FOR $ymdh."
    exit 4
  fi

  sleep 1

  ln -sf ../sst.ww3 .

# --------------------------------------------------------------------------- #
# 5.  Running extraction program for single time

  set +x
  echo "      Running extraction program ..."
  [[ "$LOUD" = YES ]] && set -x

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

  echo "$IDIML, $JDIML,$JCLIP"                              > gfsinput
  echo "$time $time"                                       >> gfsinput 

  cat gfsinput | $EXECwave/multiwavegfs

  err=$?

  if [ "$err" != '0' ]
  then
    if [ "$sigMODE" = 'prep' ]
    then
      msg="ABNORMAL EXIT: ERROR IN $wave_{modID}gfs"
      postmsg "$jlogfile" "$msg"
      set +x
      echo ' '
      echo '******************************************* '
      echo '*** FATAL ERROR : ERROR IN multiwavegfs *** '
      echo '******************************************* '
      echo ' '
      [[ "$LOUD" = YES ]] && set -x
    else
      if [ "$sigMODE" = 'forecast' ]
      then
         msg="Error in multiwavegfs for $ymdh. Retrying ..."
         postmsg "$jlogfile" "$msg"
         set +x
         echo ' '
         echo " Error in multiwavegfs for $ymdh. Retrying ..."
         echo ' '
         [[ "$LOUD" = YES ]] && set -x
      fi
    fi
    exit 5
  fi

  if [ ! -f gfs.wind ]
  then
    msg="ABNORMAL EXIT: FILE gfs.wind MISSING"
    postmsg "$jlogfile" "$msg"
    set +x
    echo ' '
    echo ' '
    echo '****************************************'
    echo '*** FATAL ERROR : gfs.wind NOT FOUND ***'
    echo '****************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    exit 6
  fi

  mv gfs.wind ../gwnd.$ymdh
  rm -f swnd.$ymdh sst.ww3 gfsinput

# --------------------------------------------------------------------------- #
# 6.  Clean up the directory

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

  cd ..
  rm -rf sig_$ymdh

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

# End of multiwavesig.sh ---------------------------------------------------- #
