#! /bin/ksh

set -x

function die {
    export err=9
    if [[ "$1" == -e ]] ; then
        export err=$2
        shift 2
    fi
    postmsg "$jlogfile" "$*"
    err_chk
    err_exit "$*"
}

function lat {
set -x
    num="$1"
    hemisphere="$2"
    case "$hemisphere" in
        [sS]) echo "$num" | awk '{print $1/-10.0}' ;;
        [nN]) echo "$num" | awk '{print $1/10.0}' ;;
        *) # Error: invalid hemisphere.  Assume N.Atl. or E.Pac.
            echo "$num" | awk '{print $1/10.0}' ;;
    esac
}

function lon {
set -x
    num="$1"
    hemisphere="$2"
    case "$hemisphere" in
        [wW]) echo "$num" | awk '{print $1/-10.0}' ;;
        [eE]) echo "$num" | awk '{print $1/10.0}' ;;
        *) # Error: invalid hemisphere.  Assume N.Atl. or E.Pac.
            echo "$num" | awk '{print $1/-10.0}' ;;
    esac
}

cen=$( $utilexec/ndate | cut -c1-2 ) # current century
# This script parses the vitals information 
from="$1"

if [[ "$from" == messages ]] ; then
    # We're using a message file
    storm_num="${2}"
    mesagdir="${3}"

    # If a storm number is specified then we are being asked to get the
    # vitals information from a message file
    if [[ ! -d "$mesagdir" ]] ; then
        die "Storm $storm_num requested but \$mesagdir (arg 3) not specified."
    fi

    # Copy the message file, inserting the century:
    cat $mesagdir/message$storm_num | \
        perl -ne 'print substr($_,0,19)."'$cen'".substr($_,19)' \
        > storm_vit
elif [[ "$from" == tcvitals ]] ; then
    stid_in=$( echo $2 | tr a-z A-Z )
    ymdh_in="$3"
    ymd_in=$( echo "$ymdh_in" | cut -c1-8 )
    hh_in=$( echo "$ymdh_in" | cut -c9-10 )
    cat $( $USHhwrf/hwrf_syndat_tcvitals.sh $ymdh_in '' '' ${CASE_ROOT:-} ) | \
        grep -E "^.....$stid_in ......... $ymd_in $hh_in" | tail -1 \
        > storm_vit
else
    die "Exiting script.  First argument must be \"messages\" or \"tcvitals\"."
fi

if [[ $( echo $( wc -l storm_vit ) ) == 0 ]] ; then
    die -e 2 "Exiting Script.  The storm name is not found in the message file."
fi
cp -pf storm_vit tmpvit

########################################################################
#           STORM MESSAGE FILE IS USED TO PRODUCE THIS INFORMATION:
#           THE HURRICANE MESSAGE IS READ AND THE 
#           STORMLAT & STORMLON ARE READ IN AND WRITTEN TO 
#           MESSAGES/storm.center. CENLA & CENLO ARE COMPUTED AND WRITTEN
#           TO the holdvars.txt file.  
########################################################################

echo ==================== VITALS INFORMATION ====================
cat storm_vit 
echo ============================================================

length=`cat storm_vit | awk '{print length($0)}'`
cen=$( $utilexec/ndate | cut -c1-2 ) # current century

export STORM_NAME=`cat storm_vit | awk '{print $3}'`
export snum=`cat storm_vit | cut -c6-7`
export STORMID=`cat storm_vit | cut -c6-8`
export stormid=`echo ${STORMID} | tr '[A-Z]' '[a-z]'`
export CYC=`cat storm_vit | cut -c29-30`
export YYYY=`cat storm_vit | cut -c20-23`
export MM=`cat storm_vit | cut -c24-25`
export DD=`cat storm_vit | cut -c26-27`
export YMDH=$YYYY$MM$DD$CYC
LATT=`cat storm_vit | cut -c34-36`
LATTH=`cat storm_vit | cut -c37-37`
LONT=`cat storm_vit | cut -c39-42`
LONTH=`cat storm_vit | cut -c43-43`

basin1=`echo ${stormid} | cut -c3-3`

STORM_LAT=$( lat "$LATT" "$LONTH" )
STORM_LON=$( lon "$LONT" "$LONTH" )

STORM_DEPTH=`cat storm_vit | cut -c95-95`
STORM_SIZE=`cat storm_vit | cut -c71-73`
STORM_INT=`cat storm_vit | cut -c68-69`

use_fcst72=no
STORM_LAT_F72=''
STORM_LON_F72=''

if [[ "$length" -ge 128 ]] ; then
    LATF72=`cat storm_vit | cut -c119-122`
    LATF72H=`cat storm_vit | cut -c123-123`
    if [[ "$LATF72" -ge 0 ]] ; then
        STORM_LAT_F72=$( lat "$LATF72" "$LATF72H" )
    fi

    LONF72=`cat storm_vit | cut -c125-128`
    LONF72H=`cat storm_vit | cut -c129-129`
    if [[ "$LONF72" -ge 0 ]] ; then
        STORM_LON_F72=$( lon "$LONF72" "$LONF72H" )
    fi
fi

STORM_LAT_F72=${STORM_LAT_F72:-missing}
STORM_LON_F72=${STORM_LON_F72:-missing}

if [[ "$STORM_LON_F72" != missing && "$STORM_LAT_F72" != missing ]] ; then
    use_fcst72=yes
fi

if [[ "$use_fcst72" == yes ]] ; then
    echo "Using NHC provided 72-hr forecast to determine Domain Center"
    AVERAGING_POINT=$STORM_LON_F72
else
    echo "Center domain 10deg west of storm center if no 72hr Forecast."
    AVERAGING_POINT=$( echo "$STORM_LON" | awk '{print $1-20.0}' )
fi

echo 'STORM_NAME = ' ${STORM_NAME}  
echo 'STORMID    = ' ${STORMID}
echo 'stormid    = ' ${stormid}  
echo 'CYC        = ' ${CYC} 
echo 'YYYY       = ' ${YYYY}  
echo 'MM         = ' ${MM}
echo 'DD         = ' ${DD}
echo 'LATT       = ' ${LATT} 
echo 'LONT       = ' ${LONT} 
echo 'STORM_LAT  = ' ${STORM_LAT}
echo 'STORM_LON  = ' ${STORM_LON}
echo 'STORM_LON  = ' ${STORM_LON}
echo 'use_fcst72 = ' ${use_fcst72}

echo '72h FORECAST LAT  = ' ${STORM_LAT_F72}
echo '72h FORECAST LON  = ' ${STORM_LON_F72}
STORM=`echo $STORM_NAME`
echo 'STORM      = ' $STORM

echo 'THIS IS A FORECAST'

# ----------------------------------------------------------------------
# DETERMINE NHC ATCF NAME (AL1205, EP0406, etc.)
# ----------------------------------------------------------------------

nco=''
if [[ "$PARAFLAG" != YES ]] ; then
    nco=nco
    # That will cause the Q, W, A, B, P and S basins to abort in NCO mode.
fi

basin2=''
case "$basin1" in
    [Ll]) basin2=AL ;;        # north atlantic
    [Ee]) basin2=EP ;;        # east pacific
    [Cc]) basin2=CP ;;        # central pacific
    [Ww]$nco) basin2=WP ;;    # west pacific
    [ABab]$nco) basin2=IO ;;  # indian ocean (arabian sea, bay of bengal)
    [PSps]$nco) basin2=SH ;;  # southern hemisphere (previous, current year)
    [Qq]$nco) basin2=SL ;;    # south atlantic
    *) basin2=XX              # unknown basin
        echo "WARNING: HWRF does not currently run for storms on basin $basin1  ---- exit!!! "
        return 119;
        ;;
esac

# ----------------------------------------------------------------------
# DECIDE THE STORM CENTER
# ----------------------------------------------------------------------

CENLA=$STORM_LAT
if [ $STORM_LAT -lt 15.0 ]; then
    CENLA=15.0
fi
if [ $STORM_LAT -gt 25.0 ]; then
    CENLA=25.0
fi
if [ $STORM_LAT -ge 35.0 ]; then
    CENLA=30.0
fi
if [ $STORM_LAT -ge 40.0 ]; then
    CENLA=35.0
fi
if [ $STORM_LAT -ge 44.0 ]; then
    CENLA=40.0
fi
if [ $STORM_LAT -ge 50.0 ]; then
    CENLA=45.0
fi
if [ $STORM_LAT -ge 55.0 ]; then
    CENLA=50.0
fi
echo 'MODIN=GFS CENLA = ' ${CENLA}  

# Set CENLO to the average of the storm longitude
# and predicted 72hr longitude, correctly handling
# them being on opposite sides of the date line:
CENLO=$( echo "$STORM_LON" "$AVERAGING_POINT" | awk '{ 
                 slon=$1;
                 flon=$2;
                 diff=slon-flon;
                 if(diff>360) {
                   slon=slon-360;
                 }
                 if(diff<-360) {
                   flon=flon-360;
                 }
                 result=int((10*slon + 10*flon)/2.0)/10.0
                 if(result>180) {
                   result=result-360
                 }
                 if(result<-180) {
                   result=result+360
                 }
                 print result
               }' )

SLON=`echo $STORM_LON + 5 |bc`
if [ $CENLO -gt $SLON ]; then
    echo "Center is too far east of storm.  Moving it to $SLON."
    CENLO=$SLON
fi
SLON=`echo $STORM_LON - 5 |bc`
if [ $CENLO -lt $SLON ]; then
    echo "Center is too far west of storm.  Moving it to $SLON."
    CENLO=$SLON
fi
echo 'CENLO = ' ${CENLO} 

# Produce the variables file:

export CENLA CENLO STORM YMDH ATCFID STORM_LAT STORM_LON
export STORM_SIZE STORM_INT STORM_DEPTH basin2
"$USHhwrf/hwrf_stream_parse.pl" "$PARMhwrf/hwrf_vitals.in" "$DATA/$stormlabel.vitals.in"
