#!/bin/ksh 
var=TMIN
df=26
MM=AUG
YYYY=2024

vari=tmin
if [ $var == TMAX ] ; then
 vari=tmax
fi

cat << Eof >SAMET_$MM_${var}.ctl
dset /share/ioper/tempo/SAMeT/DAILY/$var/%y4/%m2/SAMeT_CPTEC_${var}_%y4%m2%d2.nc
options template
dtype netcdf
undef  -9.99e+08
xdef 1001 linear -83 0.05 
ydef 1381 linear -56 0.05
zdef 1 levels 1000
tdef $df linear 00Z01$MM$YYYY  24hr
vars 2
$vari=>$vari  0  t,y,x  $vari
nobs=>nobs  0  t,y,x  nobs
endvars
Eof
 
cat << Eof >SAMeT_$MM_${var}.gs
'set display grey white'
'set display color'
'c'
'open SAMET_$MM_${var}.ctl'
'open /share/ioper/tempo/SAMeT/CLIMATOLOGY/DAILY_AVERAGE/$var/SAMeT_CPTEC_${var}.ctl'
'open mask_brasil.ctl'
'br=lterp(mk.3(t=1),lat.1(t=1))'
'set lat -35 6' 
'set lon -75 -33'
'set mpdset brmap_hires'

*'media=ave($vari,time=00z01${MM}${YYYY},time=00Z${df}${MM}${YYYY})'
*'clim=ave(t$vari.2,time=00z01${MM}2020,time=00Z${df}${MM}2020)'

'medNew=0.0'
'set gxout shaded'
i=1
while(i<=26)
 if(i<10) ; ii=0%i ;else ; ii=i ;endif
* 'medNew=${vari}(time=00z'ii'${MM}${YYYY})-t$vari.2(time=00z'ii'${MM}2020) + medNew'
 'medNew=${vari}(time=00z'ii'${MM}${YYYY})-t$vari.2(time=00z'ii'${MM}2020) '
 'd medNew'
 'draw title 'ii
 'cbar'
 'q pos'
 'c'
 i=i+1
endwhile


'color  -3 3 1 -kind blue->white->red -xcbar 0.5 8.0 0.6 0.8 -fw 0.14 -fh 0.14 -edge rectangle -line off -fs 1'
'set gxout shaded'

'anomalia=medNew/26'
'set grads off'
'set grid off'
'd maskout(anomalia,mk.3(t=1))'
'draw title SAMeT \ Anomalia Temperatura - $var \ 01 ate $df - ${MM}'
'printim ${var}_Anomalia_${MM}.png'
'
'c'
if($var=TMIN)
 'color  5 25 1 -kind blue->white->red -xcbar 0.5 8.0 0.6 0.8 -fw 0.14 -fh 0.14 -edge rectangle -line off -fs 2'
else
'color  14 38 1 -kind blue->white->red -xcbar 0.5 8.0 0.6 0.8 -fw 0.14 -fh 0.14 -edge rectangle -line off -fs 2'
endif
'set gxout shaded'
'set grads off'
'set grid off'
'd maskout(lterp(media,mk.3(t=1)),mk.3(t=1))'
'draw title SAMeT \ $var - ${MM} \ 01 ate $df '
'printim ${var}_media_${MM}.png'

'quit'
Eof

grads -pc "run SAMeT_$MM_${var}.gs"
rm -f SAMeT_$MM_${var}.gs SAMET_$MM_${var}.ctl
exit
