#!/usr/bin/ksh

PS4='+ exgfdl_ocean_spinup.sh.sms line $LINENO: '

set +x
#####################################################################
echo "   ----------------------------------------------------------"
echo "   exgfdl_ocean_spinup.sh.sms - Script to run ocean model for GFDL runs"
echo "   ----------------------------------------------------------"
echo "   History: MAY 2001 - Script written by Tim Marchok"
echo "                       (timothy.marchok@noaa.gov, 609-452-6534)"
#####################################################################
set -x

numhrs=/nwprod/util/exec/nhour

export YYYY=` echo $PDY | cut -c1-4`
export YY=`   echo $PDY | cut -c3-4`
export MM=`   echo $PDY | cut -c5-6`
export DD=`   echo $PDY | cut -c7-8`
export HH=${cyc}
export ymdh=${PDY}${cyc}
export yyyymmdd=${PDY}
export YYMMDD=$YY$MM$DD

if [ -s MMDD.dat ]
then
  /bin/rm MMDD.dat
fi

echo $MM  > MMDD.dat
echo $DD  >> MMDD.dat
if [ $DD -le 15 ]; then
   MMMT2=`expr $MM - 1`
else
   MMMT2=`expr $MM + 1`
fi

if [ $MMMT2 -le 9 ]; then
   MMM2=0$MMMT2
else
   MMM2=$MMMT2
fi

if [ ${PARAFLAG} = 'YES' ]
then
  if [ ${FORAENV} = 'GFS' ]
  then
    export gfsdir=${gfsdir:-/com/gfs/${envir}/gfs.$PDY}
    hurdir=${RST_PHASE3_DIR}
    # NOTE: We ALWAYS want to use the 00z GFS data for our
    #       "production" reruns, since this is what NCO 
    #       uses for their runs, and we want to match them.
    sfcanlfile=gfs.t00z.sfcanl
    siganlfile=gfs.t00z.sanl
  else
    gfsdir=${PARA_DAT_DIR}
    hurdir=${RST_PHASE3_DIR}
    sfcanlfile=${PARA_SFCANL_FILE}
    siganlfile=${PARA_SIGANL_FILE}
  fi
else
  export gfsdir=${gfsdir:-/com/gfs/${envir}/gfs.$PDY}
  hurdir=/com/hur/${envir}/hur.${PDY}00
  mkdir -m 775 -p $hurdir
  sfcanlfile=gfs.t${cyc}z.sfcanl
  siganlfile=gfs.t${cyc}z.sanl
fi

cd $DATA

#-----------------------------------------------------------
# February 2007 -- Change for hybrid coordinate system
# Due to the new GFS files having a hybrid sigma/pressure
# vertical coordinate system, we have to adjust for this.
# We could either change our source code, which is a pain,
# or we can change the resolution of the data (this takes
# more time, but for our parallel testing, we will go this
# route to save time.
#-----------------------------------------------------------

if [ ! -s ${siganlfile} ]; then
  cp ${gfsdir}/${siganlfile} .
fi

if [ ${LEVEL_FLAG} = "HYB" ]; then

  export DATA
  export SIGINP=${siganlfile}
  export SIGOUT=${siganlfile}.standard_sigma

  export SIGHDR=${SIGHDR:-/nwprod/exec/global_sighdr}
  export JCAP=${JCAP:-`echo jcap|$SIGHDR ${SIGINP}`}
  export LEVS=${LEVS:-`echo levs|$SIGHDR ${SIGINP}`}
  if [ $JCAP = 382 ]; then
   export LONB=768
   export LATB=384
  elif [ $JCAP = 574 ]; then
   export LONB=1760
   export LATB=880
  else
    err_exit "unsupported GFS resolution"
  fi

  export OROGRAPHY=/dev/null
  export IDVC=1
  export VERBOSE=YES
  export CHGRESVARS='NVCOORD=1'
  export NTRAC=3
  export SIGLEVEL=${FIXhur}/global_siglevel.l64.txt
  export CHGRESEXEC=${EXEChur}/global_chgres

  set +x
  echo "TIMING: Time before chgres = `date`"
  set -x

  export PS4='+ global_chgres.sh line $LINENO: '
  ${EXhur}/global_chgres.sh
  rcc=$?

  export PS4='+ exgfdl_ocean_spinup.sh.sms line $LINENO: '
  set +x
  echo "TIMING: Time after chgres = `date`"
  set -x

  if [ ${rcc} -ne 0 ]; then
    set +x
    echo " "
    echo "ERROR running chgres in exgfdl_ocean_spinup.sh.sms, error = $rcc"
    echo "exiting...."
    echo " "
    set -x
    exit 99
  fi

  mv ${SIGOUT} ${SIGINP}

fi

#------------------------------------------------------------
# Extracting sst and mask data from gfs files. Note that
# the sfcio module in getsst needs the fort.11 file to
# be named "for11".

cp ${gfsdir}/${sfcanlfile} for11

ln -s -f for11                             fort.11
ln -s -f ${DATA}/${siganlfile}             fort.12
ln -s -f ${DATA}/lonlat.gfs                fort.23
ln -s -f ${DATA}/sst.gfs.dat               fort.74
ln -s -f ${DATA}/mask.gfs.dat              fort.77

export pgm=gfdl_getsst
. prep_step
startmsg

#-----------------------------------------------------------
# Execute the getsst program

$EXEChur/gfdl_getsst
export err=$?;err_chk

cp ${DATA}/sst.gfs.dat              ${hurdir}/sst.gfs.${yyyymmdd}.dat
cp ${DATA}/mask.gfs.dat             ${hurdir}/mask.gfs.${yyyymmdd}.dat
cp ${DATA}/lonlat.gfs               ${hurdir}/.

#------------------------------------------------------------
# Now run the ocean model.  If this is a production run, then
# we will be running this for both Atlantic regions.  If this is 
# a parallel run, then we will just run the model for the ocean
# region selected for this particular run, which is identified
# in the "regcode" variable that is exported into this script.
# If this is a parallel run for an eastern Pacific storm, then
# we will exit the script, as the phase3 spinup for the eastern
# Pacific is done in a separate script.

if [ ${PARAFLAG} = 'YES' ]
then
  if [ ${regcode} = 'eastpac' ]; then
    # For the eastpac, the phase3 stuff is done in a separate script 
    # which uses an executable that has different inputs and an entirely 
    # different model.  So just exit at this point.
    exit 0
  fi
  region_list="${regcode}"
else
  region_list="eastatl united"
fi

for region_id in ${region_list}
do

  set +x
  echo " "
  echo "+++ Running ocean model for ${region_id} region at `date`...."
  echo " "
  set -x

  # Make appropriate modifications to the parameters.inp file

  cp $PARMhur/gfdl_${region_id}.parm.3 parameters.inp.shell

  sed -e "s/_date_/${YYMMDD}${cyc}/g"  \
      -e "s/_name1_/${stormenv}/g"     \
      -e "s/_name2_/${stormenv}/g"     \
      parameters.inp.shell >parameters.inp

  rm parameters.inp.shell
  rm RST.*

  # Do the phase 3 ocean spin-up.  Note that there is a different
  # executable depending on the region (region_id) variable.

  rm fort.13

  #-------------

  if [ ${region_id} = 'united' ]
  then

    ln -s -f ${FIXhur}/gfdl_ocean_topo_and_mask.united         fort.66

    if [ ${LCFLAG} = 'YES' ]
    then

      if [ ${PARAFLAG} = 'YES' ]; then
        if [ ${LC_FILE_TYPE} = 'USER' ]; then
          cp ${lcdir}/lc2a.$ATCFNAME      gfdl_loop_current_rmy5.dat
          cp ${lcdir}/lc2_ring.$ATCFNAME  gfdl_loop_current_wc_ring_rmy5.dat
          cp ${lcdir}/lc2a.$ATCFNAME      ${COMIN}/${stormenv}.${yyyymmdd}${cyc}.loop_current_rmy5.dat
          cp ${lcdir}/lc2_ring.$ATCFNAME  ${COMIN}/${stormenv}.${yyyymmdd}${cyc}.loop_current_wc_ring_rmy5.dat
        else
          cp ${lcdir}/gfdl_loop_current_rmy5.dat          .
          cp ${lcdir}/gfdl_loop_current_wc_ring_rmy5.dat  .
          cp ${lcdir}/gfdl_loop_current_rmy5.dat          ${COMIN}/${stormenv}.${yyyymmdd}${cyc}.loop_current_rmy5.dat
          cp ${lcdir}/gfdl_loop_current_wc_ring_rmy5.dat  ${COMIN}/${stormenv}.${yyyymmdd}${cyc}.loop_current_wc_ring_rmy5.dat
        fi
      else
        cp ${lcdir}/gfdl_loop_current_rmy5.dat          .
        cp ${lcdir}/gfdl_loop_current_wc_ring_rmy5.dat  .
        cp ${lcdir}/gfdl_loop_current_rmy5.dat          ${COMIN}/${stormenv}.${yyyymmdd}${cyc}.loop_current_rmy5.dat
        cp ${lcdir}/gfdl_loop_current_wc_ring_rmy5.dat  ${COMIN}/${stormenv}.${yyyymmdd}${cyc}.loop_current_wc_ring_rmy5.dat
      fi

      # Check for age of loop current data.  If greater than 30 days, 
      # delete the loop current and warm core ring data files in the
      # current working directory so that the sharp program will fail
      # and default to using climatology.  If this is a parallel run,
      # we will essentially skip this check (by setting the update 
      # date equal to the current date of the run).

      if [ ${PARAFLAG} = 'YES' ]
      then
        lc_last_update_ymdh=${yyyymmdd}${cyc}
        wc_last_update_ymdh=${yyyymmdd}${cyc}
      else
        lc_last_update_ymdh=` cat gfdl_loop_current_rmy5.dat | tail -1 | awk '{print $1}'`
        wc_last_update_ymdh=` cat gfdl_loop_current_wc_ring_rmy5.dat | tail -1 | awk '{print $1}'`
      fi

      num_hr_lc=` $numhrs ${yyyymmdd}${cyc} ${lc_last_update_ymdh}`
      num_hr_wc=` $numhrs ${yyyymmdd}${cyc} ${wc_last_update_ymdh}`

      if [ ${num_hr_lc} -gt 720 -o ${num_hr_wc} -gt 720 ]; then
        rm gfdl_loop_current_rmy5.dat
        rm gfdl_loop_current_wc_ring_rmy5.dat
      fi

      ln -s -f ${FIXhur}/gfdl_gdem.${MM}.ascii                    fort.8
      ln -s -f ${FIXhur}/gfdl_gdem.${MMM2}.ascii                  fort.90 
      ln -s -f ${FIXhur}/gfdl_ocean_readu.dat.${MM}               fort.24
      ln -s -f ${FIXhur}/gfdl_ocean_spinup_gdem3.dat.${MM}        fort.82
      ln -s -f ${FIXhur}/gfdl_ocean_spinup_gspath.${MM}           fort.50
      ln -s -f ${FIXhur}/gfdl_ocean_spinup.BAYuf                  fort.55
      ln -s -f ${FIXhur}/gfdl_ocean_spinup.FSgsuf                 fort.65
      ln -s -f ${FIXhur}/gfdl_ocean_spinup.SGYREuf                fort.75
      ln -s -f gfdl_loop_current_rmy5.dat                         fort.31
      ln -s -f gfdl_loop_current_wc_ring_rmy5.dat                 fort.32
      #-- fort.13 is an output file....
      ln -s -f gfdl_init_using_loop_current.dat                   fort.13
      ln -s -f MMDD.dat                                           fort.91


      echo ${ocean_clim_flag} > input_sharp
      if [ ${ocean_clim_flag} = 1 ]; then
        ocn_clim=gdem
      elif [ ${ocean_clim_flag} = 2 ]; then
        ocn_clim=gdem3
      else
        ocn_clim=levit
      fi

      export pgm=gfdl_sharp_mcs_r_l2
      . prep_step
      startmsg

      ${EXEChur}/gfdl_sharp_mcs_rf_l2m_rmy5 < input_sharp >  ${DATA}/res.sharp_mcs.stdout
      sharp_err=$?

      if [ ${sharp_err} -ne 0 ]
      then
        set +x
        echo " "
        echo "NON-FATAL ERROR: gfdl_sharp_mcs program failed, err=${sharp_err}. Run with climate LC penetration"
        echo " "
        set -x
        cp ${FIXhur}/gfdl_initdata.gdem.${region_id}.${MM} gfdl_initdata.${region_id}.${MM}
      else
        set +x
        echo " "
        echo "gfdl_sharp_mcs program ended normally ers=$ers. Run with specified LC penetration"
        echo " "
        set -x
        mv gfdl_init_using_loop_current.dat gfdl_initdata.${region_id}.${MM}
      fi

    else
      set +x
      echo " "
      echo "LCFLAG= ${LCFLAG}. Do NOT use observed LC data.  Run with climate LC penetration."
      echo " "
      set -x
      cp ${FIXhur}/gfdl_initdata.gdem.${region_id}.${MM} gfdl_initdata.${region_id}.${MM}
    fi

    cp gfdl_initdata.${region_id}.${MM} ${hurdir}/gfdl_sharp_init.${region_id}.${PDY}

  fi

  #----------------------------------------

  if [ ${region_id} = 'eastatl' ]
  then
    cp ${FIXhur}/gfdl_initdata.${region_id}.${MM}       gfdl_initdata.${region_id}.${MM}
    cp ${FIXhur}/gfdl_initdata.gdem.united.${MM}        fort.12
    ln -s -f ${FIXhur}/gfdl_ocean_topo_and_mask.eastatl_extn       fort.66
  fi

  ln -s -f ${DATA}/parameters.inp                          fort.10
  ln -s -f ${DATA}/nullfile                                fort.15
  ln -s -f ${DATA}/sst.gfs.dat                             fort.21
  ln -s -f ${DATA}/mask.gfs.dat                            fort.22
  ln -s -f ${DATA}/lonlat.gfs                              fort.23
  ln -s -f gfdl_initdata.${region_id}.${MM}                fort.13

  export pgm=gfdl_ocean_${region_id}
  . prep_step
  startmsg

  ${EXEChur}/gfdl_ocean_${region_id}  >gfdl_ocean.${region_id}.out
  export err=$?;err_chk
  
  mkdir ${COMIN}/phase3
  mv T.* ${COMIN}/phase3/.
  mv U.* ${COMIN}/phase3/.
  mv V.* ${COMIN}/phase3/.
  mv TXY.* ${COMIN}/phase3/.
  mv GRADS* ${COMIN}/phase3/.

  mv RST.* $DATA/RST.phase3.${region_id}
  mv ${DATA}/RST.phase3.${region_id}  ${hurdir}/rst.phase3.${yyyymmdd}.${region_id}

done

set +x
echo " "
echo "+++ End of exgfdl_ocean_spinup.sh.sms at `date`...."
echo " "
set -x
