#!/bin/ksh -x
export LANG=US
ano=2022
mes=jun

df=$(cal $mes $ano |  xargs -n 1 |tail -1| awk '{print $1}' )
cat <<EOT > MERGE.ctl
dset /share/ioper/tempo/MERGE/GPM/DAILY/%y4/%m2/MERGE_CPTEC_%y4%m2%d2.grib2
options template
index ^MERGE_CPTEC.idx
undef -9.99e+08
dtype grib2
xdef 1001 linear  -120.05   0.1 
ydef 924 linear    -60.05   0.1
tdef ${df} linear 12Z01$mes$ano 24hr
zdef 1 linear 1 1
vars 2
PREC  0,1   0,15,5 ** Surface Precipitation [kg/m^2]
NEST  0,1   0,3,1 **  Number of Stations /  Grid Point 
ENDVARS
EOT

gribmap -i MERGE.ctl

rm -f MERGE_CPTEC_acum_${mes}_${ano}.nc
cat <<EOT > calcula_acumula_mes.gs
'open MERGE.ctl'
'set lon -81.95  -34.65'
'set lat -56.15   12.85'
'pacum=sum(prec,time=12z01${mes}${ano},time=12Z${df}${mes}${ano})'
'set time 12Z01$mes$ano'
'set sdfwrite -3dt -nc4 -zip   MERGE_CPTEC_acum_${mes}_${ano}.nc'
'sdfwrite pacum'
'quit'
EOT

grads -blc "run calcula_acumula_mes.gs"

rm -f  calcula_acumula_mes.gs  MERGE.ctl MERGE_CPTEC.idx
exit




for ano in $(seq 2001 2020) ; do
  df=$(cal $mes $ano |  xargs -n 1 |tail -1)
  grads -blc "run soma.gs $ano"
done
done









exit
export LANG=US
for ano in $(seq 2000 2021) ; do
 for mes in $(echo "jan feb mar apr may jun jul aug sep oct nov dec") ; do 
  df=$(cal $mes $ano |  xargs -n 1 |tail -1)
  grads -blc "run calc_valesca.gs $df $mes $ano"
  echo $ano"  "$mes"  "$df
done
done
