#!/usr/bin/ksh

set +x
#####################################################################
echo "-------------------------------------------------------"
echo "exgfdl_post.sh.sms - Script to run GFDL post-processing"
echo "-------------------------------------------------------"
echo "History: JUN 1997 - First implementation of this new script."
echo "         JAN 1998 - Rewritten by David Michaud to standardize"
echo "         AUG 1998 - Modified by Peter Henrichsen to use script"
echo "                    onebul.sh to make and send storm bulletin."
echo "         NOV 2000 - Modified by Peter Henrichsen to replace "
echo "                    onebul.sh with formbul.pl."
echo "         MAR 2001 - Tim Marchok added save of stats.short file"
echo "                    to STOREhur directory, plus coupled plots"
echo "         JAN 2006 - L. Sager  Modified to use form_ntc.pl to  "
echo "                    send bulletins to TOC via NTC         "
#####################################################################
set -x

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

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

export datein=`echo $DATEIN | tr [A-Z] [a-z]`
export DTEE=$YYMMDD$HRIN

cd $DATA

######################################################################
# Do post processing, including making all grib files and 
# atcfunix files.
######################################################################

#--------------------------------------------------------------------#
# Determine script variables from ENVIRONMENTAL VARS....
#--------------------------------------------------------------------#

DATE=$YYMMDD$HRIN
case $HRIN in
  00) hoo="06"
      DATO=$YYMMDD$hoo;;
  06) hoo="12"
      DATO=$YYMMDD$hoo;;
  12) hoo="18"
      DATO=$YYMMDD$hoo;;
  18) hoo="00"
      YYMMDDp1=`sh /nwprod/util/ush/finddate.sh $Y4PREFIX$YYMMDD d+01 | cut -c3-8`
      DATO=$YYMMDDp1$hoo;;
   *):;;
esac

ATCF=`echo $ATCFNAME | cut -c1-4`
ATCC=`echo $ATCFNAME | cut -c1-4`$YEARA
AT=`echo $ATCFNAME | cut -c1-2`
NO=`echo $ATCFNAME | cut -c3-4`

if [ ${NUMLEVS} -eq 18 ]
then
  MODEL='63GFDL'
  MODEO='64GFDO'
else
  MODEL='63GFDL'
  MODEO='66GF2O'
fi

case $AT in
   AL)
     SLFM=${NO}L
     ;;
   EP)
     SLFM=${NO}E
     ;;
   CP)
     SLFM=${NO}C
     ;;
   WP)
     SLFM=${NO}W
     ;;
   *)
     echo  ATCF file name in error
     exit
     ;;
esac

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

echo $SLFM  > slfm
echo $MODEL > model
echo $ATCC  > atcc
echo $DATE  > date
echo $MODEO > modeo
echo $DATO  > dato

rm fort.*

export pgm=gfdl_atcfcst
. prep_step

ln -s -f $COMIN/$ATCFNAME.integrals                  fort.15
ln -s -f slfm                                        fort.41
ln -s -f model                                       fort.42
ln -s -f atcc                                        fort.43
ln -s -f date                                        fort.44
ln -s -f modeo                                       fort.45
ln -s -f dato                                        fort.46
ln -s -f atcff-$STORMENV-$DATEIN-$HRIN-text.s2       fort.57
ln -s -f atcff-$STORMENV-$DATEIN-$hoo-text.s2        fort.58

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

rm slfm model atcc date modeo dato

if test $SENDCOM = 'YES'
then
  cp atcff-$STORMENV-$DATEIN-$HRIN-text.s2 $COMOUT/$stormenv.${YMDH}.atcf
  cp atcff-$STORMENV-$DATEIN-$hoo-text.s2  $COMOUT/$stormenv.${YMDH}.atcf.offset
fi

##########################################################################
# Make Grib Fields and Store in /com directory
#########################################################################
if [ -s mkgrib1deg.cmdfile ]
then
   rm mkgrib1deg.cmdfile
fi
 
cp $COMIN/mess-$stormenv-$datein-$HRIN mess-$stormenv-$datein-$HRIN

if [ ${FCST5DAY} = 'YES' ]
then
  for HOUR in 0 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96 102 108 114 120 126
  do
    echo "$EXhur/gfdl_post_mkgrib.sh $HOUR" >> mkgrib1deg.cmdfile
  done
else
  for HOUR in 0 6 12 18 24 30 36 42 48 54 60 66 72 78
  do
    echo "$EXhur/gfdl_post_mkgrib.sh $HOUR" >> mkgrib1deg.cmdfile
  done
  for dum in 15 16 17 18 19 20 21 22
  do
    echo "echo Null action (echo) for processor ${dum} since only 3 day forecast" >>mkgrib1deg.cmdfile
  done
fi

export MP_PGMMODEL=mpmd
export MP_CMDFILE=mkgrib1deg.cmdfile
export MP_LABELIO=YES
export MP_INFOLEVEL=3
export MP_STDOUTMODE=ordered

poe

#########################################################################
# Make the AFOS file and copy it to /com space.
# Bring in the NHC vitals file for the initial position:
########################################################################
cp $FIXhur/gfdl_fildef.afos fildef.afos

cp ${COMIN}/$stormenv.${YMDH}.stats.short .
cp ${COMIN}/$stormenv.${YMDH}.stats.complete .
cp ${COMIN}/coupled_status.${ATCFNAME}.${PDY}${cyc} .

export pgm=gfdl_afos
. prep_step

ln -s -f coupled_status.${ATCFNAME}.${PDY}${cyc}  fort.2
ln -s -f $COMIN/${ATCFNAME}.vitals.$YYMMDD$cyc    fort.11
ln -s -f $stormenv.${YMDH}.stats.short            fort.12
ln -s -f $stormenv.${YMDH}.afos                   fort.51

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

rm fort.11 fort.12

########################################################################
# Run awk code on the stats.complete file to determine how long
# the forecast ran coupled.  The key is the 7th element in the 
# line, which is also currently the last element in the line.  That 
# element indicates the average cooling of the SST's within a certain 
# radius of the storm center.  If that number is exactly zero, then 
# that indicates that the forecast is no longer running coupled.
# A message is output indicating the length of time that the model
# ran coupled, and this message will be appended to the bottom of
# the stats.tpc message file.
########################################################################

awk '

  BEGIN { coupled_status = "complete" }
  
  {
    hourly_coupled_flag = $7
    if (hourly_coupled_flag == 0.000 || NF < 7) {
      if (previous_hour == 0) {
        printf ("    FORECAST WAS RUN UNCOUPLED....\n")  
        coupled_status = "notrequested"
      }
      else {
        coupled_status = "cutshort"
      }
      exit
    }
    else {
      previous_hour = int($1)
    }  
  }

  END {
    if (coupled_status == "complete" || coupled_status == "cutshort")
      printf ("    FORECAST RAN COUPLED TO HOUR: %d\n",previous_hour)

}' previous_hour=0 $stormenv.${YMDH}.stats.complete >coupled_lasthour.txt

########################################################################
# Reformat the stats.short file to include a header and to reformat
# the output to fit in column form in less than 73 characters across.
# We will use the top 8 lines of the header directly from the afos 
# file just created, so obviously it is vital that this stuff always
# be placed AFTER the afos program.  This reformatting was requested
# by TPC because the whole width of the stats.short was too wide for
# their printers.  Note that there are 2 awk statements.  The first 
# is to add a space between "HOUR:" and the hour value and to add a 
# space between "(KNOTS):" and the wind value, in case these values 
# exceed 100.  The second awk statement is to check to see if the
# storm dissipated and, if so, to write a message to that effect.
########################################################################

sed -n 1,8p $stormenv.${YMDH}.afos >newstats
echo "FORECAST POSITIONS (FROM STATS.SHORT FILE...)" >>newstats
echo "                                             " >>newstats
echo "HOUR     LATITUDE    LONGITUDE    MIN PRESS (hPa)     MAX SFC WIND (KTS)" >>newstats
echo "                                             " >>newstats

awk '{ printf ("%s %s %s\n",substr($0,1,5),substr($0,6,84),substr($0,90))}' $stormenv.${YMDH}.stats.short >tmpstats

awk '{
  dissip_flag = $2
  if (dissip_flag < 0) {
    if (oldhr > 0) {
      printf ("    STORM DISSIPATED AT %d HOURS AT ABOVE POSITION....\n",oldhr) }
    else {
      printf ("    STORM DISSIPATED BEFORE 6 HOURS....\n") }
    }
  else {
    oldhr = int($2)
    printf (" %3d       %5.2f      %7.2f         %4d                 %3d\n",int($2),$6,$4,int($10+0.5),int($15+0.5))  }
}' tmpstats >>newstats

cat coupled_lasthour.txt          >>newstats
cat ${FIXhur}/gfdl_disclaimer.txt >>newstats

if test $SENDCOM = 'YES'
then
  cp newstats $stormenv.${YMDH}.stats.tpc
fi

########################################################################
# Copy the afos file back to the com location
# Copy bulletin to /com directory
# Copy the modified TPC stats file to the com location
########################################################################
cp $stormenv.${YMDH}.afos $stormenv.${YMDH}.afos.nodisc

sed -n 1,7p   $stormenv.${YMDH}.afos >$stormenv.${YMDH}.afostemp.part1
sed -n 8,"$"p $stormenv.${YMDH}.afos >$stormenv.${YMDH}.afostemp.part2
cat $stormenv.${YMDH}.afostemp.part1 \
    ${FIXhur}/gfdl_disclaimer.txt    \
    $stormenv.${YMDH}.afostemp.part2 >$stormenv.${YMDH}.afos

if test $SENDCOM = 'YES'
then
   cp $stormenv.${YMDH}.afos $COMOUT/$stormenv.${YMDH}.afos
   cp $stormenv.${YMDH}.afos $COMOUT/whxx04.$cycle.$stormenv
   cp $stormenv.${YMDH}.stats.tpc $COMOUT/$stormenv.${YMDH}.stats.tpc
fi

if test $SENDDBN = 'YES'
then
   $DBNROOT/bin/dbn_alert MODEL GFDL_AFOS $job $COMOUT/$stormenv.${YMDH}.afos
   $DBNROOT/bin/dbn_alert MODEL GFDL_STATS $job $COMOUT/$stormenv.${YMDH}.stats.tpc
fi


#########################################################################
# Now create the unix atcf output file.  This is new in 2000.  Unlike the
# old atcf format, in which all the information for the whole forecast 
# was included on one line, in this format there is a separate line for
# each forecast hour.  In this way, we can write output for as many 
# forecast hours as we like (the old atcf format was limited to reporting
# only the 12, 24, 36, 48 and 72h positions.  Just reformat the stats.short 
# file into what we need.  For each record, we also need to know the basin, 
# basin storm number and input YMDH.
#########################################################################

if [ ${PARAFLAG} = 'YES' ]
then
  if [ $BULK -gt 0 ]
  then
    if [ ${GRID_CONFIG} = 'equatorward' ]
    then
      gfdlname=GFDM
    else
      gfdlname=GFDM
    fi
  else
    if [ ${GRID_CONFIG} = 'equatorward' ]
    then
      gfdlname=GFDM
    else
      gfdlname=GFDM
    fi
  fi
else
  gfdlname=GFDL
fi

awk '{ printf ("%s %s %s\n",substr($0,1,5),substr($0,6,84),substr($0,90))}' $stormenv.${YMDH}.stats.short >tmpstats

awk '{
  dissip_flag = $2
  if (dissip_flag >= 0) {
    fcsthour = int($2)
    if (fcsthour % 6 == 0) {
      if ($4 < 0) {
        ilon = int($4 * -10 + 0.5)
        lonew = "W"
      }
      else {
        ilon = int($4 *  10 + 0.5)
        lonew = "E"
      }
      if ($6 < 0) {
        jlat = int($6 * -10 + 0.5)
        latns = "S"
      }
      else {
        jlat = int($6 *  10 + 0.5)
        latns = "N"
      }
      kts  = int($15 + 0.5)
      mslp = int($10 + 0.5)
      printf ("%s, %s, %s, 03, %4s, %3d, %3d%1s, %4d%1s, %3d, %4d\n",basin,stnum,ymdh,modname,int($2),jlat,latns,ilon,lonew,kts,mslp) }
  }
}' basin=${AT} stnum=${NO} ymdh=${YMDH} modname=${gfdlname} tmpstats >atcf.unix

if [ ${PARAFLAG} = 'YES' ]; then
  cat atcf.unix >>${EXhur}/atcfunix.tpm_qpf.txt
fi

if test $SENDCOM = 'YES'
then
  cp atcf.unix $COMOUT/$stormenv.${YMDH}.atcfunix

  export ATCFdir=${ATCFdir:-/com/tpc/${envir}/atcf}

  YYYY=`echo $YMDH | cut -c1-4`
  YY=`  echo $YMDH | cut -c3-4`
  at=` echo ${AT} | tr '[A-Z]' '[a-z]'`

  if [ ! -d $ATCFdir/${at}${NO}${YYYY} ]
  then
      mkdir -p $ATCFdir/${at}${NO}${YYYY}
  fi
  cat atcf.unix >>$ATCFdir/${at}${NO}${YYYY}/ncep_a${at}${NO}${YYYY}.dat
  set +x
  echo " "
  echo "+++ Adding records to  TPC ATCFUNIX directory: $ATCFdir/${at}${NO}${YYYY}"
  echo " "
  set -x

  # Dump atcf records into the /com/hur/prod/global/ archive....

  export gltrkdir=${gltrkdir:-/com/hur/${envir}/global}
  glatuxarch=${glatuxarch:-${gltrkdir}/tracks.atcfunix.${YY}}
  cat atcf.unix >>${glatuxarch}

fi

#########################################################################
# create the storm bulletin by using form_ntc.pl
# to make and send the bulletin
#########################################################################

intext=$stormenv.${YMDH}.afos
name=whxx04
outname=whxx04.hurbul.$stormenv.$job

if [ ${SENDCOM} = 'YES' -a ${PARAFLAG} != 'YES' ]
then
  $EXbulls/form_ntc.pl -d $name -f $intext -j $job -m $model -p $COMOUT -s $SENDDBN -o $outname
  chmod 770 $COMOUT/$outname
#  chgrp tpc $COMOUT/$outname
fi


#########################################################################
# Make the meta file of the environmental field.
# This is very important:
#   As a diagnosis of how the synthesised vortex is behaving and
#   As a determination of how well it is being removed from
#   the global analysis
#########################################################################
export pgm=gfdl_plotenv
. prep_step

rm fort.78

ln -s -f $COMIN/${ATCFNAME}.fcst000.nobogus       fort.10
ln -s -f $COMIN/$ATCFNAME.rfavg.${PDY}${cyc}     fort.15
ln -s -f $COMIN/mess-$stormenv-$datein-$HRIN      fort.19

startmsg
$EXEChur/gfdl_plotenv < $COMIN/$ATCFNAME.env.fcst000 >> $pgmout 2>errfile
export err=$?;err_chk

if test $SENDCOM = 'YES'
then 
  cp gmeta $COMOUT/$stormenv.${YMDH}.fcst000.env.meta
  ctrans -d ps.mono  gmeta > psstorm
  mv psstorm $COMOUT/$stormenv.${YMDH}.fcst000.env.ps
fi

#########################################################################
# Now copy the stats.short file over into a storage directory that
# will contain all of the stats.short files.  The coupled model
# pre-processing uses the stats.short file.
#########################################################################

cp ${COMOUT}/$stormenv.${YMDH}.stats.short ${STOREhur}/${ATCFNAME}.${YMDH}.stats.short

########################################
# Print out file for SDM, then exit....
########################################

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

  echo " "

else

#  Print at sdm's desk 4th floor WWB

   if test $SENDDBN = 'YES'
   then
      $DBNROOT/bin/dbn_alert PRINT_TEXT TXT $job \
             $COMOUT/whxx04.$cycle.$stormenv
   fi

fi


#########################################################################
# Tar all the files together and exit the script
#########################################################################

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

  if [ ${AUTOSUBMIT} = 'YES' ]
  then
    set +x
    echo " "
    echo "Deleting $DATA directory"
    echo " "
    cd ${DATA}
    cd ..
    rm -rf ${DATA}
    rm ${COMIN}/${ATCFNAME}.hour6
    rm ${COMIN}/${ATCFNAME}.hour18
    rm ${COMIN}/${ATCFNAME}.hour24
    rm ${COMIN}/${ATCFNAME}.hour30
    rm ${COMIN}/${ATCFNAME}.hour36
    rm ${COMIN}/${ATCFNAME}.hour42
    rm ${COMIN}/${ATCFNAME}.hour48
    rm ${COMIN}/${ATCFNAME}.hour54
    rm ${COMIN}/${ATCFNAME}.hour60
    rm ${COMIN}/${ATCFNAME}.hour66
    rm ${COMIN}/${ATCFNAME}.hour72
    rm ${COMIN}/${ATCFNAME}.hour78
    rm ${COMIN}/${ATCFNAME}.hour84
    rm ${COMIN}/${ATCFNAME}.hour90
    rm ${COMIN}/${ATCFNAME}.hour96
    rm ${COMIN}/${ATCFNAME}.hour102
    rm ${COMIN}/${ATCFNAME}.hour108
    rm ${COMIN}/${ATCFNAME}.hour114
    rm ${COMIN}/${ATCFNAME}.hour120
    rm ${COMIN}/${ATCFNAME}.hour126
    rm ${COMIN}/${ATCFNAME}.fcst000.nobogus
    rm ${COMIN}/${ATCFNAME}.hour0.lgi20
    rm ${COMIN}/${ATCFNAME}.swath
    rm ${COMIN}/${ATCFNAME}.swathc
###    rm ${COMIN}/rst.phase3.*
###    rm ${COMIN}/*distur*
  fi

fi