#!/bin/csh

# SCRIPT TO LOOP THRU MODEL TIMES AND INPUT THEM INTO SNOW RATIO NUERAL
# NETWORK
# WILL WORK FOR GFS and NAM models
#
# On The Compute Farm, the cron will start the script every 5-minutes.
#
# For NAM runs, the script will start at 1:45Z and 13:45Z and the cron will 
# start up every 5 minutes until 2:55Z and 14:55Z. When the start hour is 
# 1,2,13, or 14, the snow ratio from the NAM will be calculated.
#
# For GFS runs, the script will start at 3:40Z and 15:40Z and the cron will
# start up every 5 minutes until 4:55Z and 16:55Z. When the start hour is
# 3,4,15, or 16, the snow ratio from the GFS will be calculated.
#
# The script $OPSDIR/bailey/slr/cobb/run_cobb.scrp is called at the end of this
# script. It creates the COBB method SLR. The nextppt and run hour info needed 
# for the chkrflg call is passed to the script.
#
# log:
# 6/23/08	Added C06I and P06I to output file and multiply S06I by WXTS
#                  C06I = Model P06I*ClimoSLR*WXTS
#                  P06I = Model P06I*SLRA*WXTS
#                  S06I = Model P06I*SLR*WXTS
# 6/24/09       Changes SLR of 10 to 11 in SLRA computation
# 10/25/11	Switch to RHEL5
# 7/27/12	Use nam32 instead of nam40
# 4/2/14	put nam and gfs into seperate directories
# 4/11/14	add grib2 conversion for AWIPSII Migration
# 8/28/14	change ssh call to gc to ssgc
 
cd $HOME/bailey/slr/offhr/

set fullddate = "`date -u +%Y%m%d`"
set ddate = `echo $fullddate | cut -c3-8`
set month = "`date -u +%m`"
set day = "`date -u +%d`"

set xday = `expr ${day} + 0`

set yfullddate = `yesterday`

set workdir = `pwd`
set starttime = `date`

set starthour = "`date -u +%k`"

if ( "."${1} != "." ) then
 set lookhour = ${1}
 if( .${1} != ".00" && .${1} != ".06" && .${1} != ".12" && .${1} != ".18") then
   echo "Need to Select Model Run Hour"
   echo " "
   echo "               EX:       run_network.com {hh} {model}"
   exit
 endif
 if("."${2} != ".") then 
   set mdl = ${2}
 else
   echo "SELECT MODEL (gfs or nam)"
   echo "               EX:       run_network.com {hh} {model}"
   exit
 endif
 if (${mdl} == "nam") set mdl = "nam32"
 set runhour = ${lookhour}
 goto run
else
 set lookhour = "25"
 if (${starthour} == 19 || ${starthour} == 20 || ${starthour} == 21 || ${starthour} == 22 ) set lookhour = "18"
 if (${starthour} == 13 || ${starthour} == 14 || ${starthour} == 15 || ${starthour} == 16 ) set lookhour = "12"
 if (${starthour} == 7 || ${starthour} == 8 || ${starthour} == 9 || ${starthour} == 10 ) set lookhour = "06"
 if (${starthour} == 1 || ${starthour} == 2 || ${starthour} == 3 || ${starthour} == 4 ) set lookhour = "00"

 if (${starthour} == 1 || ${starthour} == 2 ||  ${starthour} == 7 || ${starthour} == 8 || ${starthour} == 13 || ${starthour} == 14 || ${starthour} == 19 || ${starthour} == 20) then
    set mdl = "nam"
    set runhour = ${lookhour}
 else if (${starthour} == 3 || ${starthour} == 4 || ${starthour} == 9 || ${starthour} == 10 || ${starthour} == 15 || ${starthour} == 16 || ${starthour} == 21 || ${starthour} == 22 ) then
    set mdl = "gfs"
    set runhour = `expr ${lookhour} + 2`
 endif

 if ( .${lookhour} != ".00" && .${lookhour} != ".06" && .${lookhour} != ".12" && .${lookhour} != ".18" ) then
   echo "Need to Select Model Run Hour and model (gfs or nam)"
   echo "               EX:       run_network.com {hh} {model}"
   exit
 endif
 
endif

# Find Latest Model

wait:

set workdir = "$HOME/bailey/slr/offhr/${mdl}"

if (${mdl} == "nam") set mdl = "nam32"

cd $MODEL/${mdl}/

set lastfile = `ls -1 | tail -1`

if (${mdl} == "gfs") then
    set lastfhr = `echo ${lastfile} | cut -c16-18`
    set hour = `echo ${lastfile} | cut -c13-14`
else
    set lastfhr = `echo ${lastfile} | awk -F"f" '{print $2}'`
    set hour = `echo ${lastfile} | awk -F"f" '{print $1}' | awk -F"_" '{print $2}' | cut -c9-10`
endif

set xlastfhr = `expr ${lastfhr} + 0`

if (${xlastfhr} < 84) then
    echo "Model times not available"
endif

if ($lookhour != $hour) then
#    sleep 180 
#    goto wait
    exit(0)
endif

run:

cd ${workdir}
set hour = ${lookhour}

# WRITE script flag to runflags directory

set nextppt = 0
set nextppt = `chkrflg run_network_offhr.com ${fullddate}${runhour} ${nextppt} 5`
set cstatus = $status
echo $cstatus
if ($cstatus == 0) then
set month = `echo ${fullddate} |cut -c5-6`

# Create Output file
# Use Grid 212 (Nam40) for nam32 and gfs (1x1 deg) for gfs

set cpyfil = "$MODEL/${mdl}/${mdl}_${fullddate}${hour}F000"
if (${mdl} == "nam32") set cpyfil = "#212"

rm -f temp_prcp.grd

gdcfil << EOF
GDOUTF   = temp_prcp.grd
PROJ     =
GRDAREA  = 
KXKY     =
MAXGRD   = 200
CPYFIL   = ${cpyfil}
ANLYSS   = 4/2;2;2;2
r

exit

EOF

gpend

rm -f output.grd

gdcfil << EOF
GDOUTF   = output.grd
PROJ     = 
GRDAREA  = 
KXKY     = 
MAXGRD   = 200
CPYFIL   = ${cpyfil}
ANLYSS   = 4/2;2;2;2
r

exit

EOF

gpend

# Create a gfs grid using grid #212 for SLR to be copied to from output.grd
if (${mdl} == "gfs" ) then

gdcfil << EOF
GDOUTF  = gfs.grd
PROJ    =
KXKY    =
GRDAREA = 
CPYFIL  = #212
MAXGRD  = 1000
ANLYSS  = 4/2;2;2;2
r

exit

EOF

gpend

endif

else if ($cstatus == 10) then
exit
else if ($cstatus == 11) then
echo "Script finished"
exit
else
echo "status = else"
endif

set month = `echo ${fullddate} |cut -c5-6`
set xmonth = `expr $month + 0`

foreach fhr (003 009 015 021 027 033 039 045 051 057 063 069 075 081)

set xfhr = `expr ${fhr} + 0`

# set HPCWWD forecast hour
@ wwdfhr = ${xfhr} - 12
if (${wwdfhr} < 10) then 
    set wwdfhr = "00${wwdfhr}"
else if (${wwdfhr} >= 10 && ${wwdfhr} < 100) then
    set wwdfhr = "0${wwdfhr}"
endif

if ( .${hour} == ".00") then
    set wwdcycle = "12"
    set wwdfullddate = ${fullddate}
else if ( .${hour} == ".12") then
    set wwdcycle = "00"
    set wwdfullddate = `datetime ${ddate}/0000 24 %Y%m%d`
endif
set wwdddate = `echo ${wwdfullddate} | cut -c3-8`

# WRITE script flag information to runflags directory

set nextppt = `chkrflg run_network_offhr.com ${fullddate}${runhour} ${nextppt} 5`
if ($status == 0) then

echo ${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f${fhr}

tryagain:

if (! -e ${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f${fhr}) then
    sleep 60
    goto tryagain
endif

if (${mdl} == 'gfs' ) then

  set fhr1 = `expr ${xfhr} - 6`
  if(${fhr1} < 10) set fhr1 = "0${fhr1}"
  set gfunc = "P03M"
  set typegfunc = "WXTS03"

else

  set gfunc = "P03M"
  #if (${xfhr} == 6 || ${xfhr} == 18 || ${xfhr} == 30 || ${xfhr} == 42 || ${xfhr} == 54 || ${xfhr} == 66 || ${xfhr} == 78 ) then

   # @ fhr1 = ${xfhr} - 6
   # if(${fhr1} < 10) set fhr1 = "0${fhr1}"
   # set gfunc = "P03M"

  #else if (${xfhr} == 12 || ${xfhr} == 24 || ${xfhr} == 36 || ${xfhr} == 48 || ${xfhr} == 60 || ${xfhr} == 72 || ${xfhr} == 84 ) then

  #  @ fhr1 = ${xfhr} - 6
  #  if(${fhr1} < 10) set fhr1 = "0${fhr1}"
  #  set gfunc = "sub(P12M,P06M+2^${ddate}/${hour}00f0${fhr1})"
  #endif
  set typegfunc = "WXTS"
endif

#set oldfile = ${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f0${fhr1}
#echo $oldfile

# MOVE P06M and WXTS grids TO temp_prcp.grd

gddiag << EOF
GDFILE   = ${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f${fhr}+temp_prcp.grd
GDOUTF   = temp_prcp.grd
GFUNC    = ${gfunc}
GDATTIM  = ${ddate}/${hour}00F${fhr}
GLEVEL   = 0
GVCORD   = none
GRDNAM   = P03M^${ddate}/${hour}00F${fhr} 
GRDTYP   = S
GPACK    =  
GRDHDR   = 0/0
PROJ     = str/90;-100;0
GRDAREA  =  
KXKY     = 10;10
MAXGRD   = 200
CPYFIL   = 
ANLYSS   = 4/2;2;2;2
r

GFUNC    = ${typegfunc}
GRDNAM   = WXTS^${ddate}/${hour}00F${fhr}
r

exit

EOF

set modelfile = "${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f${fhr}"

# Copy NAM32 grid to 40-km grid file (grid 212)

if ( ${mdl} == "nam32" ) then

foreach level ( 1000 975 950 925 900 875 850 825 800 775 750 725 700 675 650 625 600 575 550 525 500 475 450 425 400 375 350 325 300 275 250 225 200 175 150 125 100)

gddiag << EOF
GDFILE   = ${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f${fhr}
GDOUTF   = nam40_${fullddate}${hour}f${fhr}
GFUNC    = TMPK
GDATTIM  = ${ddate}/${hour}00F${fhr}
GLEVEL   = $level
GVCORD   = PRES
GRDNAM   =
GRDTYP   = S
GPACK    =
GRDHDR   =
PROJ     = MER
GRDAREA  =
KXKY     = 10;10
MAXGRD   = 200
CPYFIL   = #212
ANLYSS   = 4/2;2;2;2
r

GFUNC    = RELH
r

GFUNC    = OMEG
r

exit
EOF

end # level

# Copy 2m temp, relh, 10m urel, vrel, and surface pressure
gddiag << EOF
GDFILE   = ${MODEL}/${mdl}/${mdl}_${fullddate}${hour}f${fhr}
GDOUTF   = nam40_${fullddate}${hour}f${fhr}
GFUNC    = TMPK
GLEVEL   = 2
GVCORD   = HGHT
r

GFUNC    = RELH
r

GFUNC    = OMEG
r

GFUNC    = PRES
GLEVEL   = 0
GVCORD   = NONE
r

GFUNC    = P03M
r

GFUNC    = P06M
r

GFUNC    = P09M
r

GFUNC    = P12M
r

GFUNC    = UREL
GLEVEL   = 10
GVCORD   = HGHT
r

GFUNC    = VREL
r
exit
EOF

set modelfile = "nam40_${fullddate}${hour}f${fhr}"

endif

echo ${modelfile} ${ddate}/${hour}00F${fhr} ${month} ${mdl}
${HOME}/bailey/slr/${NA_OS}/myprogram ${modelfile} ${ddate}/${hour}00F${fhr} 1 ${month} ${mdl}

# Set season for snowratio climo
if (${xmonth} > 3 && ${xmonth} < 8) then
  set season = "spring"
else if (${xmonth} >= 8 && ${xmonth} < 12) then
  set season = "fall"
else if (${xmonth} == 12) then
  if (${xday} > 20) then
    set season = "winter"
  else
    set season = "fall"
  endif
else if ( ${xmonth} == 3) then
  if (${xday} > 20) then
    set season = "spring"
  else
    set season = "winter"
  endif
else
  set season = "winter"
endif

# AVERAGE SLR WITH CLIMO and SLR of 11
# add ClimoSLR (SNOWR) to SLR10, add SLR
gddiag << EOF
GDFILE   = ${OPSDIR}/ops/grids/snowratio_${season}.grd
GDOUTF   = output.grd
GFUNC    = add(SNOWR,11)
GDATTIM  = 000101/0000
GLEVEL   = 0
GVCORD   = NONE
GRDNAM   = SLRA^${ddate}/${hour}00F${fhr}
GRDTYP   = S
GPACK    = grib
GRDHDR   = 0/0
PROJ     =
GRDAREA  =
KXKY     =
MAXGRD   = 200
CPYFIL   = #212
ANLYSS   = 4/2;2;2;2
r

GDFILE   = output.grd
GFUNC    = add(SLR,SLRA)
GDATTIM  = ${ddate}/${hour}00F${fhr}
GRDNAM   = SLRA^${ddate}/${hour}00F${fhr}
r

! Copy climoSLR to output.grd as C03I
GDFILE   = ${OPSDIR}/ops/grids/snowratio_${season}.grd
GDOUTF   = output.grd
GFUNC    = SNOWR
GDATTIM  = 000101/0000
GLEVEL   = 0
GVCORD   = NONE
GRDNAM   = C03I^${ddate}/${hour}00F${fhr}
r

exit
EOF

if (${mdl} == "gfs") then

gddiag << EOF
GDFILE   = output.grd
GDOUTF   = gfs.grd
GFUNC    = S03I
GDATTIM  = ${ddate}/${hour}00F${fhr}
GLEVEL   = 0
GVCORD   = none
GRDNAM   = 
GRDTYP   = S
GPACK    = grib
GRDHDR   = 0/0
PROJ     = 
GRDAREA  = 
KXKY     = 
MAXGRD   = 200
CPYFIL   = #212
ANLYSS   = 4/2;2;2;2
r

GFUNC    = hprb
r

GFUNC    = mprb
r

GFUNC    = lprb
r

GFUNC    = slr
r

! Add NAM SLR to Average for GFS MODEL
GDFILE   = output.grd+$MODEL/slr/slr_roebnam_${fullddate}${hour}
GFUNC    = quo(add(SLRA,SLR+2),4)
GDATTIM  = ${ddate}/${hour}00F${fhr}
GRDNAM   = SLRA^${ddate}/${hour}00F${fhr}
r

GDFILE   = output.grd
GFUNC    = C03I
GDATTIM  = ${ddate}/${hour}00F${fhr}
GRDNAM   = C03I^${ddate}/${hour}00F${fhr}
r

exit

EOF

set outfile = "gfs.grd"

else

set outfile = "output.grd"

# Compute average from sum of NAMSLR, 11, climoSLR
gddiag << EOF
GDFILE   = output.grd
GDOUTF   = output.grd
GFUNC    = quo(SLRA,3)
GDATTIM  = ${ddate}/${hour}00F${fhr}
GRDNAM   = SLRA^${ddate}/${hour}00F${fhr}
r

exit
EOF

endif

# Compute P03I with the averageSLR and WXTS

gddiag << EOF
GDFILE   = ${outfile}+temp_prcp.grd
GDOUTF   = ${outfile}
GFUNC    = mul(mul(SLRA,P03I+2),WXTS+2)
GDATTIM  = ${ddate}/${hour}00F${fhr}
GRDNAM   = P03I^${ddate}/${hour}00F${fhr}
r

! Multiple S03I by WXTS
GFUNC    = mul(S03I,WXTS+2)
GRDNAM   = S03I^${ddate}/${hour}00F${fhr}
r

! Calculate C03I with ClimoSLR and WXTS
GDFILE   = ${outfile}+temp_prcp.grd
GFUNC    = mul(mul(C03I,WXTS+2),P03I+2)
GRDNAM   = C03I^${ddate}/${hour}00F${fhr}
r

exit
EOF


# Create Snow Density GRIB2 files, Only do if fhr > 12 (wwdfhr > 0)
if ( ${xfhr} > 12 ) then

# Create grib message for forecast hour
gddiag << EOF
GDFILE   = ${outfile}
GDOUTF   = ndfd_tmp.grd
GFUNC    = quo(1000,SLR)
GDATTIM  = ${ddate}/${hour}00F${fhr}
GLEVEL   = 0
GVCORD   = none
GRDNAM   = snoden^${wwdddate}/${wwdcycle}00F${wwdfhr}
GRDTYP   = S
GPACK    = NONE
GRDHDR   =
PROJ     = LCC/25.0;-95.0;25.0
GRDAREA  = 20.192;-121.554;50.1055;-60.8856
KXKY     = 2145;1377
CPYFIL   = #1
MAXGRD   = 64
ANLYSS   = 1/2;2;2;2
r

ex
EOF

#  Create the snow density GRIB file:

cat << EOF > wmo.tbl
000 001 061 000 Snow Density                     kg m**-3             SNODEN           0  -9999.00
000 001 050 008 Snow Precipitation X Roeb SLR    kg m**-2             S--M             0  -9999.00
000 001 008 008 Snow Precipitation X SLRA        kg m**-2             P--M             0  -9999.00
000 001 010 008 Snow Precipitation X ClimoSLR    kg m**-2             C--M             0  -9999.00
EOF

if (${mdl} == "gfs") then
    set procid = "132"
else
    set procid = "134"
endif

gdgrib2 << EOF
GDFILE   = ndfd_tmp.grd
GFUNC    = SNODEN
GDATTIM  = ${wwdddate}/${wwdcycle}00F${wwdfhr}
GLEVEL   = 0
GVCORD   = none
GBFILE   = 2.5km_${mdl}_snoden_${wwdfullddate}${wwdcycle}f${wwdfhr}.grb
CPYFIL   =
G2TBLS   = wmo.tbl
G2IS     =
G2IDS    = 7;5
G2PDT    = 0|;;2;0;${procid};255;
G2DRT    = 40|0|0
WMOHDR   =
r

ex
EOF

#$DBNALERT DATA SEND_TO_HPCN_GRIB job 2.5km_${mdl}_snoden_${wwdfullddate}${wwdcycle}f${wwdfhr}.grb

endif

# Create GRIB2 Files for awips2
if (${mdl} == "gfs") then
    set procid = "14"
else
    set procid = "19"
endif

! Converted SLR to Snow Density
gdgrib2 << EOF
GDFILE   = ${outfile}
GFUNC    = SNODEN
GDATTIM  = ${ddate}/${hour}00F${fhr}
GLEVEL   = 0
GVCORD   = none
GBFILE   = ${mdl}_slr_roeb_${fullddate}${hour}f${fhr}.grb
CPYFIL   =
G2TBLS   = wmo.tbl
G2IS     =
G2IDS    = 7;5
G2PDT    = 0|;;2;0;${procid};255;
G2DRT    = 40|0|0
WMOHDR   =
r

GFUNC    = S03M
G2PDT    = 8|;;2;0;${procid};255;;;;;;;;-1;-1;;;;;;;;0;1;;;;1;0
G2DRT    = 40|0|-3
r

GFUNC    = P03M
r

GFUNC    = C03M
r

ex

EOF

else if ($status == 10) then
exit
endif

end

set nextppt = `chkrflg run_network_offhr.com ${fullddate}${runhour} ${nextppt} 5`
if ($status == 0) then

if (${mdl} == "nam32") set mdl = "nam"

cp output.grd roeb${mdl}_${fullddate}${hour}

if (${mdl} == "gfs") then
  mv gfs.grd roeb${mdl}_${fullddate}${hour}
endif

mv roeb${mdl}_${fullddate}${hour} ../slr_roeb${mdl}_${fullddate}${hour}

# Write flag indicating that the off hours are done for other script.
echo ${fullddate}${hour} > ../.offflag_${mdl}

setenv DBNROOT /dbnet/dbnet_ops
/dbnet/dbnet_ops/bin/dbn_alert MODEL SLR_GEMPAK sending_to_ncosrv ${workdir}/slr_roeb${mdl}_${fullddate}${hour} 
$DBNALERT MODEL SLR_GEMPAK sending_to_ncosrv ${workdir}/slr_roeb${mdl}_${fullddate}${hour}

rm -f ../slr_roeb${mdl}_${yfullddate}${hour}

set endtime = `date`

echo ${starttime}
echo ${endtime}

else if ($status == 10) then
exit
endif

# Copy grib files to ftp server
scp 2.5km_*.grb hpc@${RZDM}:~/www/htdocs/wwd/internal/grib2/
# clean up
if (${mdl} == "nam") then
    ssgc hpc@${RZDM} www/htdocs/wwd/internal/grib2 2.5km_${mdl}32_snoden_YYYYMMDDHHfFFF.grb 3 r
else
    ssgc hpc@${RZDM} www/htdocs/wwd/internal/grib2 2.5km_${mdl}_snoden_YYYYMMDDHHfFFF.grb 3 r
endif

rm -f *.grb

set nextppt = `chkrflg run_network_offhr.com ${fullddate}${runhour} ${nextppt} 5 D`

# Remove temp file
rm -f temp_prcp.grd
rm -f ndfd_tmp.grd
rm -f nam40_*

exit

