#!/bin/csh -f

rm -f reanalconv.out soilconv.out

if ($#argv != 3) then
echo " "
echo "need three arguments"
echo " "
echo "starting date yymmddhh"
echo "ending date   yymmddhh"
echo "interval (e.g. 06)    "
echo " "
echo " "
exit
endif

set startd=$1
set endd=$2
set interval=$3

set yy=`echo $startd | cut -c1-2`
set mm=`echo $startd | cut -c3-4`
set dd=`echo $startd | cut -c5-6`
set hh=`echo $startd | cut -c7-8`

set ROOT=`pwd`/..
cd ../../data/grib
rm -f reanalconv.out soilconv.out
set pathname=`pwd`

while ($yy$mm$dd$hh <= $endd)

echo "start while, " $yy $mm $dd $hh

## do stuff, then increment time

set start=`pwd`
set hr=T${1}Z
set int=${3}
set endtime=${2}
set model=pgb.f00
set tval=0

cd $start 

rm -f avnconv.out
if ($tval <= 9) set tval=0${tval}

set LOGDIR=$ROOT'/log'
set filename=${model}$yy$mm$dd$hh
set GRIBFILE=${pathname}/${filename}
set OUTDIR=$ROOT'/../data/prep'

umask 000

echo " "
echo " ******************************************************"
echo " *** GRIB grid processor ***"
echo " Begin processing for "$filename

# Degrib data.

if ( -e $GRIBFILE ) then

echo " Start degrib process..."

else

echo " "
echo " ************************************************************"
echo " "
echo " "$GRIBFILE" grib file not found."
exit 0

endif

# Convert degribbed data to unformatted format for local area model use.

echo " "
echo " Start degrib to formatted data conversion process..."
echo " "
 
$ROOT/exe/dgeta2model_gbl.exe << endin
$GRIBFILE
$OUTDIR
endin
 
# Cleanup.

if ($tval <= $endtime) then
@ tval += $int
endif

# end

@ hh += $interval

if ($hh >= 24) then
# tomorrow
@ hh -= 24

if ( $mm == 1 || $mm == 01 ) set mxd = 31
if ( $mm == 2 || $mm == 02 ) then
    @ leap = $yy % 4
    if ( $leap == 0 ) set mxd = 29
    if ( $leap != 0 ) set mxd = 28
endif
if ( $mm == 3 || $mm == 03 ) set mxd = 31
if ( $mm == 4 || $mm == 04 ) set mxd = 30
if ( $mm == 5 || $mm == 05 ) set mxd = 31
if ( $mm == 6 || $mm == 06 ) set mxd = 30
if ( $mm == 7 || $mm == 07 ) set mxd = 31
if ( $mm == 8 || $mm == 08 ) set mxd = 31
if ( $mm == 9 || $mm == 09 ) set mxd = 30
if ( $mm == 10 ) set mxd = 31
if ( $mm == 11 ) set mxd = 30
if ( $mm == 12 ) set mxd = 31

@ dd = $dd + 1
if ( $dd > $mxd ) then
    @ mm = $mm + 1
    if ( $mm == 13 ) then
        @ yy = $yy + 1
        set mm = 1
    endif
    set dd = 1
endif
@ yy = $yy + 0
@ mm = $mm + 0
@ dd = $dd + 0
@ hh = $hh + 0
if ( $yy < 10 ) set yy = 0$yy
if ( $mm < 10 ) set mm = 0$mm
if ( $dd < 10 ) set dd = 0$dd
endif


@ hh = $hh + 0
if ( $hh < 10 ) set hh = 0$hh
end
exit 0
