#!/bin/bash
#--------------------------------------------------------------------#
#                    GSISTAT - GDAD/CPTEC/INPE - 2017                #
#--------------------------------------------------------------------#
#BOP
#
# !DESCRIPTION:
#  Script para gerar figuras das estatisticas do GSI
#
#  Toda a configuracao da execucao deve ser feita no arquivo config.sh
#  ---> $DIR/GSI_STAT/conf/config.sh
#
# !INTERFACE:
#  ./plot_all.sh DataType DataInicial DataFinal Incremento
#
#    em que:
#           DataType      : Tipo de info.: 1: First Guess: 2 Analise
#           DataInicial   : Data inicial [%y4%m2%d2%h2]
#           DataFinal     : Data final [%y4%m2%d2%h2]
#           Incremento    : Diferenca em horas entre cada data a ser 
#                           avaliada 
#
# Apenas os 2 primeiros argumentos sao estritamente necessarios, os 
# demais devem ser utilizados apenas em casos de mais de 1 data.
#
# !REVISION HISTORY:
#  02-07-2013 - Mattos, Joao    - Codigo Inicial 
#  03-03-2017 - Vendrasco, Eder - Reformulacao dos scripts/codigos
#
# !REMARKS:
#
# !BUGS:
#
#EOP
#--------------------------------------------------------------------#
#BOC

# Verificando as opcoes passadas pela linha de comando
if [ $#  != 4 ]; then echo "ERRO: ${0} [01/02] [YYYYMMDDHH] <YYYYMMDDHH> <nh> "; exit; fi

DataType=${1}
LABELANL=${2}
LABELFCT=${3}
Incremento=${4}

# Carregando os modules do Tupa
. /opt/modules/default/etc/modules.sh
module load grads

# Carregando Configuracoes
source ${stat_util}/conf/config.sh 
writedconf ${GStatCfg} $NProc

echo "Arquivo de logs do opengrads" > opengrads_plot_all${DataType}.log
echo
echo -e "\033[32;1m Veja informacoes de log da rodada do grads no arquivo: opengrads_plot_all${DataType}.log \033[m"

for ObsType in $(echo $obspross); do

 if [ $ObsType = "conv" ]; then 

   while [ ${DataInicial} -le ${DataFinal} ]; do

     ym=${DataInicial:0:6}
     dh=${DataInicial:6:4}

     #------------------------------------------------------#
     # Plotando cada uma das 5 informacoes sobre a contagem #
     #
     #------------------------------------------------------#
     # Indice |                 Descricao
     #------------------------------------------------------#
     #   [1]  |    Total de Observacoes                     #
     #   [2]  |    Total Utilizado                          #
     #   [3]  |    Total Nao Utilizado                      #
     #   [4]  |    Total Rejeitado pelo QC                  #
     #   [5]  |    Total Monitorado [Rejeitado por Pad      #
     #------------------------------------------------------#

     if [ ! -e ${GStatFig}/${ym}/${dh}/conv ];then
        mkdir -p ${GStatFig}/${ym}/${dh}/conv
     fi
     if [ ! -e ${GStatFig}/${ym}/${dh}/rad ];then
        mkdir -p ${GStatFig}/${ym}/${dh}/rad
     fi
     echo ""
     echo " Chamando o total_count.sh: "${DataInicial} ${DataType}

     for i in $(seq 1 5); do
        /bin/bash ${GStatScp}/total_count.sh ${i} ${DataInicial} ${DataType} ${GStatOut}/${ym}/${dh}/conv ${GStatFig}/${ym}/${dh}/conv
     done

     #---------------------------------------------------------#
     # Plotando cada um dos 4 tipos de contagens e 3 variaveis #
     # que contem informacoes em mais de 1 nivel               #
     #---------------------------------------------------------#
     #   Indice |    Nome do Arquivo                           #
     #---------------------------------------------------------#
     #     [1]  | summary_obs_used_level.txt                   #
     #     [2]  | summary_obs_not_used_level.txt               #
     #     [3]  | summary_obs_rejeited_level.txt               #
     #     [4]  | summary_obs_monitored_level.txt              #
     #---------------------------------------------------------#
     #                                                         #
     #  Cada arquivo possui a informacao de 6 variaveis        #
     #  convencionais que sao processadas pelo GSI:            #
     #                                                         #
     #---------------------------------------------------------#
     #   Indice |  Variavel | Descricao                        #
     #---------------------------------------+-----------------#
     #     [1]  |    SST    | Temp. da Sup. do Mar             #
     #     [2]  |     PS    | Pressao em Superficie            #
     #     [3]  |     PW    | Agua Precipitavel                #
     #     [4]  |     UV    | Vento                            #
     #     [5]  |      T    | Temperatura                      #
     #     [6]  |      Q    | Umidade Especifica               #
     #---------------------------------------------------------#

     echo " Chamando o total_count_level: "${DataInicial} ${DataType}

     for i in $(seq 1 4); do
        for j in $(seq 4 6); do
           /bin/bash ${GStatScp}/total_count_level.sh ${i} ${j} ${DataInicial} ${DataType} ${GStatOut}/${ym}/${dh}/conv ${GStatFig}/${ym}/${dh}/conv
        done
     done

   # Plotando o scatterplot e distribuicao espacial para todas as variaveis em cada nivel
     cat << eof > ${GStatCfg}/variaveis.nml
      1;  sst; Temperatura da Superficei do Mar; 1000
      2;   ps;             Pressao a Superficie; 1000
      3;   pw;                Agua Precipitavel; 1000
      4;   uv;              Velocidade do Vento; 1000 900 800 700 600 500 400 300 250 200 150 100 50 0
      5;    t;                Temperatura do Ar; 1000 900 800 700 600 500 400 300 250 200 150 100 50 0
      6;    q;               Umidade Especifica; 1000 900 800 700 600 500 400 300
      7;  gps;                Radiocultacao GPS; 1000 900 800 700 600 500 400 300 250 200 150 100 50 0
eof

     cat ${GStatCfg}/variaveis.nml | while read linha; do
        idx=`echo ${linha} | awk -F";" '{print $1}'`
        name=`echo ${linha} | awk -F";" '{print $2}'`
        levs=`echo $linha | awk -F";" '{ print substr($0, index($0,$4)) }'`

        echo " Gerando figuras para :"${DataInicial} ${DataType} ${name}

        echo -e "\033[31;1m Scatterplot comentado por gerar erros e o Joao está arrumando!!!! \033[m"

        for lv in $levs; do
         # scatterplot comentado por gerar erros e o Joao está arrumando
#         /bin/bash ${GStatScp}/scatter.sh ${idx} ${DataInicial} ${DataType} ${lv} ${GStatOut}/${ym}/${dh}/conv ${GStatFig}/${ym}/${dh}/conv

         # distribuicao espacial
        opengrads -lbc "run ${GStatScp}/plota_espacial_conv.gs ${name} diff 1 ${lv} ${DataType} ${DataInicial} ${GStatOut}/${ym}/${dh}/conv ${GStatFig}/${ym}/${dh}/conv $llati $llatf $lloni $llonf" >> opengrads_plot_all${DataType}.log
        done

      done

      DataInicial=`${stat_bin}/inctime ${DataInicial} +${Incremento}hr %y4%m2%d2%h2`

   done

  else
   
   echo " 
          Processando as radiancias:" ${LABELANL} ${LABELFCT}
   echo "
          Processando as radiancias: 
                                    " >> opengrads_plot_all${DataType}.log

   while [ "${LABELANL}" -le "${LABELFCT}" ]; do

    YYYYDDANL=`echo ${LABELANL} |cut -c 1-8`
    HHANL=`echo ${LABELANL} |cut -c 9-10`
    DDHH=`echo ${LABELANL} |cut -c 7-10`
    YYYYMM=`echo ${LABELANL} |cut -c 1-6`
    DD=`echo ${LABELANL} |cut -c 7-8`
    echo "   Data: " $LABELANL
    
    for ctlfile in `ls ${GStatOut}/${YYYYMM}/${DDHH}/rad/*.ctl`; do
     
     ctl=$(basename $ctlfile)
     instr=$(  echo $ctl | awk -F "_" '{print $2}')
     sat=$(    echo $ctl | awk -F "_" '{print $3}')
     satgs=$(echo $sat | tr - _)
     arq=$(    echo $ctl | awk -F "_" '{print $4}' | cut -c 1-3)
     chan=$(grep ${instr} ${GStatCfg}/id_sat.nml | awk '{print $3}')

     # Criando os diretorios de saida
     if test ! -s ; then mkdir -p ${GStatFig}/${YYYYMM}/${DDHH}/rad ; fi

     echo "Rodando o grads para: " spatial_distribution_rad_${arq}_${instr}_${sat}

     # Criando do script do GrADS (.gs) para gerar as figuras
     cat<< EOF > $GStatScp/spatial_distribution_rad_${arq}_${instr}_${sat}.gs
     
      LIBGRADS="${GStatLib}/grads"
      'reinit'
*     'inicia'
      'open ${GStatOut}/${YYYYMM}/${DDHH}/rad/${ctl}'
      'set lat $llati $llatf'
      'set lon $lloni $llonf'
      'set display color white'
      'c'
      
      m=1
       while(m <= ${chan})

        'set lev 'm
        say "Satelite: " $satgs " - Instrumento: " $instr " - Channel: " m 

        'set gxout stat'
        'set stat on'
        'd iusemk'
        iuse=sublin(result,8)
        use=subwrd(iuse,4)
        say " Usemark: " use 
         
        if(use=1)
       
         'set gxout stat'
         'd rchan'
         canal=sublin(result,8)
         cha=subwrd(canal,4)
          
         'c'
       
         legend.1="Distribui\`6c\`0\`6a\`0o Espacial para o dia "
         legend.2=  cha " ${instr} ${sat}"
         legend.3="Observa\`6c\`0\`6o\`0es do canal " cha " ${instr} ${sat} "
         legend.4="Distribui\`6c\`0\`6a\`0o Espacial da TB (K) do canal " cha 
         legend.10=" ${instr} ${sat} "
         legend.5="N\`6u\`0mero de Observa\`6c\`0\`6o\`0es Assimiladas: "
         legend.6="Dos valores dos flags de controle de qualidade "
         legend.7="Distribui\`6c\`0\`6a\`0o Espacial dos flags de controle de qualidade "
         legend.8="/ N. Obs. Assimiladas:"
         legend.9="para o dia" 
         
         'set gxout stnmark'
         'set cmark 3'
         'set grads off'
         'set grid off'
         LIBGRADS'/color 180 310 10 -kind darkblue->blue->deepskyblue->yellow->orange->orangered->red'
         'set mpdset brmap_hires'
         'd maskout(maskout(radobs,iusemk),-abs(qcmark))'
         'set gxout stat'
         'set stat on'
         'd maskout(maskout(radobs,iusemk),-abs(qcmark))'
         valcont=sublin(result,7)
         cont=subwrd(valcont,8)

         LIBGRADS'/xcbar -edge circle -line on'
         'draw map'
         LIBGRADS'/setfont large'
         'set font 0'
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0.3 'legend.4 ' 'legend.10
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0 'legend.9' ${LABELANL} 'legend.8' 'cont ' ${EXPE}'

         'printim ${GStatFig}/${YYYYMM}/${DDHH}/rad/${arq}_'cha'_${instr}_${sat}_${LABELANL}_obs.png'
         'c'
          
*OMF, first guess
         'set gxout stnmark'
         'set grads off'
         'set grid off'
         LIBGRADS'/color -10 10 1 -kind darkblue->blue->deepskyblue->yellow->orange->orangered'
         'set mpdset brmap_hires'
         'set cmark 3'
         'd maskout(maskout(OMFwbc,iusemk),-abs(qcmark))'
         LIBGRADS'/xcbar -edge circle -line on'
         'draw map'
         LIBGRADS '/setfont large'
         'set font 0'
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0.3 'legend.1 ${LABELANL} ' ' ${EXPE}
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0 do OMF (K) com bias correction canal 'legend.2
         
         'printim ${GStatFig}/${YYYYMM}/${DDHH}/rad/${arq}_'cha'_${instr}_${sat}_${LABELANL}_bc_OMF.png'
         'c'
          
         'set gxout stnmark'
         'set grads off'
         'set grid off'
         LIBGRADS'/color -10 10 1 -kind darkblue->blue->deepskyblue->yellow->orange->orangered'
         'set mpdset brmap_hires'
         'set cmark 3'
         'd maskout(maskout(OMFnbc,iusemk),-abs(qcmark))'
         LIBGRADS'/xcbar -edge circle -line on'
         'draw map'
         LIBGRADS'/setfont large'
         'set font 0'
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0.3 'legend.1 ${LABELANL}' '${EXPE}
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0 do OMF (K) sem bias correction canal ' legend.2
         
         'printim ${GStatFig}/${YYYYMM}/${DDHH}/rad/${arq}_'cha'_${instr}_${sat}_${LABELANL}_nobc_OMF.png'
         'c'
          
*OMA, analise
         'set gxout stnmark'
         'set grads off'
         'set grid off'
         LIBGRADS'/color -10 10 1 -kind darkblue->blue->deepskyblue->yellow->orange->orangered'
         'set mpdset brmap_hires'
         'set cmark 3'
         'd maskout(maskout(OMFwbc,iusemk),-abs(qcmark))'
         LIBGRADS'/xcbar -edge circle -line on'
         'draw map'
         LIBGRADS '/setfont large'
         'set font 0'
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0.3 'legend.1 ${LABELANL}' '${EXPE}
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0 do OMA (K) com bias correction canal 'legend.2
         
         'printim ${GStatFig}/${YYYYMM}/${DDHH}/rad/${arq}_'cha'_${instr}_${sat}_${LABELANL}_bc_OMA.png'

         'c'
         'set gxout stnmark'
         'set grads off'
         'set grid off'
         LIBGRADS'/color -10 10 1 -kind darkblue->blue->deepskyblue->yellow->orange->orangered'
         'set mpdset brmap_hires'
         'set cmark 3'
         'd maskout(maskout(OMFnbc,iusemk),-abs(qcmark))'
         LIBGRADS'/xcbar -edge circle -line on'
         'draw map'
         LIBGRADS'/setfont large'
         'set font 0'
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0.3 'legend.1 ${LABELANL}' '${EXPE}
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0 do OMA (K) sem bias correction canal 'legend.2
        
         'printim ${GStatFig}/${YYYYMM}/${DDHH}/rad/${arq}_'cha'_${instr}_${sat}_${LABELANL}_nobc_OMA.png'
         'c'

         'set gxout stnmark'
         'set grads off'
         'set grid off'
         LIBGRADS'/color -levs -51 -50 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 50 51 -kind cyan->darkcyan->dodgerblue->darkmagenta->mediumspringgreen->chartreuse->limegreen->green->teal->darkblue->blue->deepskyblue->firebrick->yellow->darkgoldenrod->orange->orangered->red->indigo->purple->blueviolet->deeppink->palevioletred->darkred->fuchsia->coral'
         'set mpdset brmap_hires'
         'set cmark 3'
         'd qcmark'
         LIBGRADS'/xcbar -edge circle -line on'
         LIBGRADS'/setfont large'
         'set font 0'
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0.3 'legend.7
         LIBGRADS'/draws -pos tc -xoffset 0 -yoffset 0 canal 'legend.2 ' para o dia ' ${LABELANL} ' '  ${EXPE}
        
         'printim ${GStatFig}/${YYYYMM}/${DDHH}/rad/${arq}_'cha'_${instr}_${sat}_${LABELANL}_qcmark.png'
       
       endif
       
       m=m+1
       
      endwhile

      'quit'

EOF

     opengrads -blc "run $GStatScp/spatial_distribution_rad_"${arq}"_"${instr}"_"${sat}".gs" >> opengrads_plot_all${DataType}.log
    
     rm -f $GStatScp/spatial_distribution_rad_"${arq}"_"${instr}"_"${sat}".gs
    
    done

    LABELANL=$($GStatBin/inctime ${LABELANL} +${incr}hr %y4%m2%d2%h2)

   done

 fi

done

rm -f ${GStatCfg}/variaveis.nml

#EOC
#------------------------------------------------------------------------------#

