#!/bin/ksh -x
export LANG=US

#************** CALCULA O ACUMULADO ANUAL 
cat <<EOT > acumula_anual.gs
function main(args)
'reinit'
ano=subwrd(args,1)
## BAIXAR ESTES 2 ARQUIVOS
#http://ftp.cptec.inpe.br/modelos/tempo/MERGE/GPM/DAILY/MERGE_CPTEC_2000_2022.ctl
#http://ftp.cptec.inpe.br/modelos/tempo/MERGE/GPM/DAILY/MERGE_CPTEC_2000_2022.idx

'open MERGE_CPTEC_2000_2022.ctl' 
'set lon -81.95 -34.65'
'set lat -56.15 12.85 '
'm=sum(prec,time=12z01jan'ano',time=12z31dec'ano')'
'set time 12Z01'%mes%ano
'set sdfwrite -3dt -nc4 -zip   MERGE_CPTEC_sum_'ano'.nc'
'sdfwrite m'
'quit'
return
EOT

for ano in $(seq 2001 2022) ; do
  df=$(cal $mes $ano |  xargs -n 1 |tail -1)
  grads -blc "run acumula_anual.gs $ano"
done
rm -f acumula_anual.gs MERGE_CPTEC_2000_2022.ctl MERGE_CPTEC_2000_2022.idx


#************** CALCULA A NORMAL CLIMATOLOGICA

cat <<EOT > MERGE_CPTEC_sum.ctl
dset ^MERGE_CPTEC_sum_%y4.nc
options template
undef -999000000.000000
dtype netcdf
xdef 474 linear -81.95 0.1
ydef 691 linear -56.15 0.1
zdef 1 linear 0 1
tdef 22 linear 12Z01JAN2001 1yr
vars 1
m=>m  0  t,y,x  m
endvars
EOT

cat <<EOT > calcula_Normais.gs
'reinit'
'open MERGE_CPTEC_sum.ctl'
'set lon -81.95 -34.65'
'set lat -56.15 12.85 '
'normal=ave(m,t=1,t=22)'
'set time 12Z01jan2022'
'set sdfwrite -3dt -nc4 -zip NORMAIS_CLIMATOLOGICA_MERGE_2001_2020.nc'
'sdfwrite normal'
'quit'
return
EOT

grads -blc "run calcula_Normais.gs"
rm -f MERGE_CPTEC_sum.ctl calcula_Normais.gs



exit

