#!/bin/sh

#####################################################################
# Script tpc_psurgeexceed.sh merges the results from the SLOSH model
#        and computes the height X such that Y of the storms are 
#        less than X, where Y is set to be 90% at this time
# usage: tpc_psurgeexceeed.sh <ScriptDir> <stormAdvDir> <storm>
#                            <advTime> <exceed>
#####################################################################
set -x

if [[ -z $5 ]] || [[ ! -z $6 ]]
then
  echo "usage: $0 <ScriptDir> <stormAdvDir> <storm> <advTime> <exceed>"
  exit 1
fi

ScriptDir=$1
stormAdvDir=$2
storm=$3
advTime=$4
exceed=$5

export PS4='exceed_${exceed}_T$SECONDS + '

if [ $RUN_ENVIR = "NCO" ]
then
   EXECpsurge=${EXECpsurge:-/nwprod/exec}
   SloshbsnDir=$PARMpsurge/tpc_sloshbsn
else
   SloshbsnDir=${ScriptDir}/../parm/mdl_sloshbsn
   EXECpsurge=${ScriptDir}/../exec
fi

if [ ! -d exceed_$exceed ]
then
   mkdir $DATA/exceed_$exceed
fi

cd $DATA/exceed_$exceed

/nwprod/util/ush/setup.sh

# Define the location for the SLOSH model run
## Art's new version of this script renames runDir to ansDir##
ansDir=${stormAdvDir}/ans
outDir=${stormAdvDir}/output

mkdir -p $outDir

#################################################################################
# The exceedance percent Y computes X s.t. Y% of the storms are > X
# The thresh (or percentile) percent Y computes X s.t. Y% of the storms are < X
# typically exceed=10, thresh=90=percentile
#################################################################################
thresh=$(expr 100 \- ${exceed})

# flag:
#   1 >= thresh,
#   2 <= thresh,
#   3 == thresh is 'confidence' ie % of storms less than X,
#   4 > thresh,
#   5 < thresh
### flag=3

# Basin has to have potential of >= 'potential' or no penv file is generated.
### potential=0

# skip allows one to speed up thresh by skipping frames (typically frames
# are saved every 10 min).
#skip=35
# Assuming now every 60 min.
### skip=5

# following awk script ignores first line, and first row.
bsnList=`cat ${SloshbsnDir}/ocean.txt | awk '{if (NR >= 2) {$1=""; print}}' | sed -e s#,#' '#g`

# Let us know when we start
date

tideFile=${stormAdvDir}/${storm}_${advTime}_wlevel.dat

#################################################################
# Compute "penv" files based on all basins in the run directory
#################################################################
cd ${ansDir}
/nwprod/util/ush/setup.sh
f_first=1
for bsn in $bsnList
do
  if [ -s ${ansDir}/$bsn/weight.txt ]
  then
     initHt=0.0
     if [ ${bsn} == "eoke" ]
     then
        initHt=`grep OKECHOBEE_LAKE $tideFile | cut -d',' -f2`
     fi
     cd $bsn
     /nwprod/util/ush/setup.sh
     envName=${bsn}_e${exceed}.env
     weight_file=weight.txt
     outenvFile=${outDir}/${envName}

     export pgm=tpc_psurge_penv
     . prep_step

     $EXECpsurge/tpc_psurge_penv -i ${initHt} $weight_file exceed ${thresh} ${outenvFile} >>thresh_$thresh.out
     export err=$?; ../err_chk

     if [[ $f_first -eq 1 ]]
     then
       envArg=${envName}
       bsnArg=${bsn}
       f_first=0
     else
       envArg=$envArg,${envName}
       bsnArg=$bsnArg,${bsn}
     fi
     cd ${ansDir}
  fi
done

#####
# Test if we didn't have any basins in the run directory (storm was too weak)
#####
if [[ $f_first -eq 1 ]]
then
  exit 0
fi

#####
# Merge the results together into GRIB files.
#####
year=`echo ${advTime} | cut -c 1-4`
mon=`echo ${advTime} | cut -c 5-6`
day=`echo ${advTime} | cut -c 7-8`
hour=`echo ${advTime} | cut -c 9-10`
time=${year}-${mon}-${day}T${hour}0000

cd ${outDir}

/nwprod/util/ush/setup.sh

export pgm=tpc_psurge_envmerge
. prep_step

grbindir=$SloshbsnDir
grbin=$SloshbsnDir/conus.txt
grbout1=${storm}_${advTime}_e${exceed}_1.grb

$EXECpsurge/tpc_psurge_envmerge $envArg $bsnArg $grbindir exceed $grbin ${thresh} ${time} ${grbout1} >>thresh_$thresh.out
export err=$?; err_chk

if [ $SENDCOM = YES ]
then
    cp *e10.env $COMOUT/${storm}/.
    cp $grbout1 $COMOUT/${storm}/.
fi

if [ $SENDDBN = YES ]
then
   $DBNROOT/bin/dbn_alert MODEL TPC_PSURGE_GB2 $job $COMOUT/${storm}/$grbout1
fi

cat thresh_$thresh.out >>$pgmout

echo "End of computing for thresh $thresh"

exit 0

