#!/bin/ksh
####################################################################
# hwrf_ocean_init.sh 
######################
# This script runs the GFDL ocean model spin up for the HWRF model.
# Scripts to run ocean spinup (phase3 and phase4)
# Written for Richard Yablonsky's research
# Author : Biju Thomas on 07/20/05
# Revised for HWRF operations: Vijay Tallapragada Apr 2007 
# Revised for HWRF 2008 operations: Biju Thomas and Vijay Tallapragada 
# Apr 2008; Provisions for new POM Initialization (Richard Yablonsky) 
# Jun 2009 Revised for HWRF 2009 implementation, Biju Thomas and Vijay Tallapragada
# Sep 2010 Revised loop current copying code (Sam Trahan)
# Jan 2011 Revise to include east pac Domain (Biju Thomas)
###################################################################

set -x

##### SET DATE AND OTHER ENVIRONMENTAL VARIABLE FROM THE SUPER SCRIPT #######
##### GET THE INPUT VARIABLES 

if [ $# -eq 8 ]
    then
    export DOMAIN=${1}
    export YEAR=${2}
    export MONTH=${3}
    export DATE=${4}
    export CYCLE=${5}
    export STORMID=${6}
    export LOOPDIR=${7}
    export VITALS=${8}

    echo 'DOMAIN  = ' ${DOMAIN}
    echo 'YEAR    = ' ${YEAR}
    echo 'MONTH   = ' ${MONTH}
    echo 'DATE    = ' ${DATE}  
    echo 'CYCLE   = ' ${CYCLE}
    echo 'STORMID = ' ${STORMID} 
    echo 'LOOPDIR = ' ${LOOPDIR}
else
    echo 'Usage: sh hwrf_ocean_init.sh DOMAIN YEAR MONTH DATE CYCLE STORMID LOOPDIR VITALS'
    echo 'NEED EIGHT INPUT VARIABLES'
    echo 'SCRIPT WILL EXIT'
    sh ${utilscript}/setup.sh
    err=911
    err_exit "NEED EIGHT INPUT VARIABLES"
fi  
##############################################################

# remove any ocean_status file that might be present
if [ -f ${COMOUT}/ocean_status.${DOMAIN}${STORMID}.$YEAR$MONTH$DATE$CYCLE ]
    then
    rm -f ${COMOUT}/ocean_status.${DOMAIN}${STORMID}.$YEAR$MONTH$DATE$CYCLE 
fi 

export cyc=$CYCLE
export LCASE_NAME=`echo  $DOMAIN | tr '[A-Z]' '[a-z]' `
name=$LCASE_NAME

echo 'cyc      = ' ${cyc} 
echo 'name     = ' ${name} 

### SPECIFIC TO INITIALIZATION ########

ocn_clim=GDEM  #ocn_clim=Levit #ocn_clim=gdem3

echo 'CSTREAM = ' ${CSTREAM} 

##### OTHER DIRECTORIES REQUIRED FOR THE INITIALIZATION

work_d=$CSTREAM/OCEAN/ocn2D_spin
pha3_d=$work_d/phase3-mcs
pha4_d=$work_d/phase4-mcs
exec_d=$SPINUP_EXE
fixd_d=$FIXED_DATA
parm_d=$PARAM_DATA
gfs0_d=$SPINUP_DATA/$YEAR$MONTH$DATE$CYCLE
ops_script=$PRE_SORTVIT

echo 'ocn_clim   = ' ${ocn_clim} 
echo 'work_d     = ' ${work_d}
echo 'pha3_d     = ' ${pha3_d}
echo 'pha4_d     = ' ${pha4_d}
echo 'gfs0_d     = ' ${gfs0_d}

export mm=`echo $PDY | cut -c5-6`
export yyyymmdd=`echo $PDY | cut -c1-8`
export yymmdd=`echo $PDY | cut -c3-8`
export yyyy=`echo $PDY | cut -c1-4`
export yy=`echo $PDY | cut -c3-4`
export sno=`echo $STORMID | cut -c1-2`

echo 'mm     = ' ${mm}
echo 'yymmdd = ' ${yymmdd}
echo 'yyyy   = ' ${yyyy}
echo 'yy     = ' ${yy}
echo 'sno    = ' ${sno}   
#-----------------------------------------------------
export ddm=`     echo $PDY | cut -c7-8`

if [ $ddm -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
##############################
# make working directories  
echo 'work_d = ' ${work_d}  
echo 'pha3_d = ' ${pha3_d}
echo 'pha4_d = ' ${pha4_d}

if [ -d ${work_d} ] 
    then 
    rm -rf ${work_d} 
fi 
mkdir -p $work_d 
mkdir -p $pha3_d
mkdir -p $pha4_d  
#######################################

# Extract gfs realtime sst and mask
export XLSMPOPTS="parthds=1:spins=0:yields=0:stack=128000000"

cd $work_d
pwd
rm -f fort.*
# run the executable gfdl_getsst 
sh ${utilscript}/setup.sh 
export pgm=${exec_d}/gfdl_getsst
. prep_step 
ln -sf $gfs0_d/gfs.t${cyc}z.sfcanl      for11
ln -sf $gfs0_d/gfs.t${cyc}z.sfcanl      fort.11
ln -sf $gfs0_d/gfs.t${cyc}z.sanl        fort.12
#ln -s -f $gfs0_d/gfs.t${cyc}z.sfcanl      fort.11
#ln -s -f $gfs0_d/gfs.t${cyc}z.sanl        fort.12
if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh
fi
startmsg
${exec_d}/gfdl_getsst >> getsst.out
export err=$?
echo "For executable gfdl_getsst return code err = ${err}"  
mv fort.23    lonlat.gfs
mv fort.74    sst.gfs.dat
mv fort.77    mask.gfs.dat
rm -f fort.*

########################################

# run the script gfdl_pre_ocean_sortvit.sh
ls -l ${ops_script}/gfdl_pre_ocean_sortvit.sh
ls -l "$VITALS"

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh
fi
grep -iE " ${STORMID}" "$VITALS" | ${ops_script}/gfdl_pre_ocean_sortvit.sh > track.allhours
echo \
"000  000 000000    000000 0000 000  000 000  00  000 0000  000 00  00 0000 0000 0000 0000 0000 0000 0000 0000"\
>> track.allhours

echo ================= FULL TRACK =================
cat track.allhours

# The below perl script will remove all cycles after the current one
# from the "track" file.  Otherwise, tracks out to +72 hours will be
# used when deciding whether to use ocean coupling.  That will result
# in a large number of retrospective and late real-time parallel cases
# not using ocean coupling when the real-time operational run did use
# coupling.  
cat track.allhours | perl -ne '
    if(!/^.{19}(\d{6}).(\d\d)/) { 
        # Invalid line in tcvitals, or tcvitals format changed.
        # Safest thing to do here is print the line.
        print ; next;
    } else {
        # Valid line.  Is it beyond this cycle?
        $then="$1$2";
        $now="'$yymmdd$CYCLE'";
        if($then>$now) {
            print "000  000 000000    000000 0000 000  000 000  00  000 0000  000 00  00 0000 0000 0000 0000 0000 0000 0000 0000\n";
            exit 0;
        } else {
            print ; next;
        }
    }' > track.shortened

echo ================= SHORTENED ==================
cat track.shortened
echo ==============================================

# Just in case, check that the shortened track is non-empty:
if [[ -s track.shortened ]] ; then
    echo USING SHORTENED TRACK
    /bin/cp -pf track.shortened track
else
    # If shortened track is empty (should not happen) use the full track:
    echo USING ORIGINAL TRACK SINCE SHORTENED TRACK IS EMPTY
    /bin/mv -f track.allhours track
fi
if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh
fi

echo ================= FINAL TRACK ==================
cat track
echo ==============================================

grep `echo ${yymmdd} | cut -c1-6` track | tail -1 |
${GOOD_AWK} '
{
  a=int($6)/10.  #latitude
  o=int($7)/10.  #longitude
  d=int($8)      #direction
  s=int($9)/10.  #speed
  p=int($10)     #central pressure
  v=int($13)     #max wind speed
  for (i=1; i<=12; i++) {
    if (d>=0 && s>=0) {
      a=a+cos(d*3.1415/180)*s*3600*6*i/110000
      o=o-sin(d*3.1415/180)*s*3600*6*i/110000
      printf("%7.2f %7.2f %7.2f %7.2f %7.2f\n", i*6.0, o*-1, a, p, s)
    }
    else {
      printf("%7.2f %7.2f %7.2f %7.2f %7.2f\n", i*6.0, o*-1, a, p, s)
    }
  }
} '  > shortstats

########################################
# run the executable gfdl_find_region
sh ${utilscript}/setup.sh

export pgm=${exec_d}/gfdl_find_region
. prep_step
ln -s -f ocean_region_info.txt  fort.61
startmsg
${exec_d}/gfdl_find_region < shortstats 
export err=$?
echo "For executable gfdl_find_region return code err = ${err}"  
if [ $err -ne 0 ]; then
    echo "For executable gfdl_find_region return code err = ${err}"
fi
########################################

BASIN=`echo ${STORMID} | cut -c3-3`
if [ ${BASIN} = 'E' ]; then
  export region=east_pacific
  echo ${region} >> ocean_region_info.txt
fi

export region=`tail -1 ocean_region_info.txt | $GOOD_AWK '{print $1}'`
tail -2 ocean_region_info.txt | head -1

if [ $region = east_atlantic ]; then
    export region=eastatl
elif [ $region = west_united ]; then
    export region=united
elif [ $region = east_pacific ]; then
    export region=eastpac
else
    echo 'Model will run only atmosphere'
    echo 'RUN_COUPLED=NO'  > ${COMOUT}/ocean_status.${DOMAIN}${STORMID}.$YEAR$MONTH$DATE$CYCLE
    if [[ "$PARAFLAG" == NO ]] ; then
      $SMSBIN/setev run_noncouple
      SMSPASS=FREE
      rm cdp_cmds
      SMSNAME=/${envir}${cyc}/hwrf${cyc}/hwrf${storm_num}/fcst/jhwrf${storm_num}_couple_forecast_${cyc}
      echo "login -t 60 $SMSNODE $SMSNAME $SMSPASS" > cdp_cmds
      echo "force -r complete $SMSNAME" >> cdp_cmds
      echo "exit" >> cdp_cmds
      $SMSBIN/cdp < cdp_cmds
    fi
    exit
fi

if [[ "$region" == eastatl && "$PARAFLAG" == YES && "$WHERE_AM_I" != jet && "$WHERE_AM_I" != zeus ]] ; then
    # Temporarily use HWRF copy of gfdl_ocean_eastatl since /nwprod
    # has not been updated yet.  Jet has the new gfdl_ocean_eastatl in
    # the exec_d already, so this is only needed on CCS and Vapor
    if [[ "$region" == eastatl && "$ATLEXT" == YES ]] ; then
    ocean_exe="gfdl_ocean_${region}_ext"
    else
   ocean_exe="hwrf_ocean_${region}_init"
    fi 
else
    if [[ "$region" == eastatl && "$ATLEXT" == YES ]] ; then
    ocean_exe="gfdl_ocean_${region}"
    else
    ocean_exe="hwrf_ocean_${region}_init"
    fi
fi

if [[ "$region" == united ]] ; then
    ocean_exe="hwrf_ocean_${region}_init"
fi

for final_exe in "$EXEChwrf/$ocean_exe" "$exec_d/$ocean_exe" MISSING ; do
    if [[ -x "$final_exe" ]] ; then
        ocean_exe="$final_exe"
        break
    fi
done
if [[ "$final_exe" == MISSING ]] ; then
    sh ${utilscript}/setup.sh
    err=911
    err_exit "Looked for $ocean_exe in $EXEChwrf and $exec_d but did not find it."
fi

#  
# Define all run instruction for phase3
cd $pha3_d
pwd
# ------------------------------------------------------------------
/bin/rm mmdd.dat
echo $mm  >  mmdd.dat
echo $ddm >> mmdd.dat
# --------------------------------------------------------------------

cp ${parm_d}/gfdl_${region}.parm.3   parameters.inp.shell
sed -e "s/_date_/${yymmdd}${cyc}/g"  \
    -e "s/_name1_/${name}/g"     \
    -e "s/_name2_/${name}/g"     \
    parameters.inp.shell > parameters.inp
rm -f parameters.inp.shell
#
# link all files for phase3 and run

if   [ "${ocn_clim}" = GDEM ]; then 
    echo 1 > input_sharp
elif [ "${ocn_clim}" = gdem3 ]; then
    echo 2 > input_sharp
elif [ "${ocn_clim}" = Levit ]; then
    echo 3 > input_sharp
fi
rm -f fort.* gfdl_initdata.${region}.${mm} RST.*
if [ ${region} = 'united' ];
    then

    # run executable gfdl_sharap_mcs_r_12
    sh ${utilscript}/setup.sh 
    export pgm=gfdl_sharp_mcs_rf_l2m_rmy5.xc
    . prep_step 

    ln -s -f ${fixd_d}/gfdl_ocean_topo_and_mask.${region}       fort.66
    ln -s -f ${fixd_d}/gfdl_gdem.${mm}.ascii                    fort.8
    ln -s -f ${fixd_d}/gfdl_gdem.${mmm2}.ascii                  fort.90
    ln -s -f ${fixd_d}/gfdl_ocean_readu.dat.${mm}               fort.24
    ln -s -f ${fixd_d}/gfdl_ocean_spinup_gdem3.dat.${mm}        fort.82
    ln -s -f ${fixd_d}/gfdl_ocean_spinup_gspath.${mm}           fort.50
    ln -s -f ${fixd_d}/gfdl_ocean_spinup.BAYuf                  fort.55
    ln -s -f ${fixd_d}/gfdl_ocean_spinup.FSgsuf                 fort.65
    ln -s -f ${fixd_d}/gfdl_ocean_spinup.SGYREuf                fort.75
    ln -s -f mmdd.dat                                           fort.91

    # Get the loop current data linked by the hwrf_pre_atmos.sh script:
    rm -f fort.31 fort.32
    ln -s ${LOOPDIR}/gfdl_loop_current_rmy5.dat                 fort.31
    ln -s ${LOOPDIR}/gfdl_loop_current_wc_ring_rmy5.dat         fort.32

    # Now run gfdl_sharp_mcs_rf_l2m_rmy5 to generate the input file:
    if [ -s fort.31 ]; then
        startmsg
        ${exec_d}/gfdl_sharp_mcs_rf_l2m_rmy5 <input_sharp>sharp_mcs_r_l2b
        export err=$?
        echo "For executable gfdl_sharp_mcs_rf_l2m_rmy5 return code = ${err}"  
        if [ $err -eq 0 ]; then
            set +x
            echo " "
            echo "sharp_mcs program ended normally err=$err. Run with specified LC penetration"
            set -x
            mv fort.13       gfdl_initdata.${region}.${mm}
        else
            set +x
            
            echo " "
            echo "sharp_mcs program failed, err=$err. Run with climate LC penetration"
            echo "sharp_mcs program failed, err=$err. Run with climate LC penetration" 1>&2
            set -x
            cp ${fixd_d}/gfdl_initdata.gdem.${region}.${mm} gfdl_initdata.${region}.${mm}
            ln -s -f gfdl_initdata.${region}.${mm}                fort.13
        fi
    ln -s -f gfdl_initdata.${region}.${mm}                fort.13
    else
        set +x
        echo " "
        echo "No loop current file found.  Run with climate LC penetration"
        echo "No loop current file found.  Run with climate LC penetration" 1>&2
        set -x
        cp ${fixd_d}/gfdl_initdata.gdem.${region}.${mm} gfdl_initdata.${region}.${mm}
    fi
fi
if [ ${region} = 'eastatl' ]
    then
    if [[ "$ATLEXT" == YES ]] ; then
    cp $FIXhwrf/gfdl_ocean_topo_and_mask.${region}_extn         fort.66
    cp ${fixd_d}/gfdl_initdata.gdem.united.${mm}                 fort.12
    cp ${fixd_d}/gfdl_initdata.${region}.${mm}  gfdl_initdata.${region}.${mm}
    else
    cp ${fixd_d}/gfdl_initdata.${region}.${mm}  gfdl_initdata.${region}.${mm}
    ln -s -f ${fixd_d}/gfdl_Hdeepgsu.${region}        fort.66
    fi
    ln -s -f gfdl_initdata.${region}.${mm}                fort.13
fi
if [ ${region} = 'eastpac' ]
    then
    ln -s -f temp_salin_levitus.eastpac                            fort.13
    ln -s -f ${CSTREAM}/MESSAGES/domain.center                     domain.center
    ln -s -f ${fixd_d}/gfdl_raw_temp_salin.eastpac.${mm}           fort.45
    ln -s -f ${fixd_d}/gfdl_pctwat            gfdl_pctwat
    ln -s -f eastpac_ocean_model_info                              fort.66
fi

# run executable gfdl_ocean_${region}
sh ${utilscript}/setup.sh 
pgm=$ocean_exe
. prep_step 

ln -s -f parameters.inp                               fort.10
ln -s -f nullfile                                     fort.15
ln -s -f $work_d/sst.gfs.dat                          fort.21
ln -s -f $work_d/mask.gfs.dat                         fort.22
ln -s -f $work_d/lonlat.gfs                           fort.23

startmsg
"$ocean_exe" > gfdl_ocean.${region}.phase3.out
echo "executable $ocean_exe return code err = ${err}" 
export err=$?
if [ $err -ne 0 ]; then
    echo " nonfatal error - executable $ocean_exe return code err = ${err}"
fi

mv RST.* RST.phase3.${region}
echo "Phase3 is finished"

# preparing files for phase4 
cd $pha4_d
pwd

# run executable gfdl_date2day
echo "${yymmdd}${cyc}" > date2day.inp
sh ${utilscript}/setup.sh  
export pgm=gfdl_date2day
. prep_step 
ln -s -f date2day.dat fort.61
startmsg
${exec_d}/gfdl_date2day < date2day.inp
export err=$?
echo "executable gfdl_date2day return code err = ${err}"  
if [ $err -ne 0 ]; then
    echo "executable gfdl_date2day return code err = ${err}"
fi

tmp=`cat date2day.dat`
julday=$(echo $tmp | awk '{print $1'})
juldayp6h=$(echo "2k $julday 0.25 + p" | dc)
julday=$(echo "2k $julday 3 - p" | dc)

year=$(echo $tmp | awk '{print $2}')
echo "$year $julday" > day2date.inp

# run executable gfdl_day2date
pgm=gfdl_day2date
. prep_step 
ln -s -f day2date.dat fort.61
startmsg
${exec_d}/gfdl_day2date < day2date.inp
export err=$?
echo "executable gfdl_day2date return code err = ${err}"  
if [ $err -ne 0 ]; then
    echo "executable gfdl_day2date return code err = ${err}"
fi

start_date=`cat day2date.dat`
echo 'start_date = ' ${start_date}  
echo "$year $juldayp6h" >day2datep6h.inp
/bin/rm fort.61
$exec_d/gfdl_day2date <day2datep6h.inp
export err=$?
echo "executable gfdl_day2date return code err = ${err}"  
if [ $err -ne 0 ]; then
    echo "executable gfdl_day2date return code err = ${err}"
fi
start_datep6h=` cat fort.61 `
echo "start date is = $start_date  and plus 6h is $start_datep6h"
yymmdd6p=`echo $start_datep6h | cut -c2-5`
yymmdd6p=$yy$yymmdd6p
hh6p=`echo $start_datep6h | cut -c6-7`
hh6p=${hh6p}00
#####################
ls -l  ${ops_script}/gfdl_pre_ocean_sortvit.sh
# run the script gfdl_pre_ocean_sortvit.sh 
if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh
fi
grep -i " ${STORMID}" "$VITALS" | ${ops_script}/gfdl_pre_ocean_sortvit.sh > track.allhours
echo \
"000  000 000000    000000 0000 000  000 000  00  000 0000  000 00  00 0000 0000 0000 0000 0000 0000 0000 0000"\
>> track.allhours

# New track modification thing to remove later cycles:

echo ================= FULL TRACK =================
cat track.allhours

# The below perl script will remove all cycles after the current one
# from the "track" file.  Otherwise, tracks out to +72 hours will be
# used when deciding whether to use ocean coupling.  That will result
# in a large number of retrospective and late real-time parallel cases
# not using ocean coupling when the real-time operational run did use
# coupling.  
cat track.allhours | perl -ne '
    if(!/^.{19}(\d{6}).(\d\d)/) { 
        # Invalid line in tcvitals, or tcvitals format changed.
        # Safest thing to do here is print the line.
        print ; next;
    } else {
        # Valid line.  Is it beyond this cycle?
        $then="$1$2";
        $now="'$yymmdd$CYCLE'";
        if($then>$now) {
            print "000  000 000000    000000 0000 000  000 000  00  000 0000  000 00  00 0000 0000 0000 0000 0000 0000 0000 0000\n";
            exit 0;
        } else {
            print ; next;
        }
    }' > track.shortened

echo ================= SHORTENED ==================
cat track.shortened
echo ==============================================

# Just in case, check that the shortened track is non-empty:
if [[ -s track.shortened ]] ; then
    echo USING SHORTENED TRACK
    /bin/cp -pf track.shortened track
else
    # If shortened track is empty (should not happen) use the full track:
    echo USING ORIGINAL TRACK SINCE SHORTENED TRACK IS EMPTY
    /bin/mv -f track.allhours track
fi
if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh
fi

echo ================= FINAL TRACK ==================
cat track
echo ==============================================

### ---------------------------------------
cp ${parm_d}/gfdl_${region}.parm.4 parameters.inp
sed "s/_date_/$start_date/g" parameters.inp     > tmp
sed "s/_name1_/track/g"      tmp                > parameters.inp
sed "s/_name2_/track/g"      parameters.inp     > tmp
sed "s/_rstph3file_/RST.phase3.${region}/g" tmp > parameters.inp

# run executable gfdl_ocean_${region} 
export pgm=gfdl_ocean_${region}
. prep_step

# make the links for phase4
if [ ${region} = 'eastatl' ]; then
    if [[ "$ATLEXT" == YES ]] ; then
    ln -s -f ${FIXhwrf}/gfdl_ocean_topo_and_mask.${region}_extn         fort.66
    ln -s -f ${fixd_d}/gfdl_initdata.gdem.united.${mm}                 fort.12
    ln -s -f ${fixd_d}/gfdl_initdata.${region}.${mm}                   fort.13
    else
    ln -s -f ${fixd_d}/gfdl_initdata.${region}.${mm}                   fort.13
    ln -s -f ${fixd_d}/gfdl_Hdeepgsu.${region}                         fort.66
    fi
fi

if [ ${region} = 'eastpac' ]; then
    ln -s -f ${pha3_d}/temp_salin_levitus.eastpac                    fort.13
    ln -s -f ${pha3_d}/eastpac_ocean_model_info                      fort.66
fi

if [ ${region} = 'united' ]; then
    fixloop=${fixd_d}/gfdl_initdata.gdem.${region}.${mm}
    ph3loop=${pha3_d}/gfdl_initdata.${region}.${mm}
    if [[ -s "$ph3loop" ]] ; then
        ln -sf "$ph3loop"                                              fort.13
    else
        if [[ "$PARAFLAG" == YES ]] ; then
            sh ${utilscript}/setup.sh
            err=911
            err_exit "ABORT: PHASE 3 LOOP CURRENT IS MISSING"
        else
            ln -sf "$fixloop"                                          fort.13
        fi
    fi
    ln -s -f ${fixd_d}/gfdl_ocean_topo_and_mask.${region}              fort.66
fi

ln -s -f parameters.inp                                              fort.10
ln -s -f $work_d/sst.gfs.dat                                         fort.21
ln -s -f $work_d/mask.gfs.dat                                        fort.22
ln -s -f $work_d/lonlat.gfs                                          fort.23
ln -s -f ${pha3_d}/RST.phase3.${region}                              fort.14
ln -s -f track                                                       fort.15

numvitals=` cat track | wc -l`
rm RST.*
if [ $numvitals -ge 3 ]
    then
    startmsg
    "$ocean_exe" >gfdl_ocean.${region}.phase4.out
    export err=$?
    echo "executable gfdl_ocean_${region} return code err = ${err}"  
    rm fort.*
    mv RST.* RST.final
else
    cp ${pha3_d}/RST.phase3.${region}       RST.final
fi

if [ -s RST.final ]
    then
    echo "File RST.final size greater than zero"
    echo "Probable phase 4 ocean spin-up success."
else
    echo "File RST.final size zero" 
    echo "ERROR: Phase 4 ocean spin-up failure."
    echo "Using Phase 3 ocean spin-up only."

    cp ${pha3_d}/RST.phase3.${region} RST.final
fi
#############################################################
# Determine if model initialization successful. If successful
# model will run coupled; if not it will run atmosphere only.
# Determine file sizes: give test value 1 if size greater than zero.
if [ -s $work_d/lonlat.gfs ] 
    then
    otest1=1
else
    otest1=0
fi
#
if [ -s $work_d/sst.gfs.dat ]
    then
    otest2=1
else 
    otest2=0
fi 
#
if [ -s $work_d/mask.gfs.dat ]
    then
    otest3=1
else
    otest3=0
fi
#
if [ -s RST.final ] 
    then
    otest4=1
else
    otest4=0
fi
#
# count lines in track file; give ocean otest value 1 if more than one line. 
track_lines=`wc -l $work_d/track`
track_lines=`echo "$track_lines" | awk '{print $1}'`  
echo 'track_lines = ' ${track_lines} 
if [ ${track_lines} -gt 1 ]
    then
    otest5=1
else
    otest5=0
fi 
#
echo 'otest1 = ' ${otest1}
echo 'otest2 = ' ${otest2}
echo 'otest3 = ' ${otest3}
echo 'otest4 = ' ${otest4}
echo 'otest5 = ' ${otest5}
test_sum=`expr ${otest1} + ${otest2} + ${otest3} + ${otest4} + ${otest5}` 
echo 'test_sum = ' ${test_sum}
#
# if all values of otest are equal to 1, test_sum=5 and model will run coupled
# if any otest value is 0; test_sum < 5 and model will run atmosphere alone
if [ ${test_sum} -eq 5 ]  
    then
    echo 'test_sum = 5; model will run coupled.' 
    echo 'RUN_COUPLED=YES' > ${COMOUT}/ocean_status.${DOMAIN}${STORMID}.$YEAR$MONTH$DATE$CYCLE 
    if [[ "$PARAFLAG" == NO ]] ; then
    $SMSBIN/setev run_couple
    SMSPASS=FREE
    rm cdp_cmds
    SMSNAME=/${envir}${cyc}/hwrf${cyc}/hwrf${storm_num}/fcst/jhwrf${storm_num}_noncouple_forecast_${cyc}
    echo "login -t 60 $SMSNODE $SMSNAME $SMSPASS" > cdp_cmds
    echo "force -r complete $SMSNAME" >> cdp_cmds
    echo "exit" >> cdp_cmds
    $SMSBIN/cdp < cdp_cmds
    fi
else
    echo 'test_sum < 5; model will run only atmosphere'   
    echo 'RUN_COUPLED=NO'  > ${COMOUT}/ocean_status.${DOMAIN}${STORMID}.$YEAR$MONTH$DATE$CYCLE 
    if [[ "$PARAFLAG" == NO ]] ; then
    $SMSBIN/setev run_noncouple
    SMSPASS=FREE
    rm cdp_cmds
    SMSNAME=/${envir}${cyc}/hwrf${cyc}/hwrf${storm_num}/fcst/jhwrf${storm_num}_couple_forecast_${cyc}
    echo "login -t 60 $SMSNODE $SMSNAME $SMSPASS" > cdp_cmds
    echo "force -r complete $SMSNAME" >> cdp_cmds
    echo "exit" >> cdp_cmds
    $SMSBIN/cdp < cdp_cmds
    fi
fi 

# end of script
