#!/bin/sh
###############################################################################
#                                                                             #
# This script is the actual forecast script for the ESTOFS that run under     #
# the ADCIRC model. It sets some shell script variables for                   #
# export to child scripts and copies some generally used files to the work    #
# directory. After this the actual preprocessing is performed by the          #
# following scripts:                                                          #
#                                                                             #
#  estofs_surface_forcing.sh  : Create surface forcing from GFS               #
#  estofs_adcprep.sh          : Prepare ADCIRC model run                      #
#                                                                             #
# Also used is the utililty script                                            #
#                                                                             #
#  estofs_multstart.sh  : Get time of most recent restart file                #
#                                                                             #
# Remarks :                                                                   #
#                                                                             #
#                                                                 Dec, 2011   #
#                                                                             #
###############################################################################
# Start of estofs_fcst.sh.sms script ---------------------------------------- #
# 0.  Preparations
# 0.a Basich modes of operation

  cd $DATA

  seton='-xa'
  setoff='+xa'
  set $seton

  msg="has begun on `hostname`"
  ./postmsg "$jlogfile" "$msg"
  msg="Starting ESTOFS forecast script for $modID"
  ./postmsg "$jlogfile" "$msg"

  wndh=3
  nowh=6
  lsth=180

# --------------------------------------------------------------------------- #
# 1.  Set times
# 1.a Set all necessary times.
#     The ending time of the run always is the $lsth hour forecast. The starting
#     time depends on availablility of restart files, and is obtained with
#     estofs_restart.sh
#
#     Make sure nback is set identically in the forecast script !!!
#     nback is the number of cycles (6-hour cycles) to look back.
#
#     YMDH     :  current time cycle in yyyymmddhh format
#     time_beg :  begin time of run (normally, -6 hour nowcast or the most recent restart time)
#     time_now :  current time
#     time_end :  ending time of run ($lsth hour forecast)

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

  time_now=$YMDH
  time_end=`$NDATE $lsth $YMDH`

# --------------------------------------------------------------------------- #
# 2.  Get restart time and file 
# 2.a Restart file
#     Normally, we will pick up the file ${RUN}.${modID}.${cycle}.restart from
#     the previous cycle. 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 without tidal spin-up
#     is performed automatically.
#     The corresponding starting time is set in estofs_restart.sh
#
#     Make sure nback is set identically in the preprocessor !!!

  $USHestofs/estofs_multistart.sh

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

  time_beg=$ymdh
  pdate=`echo $ymdh | cut -c1-8`
  pcycle=t`echo $ymdh | cut -c9-10`z

  pdir=${COM}/${RUN}.${pdate}
  pfile=${RUN}.${modID}.${pcycle}.restart

  if [ -d $pdir ]
  then
    if [ -f $pdir/$pfile ]
    then
      cp $pdir/$pfile ${time_beg}.${modID}.restart
    fi
  fi

  if [ ! -f ${time_beg}.${modID}.restart ]
  then
    echo "Restart file did not exist ($time_now)"
  else 
    echo "Restart file existed ($time_beg)"
    if [ $time_beg != `$NDATE -$nowh $time_now` ]
    then
      echo "Older restart file used ($time_beg)"
    fi
  fi
  
# --------------------------------------------------------------------------- #
# 3.  Run the model for nowcast
# 3.a Copy estofs partmesh and grid files

  cp $FIXestofs/${RUN}_${modID}_partmesh.txt partmesh.txt
  cp $FIXestofs/${RUN}_${modID}_grid ${RUN}.${modID}.fort.14

# 3.b Execute estofs_surface_forcing.sh for nowcast

  ymdh=$time_beg

  while [ $ymdh -le $time_now ]
  do
    $USHestofs/estofs_surface_forcing.sh $ymdh
    mv fort.51 ${ymdh}.${modID}.wind
    export err=$?
    ymdh=`$NDATE 3 $ymdh`
  done

  if [ $err -ne 0 ]
  then
    gfsfiles=no
  else
    gfsfiles=yes
  fi

  if [ $gfsfiles = yes ]
  then
    cat *.wind >> ${time_now}.${modID}.ncst.fort.22
    rm *.wind
  fi
  
  if [ ! -f ${time_now}.${modID}.ncst.fort.22 ]
  then
    echo "Ncst surface forcing file did not exist, critical error!"
    err_exit
  else
    echo "Ncst surface forcing file existed"
    cat ${time_now}.${modID}.ncst.fort.22 >> ${time_now}.${modID}.fort.22
  fi 
  
# --------------------------------------------------------------------------- #
# 4.  Set time and files for nowcast
# 4.a Copy estofs ncst template file  

  cp $FIXestofs/estofs_${modID}_fcst.tmpl ${RUN}.${modID}.fort.15

# 4.b Copy nodal factor and equilibirum argument file   

  cp ${COMGES}/${RUN}_${modID}_nod_equi ${RUN}_${modID}_nod_equi
  export err=$?; err_chk
  
# 4.c Get parameters from restart file for updating ncst input file 

  $NCDUMP -v time ${time_beg}.${modID}.restart > restart.out
  time_restart=$(grep 'time = [0-9]' restart.out | awk '{print $3}') 
  rm -f restart.out

  if [ `expr $(($time_restart/($wndh*3600))) % 2` = 0 ]
  then
    ihot=368
    cp ${time_beg}.${modID}.restart fort.68.nc
  else
    ihot=367
    cp ${time_beg}.${modID}.restart fort.67.nc
  fi

# 4.d Set parameters for ncst input file 

  ncsth=`$NHOUR $time_now $time_beg`
  ncstd=$(echo "scale=5; ($time_restart+$ncsth*3600)/86400" | bc)
  rnday=$(echo "scale=5; $ncstd+$lsth/24" | bc)
  touts=$(echo "scale=5; $rnday-($nowh+$lsth)/24" | bc)
  toutf=$rnday
  time_ncst=$(echo "$ncstd*86400" | bc)
 
# 4.e Create model input file for nowcast  

  exec 5<&0 < ${RUN}_${modID}_nod_equi
    read dummy
    read con1 fft1 facet1
    read con2 fft2 facet2
    read con3 fft3 facet3
    read con4 fft4 facet4
    read con5 fft5 facet5
    read con6 fft6 facet6
    read con7 fft7 facet7
    read con8 fft8 facet8
    read con9 fft9 facet9
    read con10 fft10 facet10

  sed -e "s/cycle/$time_now/g" \
      -e "s/ihot/$ihot/g" \
      -e "s/rnday/$ncstd/g" \
      -e "s/fft1/$fft1/g" -e "s/facet1/$facet1/g" \
      -e "s/fft2/$fft2/g" -e "s/facet2/$facet2/g" \
      -e "s/fft3/$fft3/g" -e "s/facet3/$facet3/g" \
      -e "s/fft4/$fft4/g" -e "s/facet4/$facet4/g" \
      -e "s/fft5/$fft5/g" -e "s/facet5/$facet5/g" \
      -e "s/fft6/$fft6/g" -e "s/facet6/$facet6/g" \
      -e "s/fft7/$fft7/g" -e "s/facet7/$facet7/g" \
      -e "s/fft8/$fft8/g" -e "s/facet8/$facet8/g" \
      -e "s/fft9/$fft9/g" -e "s/facet9/$facet9/g" \
      -e "s/fft10/$fft10/g" -e "s/facet10/$facet10/g" \
      -e "s/touts/$touts/g" -e "s/toutf/$toutf/g" \
                                     ${RUN}.${modID}.fort.15 | \
  sed -n "/DUMMY/!p"  >    ${time_now}.${modID}.ncst.fort.15
  rm -f ${RUN}.${modID}.fort.15

  if [ ! -f ${time_now}.${modID}.ncst.fort.15 ] 
  then
    echo "Ncst input file did not exist, critical error!"
    err_exit
  else
    echo "Ncst input file existed"
  fi 

# --------------------------------------------------------------------------- #
# 5.  Execute estofs_adcprep.sh for nowcast

  $USHestofs/estofs_adcprep.sh ${time_now} "ncst" "64"

# --------------------------------------------------------------------------- #
# 6.  Execute estofs_padcirc for nowcast

  export pgm="estofs_padcirc"
  . ./prep_step
  ./startmsg

  $EXECestofs/estofs_padcirc >>padcirc.log  2>errfile
  export err=$?; err_chk

  if [ `expr $(($time_ncst/($wndh*3600))) % 2` = 0 ]
  then
    cp fort.68.nc ${time_now}.${modID}.restart 
  else
    cp fort.67.nc ${time_now}.${modID}.restart
  fi

# 6.a Send files to com if requested

  if [ $SENDCOM = YES ]
  then
    cp ${time_now}.${modID}.restart               $COMOUT/${RUN}.${modID}.${cycle}.restart
  fi

# --------------------------------------------------------------------------- #
# 7.  Run the model for forecast

  ymdh=$YMDH

# 7.a Execute all scripts until the end of gfs hour

  while [ $ymdh -lt $time_end ]
  do
    ymdh_gfs=$ymdh

# 7.b Check the latest gfs grib2 hour

    ls -l ${COMGFS}/gfs.${cycle}.pgrb2f?? | awk '{print $9}' > times.gfs
    ls -l ${COMGFS}/gfs.${cycle}.pgrb2f??? | awk '{print $9}' >> times.gfs
    fcsth=`tail -n 1 times.gfs | cut -c43-46`
    if [ $fcsth -gt 180 ]
    then
      fcsth=180
    fi
    rm -f times.gfs

    ymdh_end=`$NDATE $fcsth $YMDH`

    ls -l ${COMGFS}/gfs.${cycle}.pgrb2f?? | awk '{print $9}' > count.gfs
    ls -l ${COMGFS}/gfs.${cycle}.pgrb2f??? | awk '{print $9}' >> count.gfs
    gfs_out=$(wc -l count.gfs | awk '{print $1}')
    rm -f count.gfs

    if [ $gfs_out -lt 61 ]
    then
       echo "Missing GFS grib2 files, FATAL ERROR!"
       err_exit
    else
       echo "GFS grib2 files existed"
    fi

    while [ $ymdh_gfs -le $ymdh_end ]
    do

# 7.c Execute estofs_surface_forcing.sh for forecast

        $USHestofs/estofs_surface_forcing.sh $ymdh_gfs
        mv fort.51 ${ymdh_gfs}.${modID}.wind
        export err=$?

        ymdh_gfs=`$NDATE $wndh $ymdh_gfs`
    done

    if [ $err -ne 0 ]
    then
      gfsfiles=no
    else
      gfsfiles=yes
    fi

    if [ $gfsfiles = yes ]
    then
      if [ -f ${time_now}.${modID}.fcst.fort.22 ]
      then
        rm -f ${time_now}.${modID}.fcst.fort.22
      fi      
      cat *.wind >> ${time_now}.${modID}.fcst.fort.22
      rm *.wind
    fi

    if [ ! -f ${time_now}.${modID}.fcst.fort.22 ]
    then
      echo "Fcst surface forcing file did not exist, critical error!"
      err_exit
    else
      echo "Fcst surface forcing file existed"
      cat ${time_now}.${modID}.fcst.fort.22 >> ${time_now}.${modID}.fort.22
    fi 
    
# --------------------------------------------------------------------------- #
# 8.  Set time and files for forecast
# 8.a Copy estfos fcst template file  

    cp $FIXestofs/estofs_${modID}_fcst.tmpl ${RUN}.${modID}.fort.15

# 8.b Get parameters from hotstart file for updating fcst input file 

    $NCDUMP -v time ${time_now}.${modID}.restart > restart.out
    time_restart=$(grep 'time = [0-9]' restart.out | awk '{print $3}') 
    rm -f restart.out

    if [ `expr $(($time_restart/($wndh*3600))) % 2` = 0 ]
    then
      ihot=368
      cp ${time_now}.${modID}.restart fort.68.nc
    else
      ihot=367
      cp ${time_now}.${modID}.restart fort.67.nc
    fi

# 8.c Set parameters for fcst input file 

    fcstd=$(echo "scale=5; ($time_ncst+$fcsth*3600)/86400" | bc)
    time_fcst=$(echo "$fcstd*86400" | bc)

# 8.d Create model input file for forecast 

    sed -e "s/cycle/$time_now/g" \
        -e "s/ihot/$ihot/g" \
        -e "s/rnday/$fcstd/g" \
        -e "s/fft1/$fft1/g" -e "s/facet1/$facet1/g" \
        -e "s/fft2/$fft2/g" -e "s/facet2/$facet2/g" \
        -e "s/fft3/$fft3/g" -e "s/facet3/$facet3/g" \
        -e "s/fft4/$fft4/g" -e "s/facet4/$facet4/g" \
        -e "s/fft5/$fft5/g" -e "s/facet5/$facet5/g" \
        -e "s/fft6/$fft6/g" -e "s/facet6/$facet6/g" \
        -e "s/fft7/$fft7/g" -e "s/facet7/$facet7/g" \
        -e "s/fft8/$fft8/g" -e "s/facet8/$facet8/g" \
        -e "s/fft9/$fft9/g" -e "s/facet9/$facet9/g" \
        -e "s/fft10/$fft10/g" -e "s/facet10/$facet10/g" \
        -e "s/touts/$touts/g" -e "s/toutf/$toutf/g" \
                                       ${RUN}.${modID}.fort.15 | \

    sed -n "/DUMMY/!p"  >    ${time_now}.${modID}.fcst.fort.15
    rm -f ${RUN}.${modID}.fort.15

    if [ ! -f ${time_now}.${modID}.fcst.fort.15 ] 
    then
      echo "Fcst input file did not exist, critical error!"
      err_exit
    else
      echo "Fcst input file existed"
    fi 
     
# --------------------------------------------------------------------------- #
# 9.  Execute estofs_adcprep.sh for fowcast

    $USHestofs/estofs_adcprep.sh ${time_now} "fcst" "64"

# --------------------------------------------------------------------------- #
#10.  Execute estofs_padcirc for forecast

    export pgm="estofs_padcirc"
    . ./prep_step
    ./startmsg

    $EXECestofs/estofs_padcirc >>padcirc.log  2>errfile
    export err=$?; err_chk

    if [ `expr $(($time_fcst/($wndh*3600))) % 2` = 0 ]
    then
      cp fort.68.nc ${time_now}.${modID}.restart
    else
      cp fort.67.nc ${time_now}.${modID}.restart
    fi

    ymdh=$ymdh_end
  done

# --------------------------------------------------------------------------- #
#11.  Save and clean up files
#11.a Send files to com if requested

  if [ $SENDCOM = YES ]
  then
    cp ${time_now}.${modID}.fort.22               $COMOUT/${RUN}.${modID}.${cycle}.fort.22
    cp fort.61.nc               $COMOUT/${RUN}.${modID}.${cycle}.points.cwl.nc
    cp fort.63.nc               $COMOUT/${RUN}.${modID}.${cycle}.fields.cwl.nc
  fi

  if [ $SENDDBN = YES ]
  then
    $DBNROOT/bin/dbn_alert MODEL ESTOFS_NETCDF $job $COMOUT/${RUN}.${modID}.${cycle}.points.cwl.nc
    $DBNROOT/bin/dbn_alert MODEL ESTOFS_NETCDF $job $COMOUT/${RUN}.${modID}.${cycle}.fields.cwl.nc
  fi

  echo "ESTOFS forecast script for $modID completed normally"
  msg="ESTOFS forecast script for $modID completed normally"
  ./postmsg "$jlogfile" "$msg"

# End of estofs_fcst.sh.sms script ------------------------------------------ #
