#!/bin/csh
#
# Get GFS analysis files 
#

set diri=$1
echo " "
echo "seti diri was defined as diri = $diri"
echo " "

cd ${diri}/ETI/data

cdo -ntime temp.nc > timestep.txt

set timestep=`cat timestep.txt`

cdo -seltimestep,$timestep temp.nc lasttemp.nc
cdo -s showdate lasttemp.nc > list.txt

set tiempos=`cat list.txt`

set datum1=`date -d $tiempos +%s`
set datum2=`date +%s`

@ dif=($datum2 - $datum1)
@ days=(($dif / (60 * 60 * 24)) - 1)

if ($days > 1) then

cd ${diri}/ETI/output
rm *

cd ${diri}/ETI/tmp
rm *

foreach i (`seq ${days} -1 2`)

set ym=`date --date=${i}" days ago" +%Y%m`
set d=`date --date=${i}" days ago" +%d`
set y=`date --date=${i}" days ago" +%Y`
set m=`date --date=${i}" days ago" +%m`

set URL="https://thredds.ucar.edu/thredds/ncss/grid/grib/NCEP/GFS/Global_0p5deg_ana/GFS_Global_0p5deg_ana_" 

foreach hracb ( 00 06 12 18 )

echo "start download...."
#curl "${URL}${ym}${d}_${hracb}00.grib2?var=Geopotential_height_isobaric&north=15&west=0.0000&east=359.5000&south=-70&disableProjSubset=on&horizStride=1&time_start=${y}-${m}-${d}T${hracb}%3A00%3A00Z&time_end=${y}-${m}-${d}T${hracb}%3A00%3A00Z&timeStride=1&vertCoord=50000&accept=netcdf" -o gfs.${y}${m}${d}_${hracb}.nc

#curl "${URL}${ym}${d}_${hracb}00.grib2?var=Geopotential_height_isobaric&north=15&west=0.0000&east=359.5000&south=-70&horizStride=1&time_start=${y}-${m}-${d}T${hracb}%3A00%3A00Z&time_end=${y}-${m}-${d}T${hracb}%3A00%3A00Z&timeStride=1&vertCoord=50000&accept=netcdf" -o gfs.${y}${m}${d}_${hracb}.nc

curl "${URL}${ym}${d}_${hracb}00.grib2?var=Geopotential_height_isobaric&north=90&west=0&east=360&south=-90&horizStride=1&time_start=${y}-${m}-${d}T${hracb}%3A00%3A00Z&time_end=${y}-${m}-${d}T${hracb}%3A00%3A00Z&timeStride=1&vertCoord=50000&accept=netcdf" -o gfs.${y}${m}${d}_${hracb}.nc

end
end

find . -name "gfs*" -type 'f' -size -160k -delete

cdo mergetime gfs* recover_analysis_primero.nc
cdo -sellonlatbox,0,360,-70,15 recover_analysis_primero.nc recover_analysis.nc

rm gfs*
rm recover_analysis_primero.nc

mv recover_analysis.nc ${diri}/ETI/output

cd ${diri}/ETI/output

cdo chname,Geopotential_height_isobaric,gh recover_analysis.nc aux.nc
rm recover_analysis.nc
cdo invertlat aux.nc recover_analysis.nc
rm aux.nc

mv recover_analysis.nc ${diri}/ETI/data

cd ${diri}/ETI/data
mv temp.nc aux.nc
cdo mergetime aux.nc recover_analysis.nc temp.nc
mv aux.nc ${diri}/ETI/data/backup
echo "The file temp.nc was updated"
echo "recoverSETI.csh finished"
echo " "

else

echo "The file temp.nc is already updated"
echo "recoverSETI.csh finished"
echo " "

endif
