#!/bin/sh
set -xa
###############################################################################
#                                                                             #
# This is the actual forcast script for the global ens  wave model.           #
#                                                                             #
# For non-fatal errors output is witten to the $modIE.log (wave.log) file.    #
#                                                                             #
#                                                            Feb. 2003        #
#                                                                             #
###############################################################################
# --------------------------------------------------------------------------- #
# 0.  Preparations
# 0.a Basic modes of operation
#
  cd $DATA
  postmsg "$jlogfile" "HAS BEGUN on `hostname`"
#
  msg="Starting ens WAVE MODEL SCRIPT"
  postmsg "$jlogfile" "$msg"
#
  echo ' '
  echo '                      ******************************'
  echo '                      ***  ENS WAVE MODEL SCRIPT ***'
  echo '                      ******************************'
  echo ' '
  echo "Starting at : `date`"
#
# --------------------------------------------------------------------------- #
# 1.  Set times
# 1.a Times
#
  export date=$PDY
  export YMDH=${PDY}${cyc}

  nrst=5
  stp_hour=6
#
  lsth=240     
#
# 1.b Set all necessary times.
#     YMDH     :  nowcast time in yyyymmddhh format
#     time_beg :  begin time of run (6 hour hindcast)
#     time_now :  nowcast time (restart file time)
#     time_end :  ending time of run ($lsth hour forecast)
#     time_inb :  start time for nesting output
#     time_rst :  nowcast time (restart file time)
#
##  ymdh=`$utilexec/ndate -6 $YMDH`

#  grep 'off_hour=' $USHwave/multiwavestart.sh   > time_info
#   grep 'stp_hour=' $USHwave/multiwavestart.sh  >> time_info
#   . time_info ; rm -f time_info

#   ymdh=`$utilexec/ndate -$off_hour $YMDH`
   ymdh=`$utilexec/ndate $stp_hour $YMDH`
   time_rsts="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
   rst_hour=`expr $nrst \* $stp_hour - $stp_hour`
   ymdh=`$utilexec/ndate $rst_hour $ymdh`
   time_rste="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
 
#   ymdh=`$utilexec/ndate -$stp_hour $ymdh`
#   time_beg="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
#   time_beg="`echo $YMDH | cut -c1-8` `echo $ymdh | cut -c9-10`0000"

   ymdh=$YMDH
   time_beg="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
   time_now="`echo $YMDH | cut -c1-8` `echo $YMDH | cut -c9-10`0000"
#
   ymdh=`$utilexec/ndate $lsth $YMDH`
   time_end="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
#
  echo ' '
  echo 'Times in wave model format :'
  echo '----------------------------'
  echo "   date / cycle  : $date $cycle"
  echo "   starting time : $time_beg"
  echo "   restart time (start) : $time_rsts"
  echo "   restart time (end)   : $time_rste"
  echo "   ending time   : $time_end"
  echo ' '
#
  time_inb=$time_beg

# 1.c Define all grids used

  ice='icean_5m'
  wind='gfs_60m'
  buoy="points"
  grids='glo_60m '

  set $setoff
  echo ' '
  echo 'Grid information  :'
  echo '-------------------'
  echo "   ice grid      : $ice"
  echo "   wind grid     : $wind"
  echo "   output points : ${modID}_$buoy"
  echo "   wave grids    : $grids"
  echo ' '
  set $seton
#
# --------------------------------------------------------------------------- #
# 2.  Get and prepare input and output files
#
  echo 'Preparing input files :'
  echo '-----------------------'
#
# 2.a Model definition file
#
  for grd in $ice $wind $buoy $grids
  do

    if [ "$grd" = "$buoy" ]
    then
      grdID=${modID}_${grd}
    else
      grdID=$grd
    fi

     ls -la $FIXwave/multiwave_$grdID.moddef
    echo "   Copy mod_def.$grdID from $FIXwave/multiwave_$grdID.moddef"
    if [ -f $FIXwave/multiwave_$grdID.moddef ]
    then
      cp $FIXwave/multiwave_$grdID.moddef mod_def.$grd
    fi

    if [ ! -f mod_def.$grd ]
    then
      msg="ABNORMAL EXIT: NO MODEL DEFINITION FILE"
      postmsg "$jlogfile" "$msg"
      set $setoff
      echo ' '
      echo '********************************************** '
      echo '*** FATAL ERROR : NO MODEL DEFINITION FILE *** '
      echo '********************************************** '
      echo ' '
      echo "$modID fcst $date $cycle : fixed file(s) missing." >> $wavelog
      echo $msg
      set $seton
      err=1;export err;err_chk
    fi
  done

#
# 2.b Wind file
#
  echo "   Copy wind.$wind from $COMIN/$modIE.$cycle.wind"
  if [ ! -f wind.$wind ] 
  then
    echo "   Copy wind.$wind from $COMIN/$modIE.$cycle.wind"
    cp $COMIN/$modIE.$cycle.wind wind.$wind
  fi
#
  if [ -f wind.$wind ]
  then
    echo "   wind.ww3 exists."
  else
    msg="ABNORMAL EXIT: NO WIND FILE"
    postmsg "$jlogfile" "$msg"
    echo ' '
    echo '********************************** '
    echo '*** FATAL ERROR : NO WIND FILE *** '
    echo '********************************** '
    echo ' '
    echo "$modIE fcst $date $cycle : wind file missing." >> $wavelog
    echo $msg
    err=2;export err;err_chk
  fi

# 2.b.2 Wind time info file

  echo "   Copy times.$wind from $COMIN/times.$cycle.$modIE"
  if [ -f $COMIN/times.$cycle.$modIE ]
  then
    cp $COMIN/times.$cycle.$modIE times.$wind
  fi

  if [ ! -f times.$wind ]
  then
    msg="ABNORMAL EXIT: NO TIMES FILE FOR THE WIND"
    postmsg "$jlogfile" "$msg"
    set $setoff
    echo ' '
    echo '**************************************** '
    echo '*** FATAL ERROR : NO WIND TIMES FILE *** '
    echo '**************************************** '
    echo ' '
    echo "$modID fcst $date $cycle : wind file missing." >> $wavelog
    echo $msg
    set $seton
    err=2;export err;err_chk
  fi

#
# 2.c Ice file
#
  echo "   Copy ice.$ice from $COMIN/$ice.$cycle.ice"
  #if [ -f $COMIN/$ice.$cycle.ice ]
  if [ -f $COMINwave/$ice.$cycle.ice ]
  then
    #cp $COMIN/$ice.$cycle.ice ice.$ice
    cp $COMINwave/$ice.$cycle.ice ice.$ice
  fi

  if [ -f ice.$ice ]
  then
    echo "   ice.$ice exists."
    ice_flag=T
  else
    echo "   ice.$ice not found.                            **** WARNING **** "
    ice_flag=F
    echo "$modIE fcst $date $cycle : no ice file." >> $wavelog
    postmsg "$jlogfile" "NON-FATAL ERROR - ice.ww3 NOT FOUND."
  fi

#----------------------------------------------------------------------------#
# 2.b.3 SST file

#  echo "   Copy sst.$wind from $COMIN/$wind.$cycle.sst"
#  if [ -f $COMIN/$wind.$cycle.sst ]
#  then
#    cp $COMIN/$wind.$cycle.sst sst.$wind
#  fi

#  if [ ! -f sst.$wind ]
#  then
#    msg="ABNORMAL EXIT: NO SST FILE"
#    postmsg "$jlogfile" "$msg"
#    set $setoff
#    echo ' '
#    echo '********************************* '
#    echo '*** FATAL ERROR : NO SST FILE *** '
#    echo '********************************* '
#    echo ' '
#    echo "$modID fcst $date $cycle : sst file missing." >> $wavelog
#    echo $msg
#    set $seton
#    err=2;export err;err_chk
#  fi

# --------------------------------------------------------------------------- #
# 2.d Restart file
#

#   export nback=2

#   $USHwave/multiwavestart.sh

#   ymdh=`head multiwavestart.out | awk '{ print $1 }'`
#   time_ini="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
#   rm -f multiwavestart.out

#   ymdh=`$utilexec/ndate $off_hour $ymdh`
#   ymdh=`$utilexec/ndate $stp_hour $ymdh`
#   rdate=`echo $ymdh | cut -c 1-8`

  rdate=$PDY

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

  for grdID in $grids
  do
    if [ -f $com/${RUN}.${rdate}/$modIE.$grdID.t${cyc}z.restart ] 
    then
      cp  $com/${RUN}.${rdate}/$modIE.$grdID.t${cyc}z.restart  restart.$grdID 
      echo " restart.$grdID   copied ($com/${RUN}.${rdate}/$modIE.$grdID.t${cyc}z.restart)."
    fi

    if [ ! -f restart.$grdID ]; then
      msg="   restart.$grdID not found (COLD START).           **** WARNING **** "
      postmsg "$jlogfile" "$msg"
      echo "   restart.$grdID not found (COLD START).           **** WARNING **** "
      echo "$modIE fcst $date $cycle : cold start." >> $wavelog
      cold_start=yes
    fi

  done
#
# 2.e Buoy location file
#
  if [ -f $FIXwave/wave_$modID.buoys ]
  then
    cp $FIXwave/wave_$modID.buoys buoy.loc
  fi
#
  if [ -f buoy.loc ]
  then
    echo "   buoy.loc copied ($FIXwave/wave_$modID.buoys)."
  else
    echo "   buoy.loc not found.                           **** WARNING **** "
    postmsg "$jlogfile" " **** WARNING **** buoy.loc NOT FOUND"
    touch buoy.loc
    echo "$modIE fcst $date $cycle : no buoy locations file." >> $wavelog
  fi
#
# 2.g Create model input file from template
#

  if [ -f $FIXwave/multiwavefcst.mens.tmpl ]
  then
    cp $FIXwave/multiwavefcst.mens.tmpl multiwavefcst.inp.tmpl 
  fi
#
  if [ ! -f multiwavefcst.inp.tmpl ]
  then
    msg="ABNORMAL EXIT: NO TEMPLATE FOR INPUT FILE"
    postmsg "$jlogfile" "$msg"
    echo ' '
    echo '************************************************ '
    echo '*** FATAL ERROR : NO TEMPLATE FOR INPUT FILE *** '
    echo '************************************************ '
    echo ' '
    echo "$modIE fcst $date $cycle : fixed file(s) missing." >> $wavelog
    echo $msg
    err=3;export err;err_chk
  fi
#

#     -e "s/FIELDS/F F T T T  T F T T F  T T T T T  T F T F F  T T F F F  F F F F F  F/g" \
  sed -e "s/RUN_BEG/$time_beg/g" \
      -e "s/RUN_END/$time_end/g" \
      -e "s/OUT_BEG/$time_beg/g" \
      -e "s/OUT_END/$time_end/g" \
      -e "s/DTFLD/ 3600/g" \
      -e "s/FIELDS/F F T F F  T F T T F  T T T T T  T F T F F  F F F F F  F F F F F  F/g" \
      -e "s/DTPNT/ 3600/g" \
      -e "/BUOY_FILE/r buoy.loc" \
      -e "s/BUOY_FILE/DUMMY/g" \
      -e "s/RST_TMES/$time_rsts/g" \
      -e "s/RST_TMEE/$time_rste/g" \
                                     multiwavefcst.inp.tmpl | \
  #sed -n "/DUMMY/!p"               > multiwavefcst_sbs.inp
  sed -n "/DUMMY/!p"               > multiwavefcst.inp

  rm -f multiwavefcst.inp.tmpl buoy.loc

#
# --------------------------------------------------------------------------- #
# 3.  Run model
#
  echo ' '
  echo 'Start the wave model :'
  echo '----------------------'
  echo ' '
  postmsg "$jlogfile" "Start the wave model."

  ln -sf times.$wind times.inp
#  ln -sf sst.$wind sst.ww3
   
  poe $EXECwave/multiwavefcst_sbs
  err=$?
#
  if [ "$err" != '0' ]
  then
    pgm=wave_fcst
    msg="ABNORMAL EXIT: ERROR IN multiwavefcst"
    postmsg "$jlogfile" "$msg"
    echo ' '
    echo '*************************************** '
    echo '*** FATAL ERROR : ERROR IN wavefcst *** '
    echo '*************************************** '
    echo ' '
    echo "$modIE fcst $date $cycle : model crashed." >> $wavelog
    echo $msg
    err=4;export err pgm;err_chk
  fi
  postmsg "$jlogfile" "Wave Model completed."
#
  if [ "$cold_start" = 'no' ] && [ -n "`grep 'old start' log.mww3`" ]
  then
    echo "$modIE fcst $date $cycle : cold start (not found until section 3)." \
    postmsg "$jlogfile" "COLD START (not found until section 3)."
  fi
#
# --------------------------------------------------------------------------- #
# 4.  Save and clean up files
# 4.a Send files to com if requested
#
  if [ "$SENDCOM" = 'YES' ]
  then
    echo ' '
    echo 'Saving output files :'
    echo '---------------------'
#
    echo "ncosp" > $COMOUT/where_waveens_ran.$cycle
#
    if [ -f log.mww3 ] 
    then
      echo "   Copying log.mww3      to $COMOUT/$modIE.$cycle.log"
               cp      log.mww3         $COMOUT/$modIE.$cycle.log
     fi

     if [ -f out_pnt.$buoy ] 
     then
        echo "   Copying out_pnt.$buoy  to $COMOUT/$modIE.$cycle.outpnt"
               cp      out_pnt.$buoy     $COMOUT/$modIE.$cycle.outpnt
     fi

#    if [ -f wind.$wind ] ; then
#      echo "   Copying wind.$wind      to $COMOUT/$modIE.$cycle.wind"
#               mv      wind.$wind         $COMOUT/$modIE.$cycle.wind
#               mv      times.$wind        $COMOUT/times.$cycle.$modIE
#    fi

    for grdID in $grids
    do

      if [ -f out_grd.$grdID ] 
      then
#        echo "   Copying out_grd.$grdID  to $COMOUT/$modIE.$grdID.$cycle.outgrd"
#                 mv      out_grd.$grdID     $COMOUT/$modIE.$grdID.$cycle.outgrd
         echo "   Copying out_grd.$grdID  to $COMOUT/$modIE.$cycle.outgrd"
                  mv      out_grd.$grdID     $COMOUT/$modIE.$cycle.outgrd
      fi

    done

# Moving restart files 

    irst=1
    ymdh=$YMDH

    while [ "$irst" -le "$nrst" ]
    do
      ymdh=`$utilexec/ndate $stp_hour $ymdh`
      ndate=`echo $ymdh | cut -c 1-8`
      ncycle=t`echo $ymdh | cut -c 9-10`z
      COMRST=${com}/${RUN}.${ndate}
      if [ ! -d $COMRST ]; then 
         mkdir -p $COMRST
      fi
      for grdID in $grids
      do
        if [ -f restart${irst}.$grdID ] ; then
            echo "   Copying restart${irst}.$grdID to $COMRST/$modIE.$grdID.$ncycle.restart"
            cp      restart${irst}.$grdID    $COMRST/$modIE.$grdID.$ncycle.restart
            ls -l $COMRST/$modIE.$grdID.$ncycle.restart
        fi
      done

      irst=`expr $irst + 1`

    done

  fi   ### END OF SENDCOM 
#
# 4.b Clean up unwanted files
#
  rm -f mod_def.* ice.* multiwavefcst_sbs.inp
  rm -f test*.mww3
  rm -f wind.ww3 ice.ww3 restart*.ww3 nest*.ww3
  rm -f wavefcst.inp
#
# --------------------------------------------------------------------------- #
# 5.  Ending output
#
  echo ' '
  echo "Ending at : `date`"
  echo ' '
  echo "                    *** End of $modIE forecast script ***"
#
  msg="End of NMWW3 ENSEMBLE ($modIE) MODEL SCRIPT"
  postmsg "$jlogfile" "$msg"
#
# End of script ------------------------------------------------------------- #
