#!/bin/ksh

#rodar na aux02

export LANG=US

DIR_OUT=/lustre_xc50/ioper/users/rozante/MERGE_V07B/CLIMATOLOGIA
DIR_CTL=/lustre_xc50/ioper/users/rozante/MERGE_V07B/BKP
DIR_CTL=/share/ioper/tempo/MERGE/GPM/DAILY/
DAILY_AVERAGE=0
MONTHLY_ACCUMULATED=1
YEAR_ACCUMULATED=0
MONTHLY_AVERAGE=0
MONTHLY_ACCUMULATED_YEARLY=0
MONTHLY_AVERAGE_YEARLY=0

if [ $DAILY_AVERAGE -eq 1 ] ; then
  mkdir -p $DIR_OUT/DAILY_AVERAGE
  grads -blc "run DAILY_AVERAGE.gs $DIR_CTL/MERGE_CPTEC.ctl"
  mv MERGE_CPTEC_12Z*.nc $DIR_OUT/DAILY_AVERAGE
fi

if [ $MONTHLY_ACCUMULATED -eq 1 ] ; then
 mkdir -p $DIR_OUT/MONTHLY_ACCUMULATED
 for mes in $(echo "jan feb mar apr may jun jul aug sep oct nov dec") ; do 
  df=$(cal $mes 2019 |  xargs -n 1 |tail -1) 
  echo $mes"  "$df
  grads -blc "run MONTHLY_ACCUMULATED.gs $mes $df $DIR_CTL/MERGE_CPTEC.ctl"
#  mv MERGE_CPTEC_acum_${mes}.nc $DIR_OUT/MONTHLY_ACCUMULATED
 done
fi

if [ $YEAR_ACCUMULATED -eq 1 ] ; then
 mkdir -p $DIR_OUT/YEAR_ACCUMULATED
 for ano in $(seq 1998 2024) ; do
   echo $ano
   grads -blc "YEAR_ACCUMULATED.gs $ano $DIR_CTL/MERGE_CPTEC.ctl "
   mv MERGE_CPTEC_acum_$ano.nc $DIR_OUT/YEAR_ACCUMULATED
 done
fi

if [ $MONTHLY_AVERAGE -eq 1 ] ; then
 mkdir -p $DIR_OUT/MONTHLY_AVERAGE
 for mes in $(echo "jan feb mar apr may jun jul aug sep oct nov dec") ; do 
  df=$(cal $mes 2019 |  xargs -n 1 |tail -1) 
  echo $mes"  "$df
  grads -blc "run MONTHLY_AVERAGE.gs $mes $df $DIR_CTL/MERGE_CPTEC.ctl"
  mv MERGE_CPTEC_mean_${mes}.nc $DIR_OUT/MONTHLY_AVERAGE
 done
fi

if [ $MONTHLY_ACCUMULATED_YEARLY -eq 1 ] ; then
  mkdir -p $DIR_OUT/MONTHLY_ACCUMULATED_YEARLY
  for ano in $(seq 1998 2024 ) ; 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)
     echo $ano"  "$mes"  "$df
     grads -blc "run MONTHLY_ACCUMULATED_YEARLY.gs $df $mes $ano $DIR_CTL/MERGE_CPTEC.ctl"
     mv MERGE_CPTEC_acum_${mes}_${ano}.nc  $DIR_OUT/MONTHLY_ACCUMULATED_YEARLY
    done 
 done 
fi

if [ $MONTHLY_AVERAGE_YEARLY -eq 1 ] ; then
  mkdir -p $DIR_OUT/MONTHLY_AVERAGE_YEARLY
  for ano in $(seq 1998 2024 ) ; 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)
     echo $ano"  "$mes"  "$df
     grads -blc "run MONTHLY_AVERAGE_YEARLY.gs $df $mes $ano $DIR_CTL/MERGE_CPTEC.ctl"
     mv MERGE_CPTEC_mean_${mes}_${ano}.nc $DIR_OUT/MONTHLY_AVERAGE_YEARLY
    done 
 done 
fi
