#!/bin/ksh
#############################################################
# Run GFDL EARLYPOST script
#############################################################
cd $DATA

set -x
export PS4='$SECONDS + '

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

if test -f "$label" = "No $stormlabel"
then
   ##############################################
   # Condition if no storms are to be run
   ##############################################
   msg="No hurricane to run."
   postmsg "$jlogfile" "$msg"

   exit
fi

if test -f ${COMIN}/${stormlabel}.holdvars.txt
then
   . ${COMIN}/${stormlabel}.holdvars.txt
else
   msg="Hurricane to Run But No ${stormlabel}.holdvars.txt file found."
   postmsg "$jlogfile" "$msg"
   export pgm=exgfdl_post.sh.sms
   export err=911;err_chk
fi

set +x
date
echo "Sleep for 5 minutes to allow time for the forecast model"
echo "to start.  No processing time will be lost by doing this."
date
set -x
sleep 300
######################################################################
# fcstofile is the fortran output file from the hurricane model
# $FCSTDATA will be the tmpnwprd directory that the 
#           hurricane model is running in.
######################################################################
fcstofile=`ls $FCSTDATA/OUTPUT.*`
if [ "${fcstofile}ZZ" = "ZZ" ] ; then
  err_exit "NO STDOUT FROM HURRICANE FORECAST.  CHECK IF FORECAST IS RUNNING"
fi

loopflag='y'
statsflag='n'
ict=1

while [ $loopflag = 'y' -a $ict -lt 180 ]
do

  if [ -f $fcstofile ]
  then

    stopcheck=` cut -c1-200 $fcstofile | egrep "INTEGRATION STOPPED|HELD FROM MOVING|MPI_ABORT" | wc -l`

    awk '{
     if (substr($0,6,1) ~ /\./ && substr($0,16,1) ~ /\./ ) {print $0}
    }' $fcstofile >tempstats

    numhours=` cat tempstats | wc -l`

    #if [ $numhours -gt 79 ]

    if [ $numhours -gt 84 -a $stopcheck -eq 0 ]
    then

      # Make sure that the swath binary file has been flushed.
      # Check the size of it:

      swathsize=` ls -l ${FCSTDATA}/datakhwnd | awk '{print $5}'`

#      if [ $swathsize -ge 3611712 ]
#      if [ $swathsize -ge 12615408 ]
#      then

      echo "78" >ihours
      loopflag='n'
      statsflag='y'

#      else
#        set +x
#        echo "swath file not big enough yet"
#        set -x
#        let ict=ict+1
#        sleep 30
#      fi

    else

      if [ $stopcheck -gt 0 ]
      then

        if [ ! -f ${FCSTDATA}/datakhwnd ]
        then
          loopflag='n' 
          statsflag='n'
          echo "The FCST job has finished and cleaned up the FCST directory."
          echo "The regular POST job will run now."
          echo "There is no need to run the early_post at this point."
          exit 0
        else
          swathsize=` ls -l ${FCSTDATA}/datakhwnd | awk '{print $5}'`
          let testsize=numhours*87074
          #let testsize=numhours*148261
          if [ $swathsize -ge $testsize ]
          then
            let ih=numhours-2
            echo "$ih" >ihours
            loopflag='n'
            statsflag='y'
          else
            set +x
            echo "swath file not big enough yet"
            set -x
            let ict=ict+1
            sleep 30
          fi
        fi

      else

        let ict=ict+1
        sleep 30

      fi

    fi

  else

    loopflag='n' 
    statsflag='n'

  fi

done

if [ $statsflag = 'y' ]
then

#####################################################################
# Create the wind swath postscript file.  First, if the number
# of hours that the model integrated to is less than 0, then 
# set it equal to 1.
#####################################################################
   #ih_check=` cat ihours | wc -l`
   #if [ ${ih_check} -lt 0 ]
   #then
   #  echo "  1" >tmphrs
   #  mv tmphrs ihours
   #fi

   if [ -s ihours ] 
   then
      if [ `cat ihours` -eq 0 ]
      then
        echo "  1" >tmphrs
        mv tmphrs ihours
      fi
   else
      echo "  1" >tmphrs
      mv tmphrs ihours
   fi


   echo $NMO       > nmo
   echo $HRIN      > hrin
   echo $DAY       > day
   echo $STORMENV  > stormenv
   echo ${Y4PREFIX}$YEARA   > yeara

   cp ${COMIN}/coupled_status.${ATCFNAME}.${PDY}${cyc} .
   cp ${FCSTDATA}/datakhwnd swath.ieee

   export pgm=gfdl_swathps
   . prep_step

   ln -s -f coupled_status.${ATCFNAME}.${PDY}${cyc}  fort.2
   ln -s -f swath.ieee              fort.9
   ln -s -f ihours                  fort.78
   ln -s -f nmo                     fort.31
   ln -s -f hrin                    fort.32
   ln -s -f day                     fort.33
   ln -s -f stormenv                fort.34
   ln -s -f yeara                   fort.35

   startmsg
   $EXEChur/gfdl_swathps >> $pgmout 2>errfile
   export err=$?;err_chk

##################################################################### 
# The generated meta file and postscript version will be stored in
# /com region for NHC to ftp to their site.....>
#####################################################################
   
   if test $SENDCOM = 'YES'
   then
     cp gmeta $COMOUT/$stormenv.${YMDH}.swath78.meta
     cp gmeta gmeta.wind
     ctrans -d ps.mono  gmeta   > psstorm
     mv psstorm $COMOUT/$stormenv.${YMDH}.swath78.ps
   fi
#####################################################################
# Now create new stats file
#####################################################################

   echo "                                             "   >stats.early
   echo "${STORMENV} GFDL FORECAST FROM ${YMDH}       "  >>stats.early
   echo "                                             "  >>stats.early
   echo "QUICK LOOK TRACK & INTENSITY STATS           "  >>stats.early
   echo "                                             "  >>stats.early
   echo "FORECAST POSITIONS AND INTENSITY STATS FOLLOW:" >>stats.early
   echo "                                             "    >>stats.early
   echo "HOUR     LATITUDE    LONGITUDE    MIN PRESS (hPa)     MAX SFC WIND (KTS)" >>stats.early
   echo "                                             " >>stats.early

   awk '{
     if (($1 % 6) == 0) {
     printf (" %3d       %5.2f      %7.2f         %4d                 %3d\n",int($1),$3,$2,int($6+0.5),int($4*1.944+0.5)) }
   }' tempstats >>stats.early

   if test $SENDCOM = 'YES'
   then
     cp stats.early ${COMOUT}/$stormenv.${YMDH}.stats78.tpc
   fi

   if test $SENDHPC = 'YES'
   then
      if test $SENDDBN = 'YES'
      then
        $DBNROOT/bin/dbn_alert PRINT_GHM TXT $job \
               ${COMOUT}/$stormenv.${YMDH}.stats78.tpc
        $DBNROOT/bin/dbn_alert PRINT_GHM PS $job \
               $COMOUT/$stormenv.${YMDH}.swath78.ps

        # lpr -Plj8-44 $COMOUT/$stormenv.${YMDH}.swath78.ps
        # lpr -Plj8-44txt ${COMOUT}/$stormenv.${YMDH}.stats78.tpc

        # lpr -Php8000n $COMOUT/$stormenv.${YMDH}.swath78.ps
        # lpr -Php8000ntxt ${COMOUT}/$stormenv.${YMDH}.stats78.tpc
      fi
   fi

else

  set +x
  echo "!!! ERROR: The early stats work cannot be done."
  set -x

fi
