#!/bin/csh

cd /moe/r0/rhart/machines/archive
set stime0 = `date -u +%s`

set mins = "02 07 12 17 22 27 32 37 42 47 52 57"
set hrs = "00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23"
set mons = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC"
set date1 = `date -u +%Y%m%d`
set date2 = `date -u +%Y%m%d --date="1 day ago"`
set date3 = `date -u +%Y%m%d --date="2 days ago"`
set date4 = `date -u +%Y%m%d --date="3 days ago"`
set date5 = `date -u +%Y%m%d --date="4 days ago"`
set date6 = `date -u +%Y%m%d --date="5 days ago"`
set date7 = `date -u +%Y%m%d --date="6 days ago"`
set date8 = `date -u +%Y%m%d --date="7 days ago"`
set dates = "$date8 $date7 $date6 $date5 $date4 $date3 $date2 $date1"

set date0 = `date -u +%Y%m --date="40 days ago"`

rm -rf ${date0}*

rm -f dtgs
foreach date ($dates)
    set sdate = `echo $date | cut -c1-8`
    set year  = `echo $date | cut -c1-4`
    set mon  = `echo $date | cut -c5-6`
    set mon2  = `echo $mons | cut -d" " -f${mon}`
    set day  = `echo $date | cut -c7-8`
    foreach hr ($hrs)
        foreach min ($mins)
             set stime = `date -u +%s --date="$mon2 $day ${hr}:${min}:00 UTC $year"`
             if ($stime0 >= $stime) then
                 echo "${sdate}/${date}${hr}${min}" >> dtgs 
             endif
        end
    end
end

set dtgs = `tail --lines=2016 dtgs`
set dtg0 = `echo $dtgs[1] | cut -d"/" -f2`
set year = `echo $dtg0|  cut -c1-4`
set month = `echo $dtg0 |  cut -c5-6`
set day = `echo $dtg0 |  cut -c7-8`
set hr = `echo $dtg0 |  cut -c9-10`
set min = `echo $dtg0 |  cut -c11-12`
set mons = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC"
set month2 = `echo $mons | cut -d" " -f${month}`
set gdtg = "${hr}:${min}Z${day}${month2}${year}"

set machines = "moe barney bart homer marge frink itchy patti selma scorpio otto rod jimbo milhouse"
foreach machine ($machines)
   rm -f data.txt
   foreach dtg ($dtgs)
       set data = `egrep "${machine}.png" ${dtg}* | head --lines=1 | sed 's/<BR>//g' | cut -d">" -f34- | cut -d"<" -f2 | cut -d">" -f2`
       if ($data == "") then
                set data = "-999"
       endif
       echo $data >> data.txt
   end
   ./a.out
cat << EOF_CAT > test.ctl
dset ^data.grads
undef -999
title gfs.t00z.pgrb2f03
ydef 1 linear -90 0.5
xdef 1 linear 0 0.5
tdef 2016 linear $gdtg 5MN
zdef 1 linear 1000 5
vars 1   
load 1 99 load
ENDVARS
EOF_CAT
echo $machine | opengrads  -clb "run plot.gs"
echo $machine | opengrads  -clb "run plot.week.gs"
end
