#! /bin/csh -f
#
# Determine if this is a leap year or not.
# Also, determine if last year was a leap year or not.

setenv O /Net/elninost/obs/TRMM-3B42/data/TRMM/Gridded/3B42_V7_daily
setenv D /Net/elninost/obs/TRMM-3B42/data/TRMM/Gridded/3B42_V7

@ yr = 2000
while ($yr <= 2015)
#################################
#### Create Year Directory
#################################
mkdir $O/$yr
cd $O/$yr
## Check for Leap year
set dcount = 365
echo "$yr / 4" >> leaptmp
echo quit >> leaptmp
set leap = `bc -l < leaptmp`
rm -f leaptmp
set leaptrue = `echo $leap | cut -c5`
if ($leaptrue == 0) then
   echo $yr is a leap year
   set dcount = 366
endif
#################################
## Initialize Day One and Month 1
#################################
set nmon = 1
set nday = 1

@ loop = 1
while ($loop <= $dcount )
##while ($loop <= 10)
   if ($nday > 31 && ($nmon == 1 || $nmon == 3 || $nmon == 5 || $nmon == 7 || $nmon == 8 || $nmon == 10 || $nmon == 12)) then
      @ nday = 1
      @ nmon = $nmon + 1
      if ($nmon > 12) then
         @ nmon = 1
      endif
   else if ($nmon == 2 && $nday > 28 && $leaptrue != 0) then
      @ nday = 1
      @ nmon = $nmon + 1
   else if ($nmon == 2 && $nday > 29 && $leaptrue == 0) then
      @ nday = 1
      @ nmon = $nmon + 1
   else if ($nday > 30 && ($nmon == 4 || $nmon == 6 || $nmon == 9 || $nmon == 11)) then
      @ nday = 1
      @ nmon = $nmon + 1
   endif

   if ($nmon == 1) set mon2='Jan'
   if ($nmon == 2) set mon2='Feb'
   if ($nmon == 3) set mon2='Mar'
   if ($nmon == 4) set mon2='Apr'
   if ($nmon == 5) set mon2='May'
   if ($nmon == 6) set mon2='Jun'
   if ($nmon == 7) set mon2='Jul'
   if ($nmon == 8) set mon2='Aug'
   if ($nmon == 9) set mon2='Sep'
   if ($nmon == 10) set mon2='Oct'
   if ($nmon == 11) set mon2='Nov'
   if ($nmon == 12) set mon2='Dec'

 if ($nday < 10) set nday=0$nday
 if ($nmon < 10) set nmon=0$nmon

   set ntim = $yr$nmon$nday
   echo $ntim


rm -rf makedaily_$ntim.gs
cat>> makedaily_$ntim.gs << EOF
'reinit'
'open ${D}/3B42.ctl'
'set x 1 1440 ';'set y 1 400';'set undef -9999.9'
'define prate=ave(r, time=00z$nday$mon2$yr,time=21z$nday$mon2$yr)'
'set sdfwrite -flt TRMM_3B42.$yr$nmon$nday.nc'
'sdfwrite prate'
'quit'
EOF
/usr/people/amishra/pkg/grads-2.1.a1/bin/grads -blc "run makedaily_$ntim.gs"
wait
rm -rf makedaily_$ntim.gs
   set nmontmp = `echo $nmon | cut -c1-1`
   if ($nmontmp < 1) set nmon = `echo $nmon | cut -c2-2`
   endif

   set ndaytmp = `echo $nday | cut -c1-1`
   if ($ndaytmp < 1) then
      set nday = `echo $nday | cut -c2-2`
   endif

   @ nday = $nday + 1
   @ loop = $loop + 1
end
@ yr = $yr + 1
end
exit
