#!/bin/bash
#--------------------------------------------------------------------#
#                    GSISTAT - GDAD/CPTEC/INPE - 2017                #
#--------------------------------------------------------------------#
#BOP
#
# !DESCRIPTION:
#  Script para gerar figuras (series temporais) 
#  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_temporal.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 
#  07-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

diffdate ${LABELANL}0000 ${LABELFCT}0000
(( Inclx = \( 86400 * dias \) / 5 ))
if [ $dias -eq 0 ] ; then (( Inclx = 86400 / 5 )) ; fi

#--------------------------------------------------------------------#
# Plotando a serie temporal para cada uma das variaveis disponiveis  #
# no arquivo de diagnostico. Sao plotados os grafivos para cada um   #
# dos niveis escolhidos no nanelist abaixo.                          #   
#--------------------------------------------------------------------#

#---------------------------------------------------------#
#   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               #
#---------------------------------------------------------#

for ObsType in $(echo $obspross); do

 if [ $ObsType = "conv" ]; then 

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

   if [ ! -e ${GStatFig}/temporal/conv ];then
      mkdir -p ${GStatFig}/temporal/conv
   fi

   cat << EOF > ${GStatCfg}/variaveis_serie_temporal.nml
   2;   ps; 180 181; 1000
   4;   uv; 220 282; 1000
   5;    t; 180 ; 1000
   6;    q; 180 ; 1000
EOF

   cat ${GStatCfg}/variaveis_serie_temporal.nml | while read linha; do

     idx=$(echo     ${linha} | awk -F";" '{print $1}')
     var=$(echo     ${linha} | awk -F";" '{print $2}' | sed 's/ //g')
     RepType=$(echo ${linha} | awk -F";" '{print $3}')
     levs=$(echo    ${linha} | awk -F";" '{print $4}')

    echo 
    echo -e "\033[34;1m Serie Temporal de OMF e OMA \033[m"

     for rt in $RepType; do
        l=1
        for lv in $levs; do
           # Serie Temporal de OMF e OMA
           for h in 00 06 12 18; do
            if test -s ${GStatOut}/temporal/conv/omfgs_${var}.0${rt}_${h}.dat -o -s ${GStatOut}/temporal/conv/omanl_${var}.0${rt}_${h}.dat; then
             echo ""
             echo " ----> omanl_${var}.0${rt}_${h}.dat"
             /bin/bash ${GStatScp}/plota_omf_oma.sh ${idx} ${l} ${DataInicial} ${DataFinal} ${rt} ${h} ${GStatOut}/temporal/conv ${GStatFig}/temporal/conv ${Inclx}
            fi
           done
        l=$((l+1))
        done
     done
   done

  else

   if [ ! -e ${GStatFig}/temporal/rad ];then
      mkdir -p ${GStatFig}/temporal/rad
   fi

   for txtfile in `ls ${GStatOut}/temporal/rad/omfb*amsua_n15*ges.txt`; do

    echo
    echo -e "\033[34;1m Processando: $txtfile \033[m"

    txt=$(basename $txtfile)
    instr=$(  echo $txt | awk -F "_" '{print $2}')
    sat=$(    echo $txt | awk -F "_" '{print $3}')
    arq=$(    echo $txt | awk -F "_" '{print $4}' | cut -c 1-3)
    chan=$(grep ${instr} ${GStatCfg}/id_sat.nml | awk '{print $3}')

    for ch in `echo $(seq 1 ${chan})`; do
    
     nmlsat=${GStatCfg}/${instr}_${sat}.nml
     rchan=$(grep -w "     ${ch}     ". ${nmlsat} | awk '{print $3}')
     iuse=$(grep  -w "     ${ch}     ". ${nmlsat} | awk '{print $4}')
     usado="1.00000000"

     if [ "${iuse}" == 1.00000000 ]; then
       echo
       echo " Canal " ${rchan} " e' utilizado " ${instr} "  " ${sat}
       echo
       num=$((${ch}+1))
       outeps=${GStatFig}/temporal/rad/omf_assim_${rchan}_${instr}_${sat}.eps
       outpng=${GStatFig}/temporal/rad/omf_assim_${rchan}_${instr}_${sat}.png
      
       LABELANL=${DataInicial}
       while [ "${LABELANL}" -le "${LABELFCT}" ]; do

        oma_bcges=$(grep  "${LABELANL}" ${GStatOut}/temporal/rad/omfb_${instr}_${sat}_ges.txt  | awk '{print $'${num}'}' | sort -u)
        oma_nbcges=$(grep "${LABELANL}" ${GStatOut}/temporal/rad/omfnb_${instr}_${sat}_ges.txt | awk '{print $'${num}'}' | sort -u)
        oma_bcanl=$(grep  "${LABELANL}" ${GStatOut}/temporal/rad/omfb_${instr}_${sat}_anl.txt  | awk '{print $'${num}'}' | sort -u)
        oma_nbcanl=$(grep "${LABELANL}" ${GStatOut}/temporal/rad/omfnb_${instr}_${sat}_anl.txt | awk '{print $'${num}'}' | sort -u)

        if [ 'x'${oma_bcges} = "x"  ]; then oma_bcges=0.0  ; fi
        if [ 'x'${oma_nbcges} = "x" ]; then oma_nbcges=0.0 ; fi
        if [ 'x'${oma_bcanl} = "x"  ]; then oma_bcanl=0.0  ; fi
        if [ 'x'${oma_nbcanl} = "x" ]; then oma_nbcanl=0.0 ; fi

        cat << EOF > ${GStatOut}/temporal/rad/fma_${rchan}_${LABELANL}.cont
         ${LABELANL}   ${oma_bcges}    ${oma_nbcges}  ${oma_bcanl}   ${oma_nbcanl}
EOF

        LABELANL=`${GStatBin}/inctime ${LABELANL} +6hr %y4%m2%d2%h2`

       done

       cat ${GStatOut}/temporal/rad/fma_${rchan}*cont > ${GStatOut}/temporal/rad/fma_temporal_${rchan}.txt

       cat ${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt | sort -u > ${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt.tmp
       mv ${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt.tmp ${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt

       min=$(awk '{for(x='$num';x<='$num';x++)a[++y]=$x}END{c=asort(a);print a[1]}' ${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt)
       max=$(awk '{for(x='$num';x<='$num';x++)a[++y]=$x}END{c=asort(a);print a[c]}' ${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt)

       yrg=0
       if [ "$min" = "$max" ]; then
        min=$( echo "$min - 1" | bc -l )
        max=$( echo "$max + 1" | bc -l )
        yrg=1
       fi

       gnuplot << EOF 
       reset

       set xtics format ""
       set xdata time
       set timefmt "%Y%m%d%H"
       set format x "%d %b\n%H Z"
       set encoding utf8
       set term postscript enhanced color
       set output "${outeps}"
       set multiplot layout 3, 1 
       set tmargin 2
       set bmargin 3
       set lmargin 10
       set rmargin 20
       set object 2 rect from graph 0, graph 0 to graph 1, graph 1 behind
       set object 2 rect fc rgb "#FFF9D9" fillstyle solid 1.0
       set style fill pattern 2 bo 1
       set xrange ["${DataInicial}":"${DataFinal}"]
       set xtics "${DataInicial}",${Inclx},"${DataFinal}"
       set style data linespoints


       if ( $yrg == 1 ) set yrange [$min:$max]
       
       set ylabe "Número de Obs."
       set title "Número Total de Observacões Assimiladas - Satélite/Instrumento: ${sat}/${instr} - Canal: ${rchan}"
       set key box reverse right outside title "Legenda"
       plot '${GStatOut}/temporal/rad/assim_${instr}_${sat}_${arq}.txt' using 1:${num} w l lw 5 lc rgb"red" title "Assimiladas"
        
       set ylabe "TB [K]"
       set title "Média Global de Observacão-First Guess "
       set key box reverse right outside title "Legenda"

       plot '${GStatOut}/temporal/rad/omfb_${instr}_${sat}_ges.txt' using 1:${num} w l lw 5 lc rgb"red" title " OMF com BC",\
            '${GStatOut}/temporal/rad/omfnb_${instr}_${sat}_ges.txt' using 1:${num} w l lw 5 lc rgb"blue" title " OMF sem BC"

       set ylabe "TB [K]"
       set title "Média Global de Observacão-Análise "
       set key box reverse right outside title "Legenda"
       plot '${GStatOut}/temporal/rad/omfb_${instr}_${sat}_anl.txt' using 1:${num} w l lw 5 lc rgb"red" title " OMA com BC",\
            '${GStatOut}/temporal/rad/omfnb_${instr}_${sat}_anl.txt' using 1:${num} w l lw 5 lc rgb"blue" title " OMA sem BC"

       exit
EOF

       fileouteps=${GStatFig}/temporal/rad/fma_${rchan}_${instr}_${sat}.eps
       fileoutpng=${GStatFig}/temporal/rad/fma_${rchan}_${instr}_${sat}.png
       fileinput=${GStatOut}/temporal/rad/fma_temporal_${rchan}.txt

       min=$(awk '{for(x=2;x<=NF;x++)a[++y]=$x}END{c=asort(a);print a[1]}' $fileinput)
       max=$(awk '{for(x=2;x<=NF;x++)a[++y]=$x}END{c=asort(a);print a[c]}' $fileinput)
       
       yrg=0
       if [ "$min" = "$max" ]; then
        min=$( echo "$min - 1" | bc -l )
        max=$( echo "$max + 1" | bc -l )
        yrg=1
       fi
        
       cat $fileinput | sort -u > ${fileinput}.tmp
       mv ${fileinput}.tmp $fileinput

       gnuplot << EOF 
       
       reset
       set xtics format ""
       set xdata time
       set timefmt "%Y%m%d%H"
       set format x "%d %b\n%H Z"
       set encoding utf8
       set term postscript enhanced color
       set output "${fileouteps}"
       set object 2 rect from graph 0, graph 0 to graph 1, graph 1 behind
       set object 2 rect fc rgb "#FFF9D9" fillstyle solid 1.0
       set style fill pattern 2 bo 1
       set xrange ["${DataInicial}":"${DataFinal}"]
       set xtics "${DataInicial}",${Inclx},"${DataFinal}"
       set title "AMF - Satélite/Instrumento: ${sat}/${instr} - Canal: ${rchan}"
       set key box reverse below title "Legenda"
       set xlabel "Data" 
       set ylabel "Temperatura de Brilho [k]" 
       
       if ( $yrg == 1 ) set yrange [$min:$max]
       
       plot "${fileinput}" using 1:(\$4-\$2) w l lw 5 lc rgb"red" title " AMF com BC",\
            "${fileinput}" using 1:(\$5-\$3) w l lw 5 lc rgb"blue" title " AMF sem BC"
       exit
EOF

       convert -rotate 90 -density 100 -flatten ${outeps}     ${outpng}
       convert -rotate 90 -density 100 -flatten ${fileouteps} ${fileoutpng}
      
      else

       echo
       echo " Canal " ${rchan} " nao e' utilizado " ${instr} "  " ${sat} "  " ${arq}
       echo
          
     fi

    done
    
   done
   
   cd ${GStatOut}/temporal/rad
   
   LABELANL=${DataInicial}
   while [ "${LABELANL}" -le "${LABELFCT}" ]; do
   
    YYYYMM=$(   echo ${LABELANL} | cut -c 1-6)
    YYYYDDANL=$(echo ${LABELANL} | cut -c 1-8)
    HHANL=$(    echo ${LABELANL} | cut -c 9-10)
    DDHH=$(     echo ${LABELANL} | cut -c 7-10)

    # AMSU-A
    if test -s cont_amsua_aqua_ges.txt     ; then amsua_aqua=`grep   "${LABELANL}" cont_amsua_aqua_ges.txt    | awk '{print $6}' | sort -u` ; else  amsua_aqua=0.0   ; fi
    if test -s cont_amsua_metopa_ges.txt   ; then amsua_metopa=`grep "${LABELANL}" cont_amsua_metop-a_ges.txt | awk '{print $6}' | sort -u` ; else  amsua_metopa=0.0 ; fi
    if test -s cont_amsua_n15_ges.txt      ; then amsua_n15=`grep    "${LABELANL}" cont_amsua_n15_ges.txt     | awk '{print $6}' | sort -u` ; else  amsua_n15=0.0    ; fi
    if test -s cont_amsua_n18_ges.txt      ; then amsua_n18=`grep    "${LABELANL}" cont_amsua_n18_ges.txt     | awk '{print $6}' | sort -u` ; else  amsua_n18=0.0    ; fi
    if test -s cont_amsua_n19_ges.txt      ; then amsua_n19=`grep    "${LABELANL}" cont_amsua_n19_ges.txt     | awk '{print $6}' | sort -u` ; else  amsua_n19=0.0    ; fi
    
    # HIRS-4
    if test -s cont_hirs4_metop-a_ges.txt  ; then hirs4_metopa=`grep "${LABELANL}" cont_hirs4_metop-a_ges.txt | awk '{print $6}' | sort -u` ; else  hirs4_metopa=0.0 ; fi
    if test -s cont_hirs4_n18_ges.txt      ; then hirs4_n18=`   grep "${LABELANL}" cont_hirs4_n18_ges.txt     | awk '{print $6}' | sort -u` ; else  hirs4_n18=0.0    ; fi
    if test -s cont_hirs4_n19_ges.txt      ; then hirs4_n19=`   grep "${LABELANL}" cont_hirs4_n19_ges.txt     | awk '{print $6}' | sort -u` ; else  hirs4_n19=0.0    ; fi
    
    # MHS
    if test -s cont_mhs_metop-a_ges.txt    ; then mhs_metopa=`grep "${LABELANL}" cont_mhs_metop-a_ges.txt | awk '{print $6}' | sort -u`     ; else  mhs_metopa=0.0   ; fi
    if test -s cont_mhs_n18_ges.txt        ; then mhs_n18=`   grep "${LABELANL}" cont_mhs_n18_ges.txt     | awk '{print $6}' | sort -u`     ; else  mhs_n18=0.0      ; fi
    if test -s cont_mhs_n19_ges.txt        ; then mhs_n19=`   grep "${LABELANL}" cont_mhs_n19_ges.txt     | awk '{print $6}' | sort -u`     ; else  mhs_n19=0.0      ; fi
    
    # AIRS
    if test -s cont_airs_aqua_ges.txt      ; then airs_aqua=`grep "${LABELANL}" cont_airs_aqua_ges.txt | awk '{print $6}' | sort -u`        ; else  airs_aqua=0.0    ; fi
    
    # IASI
    if test -s cont_iasi_metop-a_ges.txt   ; then iasi_metopa=`grep "${LABELANL}" cont_iasi_metop-a_ges.txt | awk '{print $6}' | sort -u`   ; else  iasi_metopa=0.0  ; fi

    # AMSU-A
    if [ 'x'$amsua_aqua   = 'x' ]; then amsua_aqua=0.0   ; fi
    if [ 'x'$amsua_metopa = 'x' ]; then amsua_metopa=0.0 ; fi
    if [ 'x'$amsua_n15    = 'x' ]; then amsua_n15=0.0    ; fi
    if [ 'x'$amsua_n18    = 'x' ]; then amsua_n18=0.0    ; fi
    if [ 'x'$amsua_n19    = 'x' ]; then amsua_n19=0.0    ; fi
    
    # HIRS-4
    if [ 'x'$hirs4_metopa = 'x' ]; then hirs4_metopa=0.0 ; fi
    if [ 'x'$hirs4_n18    = 'x' ]; then hirs4_n18=0.0    ; fi
    if [ 'x'$hirs4_n19    = 'x' ]; then hirs4_n19=0.0    ; fi
    
    # MHS
    if [ 'x'$mhs_metopa   = 'x' ]; then mhs_metopa=0.0   ; fi
    if [ 'x'$mhs_n18      = 'x' ]; then mhs_n18=0.0      ; fi
    if [ 'x'$mhs_n19      = 'x' ]; then mhs_n19=0.0      ; fi
    
    # AIRS
    if [ 'x'$airs_aqua    = 'x' ]; then airs_aqua=0.0    ; fi
    
    # IASI
    if [ 'x'$iasi_metopa  = 'x' ]; then  iasi_metopa=0.0  ; fi




    cat<< EOF > ${GStatOut}/temporal/rad/cptec.diag_obs_ges_${LABELANL}.cont
    ${LABELANL} ${amsua_aqua} ${amsua_metopa}  ${amsua_n15} ${amsua_n18} ${amsua_n19} ${hirs4_metopa} ${hirs4_n19} ${mhs_metopa} ${mhs_n18} ${airs_aqua} ${iasi_metopa}
EOF

    LABELANL=`${GStatBin}/inctime ${LABELANL} +6hr %y4%m2%d2%h2`

   done

   cat ${GStatOut}/temporal/rad/cptec.diag_obs_ges*.cont > ${GStatOut}/temporal/rad/acumulado_ges_satelites.txt
   
   filein=${GStatOut}/temporal/rad/acumulado_ges_satelites.txt
   epsfile=${GStatFig}/temporal/rad/conttemp.eps
   pngfile=${GStatFig}/temporal/rad/conttemp.png

   cat $filein | sort -u > ${filein}.tmp
   mv ${filein}.tmp $filein

   gnuplot << EOF 

   reset
   set xdata time
   set timefmt "%Y%m%d%H"
   set format x "%d %b\n%H Z"
   set xlabel "Data" 
   set ylabel "Número de Observacões" 
   set encoding utf8
   set term postscript enhanced color
   set output "${epsfile}"
   set object 2 rect from graph 0, graph 0 to graph 1, graph 1 behind
   set object 2 rect fc rgb "#FFF9D9" fillstyle solid 1.0
   set style fill pattern 2 bo 1
   set xrange ["${DataInicial}":"${DataFinal}"]
   set xtics "${DataInicial}",${Inclx},"${DataFinal}"
   set style data linespoints
   set title "Número total de dados de radiância assimilados pelo GSI"
   set key box reverse below title "Legenda"

   plot '${filein}' using 1:(\$2+\$3+\$4+\$5+\$6) w l lw 5 lc rgb"red" title "AMSU-A",\
        '${filein}' using 1:(\$7+\$8) w l lw 5 lc rgb"blue" title "HIRS4",\
        '${filein}' using 1:(\$9+\$10) w l lw 5 lc rgb"purple" title "MHS",\
        '${filein}' using 1:(\$11) w l lw 5 lc rgb"black" title "AIRS",\
        '${filein}' using 1:(\$12) w l lw 5 lc rgb"green" title "IASI"

   exit
EOF

   convert -rotate 90 -density 100 -flatten ${epsfile} ${pngfile}

   rm ${GStatFig}/temporal/rad/*.eps
   rm ${GStatOut}/temporal/rad/cptec.diag_obs_ges*.cont

 fi

done



