#!/bin/bash -x
#---------------------------------------------------------------------------#
#           Group on Data Assimilation Development -GDAD/CPTEC/INPE         #
#---------------------------------------------------------------------------#
#BOP
#
# !ISCRIPT: total_count_levels.php
#
# !DESCRIPTON: Este script é utilizado para plotar o resultado das
#              contagens de dados processados pelo sistema de
#              assimilação de dado GSI.
#              São produzidos graficos de barra para o total de
#              observações convencionais aceitos, rejeitados e
#              monitorados por nível atmosférico.
#              
#              Para a produção destes graficos são utilizados os
#              seguintes arquivos no formato ascii:
#
#               -------+----------------------------
#               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 informação de 6 variaveis
#              convencionais que são processadas pelo GSI:
#
#               -------+-----------+----------------
#               Indice |  Variavel | Descrição
#               -------+-----------+-----------------
#                 [1]  |    SST    | Temp. da Sup. do Mar
#                 [2]  |     PS    | Pressão em Superfície
#                 [3]  |     PW    | Agua Precipitável
#                 [4]  |     UV    | Vento
#                 [5]  |      T    | Temperatura
#                 [6]  |      Q    | Umidade Específica
#               -------+-----------+-----------------                
#
#              Os resultados são plotados por níveis atmosféricos
#              definidos no programa fortran que pos processa as informações
#              do GSI.
#
#\\
#\\
#
#
# !INTERFACE:
#

StatPlot=${1}
VarPlot=${2}
TimeFile=${3}
DataType=${4} # tipo de informacao: 1 - First Guess, 2 Analise
PathInp=${5}
PathOut=${6}


#
#
# !REVISION HISTORY:
#  17 May 2012 - J. G. de Mattos - Initial Version
#
#
#
# !SEE ALSO:
#   
#   diag_gsi_conf.f90 : programa fortran que pos-processa as
#                       informações de diagnostico do GSI.
#
#EOP
#---------------------------------------------------------------------------//
#BOC

#
# BEGIN: Configuração
#


#
#Nomes Para titulo e Arquivo de Saida
#

stat[1]="tused"
stat[2]="nused"
stat[3]="rejec"
stat[4]="monit"

varname[1]="sst"
varname[2]="ps"
varname[3]="pw"
varname[4]="uv"
varname[5]="t"
varname[6]="q"
varname[7]="gps"


StatTitle[1]="Observacoes Utilizadas"
StatTitle[2]="Observacoes Nao Utilizadas"
StatTitle[3]="Observacoes Rejeitadas"
StatTitle[4]="Observacoes Monitoradas"

NTitle[1]="Temp. da Sup. do Mar"
NTitle[2]="Pressão em Superfície"
NTitle[3]="Água Precipitável"
NTitle[4]="Vento"
NTitle[5]="Temperatura do ar"
NTitle[6]="Umidade Específica"


#
# tipo de informacao
#

type[1]="fgs"
type[2]="anl"

#
# Pegando Ano, Mes, dia e Hora
#

ano=${TimeFile:0:4}
mes=${TimeFile:4:2}
dia=${TimeFile:6:2}
hor=${TimeFile:8:2}

#
# Titulo dos eixos
#

TitleXAxis="Níveis (hPa)"
TitleYAxis="Número de Observações"


#
# Arquivos de entrada/saida
#

FNameInp="${PathInp}/socl.${stat[$StatPlot]}.${TimeFile}.${type[DataType]}.dat"
FNameOut="${PathOut}/socl.${varname[$VarPlot]}_${stat[$StatPlot]}.${TimeFile}.${type[DataType]}"



gnuplot << EOF

reset

#
# estilo do grafico
#

set boxwidth 0.8
set style fill solid 1.0 border -1

#
# Definindo e Identificando os Eixos
#
# Algumas modificacoes sao feitas pois o gnuplot não gera grafico de
# barras na horizotal

###
# eixo X
###

#set xlabel "${TitleXAxis}"

set xtics rotate by 90 right offset graph 0, graph 0.01
set xrange [*:*] reverse
set xlabel " "
set label 1 at graph 0.5, graph -0.11 "${TitleXAxis}" center rotate by 180

###
# eixo y
###

#set ylabel "${TitleYAxis}"
set ytics format ""
#set y2tics format "%.0s.10^%T" rotate by 45 offset graph -0.04, graph -0.02
set y2tics out format "%.0s.10^%T" rotate by 90 offset graph 0, graph -0.04
set y2label "${TitleYAxis}"

#
# Definindo titulo
#

#set title "${NTitle[$VarPlot]}"
set label 2 at graph -0.03, graph 0.5   "${NTitle[$VarPlot]} : ${dia}/${mes}/${ano} ${hor}UTC" center rotate by 90

#
# adicionando background
#

set object 1 rect from graph 0, graph 0 to graph 1, graph 1 back
set object 1 rect fc rgb "#FFF9D9" fillstyle solid 1.0

#
# adicionando grade
#
#EPV
#set grid front lc rgb "black"

#
# removendo a lengenda
#

set key off

#
# cores das linhas
#
set style line  1 lt 1 lc rgb "#AD22CF"
set style line  2 lt 1 lc rgb "#7B00D7"
set style line  3 lt 1 lc rgb "#3E24F1"
set style line  4 lt 1 lc rgb "#106BFF"
set style line  5 lt 1 lc rgb "#00ADED"
set style line  6 lt 1 lc rgb "#00CABC"
set style line  7 lt 1 lc rgb "#00D383"
set style line  8 lt 1 lc rgb "#00DB09"
set style line  9 lt 1 lc rgb "#80E428"
set style line 10 lt 1 lc rgb "#CFDF32"
set style line 11 lt 1 lc rgb "#E6C42F"
set style line 12 lt 1 lc rgb "#EA9D2B" 
set style line 13 lt 1 lc rgb "#F36F2D"  
set style line 14 lt 1 lc rgb "#F93445"  
set style line 15 lt 1 lc rgb "#F00082"


#
# Arquivo de saida
#

set encoding utf8
set term postscript enhanced color
set output "${FNameOut}.eps"

#
# Aspecto do grafico
#

set size 0.6,1

#
# plotando
#

#
# explicacao do comando:
# (\$0):2:(\$0):xtic(1)
#   1   2   3    4
#
# 1 - boxes centered on 0,1,2,3,....
# 2 - data column to be plotted
# 3 - linecolor column.  first box has line color ls 0, second box has linecolor ls 1, etc ...
# 4 - label of xtic




plot "${FNameInp}" using (\$0):$((VarPlot+1)):(\$0):xtic(1) every ::1 w boxes lc variable, \
"${FNameInp}" using (\$0):( \$$((VarPlot+1)) -\$$((VarPlot+1))/2):$((VarPlot+1)) every ::1 with labels  font "Helvetica,10" textcolor rgb "white" rotate by 90

#plot "${FNameInp}" using (\$0):$((VarPlot+1)):(\$0):xtic(1) every ::1 w boxes lc variable, \
#"${FNameInp}" using (\$0):(\$$((VarPlot+1))):$((VarPlot+1)) every ::1 with labels left textcolor rgb "black" rotate by 90


#
# saindo
#

exit

EOF

#
# Convertendo para PNG
#

convert -rotate 180 -density 100 ${FNameOut}.eps -flatten ${FNameOut}.png
#convert -rotate 180 -density 100 ${FNameOut}.eps -flatten tmp.png
#/bin/bash ../bin/autotrim tmp.png ${FNameOut}.png
rm -fr ${FNameOut}.eps 


