#!/bin/sh
###############################################################################
#                                                                             #
# This is the actual forcast script for the GLW multi-grid wave model. It     #
# uses only a single ush script                                               #
#                                                                             #
#    multiwavestart.sh   Determine the time for the most recent available     #
#                        restart file                                         #
#                                                                             #
# For non-fatal errors output is witten to the wave.log file.                 #
#                                                                             #
#                                                                 July, 2007  #
#                                                                             #
###############################################################################
# --------------------------------------------------------------------------- #
# 0.  Preparations
# 0.a Basic modes of operation

  cd $DATA

# 0.a.1 Grids

  grids='grl'
  winds='grl'
  ice='grl'
  buoy='points'

  seton='-xa'
  setoff='+xa'
  postmsg "$jlogfile" "HAS BEGUN on `hostname`"

  msg="Starting GLW WAVE MODEL SCRIPT"
  postmsg "$jlogfile" "$msg"

  set $setoff
  echo ' '
  echo '                      *****************************'
  echo '                      *** GLW WAVE MODEL SCRIPT ***'
  echo '                      *****************************'
  echo ' '
  echo "Starting at : `date`"
  set $seton

# --------------------------------------------------------------------------- #
# 1.  Set times
# 1.a Times

  export date=$PDY
  export YMDH=${PDY}${cyc}

  wndID=`cat $COMIN/what_waveglwn_used.t${cyc}z`

#  if [ -f $COMIN/glwn.t${cyc}z.NDFDused ]
#  then
#    export wndID='NDFD'
#    lsth=144 
#  else
#    if [ -f $COMIN/glwn.t${cyc}z.NAMused ]
#    then
#      export wndID='NAM'
#      lsth=84 
#    else
#      echo ' Wind source not recognized '
#      exit
#    fi
#  fi

  if [ "$wndID" = 'NDFD' ]
  then
    lsth=144
  else
    lsth=84
  fi

  nrst=1

# 1.b Set all necessary times.
#     YMDH     :  nowcast time in yyyymmddhh format
#     time_beg :  begin time of run (9 hour hindcast)
#     time_rst :  restart file time (6 hours after $time_beg)
#     time_end :  ending time of run ($lsth hour forecast)

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

  ymdh=`$utilexec/ndate $off_hour $YMDH`
  time_beg="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"

  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 $off_hour $YMDH`
  ymdh=`$utilexec/ndate $lsth $ymdh`
  time_end="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"

  set $setoff
  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 ' '

# --------------------------------------------------------------------------- #
# 2.  Get and prepare input and output files

  echo 'Preparing input files :'
  echo '-----------------------'
  set $seton

# 2.a Model definition file

  for grd in $grids $buoy
  do

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

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

    if [ -f mod_def.$grd ]
    then
      echo "   mod_def.$grd exists."
    else
      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

  for grdID in $winds
  do

    if [ ! -f wind.$grdID ]
    then
      echo "   Copy wind.$grdID from $COMIN/$modID.$grdID.$cycle.wind"
      cp $COMIN/$modID.$grdID.$cycle.wind wind.$grdID
    fi

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

  done

# 2.c Boundary data file

   echo '*******************************************'
   echo '*** NO BOUNDARY DATA FILE FOR GLW MODEL ***'
   echo '*******************************************'

# if [ ! -f nest.ww3 ]
# then
#   echo "   Copy nest.ww3 from $COMIN/$modID.$cycle.nest"
#   cp $COMIN/$modID.$cycle.nest nest.ww3
# fi

# if [ -f nest.ww3 ]
# then
#   echo "   nest.ww3 exists."
# else
#   msg="ABNORMAL EXIT: NO BOUNDARY DATA FILE"
#   postmsg "$jlogfile" "$msg"
#   set $setoff
#   echo ' '
#   echo '*******************************************'
#   echo '*** FATAL ERROR : NO BOUNDARY DATA FILE ***'
#   echo '*******************************************'
#   echo ' '
#   echo "$modID $gridID fcst $date $cycle : nest file missing." >> $wavelog
#   echo $msg
#   set $seton
#   err=3;export err;err_chk
# fi

# 2.d Ice file

  for grdID in $ice
  do

    if [ ! -f ice.$grdID ]
    then
      echo "   Copy ice.$grdID from $COMIN/$modID.$grdID.$cycle.ice"
      cp $COMIN/$modID.$grdID.$cycle.ice ice.$grdID
    fi
                                                                                                       
    if [ -f ice.$grdID ]
    then
      echo "   ice.$grdID exists."
      ice_flag=T
    else
      echo "   ice.$grdID not found.               **** WARNING **** "
      ice_flag=F
      echo "$modID $grdID fcst $date $cycle : no ice file." >> $wavelog
      postmsg "$jlogfile" "NON-FATAL ERROR - ice.$grdID NOT FOUND."
    fi

  done

# --------------------------------------------------------------------------- #
# 2.e Restart file
#     Normally, we will pick up the file $modID.$grdID.$cycle.restart file 
#     that has been placed here from the previous cycle run. If that file
#     is not there, we try to find a restart from a  cycle up to a maximum
#     of nback cycles back. If there is no restart file anywhere, a cold
#     start is performed automatically. The corresponding starting time
#     is set in multiwavestart.sh
#
#     Make sure nback is set identically in the preprocessor !!!

  export nback=3

  $USHwave/multiwavestart_glwn.sh

  ymdh=`head multiwavestart.out | awk '{ print $1 }'`
  rm -f multiwavestart.out

  time_ini="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"
  ymdh=`$utilexec/ndate -$off_hour $ymdh`
  rdate=`echo $ymdh | cut -c 1-8`
  rcycle=t`echo $ymdh | cut -c 9-10`z



  dir=$com/${RUN}.${rdate}

  echo "Attempting to copy restart file from $dir"

  for grdID in $grids
  do

    file=$modID.$grdID.${rcycle}.restart
    if [ -d $dir ]
    then
      if [ -f $dir/$file ]
      then
        cp  $dir/$file restart.$grdID
      fi
    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 "$modID $gridID fcst $date $cycle : cold start." >> $wavelog
      cold_start=yes
    else
      echo "   restart.$grdID copied ($dir/$file)."
      if [ "$time_ini" != "$time_beg" ]
      then
       set $setoff
        echo ' '
        echo " model start time and restart times are not compatible (older restart is being used)"
        echo "  restart time     = $time_ini"
        echo "  model start time = $time_beg"
        echo ' '
        set $seton
        echo "$modID fcst $date $cycle : older restart used ($rdate $rcycle)." >> $wavelog
        postmsg "$jlogfile" "OLDER RESTART USED ($rdate $rcycle)."
      fi
      cold_start=no
    fi

  done

# 2.f 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 "$modID fcst $date $cycle : no buoy locations file." >> $wavelog
  fi

# 2.g Create model input file from template

  if [ -f $FIXwave/multiwavefcst.$modID.tmpl ]
  then
    cp $FIXwave/multiwavefcst.$modID.tmpl multiwavefcst.inp.tmpl
  fi

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

  sed -e "s/RUN_BEG/$time_ini/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.inp

  rm -f multiwavefcst.inp.tmpl

# --------------------------------------------------------------------------- #
# 3.  Run model

  set $setoff
  echo ' '
  echo 'Start the wave model :'
  echo '----------------------'
  echo ' '
  echo "  model is using $wndID winds "
  echo ' '
  set $seton
  postmsg "$jlogfile" "Start the wave model."

  poe $EXECwave/multiwavefcst
  err=$?

  if [ "$err" != '0' ]
  then
    pgm=wave_fcst
    msg="ABNORMAL EXIT: ERROR IN multiwavefcst"
    postmsg "$jlogfile" "$msg"
    set $setoff
    echo ' '
    echo '******************************************** '
    echo '*** FATAL ERROR : ERROR IN multiwavefcst *** '
    echo '******************************************** '
    echo ' '
    echo "$modID fcst $date $cycle : model crashed." >> $wavelog
    echo $msg
    set $seton
    err=4;export err pgm;err_chk
  fi
  postmsg "$jlogfile" "Wave Model completed."

  if [ "$cold_start" = 'no' ] && [ -n "`grep 'old start' log.ww3`" ]
  then
    echo "$modID fcst $date $cycle : cold start (not found until section 3)." \
                                                                   >> $wavelog
    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
    set $setoff
    echo ' '
    echo 'Saving output files :'
    echo '---------------------'
    set $seton

    echo "`hostname -s`" > $COMOUT/where_wave_${modID}_ran.$cycle

    if [ -f log.mww3 ] ; then
      echo "   Copying log.mww3      to $COMOUT/$modID.$cycle.log"
               cp      log.mww3         $COMOUT/$modID.$cycle.log
    fi

    if [ -f out_pnt.points ] ; then
      echo "   Copying out_pnt.points  to $COMOUT/$modID.$cycle.outpnt"
               cp      out_pnt.points     $COMOUT/$modID.$cycle.outpnt
    fi

    for grdID in $grids
    do
 
      if [ -f log.$grdID ] ; then
        echo "   Copying log.$grdID      to $COMOUT/$modID.$grdID.$cycle.log"
                 mv      log.$grdID         $COMOUT/$modID.$grdID.$cycle.log
      fi

      if [ -f out_grd.$grdID ] ; then
        echo "   Copying out_grd.$grdID  to $COMOUT/$modID.$grdID.$cycle.outgrd"
                 cp      out_grd.$grdID     $COMOUT/$modID.$grdID.$cycle.outgrd
      fi

    done

    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}
      for grdID in $grids
      do
        if [ -f restart${irst}.$grdID ] ; then
          echo "   Copying restart${irst}.$grdID to $COMRST/$modID.$grdID.$ncycle.restart"
                 cp      restart${irst}.$grdID    $COMRST/$modID.$grdID.$ncycle.restart
        fi
      done

      irst=`expr $irst + 1`

    done

  fi

# 4.b Clean up unwanted files

  rm -f mod_def.* wind.* ice.* restart* 
  rm -f multiwavefcst.inp

# --------------------------------------------------------------------------- #
# 5.  Ending output

  set $setoff
  echo ' '
  echo "Ending at : `date`"
  echo ' '
  echo '                    *** End of GLW forecast script ***'

  msg="End of GLW WAVE MODEL SCRIPT"
  postmsg "$jlogfile" "$msg"

# End of script ------------------------------------------------------------- #
