#!/usr/bin/ksh

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

set +x
#####################################################################
echo "   ------------------------------------------------------------------"
echo "   exgfdl_pre_atmos.sh.sms - Script to run analysis to set up GFDL Forecast."
echo "   ------------------------------------------------------------------"
echo "   History: JUN 1997 - First implementation of this new script."
echo "            JAN 1998 - Rewritten by David Michaud to standardize"
echo "            MAR 2001 - Modified by Tim Marchok for Coupled Model"
echo "            APR 2002 - Modified by Tim Marchok to extract datalat processing"
#####################################################################
set -x

####################################################
# First make sure that we've got the stormlabel
# card in the COMOUT directory, then make sure
# that there is a holdvars.txt file in there as 
# well.  Source the  holdvars.txt file, as it 
# contains needed environmental variables from 
# the JGFDL_PRE_MASTER job that have to be passed
# into this script.
####################################################

label="cat $COMOUT/$stormlabel.$cycle"

if test -f "$label" = "No $stormlabel"
then
   ##############################################
   # Condition if no storms are to be run
   ##############################################
   msg="GFDL ERROR in exgfdl_pre_atmos.sh.sms: No hurricane to run."
   postmsg "$jlogfile" "$msg"
   export pgm=exgfdl_pre_atmos.sh.sms
   export err=911;err_chk
fi

setvarfile=${COMIN}/${stormlabel}.holdvars.txt
if test -f ${setvarfile}
then
   . ${setvarfile}
else
   msg="GFDL ERROR: Hurricane to run but no ${stormlabel}.holdvars.txt file found."
   postmsg "$jlogfile" "$msg"
   export pgm=exgfdl_pre_atmos.sh.sms
   export err=911;err_chk
fi


######################################################
# Now set up the directory from which we will 
# pull the global spectral and surface files.  
# Then go ahead and copy the surface file.
######################################################
#SEC for testing
#bsm envir=test
#SEC
if [ $FORAENV = "GDAS" ]
then
   export FORA="gfs/${envir}/gdas.${Y4PREFIX}${YYMMDD}/gdas.t${HRIN}z"
elif [ $FORAENV = "GFS" ]
then
   export FORA="gfs/${envir}/gfs.${Y4PREFIX}${YYMMDD}/gfs.t${HRIN}z"
elif [ $FORAENV = "PARA" ]
then
   export FORA="${PARA_DAT_DIR}/${PARA_FILE_ROOT}"
#   export FORA="${PARA_DAT_DIR}/sfcanl.fnl.${PDY}${cyc}"
fi
#SEC
#bsm envir=prod
#SEC
set +x
echo " "
echo "FORA = $FORA"
echo "HRIN = $HRIN"
echo " "
set -x

if [ $FORAENV = "GDAS" -o $FORAENV = "GFS" ]
then
  if test -f /com/${FORA}.sfcanl
  then
     cp /com/${FORA}.sfcanl   for11
  else
     export pgm=exgfdl_pre_atmos.sh
     export err=911;err_chk
  fi
else
#  cp ${FORA}.sfcanl  for11.atmos
#  cp ${FORA}.${PDY}${cyc}  for11.atmos
  cp ${FORA}  for11.atmos
  mv for11.atmos for11
fi

###################################################################
# Copy in the current spectral files and interpolate them onto
# the GFDL integration grid.  In April, 2002, we changed this
# so that only the 00h file is converted in this Pre_Atmos
# part of the system.  The remaining forecast hours are processed
# in the Pre_Lats job.
###################################################################

set +x
echo " "
echo "TIMING: date before spc2grd hour 00 is `date`"
echo " "
set -x

$EXhur/gfdl_pre_atmos_spc2grd.sh 00

set +x
echo " "
echo "TIMING: date after  spc2grd hour 00 is `date`"
echo " "
set -x


####################################################################
# Create the analysis and initialization portions of the system
#
# Determine the position of the inner nests based on the 
# current storm position and the western and southern boundary
# of the outermost nest.
#
# Bring in boundary limits from bogus start up file
#
# CAUTION: Since this could be running at the same time as the
# pre_lats job (for a parallel run), it is a good idea to create
# a separate and distinct $DATA subdirectory so as not to stomp
# out files from each job when running the same executable in
# both jobs.
#
####################################################################

ATMOSDIR=${DATA}/atmos
if [ ! -d ${ATMOSDIR} ]
then
  mkdir -p ${ATMOSDIR}
fi
cd ${ATMOSDIR}
sh $utilscript/setup.sh

export STORM="${STORMENV}${DAY}$HRIN"
export FILE="mess-$STORMENV-$DATEIN-$HRIN"

FILE_s=`echo "mess-$STORMENV-$DATEIN-$HRIN" | tr '[A-Z]' '[a-z]'`

if [ -s $COMIN/$FILE_s ]; then
  cp $COMIN/$FILE_s $FILE
  export WBOUND=`head -1 $FILE`
  export CENLON=`head -2 $FILE | tail -1`
  export CENLAT=`head -3 $FILE | tail -1`
else
  echo "!!! ERROR: The mess file ${FILE_s} does not exist.  Exiting...."
  exit 99
fi

####################################################
# Create grid.input file
####################################################
stormlat=` cat $FILE | sed -n 3p | awk '{print $1}' `
if [ ${stormlat} -lt 0 ]; then
  storm_hem=southern
else
  storm_hem=northern
fi

if [ ${storm_hem} = 'northern' ]
then
  if [ ${GRID_CONFIG} = 'poleward' ]
  then
#   more poleward, shorter timestep
    south_bound=-10
    outer_grid_tstep=48
  else
#   more equatorward, longer timestep
    south_bound=-15
    outer_grid_tstep=60
  fi
else
  if [ ${GRID_CONFIG} = 'equatorward' ]
  then
#   more equatorward, longer timestep
    south_bound=-60
    outer_grid_tstep=60
  else
#   more poleward, shorter timestep
    south_bound=-65
    outer_grid_tstep=48
  fi
fi

echo "export STORM_HEM=${storm_hem}"   >>${setvarfile}

export TITLE="`echo $STORMENV $DATEIN $HRIN BOGUS FCST $FORAENV`"
cat << _EOF_ > grid.input
3
1
$WBOUND ${south_bound}.   <....outer domain SW corner  (45deg. west of storm rounded to 5deg)
0.5
0.5
${outer_grid_tstep}.      <......... time step of outer grid
1
2
75. 75.        <......... outer domain size in degrees
1
0
$CENLON $CENLAT   <............center mesh 2
3
1
0
11. 11.     <......... middle domain size in degrees
1
1
0
$CENLON $CENLAT   <.........center mesh 3
2
1
0
5. 5.     <......... inner domain size in degrees
1
1
$TITLE            <........frame title
$TITLE            <........exp. name
_EOF_

export pgm=gfdl_setgrid
. prep_step
startmsg

ln -s -f grid.input                 fort.33
ln -s -f gridinf.${STORM}           fort.77
ln -s -f domain.${STORM}            fort.78

$EXEChur/gfdl_setgrid >> output-gridbatch.$STORM
export err=$?;err_chk

cp gridinf.${STORM} ${DATA}/.
cp domain.${STORM}  ${DATA}/.
cp ${FILE}          ${DATA}/.
cp ${FILE_s}        ${DATA}/.

if [ $SENDCOM = 'YES' ]
then
  echo "Doing NCAR Graphics stuff for setgrid...."
  cp gmeta $COMOUT/$stormenv.meta.gridconfig   
  ctrans -d ps.mono  gmeta   > psstorm
  mv psstorm   $COMOUT/$stormenv.ps.gridconfig  
else
  echo "!!! NOT DOING NCAR Graphics stuff for setgrid...."
fi

cd ${DATA}

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

export MI=`echo $DATEIN | cut -c1`

if test $FORAENV = "GDAS"
then
   export FORA="GDAS.${HRIN}"
else
   export FORA="GFS.${HRIN}"
fi

export FORA1=`echo $FORA | cut -c1`

######################################################
# Build ICDATE from DATE & DAY file
######################################################
export ICDATE="${NMO}${DAY}${Y4PREFIX}${YEARA}${HRIN}"

case $NMO in
  01) export SEASON="winter";;
  02) export SEASON="winter";;
  03) export SEASON="spring";;
  04) export SEASON="spring";;
  05) export SEASON="spring";;
  06) export SEASON="summer";;
  07) export SEASON="summer";;
  08) export SEASON="summer";;
  09) export SEASON="fall";;
  10) export SEASON="fall";;
  11) export SEASON="fall";;
  12) export SEASON="winter";;
esac

######################################################
# Ensure NAME has 12 characters
######################################################
export NAME=${MI}${DAY}${FORA1}.${STORMENV}${HRIN}
export NAME12="`echo ${NAME}topto | cut -c1-12`"

######################################################
# Create unit 7 with old h-files and name&data
######################################################
echo  0000 $NAME12 $ICDATE > header.file

cat header.file domain.${STORM} gridinf.${STORM} > header.in 

export pgm=gfdl_mkflds
. prep_step

ln -s -f header.in                      fort.7
ln -s -f $FIXhur/gfdl_height            fort.10
ln -s -f $FIXhur/gfdl_pctwat            fort.11
ln -s -f $FIXhur/gfdl_znot              fort.12
ln -s -f $FIXhur/gfdl_wetness           fort.13
ln -s -f $FIXhur/gfdl_albedo.${SEASON}  fort.14
ln -s -f fcst000gaus                    fort.20
ln -s -f datatop                        fort.40

if [ ${PARAFLAG} = 'YES' ]
then
  if [ ${RUN_FROM_SPECTRAL} = 'YES' ]; then
    startmsg
    $EXEChur/gfdl_mkflds >> $pgmout 2>errfile
    export err=$?;err_chk
  else
    cp ${COMIN}/${ATCFNAME}.datatop datatop
  fi
else
  startmsg
  $EXEChur/gfdl_mkflds >> $pgmout 2>errfile
  export err=$?;err_chk
fi

set +x
echo " "
echo "TIMING: date before cnvanl hour 000 is `date`"
echo " "
set -x

$EXhur/gfdl_pre_atmos_cnvanl.sh 000

set +x
echo " "
echo "TIMING: date after  cnvanl hour 000 is `date`"
echo " "
set -x

set +x
echo " "
echo " *******************************************************"
echo "  Back in exgfdl_pre_atmos.sh.sms, just before ckbound...."
echo " *******************************************************"
echo " "
set -x


#######################################
# Do Bounds Check for datahis
#######################################

cp fcst000 datahis

export pgm=gfdl_ckbound
. prep_step

ln -s -f datahis                 fort.8
ln -s -f max_mins                fort.9

startmsg
$EXEChur/gfdl_ckbound > ckbound.out
export err=$?;err_chk

cat max_mins
ERRORS="`grep BOUNDS ckbound.out | wc -l`"
if test $ERRORS -gt 1
then
  echo "!!! BOUNDS ERROR DETECTED IN ckbound PROGRAM, EXITING...."
  export err=3
  err_exit
fi

if test "$SENDCOM" = 'YES'
then
   cp fcst000.nobogus $COMOUT/$ATCFNAME.fcst000.nobogus
###   cp datalat $COMOUT/$ATCFNAME.datalat
   cp datatop $COMOUT/$ATCFNAME.datatop
   cp datahis $COMOUT/$ATCFNAME.hour0.lgi20
fi

if [ ${PARAFLAG} = 'YES' ]
then
  if [ ${STOP_AFTER_NOBOGUS} = 'YES' ]
  then
    set +x
    echo " "
    echo "+++ AT USER REQUEST, STOPPING AFTER CREATING AND BOUNDS-"
    echo "+++ CHECKING DATALAT AND FCST000.NOBOGUS...."
    echo " "
    set -x
    ${EXhur}/tar_t254_para_gfdl_to_hsm.sh ${PDY}${cyc} ${ATCFNAME} ${COMIN} nobogus
    exit 75
  else
    if [ ${ALREADY_HAVE_DATALAT} = 'YES' ]
    then

#     We already have datalat, so the PRE_LATS job is not being run.
#     However, the ocean pre-processing may be running along side 
#     this PRE_ATMOS job, so we need to check for the existence of 
#     the ocean files before moving on.

      set +x
      echo "TIMING: pre_atmos done, starting to wait for ocean at `date`"
      set -x

      ocean_status_file=ocean_status.${ATCFNAME}.${PDY}${cyc}

      # Loop & sleep for 20 minutes, or until the ocean pre-processing
      # job finishes, whichever comes first.... 

      ocean_done=NO
      waitflag=WAIT
      ict=1
      while [ $ict -lt 61 -a ${waitflag} = 'WAIT' ]
      do
        
        if [ -s ${COMOUT}/${ocean_status_file} -a ${ocean_done} = 'NO' ]
        then
          ocean_done=YES
          set +x
          echo " "
          echo "+++ Ocean Pre available at `date`"
          set -x
        fi
          
        if [ ${ocean_done} = 'YES' ]
        then
          waitflag=DONE
          set +x
          echo "+++ Pre_Ocean job is done at `date`"
          set -x
        else
          let iwaittime=ict*20
          set +x
          echo " "
          echo "!!! Ocean Pre is NOT done yet, sleeping 20 seconds "
          echo "!!! at `date`."
          echo "!!! Total wait time for ocean so far is ${iwaittime} seconds...."
          echo "!!! ocean_done flag = ${ocean_done}"
          set -x
          sleep 20
          let ict=ict+1
        fi
        
      done

      if [ ${waitflag} = 'WAIT' ]
      then
        # Ocean pre-processing must have gotten hung up somehow.  
        # We can just bag the coupling and run uncoupled.
        if [ ${ocean_done} = 'NO' ]
        then
          set +x
          echo " "
          echo "!!! ERROR: Ocean Pre NOT done yet -- CANNOT WAIT ANY LONGER -- "
          echo "!!! We will run uncoupled.  Time: `date`"
          echo " "
          set -x
          echo 0 > ${ocean_status_file}
          cp ${ocean_status_file} ${COMOUT}/.
        fi
      fi

    fi

  fi
fi

if [ ${PARAFLAG} = 'YES' ]
then
  echo 1 > ${COMIN}/atmos_status.${ATCFNAME}.${PDY}${cyc}
fi
