#!/bin/csh -f

#set up times for 1-hour increments over a date range for this specified year

foreach year (2008)

set net = Y4
set loc = "--"

@ pyear = $year - 1
set bjday = `./datecalc -j $pyear 12 31`

set jday_start=`./datecalc -j $year 12 10`
set jday_end=`./datecalc -j $year 12 28`

foreach jday (`seq $jday_start $jday_end`)

#convert sday to month and day
set wdate = `./datecalc -j $jday`
set month = $wdate[2]
set sday = $wdate[3]

@ eday = $sday + 1

if ($month < 10) then
 set month = 0$month
endif

if ($sday < 10) then
 set sday=0$sday
endif

if ($eday < 10) then
 set eday=0$eday
endif

@ jd = $jday - $bjday

if ($jd < 10) then
set jd = 00$jd
endif

if ($jd > 9 & $jd < 100) then
set jd = 0$jd
endif

echo day $jd

foreach sta (`cat station_list.txt`)
foreach cha (`cat cha_list.txt`) 

#create the output directory for this (Julian numbered) day
if ! -e Data\_$sday mkdir Data\_$jd

#loop through the hours of the day
foreach hour (00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23)

@ hourp1 = $hour + 1 

if ($hourp1 < 10) then
set hourp1 = 0$hourp1
endif

#create the start and end time strings for the IRIS web request call
set start = $year-$month-$sday"T"$hour":00:00"
set end =   $year-$month-$sday"T"$hourp1":00:00"

#create a name for the (zipped) output file
set outfile = outfile\_$year\_$jd\_$sta\_$cha\_$hour.zip

#uncomment to monitor webrequest calls
#echo "curl --output $outfile https://service.iris.edu/irisws/timeseries/1/query?net=$net&sta=$sta&cha=$cha&start=$start&end=$end&format=sac.zip&loc=$loc"

#request a timeseries here
curl --output $outfile "https://service.iris.edu/irisws/timeseries/1/query?net=$net&sta=$sta&cha=$cha&start=$start&end=$end&format=sac.zip&loc=$loc"

#did the request return any data?, if not delete the output file
set x = `head -1 $outfile | awk '/Error/ {print 1}'`
if $x == 1 then
 rm $outfile
endif

#move the output file to the day directory
if -e $outfile then
mv $outfile Data\_$jd
endif

end

end

end

end
