#bin/sh
###############################################################################
#                                                                             #
# This script is the preprocessor for the ESTOFS that runs under the ADCIRC   #
# model. This script also is the tidal spin-up for the ESTOFS.                #
# 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_nod_fac.sh  : Calculate nodal factor and equilibrium arguments      #
#  estofs_adcprep.sh  : Prepare ADCIRC run, if it's necessary                 #
#                                                                             #
# Also used is the utililty script                                            #
#                                                                             #
#  estofs_multistart.sh  : Get time of most recent restart file               #
#                                                                             #
# Remarks :                                                                   #
# - This spin-up runs only at the first operational run                       #
#                                                                             #
#                                                                 Dec, 2011   #
#                                                                             #
###############################################################################
# Start of estofs_prep.sh.sms script ---------------------------------------- #
# 0.  Preparation
# 0.a Basic modes of operation

  cd $DATA

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

  msg="$job has begun on `hostname`"
  ./postmsg "$jlogfile" "$msg"

  spinh=162
  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_multistart.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
  qfile=${RUN}.${modID}.${pcycle}.hotstart

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

  if [ ! -f ${time_beg}.${modID}.restart ]
  then
    echo "Restart file did not existed (tidal spin-up)"
    tidal_spinup=yes
  else
    echo "Restart file existed ($time_beg)"
    tidal_spinup=no
  fi
  
# --------------------------------------------------------------------------- #
# 3.  Run the model for tidal spin-up, if it's necessary

  if [ $tidal_spinup = yes ]
  then

# 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 Copy estofs spin template file

    cp $FIXestofs/${RUN}_${modID}_spin.tmpl ${RUN}.${modID}.fort.15

# 3.c Execute estofs_tide_fac.sh 
#     Normally, nodal factors are set on the middle of simulation period, 
#     thus one year is assumed as the operatinal purpose.

    time_beg=`$NDATE -$nowh $time_now`
    time_spi=`$NDATE -$spinh $time_beg`

    $USHestofs/estofs_tide_fac.sh ${time_spi}

    cp ${RUN}_${modID}_nod_equi ${COMGES}/.

# 3.d Set parameters for spin input file 

    ihot=0
    rnday=$(echo "scale=5; $spinh/24" | bc)
    dramp=$(echo "scale=5; $spinh/24" | bc)
    touts=0.00000
    toutf=$rnday
    time_hotstart=$(echo "$rnday*86400" | bc)

# 3.e Create model input file for tidal spin-up  

    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_spi/g" \
        -e "s/ihot/$ihot/g" \
        -e "s/rnday/$rnday/g" \
        -e "s/dramp/$dramp/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_spi}.${modID}.spin.fort.15
    rm -f ${RUN}.${modID}.fort.15 

    if [ ! -f ${time_spi}.${modID}.spin.fort.15 ]
    then
      echo "Tidal spin-up input file did not exist"
    else
      echo "Tidal spin-up input file existed"
    fi
        
# --------------------------------------------------------------------------- #
# 4.  Execute estofs_adcprep.sh for tidal spin-up

    $USHestofs/estofs_adcprep.sh ${time_spi} "spin" "64"

# --------------------------------------------------------------------------- #
# 5.  Execute estofs_padcirc for tidal spin-up

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

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

# --------------------------------------------------------------------------- #
# 6.  Save and clean up files
# 6.a Send files to $com

    hdate=`echo $time_beg | cut -c1-8`
    hcycle=t`echo $time_beg | cut -c9-10`z
    hdir=${COM}/${RUN}.${hdate}
    hfile=${RUN}.${modID}.${hcycle}.restart
    ifile=${RUN}.${modID}.${hcycle}.hotstart

    if [ ! -d $hdir ]
    then
      mkdir -p $hdir
    fi

    if [ `expr $(($time_hotstart/($wndh*3600))) % 2` = 0 ]
    then
      cp fort.68.nc $hdir/$hfile
      cp fort.68.nc $hdir/$ifile
    else
      cp fort.67.nc $hdir/$hfile
      cp fort.67.nc $hdir/$ifile
    fi
  fi

# --------------------------------------------------------------------------- #
# 7.  Set time and files for tide-only run
# 7.a Copy hotstart file

  if [ $tidal_spinup = yes ]
  then
    rm fort.61.nc fort.63.nc
    cp fort.68.nc ${time_beg}.${modID}.hotstart
  fi

# 7.1 Copy estofs partmesh and grid files

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

# 7.b Copy estofs spin template file

  cp $FIXestofs/${RUN}_${modID}_spin.tmpl ${RUN}.${modID}.fort.15

# 7.c Copy nodal factor and equilibirum argument file

  cp ${COMGES}/${RUN}_${modID}_nod_equi ${RUN}_${modID}_nod_equi

# 7.e Get parameters from hotstart file for updating tide input file

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

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

# 7.f Set parameters for tide input file

  tideh=`$NHOUR $time_now $time_beg`
  tided=$(echo "scale=5; ($time_hotstart+$tideh*3600)/86400" | bc)
  rnday=$(echo "scale=5; $tided+$lsth/24" | bc)
  dramp=0.00000
  touts=$(echo "scale=5; $rnday-($nowh+$lsth)/24" | bc)
  toutf=$rnday
  time_tide=$(echo "$tided*86400" | bc)

  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/$tided/g" \
      -e "s/dramp/$dramp/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}.spin.fort.15
  rm -f ${RUN}.${modID}.fort.15

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

# --------------------------------------------------------------------------- #
# 8.  Execute estofs_adcprep.sh for tide-only run

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

# --------------------------------------------------------------------------- #
# 9.  Execute estofs_padcirc for tide_only run

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

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

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

# 9.a Send files to com if requested

  if [ $SENDCOM = YES ]
  then
    echo "Copying ${time_now}.${modID}.hotstart to $COMOUT/${RUN}.${modID}.${cycle}.hotstart"
    cp ${time_now}.${modID}.hotstart               $COMOUT/${RUN}.${modID}.${cycle}.hotstart
  fi

# --------------------------------------------------------------------------- #
#10.  Set time and files for tide-only run
#10.a Copy estofs spin template file

  cp $FIXestofs/${RUN}_${modID}_spin.tmpl ${RUN}.${modID}.fort.15

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

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

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

#10.c Set parameters for tide input file

  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/$rnday/g" \
      -e "s/dramp/$dramp/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}.spin.fort.15
  rm -f ${RUN}.${modID}.fort.15

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

# --------------------------------------------------------------------------- #
#11.  Execute estofs_adcprep.sh for tide-only run

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

# --------------------------------------------------------------------------- #
#12.  Execute estofs_padcirc for tide_only run

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

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

# --------------------------------------------------------------------------- #
#13.a Send files to com and pcom if requested

  if [ $SENDCOM = YES ]
  then
    echo "Copying fort.61.nc to $COMOUT/${RUN}.${modID}.${cycle}.points.htp.nc"
    cp fort.61.nc               $COMOUT/${RUN}.${modID}.${cycle}.points.htp.nc

    echo "Copying fort.63.nc to $COMOUT/${RUN}.${modID}.${cycle}.fields.htp.nc"
    cp fort.63.nc               $COMOUT/${RUN}.${modID}.${cycle}.fields.htp.nc
  fi

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

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

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