#!/bin/bash
## e.g. # lmdz_check.bash -1:6:3:26 wrfout_d01_1979-12-01_00:00:00 /home/lluis/PY /home/lluis/etudes/WRF_LMDZ/WaquaL/LaTeX/NPv31_hgardfou/figs 0 None 0 
## e.g. # lmdz_check.bash -1:9:9:4 iphysiq1_time_step150/wrfout_d01_check.nc /home/lfita/PY iphysiq1_time_step150/check 1 None 0
if test $1 = '-h'; then
  echo "**********************************"
  echo "***   Shell script to analyze  ***"
  echo "*** LMDZ runs at a given point ***"
  echo "**********************************"
  echo "lmdz_check.bash [point](as Time:z:y:x, -1 last value) [infile] [pyhome] \
    (place with pthon scripts) [ofold](output folder) [getvals](0, no; 1: yes, \
    whether to compute intermediary files) [mapv](None, no; map characteristics:[proj],[res])"
  echo "  [point]: as Time:z:y:x, (-1 for last value, python style (0 based))"
  echo "  [infile]: file to use"
  echo "  [pyhome]: place with pthon scripts"
  echo "  [ofold]: output folder"
  echo "  [getvals]: 0, no; 1: yes, whether to compute intermediary files"
  echo "  [mapv]: None, no; map characteristics:[proj],[res]"
  echo "  [visualize]: 0, no; 1: yes, whether to visualize results"
else

function vals_textab() {
# Function to provide an LaTeX like table from a series of ':' separated values
#   values= list of values
#   ncols= number of columns
#   labels= which labels
#     'inum': integer ascending numbers
#     'labs@'[labels]: as a list of given ':' separated labels
#   caption= text as caption '*' for spaces
#   tablabel= text as label of the table

# Output in `vals_textab.tex' as:
#   A LaTeX table as \verb+[ilabel]:+ & [ivalue] & ... & [Ncol]
  errmsg='ERROR -- error -- ERROR -- error'
  fname='vals_textab'

  values=$1
  ncols=$2
  labels=$3
  caption=$4
  tablabel=$5

  vals=`echo ${values} | tr ':' ' '`
  cap=`echo ${caption} | tr '*' ' '`

  Nvals=`echo ${vals} | wc -w | awk '{print $1}'`

  ofile='vals_textab.tex'

  icol=1
  tabfmt=''
  while test ${icol} -le ${ncols}; do
    tabfmt=${tabfmt}'lc'
    icol=`expr ${icol} + 1`
  done

  labk=${labels:0:4}
  case ${labk} in
    'inum')
      in=1
      while test ${in} -le ${Nvals}; do
        labvals=${labvals}${in}':'
        in=`expr ${in} + 1`
      done
    ;;
    'labs')
      labvals=`echo ${labels} | tr '@' ' ' | awk '{print $2}'`
    ;;
    *)
      echo ${errmsg}
      echo "  "${fname}": kind of labels '"${labk}"' not ready!!"
      exit
    ;;
  esac

  cat << EOF > ${ofile}
\\begin{table}
\\caption{${cap}}
\\label{tab:${tablabel}}
\\begin{center}
\\begin{tabular}{${tabfmt}}
EOF
  Nmultivalscols=`expr ${Nvals} % ${ncols}`
  if test ${Nmultivalscols} -ne 0; then
    Nvals0=`expr ${Nvals} - ${Nmultivalscols}`
  else
    Nvals0=${Nvals}
  fi

  ival=1
  line=''

  while test ${ival} -le ${Nvals}; do
    modival=`expr ${ival} % ${ncols}`
    vali=`echo ${values} | tr ':' '\n' | head -n ${ival} | tail -n 1`
    labi=`echo ${labvals} | tr ':' '\n' | head -n ${ival} | tail -n 1`

    if test ${modival} -eq 0; then
      line=${line}'\verb+'${labi}':+ & '${vali}' \\ '
      echo ${line} >> ${ofile}
      line=''
    else
      line=${line}'\verb+'${labi}':+ & '${vali}' & '
    fi

    ival=`expr ${ival} + 1`
  done

  if test ${Nmultivalscols} -ne 0; then
    Nemptycols=`expr ${ncols} - ${Nmultivalscols}`
    if test ${Nemptycols} -ne 0; then
      iecol=1
      while test ${iecol} -lt ${Nemptycols}; do
        line=${line}' & & '
        iecol=`expr ${iecol} + 1`
      done
    fi
    line=${line}' & \\ '
    echo ${line} >> ${ofile}
  fi

  cat << EOF >> ${ofile}
\\end{tabular}
\\end{center}
\\end{table}
EOF

  return
}

function to_LaTeX() {
#   Function to transform an ASCII to LaTeX
    asc=$1

# Characters to find ('\' must be de first)
    findchars='\\:_:%:&'

# ASCII chains to substitue with
    substchars='\backslash:\_:\%:\&'

    fchars=`echo ${findchars} | tr ':' ' '`

    foundv=0
    for chv in ${fchars}; do
      found=`expr index ${asc} ${chv}`
      if test ${found} -ne 0; then 
        foundv=1
        break
      fi
    done

    if test ${foundv} -eq 0; then 
      echo ${asc}
      return 
    fi 

    ich=1
    newasc=''

    Lasc=`expr length ${asc}`
    partasc=${asc}
    for chv in ${fchars}; do
      Lpartasc=${Lasc}
      while test ${Lpartasc} -gt 0; do
        found=`expr index ${partasc} ${chv}`
        if test ${found} -ne 0; then
          newpart=`echo ${partasc} | tr ${chv} ' ' | awk '{print $1}'`
          Lnewpart=`expr length ${newpart}`
          Lnewpart1=`expr ${Lnewpart} + 1`
          Lwithoutnewpart=`expr ${Lpartasc} - ${Lnewpart} - 1`
          partasc=${partasc:${Lnewpart1}:${Lwithoutnewpart}}
          newchar=`echo ${substchars} | tr ':' '\n' | head -n ${ich} | tail -n 1`
          newasc=${newasc}${newpart}${newchar}
          Lpartasc=`expr length ${partasc}`
        else
          Lnewpart=`expr length ${newpart}'0'`
          if test ${Lnewpart} -gt 1; then
            newasc=${newasc}${partasc}
          fi
          Lpartasc=-1
          Lnewasc=`expr length ${newasc}'0'`
          if test ${Lnewpart} -eq 1; then
            partasc=${asc}
          else
            partasc=${newasc}
          fi
          newpart=''
        fi
      done
      Lpartasc=`expr length ${newasc}`
      ich=`expr ${ich} + 1`
    done
    echo ${newasc}

    return
}

####### ###### ##### #### ### ## #

  rootsh=`pwd`
  errmsg='ERROR -- error -- ERROR -- error'
  main='lmdz_check.bash'

  point=$1
  infile=$2
  PYHOME=$3
  ofold=$4
  getvals=$5
  mapv=$6
  vis=$7

# To paint figures
  draw=1

# To generate Hovmoller graph
  dohov=1

# To generate point graph
  dopt=1

# To generate horizontal graph
  dohor=1

# To generate neighbourghood evol graph
  doneig=1

# To generate LaTeX
  dolatex=1

  vartypes='dt:st:sfc'

  dtvariables='AJS:CON:DYN:EVA:LSCST:LSCTH:LSC:PHY:THE:VDF:WAK'
  stvariables='QVAPOR:QCLOUD:LGEOP:LTEMP:LTHETA:LVITU:LVITV:LVITW:LRHUM:LH2O:LPR_CON_I:'
  stvariables=${stvariables}'LPR_CON_L:LPR_LSC_I:LPR_LSC_L:LLWCON:LIWCON:LPTCONV:'
  stvariables=${stvariables}'LVPRECIP:LRNEB:LRNEBCON:LRNEBLS:LTKE:LWAKE_OMG:'
  stvariables=${stvariables}'LWAKE_DELTAQ:LWAKE_DELTAT:LDTSW0:LDTLWR:'
  stvariables=${stvariables}'LQ_TH:LLAMBDA_TH:LTNT:LTNTC:LTNTR:LTNTSCPBL'
  sfcvariables='LSNOW:LEVAP:LPRECIP:LPLUC:LPLUL:LRH2M:T2:LRH2M:U10:V10:LPBASE:'
  sfcvariables=${sfcvariables}'LFBASE:LCLDL:LCLDM:LPLCL:LPLFC:'
  sfcvariables=${sfcvariables}'LCLDH:PSFC:LS_PBLH:LS_PBLT:LS_LCL:LZMAX_TH:'
  sfcvariables=${sfcvariables}'LWAKE_H:LWAKE_S'

  kvalues='2dh:hovz:tevol'

  filetexn='lmdz_check.tex'
  otex=${ofold}'/'${filetexn}
####### ###### ##### #### ### ## #
# Levels to interpolate
  plevels='100000.,97500.,95000.,92500.,90000.,85000.,80000.,75000.,70000.,'
  plevels=${plevels}'65000.,60000.,55000.,50000.,45000.,40000.,35000.,30000.,'
  plevels=${plevels}'25000.,20000.,15000.,10000.,5000.,2500.,1000.,'
  plevels=${plevels}'500.,250.'

  tval=`echo ${point} | tr ':' ' ' | awk '{print $1}'`
  zval=`echo ${point} | tr ':' ' ' | awk '{print $2}'`
  yval=`echo ${point} | tr ':' ' ' | awk '{print $3}'`
  xval=`echo ${point} | tr ':' ' ' | awk '{print $4}'`

  infileS=`echo ${infile} | tr '.' ' ' | awk '{print $1}'`

#######    #######
## MAIN
    #######
  mkdir -p ${ofold}

  vtypes=`echo ${vartypes} | tr ':' ' '`
  kvals=`echo ${kvalues} | tr ':' ' '`

# All variables
  allvars0=''

  for vt in ${vtypes}; do
    case $vt in 
      'dt' )
        var0s=`echo ${dtvariables} | tr ':' ' '`
        for var0 in $var0s; do
          allvars0=${allvars0}'LDQ'${var0}',LDT'${var0}','
          if test ${var0} = 'CON' || test ${var0} = 'DYN' || test ${var0} = 'VDF'; then
            allvars0=${allvars0}'LDU'${var0}',LDV'${var0}','
          fi
        done
      ;;
      'sfc' )
        var0s=`echo ${sfcvariables} | tr ':' ' '`
        for var0 in $var0s; do
          allvars0=${allvars0}${var0}','
        done
      ;;
      'st' )
        var0s=`echo ${stvariables} | tr ':' ' '`
        for var0 in $var0s; do
          allvars0=${allvars0}${var0}','
        done
      ;;
    esac
  done
  Lallvars0=`expr length ${allvars0}`
  Lallvars01=`expr ${Lallvars0} - 1`
  allvars=${allvars0:0:${Lallvars01}}
  echo "all vars: '"${allvars}"'"

  if test ${getvals} -eq 1; then
    for kvn in ${kvals}; do
      echo "  kind of values: "${kvn}
      case $kvn in
        '2dh')
          pyvls='Time,'${tval}','${tval}',1@bottom_top,'${zval}','${zval}',1'
        ;;
        'hovz')
          pyvls='south_north,'${yval}','${yval}',1@west_east,'${xval}','${xval}',1'
        ;;
        'tevol')
          pyvls='bottom_top,'${zval}','${zval}',1@south_north,'${yval}','${yval}
          pyvls=${pyvls}',1@west_east,'${xval}','${xval}',1'
        ;;
      esac
      ofile=`python ${PYHOME}/nc_var.py -o DataSetSection_multidims -f ${infile}     \
        -S ${pyvls} | grep succesfull | awk '{print $6}' | tr '"' ' '`
      if test $? -ne 0; then
        echo ${errmsg}
        echo "  "${main}": python failed!"
        echo "    python "${HOME}/nc_var.py -o DataSetSection_multidims              \
          -f ${infile} -S ${pyvls}
        exit
      fi
      case $kvn in
        '2dh')
# Adding CF longitudes and latitudes
          python ${PYHOME}/nc_var.py -f ${ofile} -o WRF_CFlonlat_creation            \
            -S longitude,latitude -v XLONG,XLAT
        ;;
        'tevol')
# Adding CF time
          python ${PYHOME}/nc_var.py -f ${ofile} -o WRF_CFtime_creation              \
            -S 19491201000000,hours -v time
        ;;
        'hovz')
# Adding CF time
          python ${PYHOME}/nc_var.py -f ${ofile} -o WRF_CFtime_creation              \
            -S 19491201000000,hours -v time
# Adding variable dimension from 'bottom_top'
          python ${PYHOME}/nc_var.py -f ${ofile} -o dimVar_creation -S bottom_top
# Vertical interpolation
#          dvals='T:Time,Z:bottom_top,Y:south_north,X:west_east'
#          python ${PYHOME}/vertical_interpolation.py -f ${ofile} -o WRFp             \
#            -i ${plevels} -k 'lin' -v ${allvars} -d ${dvals}                         \
#            -D T:Times,Z:ZNU,Y:XLAT,X:XLONG
#          if test $? -ne 0; then
#            echo ${errormsg}
#            echo "  "${main}": drawing.py fails!"
#            echo python ${PYHOME}/vertical_interpolation.py -f ${ofile} -o WRFp \
#             -i ${plevels} -k 'lin' -v ${allvars} -d ${dvals} \
#             -D T:Times,Z:ZNU,Y:XLAT,X:XLONG
#            exit
#          fi
#          ofilen0=`echo ${ofile} | tr '.' ' ' | awk '{print $1}'`
#          mv vertical_interpolation_WRFp.nc ${ofilen0}_WRFp.nc
        ;;
      esac
    done
  fi

#exit
  if test $draw -eq 1; then
  echo "Drawing..."
  mkdir -p ${ofold}/figs

  for vt in ${vtypes}; do
    echo "variable type: "${vt}
    case $vt in 
      'dt' )
        var0s=`echo ${dtvariables} | tr ':' ' '`
        vars=''
        for var0 in $var0s; do
          vars=${vars}'LDQ'${var0}' LDT'${var0}' '
          if test ${var0} = 'CON' || test ${var0} = 'DYN' || test ${var0} = 'VDF'; then
            vars=${vars}'LDU'${var0}' LDV'${var0}' '
          fi
        done
      ;;
      'sfc' )
        vars=`echo ${sfcvariables} | tr ':' ' '`
      ;;
      'st' )
        vars=`echo ${stvariables} | tr ':' ' '`
      ;;
    esac
    echo ${vars}
    for var in ${vars}; do
      echo "  var: "${var}
      varvals=`python ${PYHOME}/drawing.py -o variable_values -S ${var} | grep all_values`
      if test $? -ne 0; then
        echo "  "${main}": Variable '"${var}"' not defined !!!!"
        exit
      fi
      stdn=`echo ${varvals} | tr ',' ' ' | awk '{print $3}'`
      cbar=`echo ${varvals} | tr ',' ' ' | awk '{print $9}'`
      min=`echo ${varvals} | tr ',' ' ' | awk '{print $5}'`
      max=`echo ${varvals} | tr ',' ' ' | awk '{print $6}'`

      if test $dohov -eq 1 && ! test ${vt} = 'sfc'; then
# Shadded vertical Hovmoller diagrams
      filetail='south_north_B'${yval}'-E'${yval}'-I1_west_east_B'${xval}
      filetail=${filetail}'-E'${xval}'-I1'

# Let's make it easy
      if test ${vt} = 'st';then
        min='Saroundminmax@0.97'
        max='Saroundminmax@0.97'
      else
        min='Spercentile@1'
        max='Spercentile@1'
      fi

      if test ${var} = 'LDQEVA' || test ${var} = 'LDTEVA' || test ${var} = 'LH2O';then
        min='Saroundminmax@0.75'
        max='Saroundminmax@0.75'
        if test ${var} = 'LDQEVA'; then
          cbar='Reds'
        else
          cbar='Blues'
        fi
      fi

      echo "    min: "${min}" max: "${max}

      values=${stdn}':Time|-1,bottom_top|-1:varDIMbottom_top:time:'${cbar}':'
      values=${values}${min}','${max}':vertical|temporal|evolution|:pdf:'
      values=${values}'transpose:time|hours!since!1949-12-01|exct,12,h|'
      values=${values}'$%d^{%H}$|date!($[DD]^{[HH]}$)|x:True'

      python ${PYHOME}/drawing.py -o draw_2D_shad_time -f ${infileS}_${filetail}.nc   \
        -S ${values} -v ${var},time
      if test $? -ne 0; then
        echo ${errormsg}
        echo "  "${main}": drawing.py fails!"
        echo python ${PYHOME}/drawing.py -o draw_2D_shad_time \
          -f ${infileS}_${filetail}.nc -S ${values} -v ${var},time
        exit
      else
        mv 2Dfields_shadow_time.pdf ${ofold}/figs/${stdn}_Hovmoller.pdf
        if test $vis -eq 1; then evince ${ofold}/figs/${stdn}_Hovmoller.pdf & fi
      fi
      fi
      
      if test $dopt -eq 1; then
# Point evolution
      filetail='bottom_top_B'${zval}'-E'${zval}'-I1_south_north_B'${yval}'-E'
      filetail=${filetail}${yval}'-I1_west_east_B'${xval}'-E'${xval}'-I1'

      values=${stdn}':time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at'
      values=${values}'|(x='${xval}',y='${yval}',z='${zval}'):1:pdf'
      python ${PYHOME}/drawing.py -o draw_timeSeries -f ${infileS}_${filetail}.nc     \
        -S ${values} -v ${var},time
      if test $? -ne 0; then
        echo ${errormsg}
        echo "  "${main}": drawing.py fails!"
        echo python ${PYHOME}/drawing.py -o draw_timeSeries \
          -f ${infileS}_${filetail}.nc -S ${values} -v ${var},time
        exit
      else
        mv TimeSeries_${stdn}.pdf ${ofold}/figs/${stdn}_TimeSeries.pdf
        if test $vis -eq 1; then evince ${ofold}/figs/${stdn}_TimeSeries.pdf & fi
      fi
      fi

      if test $dohor -eq 1; then
# Horizontal plot
      filetail='Time_B'${tval}'-E'${tval}'-I1_bottom_top_B'${zval}
      filetail=${filetail}'-E'${zval}'-I1'

      min=`echo ${varvals} | tr ',' ' ' | awk '{print $5}'`
      max=`echo ${varvals} | tr ',' ' ' | awk '{print $6}'`

      if test ${vt} = 'dt'; then
        min='Spercentile@1'
        max='Spercentile@1'
      elif test ${vt} = 'st'; then
        min='Saroundminmax@0.97'
        max='Saroundminmax@0.97'
      fi

      if test ${var} = 'LRH2M'; then
        max='100.'
      elif test ${var} = 'T2'; then
        min='270'
        max='300.'
      fi

      echo "    min: "${min}" max: "${max}

      values=${stdn}':south_north|-1,west_east|-1:longitude:latitude:'${cbar}':'
      values=${values}${min}','${max}':horizontal|section|at|(t='${tval}
      values=${values}',z='${zval}'):pdf:None:'${mapv}':True'

      python ${PYHOME}/drawing.py -o draw_2D_shad -f ${infileS}_${filetail}.nc        \
        -S ${values} -v ${var}
      if test $? -ne 0; then
        echo ${errormsg}
        echo "  "${main}": drawing.py fails!"
        echo python ${PYHOME}/drawing.py -o draw_2D_shad \
          -f ${infileS}_${filetail}.nc -S ${values} -v ${var}
        exit
      else
        mv 2Dfields_shadow.pdf ${ofold}/figs/${stdn}_hor.pdf
        if test $vis -eq 1; then evince ${ofold}/figs/${stdn}_hor.pdf & fi
      fi
      fi

      if test $doneig -eq 1; then
# Neighbourghood plot
      filetail=''

      min=`echo ${varvals} | tr ',' ' ' | awk '{print $5}'`
      max=`echo ${varvals} | tr ',' ' ' | awk '{print $6}'`

      if test ${vt} = 'dt'; then
        min='Spercentile@1'
        max='Spercentile@1'
      elif test ${vt} = 'st'; then
        min='Saroundminmax@0.97'
        max='Saroundminmax@0.97'
      fi

      if test ${var} = 'LRH2M'; then
        max='100.'
      elif test ${var} = 'T2'; then
        min='270'
        max='300.'
      fi

      echo "    min: "${min}" max: "${max}

      values=${stdn}':Time|-1|Times,bottom_top|'${zval}'|ZNU,south_north|'${yval}
      values=${values}'|XLAT,west_east|'${xval}'|XLONG:south_north,west_east:5:auto:'
#      values=${values}'time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,2,h|exct,1,d:'
#      values=${values}'$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution:'
      values=${values}'time|([MI]),time|($[DD]^{[HH]-[MI]}$):exct,2,i|exct,30,i:'
      values=${values}'$%M$,$%d^{%H-%M}$:5|pts|neighbourghood|temporal|evolution:'
      values=${values}${min}','${max}':'${cbar}':pdf:False'

      python ${PYHOME}/drawing.py -o draw_Neighbourghood_evol -f ${infile}           \
        -S ${values} -v ${var}
      if test $? -ne 0; then
        echo ${errormsg}
        echo "  "${main}": drawing.py fails!"
        echo python ${PYHOME}/drawing.py -o draw_Neighbourghood_evol \
          -f ${infile} -S ${values} -v ${var}
        exit
      else
        mv Neighbourghood_evol.pdf ${ofold}/figs/${stdn}_Neighbourghood_evol.pdf
        if test $vis -eq 1; then evince ${ofold}/figs/${stdn}_Neighbourghood_evol.pdf & fi
      fi
      fi

#      exit
    done
  done
  fi

# LaTeX file generation
##
#
  if test $dolatex -eq 1; then
  echo "  LaTeX file '"${otex}"' generation..."

# Vertical pressure values
  dvals='Time:-9|bottom_top:-1|south_north:'${yval}'|west_east:'${xval}
  pvals=`python ${PYHOME}/nc_var.py -o varout -f ${infile} -S ${dvals} -v LPRES | awk '{print $2}'`
  presvals=`echo ${pvals} | tr ' ' ':'`
  vals_textab ${presvals} 3 inum 'level*pressure*(Pa)*equivalencies' pres_vals

  if test ${tval} -eq -1; then tvalS='last'; fi

  cat << EOF > ${otex}
\\documentclass{article}
\\usepackage{graphicx}
\\usepackage[colorlinks=true,urlcolor=blue]{hyperref}

\\textwidth=18cm
\\textheight=23cm
\\oddsidemargin=-1cm
\\evensidemargin=-1cm
\\topmargin=-1cm

\\begin{document}

\\title{checking LMDZ at time=${tval}, z=${zval}, y=${yval}, x=${xval}}
\\author{}

\\maketitle

\\listoffigures
\\newpage

EOF
  cat vals_textab.tex >> ${otex}

  cat << EOF >> ${otex}

\\clearpage

EOF

  for vt in ${vtypes}; do
    echo "variable type: "${vt}
    case $vt in 
      'dt' )
        vars=`echo ${dtvariables} | tr ':' ' '`
        ivar=1
        for var in ${vars}; do
          varL=`to_LaTeX ${var}`
          varvals=`python ${PYHOME}/drawing.py -o variable_values -S LDQ${var} \
            | grep all_values`
#          varn=`echo ${varvals} | tr ',' ' ' | awk '{print $3}'`
          varn=`echo ${var} | tr '[:upper:]' '[:lower:]'`
          ln=`echo ${varvals} | tr ',' ' ' | awk '{print $7}'`
          echo "    var: "${varn}

          cat << EOF >> ${otex}
% d[q/t]_${varn}
%%

\\begin{figure}
\\begin{center}
\\begin{tabular}{cc}
\\includegraphics[height=0.2\\textheight]{figs/dq${varn}_hor}
&
\\includegraphics[height=0.2\\textheight]{figs/dt${varn}_hor}
\\\\
\\includegraphics[height=0.2\\textheight]{figs/dq${varn}_Hovmoller}
&
\\includegraphics[height=0.2\\textheight]{figs/dt${varn}_Hovmoller}
\\\\
\\includegraphics[height=0.2\\textheight]{figs/dq${varn}_TimeSeries}
&
\\includegraphics[height=0.2\\textheight]{figs/dt${varn}_TimeSeries}
\\\\
\\includegraphics[height=0.2\\textheight]{figs/dq${varn}_Neighbourghood_evol}
&
\\includegraphics[height=0.2\\textheight]{figs/dt${varn}_Neighbourghood_evol}
\\end{tabular}
EOF
          if test ${ivar} -eq 1; then
            firstvar=${varn}
            caption='\caption{Instantaneaous value at time='${tvalS}', z='${zval}
            caption=${caption}' level of humidity tendency due to '${varn}' ['${varL}'] (top left)'
            caption=${caption}', thermal tendency (top right), temporal evolution of '
            caption=${caption}'the vertical profile at yval='${yval}', xval='${xval}
            caption=${caption}'humidity tendency (2nd row left), thermal tendency '
            caption=${caption}'(2nd row right), temporal evolution at the given point'
            caption=${caption}' (3rd row), evolution of a box of 5x5 centered on the '
            caption=${caption}'point (bottom)}'
          else
            caption='\caption{As in figure \ref{fig:d_qt_'${firstvar}'}, but for '
            caption=${caption}${varn}' ['${varL}']}'
          fi
          cat << EOF >> ${otex}
${caption}
\\label{fig:d_qt_${varn}}
\\end{center}
\\end{figure}
\\clearpage
EOF
# LD[U/V]
##
          if test ${var} = 'CON' || test ${var} = 'DYN' || test ${var} = 'VDF'; then
            varvals=`python ${PYHOME}/drawing.py -o variable_values -S LDU${var} \
              | grep all_values`
#          varn=`echo ${varvals} | tr ',' ' ' | awk '{print $3}'`
            varn=`echo ${var} | tr '[:upper:]' '[:lower:]'`
            ln=`echo ${varvals} | tr ',' ' ' | awk '{print $7}'`
            echo "    var: "${varn}

            cat << EOF >> ${otex}
% d[u/v]_${varn}
%%

\\begin{figure}
\\begin{center}
\\begin{tabular}{cc}
\\includegraphics[height=0.2\\textheight]{figs/du${varn}_hor}
&
\\includegraphics[height=0.2\\textheight]{figs/dv${varn}_hor}
\\\\
\\includegraphics[height=0.2\\textheight]{figs/du${varn}_Hovmoller}
&
\\includegraphics[height=0.2\\textheight]{figs/dv${varn}_Hovmoller}
\\\\
\\includegraphics[height=0.2\\textheight]{figs/du${varn}_TimeSeries}
&
\\includegraphics[height=0.2\\textheight]{figs/dv${varn}_TimeSeries}
\\\\
\\includegraphics[height=0.2\\textheight]{figs/du${varn}_Neighbourghood_evol}
&
\\includegraphics[height=0.2\\textheight]{figs/dv${varn}_Neighbourghood_evol}
\\end{tabular}
EOF
            caption='\caption{As in figure \ref{fig:d_qt_'${firstvar}'}, but for '
            caption=${caption}${varn}'[ '${varL}']}'
            cat << EOF >> ${otex}
${caption}
\\label{fig:d_qu_${varn}}
\\end{center}
\\end{figure}
\\clearpage
EOF
          fi
          ivar=`expr ${ivar} + 1`
        done
cat << EOF >> ${otex}
\\clearpage
EOF
      ;;
      'sfc' )
        vars=`echo ${sfcvariables} | tr ':' ' '`
        ivar=1
        for var in ${vars}; do
          varL=`to_LaTeX ${var}`
          varvals=`python ${PYHOME}/drawing.py -o variable_values -S ${var} \
            | grep all_values`          
          varn=`echo ${varvals} | tr ',' ' ' | awk '{print $3}'`
          echo "    var: "${varn}
          ln=`echo ${varvals} | tr ',' ' ' | awk '{print $7}'`
          cat << EOF >> ${otex}
% ${varn}
%%

\\begin{figure}
\\begin{center}
\\begin{tabular}{ccc}
\\includegraphics[width=0.33\\textwidth]{figs/${varn}_hor}
&
\\includegraphics[width=0.33\\textwidth]{figs/${varn}_TimeSeries}
&
\\includegraphics[width=0.33\\textwidth]{figs/${varn}_Neighbourghood_evol}
\\end{tabular}
EOF
          if test ${ivar} -eq 1; then
            firstvar=${varn}
            caption='\caption{Instantaneaous value at time='${tvalS}' of '${varn}
            caption=${caption}' ['${varL}'] (left), temporal evolution at the given point'
            caption=${caption}' (middle), evolution of a box of 5x5 centered on the '
            caption=${caption}'point (right)}'
          else
             caption='\caption{As in figure \ref{fig:state_'${firstvar}'}, but for '
             caption=${caption}${varn}' ['${varL}']}'
          fi
          cat << EOF >> ${otex}
${caption}
\\label{fig:state_${varn}}
\\end{center}
\\end{figure}
EOF
          modivar=`expr ${ivar} % 3`
          if test ${modivar} -eq 0; then
            echo "\\clearpage" >> ${otex}
          fi
          ivar=`expr ${ivar} + 1`
        done
cat << EOF >> ${otex}
\\clearpage
EOF
      ;;
      'st' )
        vars=`echo ${stvariables} | tr ':' ' '`
        ivar=1
        for var in ${vars}; do
          varL=`to_LaTeX ${var}`
          varvals=`python ${PYHOME}/drawing.py -o variable_values -S ${var} \
            | grep all_values`          
          varn=`echo ${varvals} | tr ',' ' ' | awk '{print $3}'`
          echo "    var: "${varn}
          ln=`echo ${varvals} | tr ',' ' ' | awk '{print $7}'`
          cat << EOF >> ${otex}
% ${varn}
%%

\\begin{figure}
\\begin{center}
\\begin{tabular}{cc}
\\includegraphics[width=0.5\\textwidth]{figs/${varn}_hor}
&
\\includegraphics[width=0.5\\textwidth]{figs/${varn}_Hovmoller}
\\\\
\\includegraphics[width=0.5\\textwidth]{figs/${varn}_TimeSeries}
&
\\includegraphics[width=0.5\\textwidth]{figs/${varn}_Neighbourghood_evol}
\\end{tabular}
EOF
          if test ${ivar} -eq 1; then
            firstvar=${varn}
            caption='\caption{Instantaneaous value at time='${tvalS}', z='${zval}
            caption=${caption}' level of '${varn}' ['${varL}'] (top left), temporal evolution of the'
            caption=${caption}' vertical profile at yval='${yval}', xval='${xval}
            caption=${caption}' (top right), temporal evolution at the given point '
            caption=${caption}' (bottom left), evolution of a box of 5x5 centered on the '
            caption=${caption}'point (bottom right)}'
          else
             caption='\caption{As in figure \ref{fig:state_'${firstvar}'}, but for '
             caption=${caption}${varn}' ['${varL}']}'
          fi
          cat << EOF >> ${otex}
${caption}
\\label{fig:state_${varn}}
\\end{center}
\\end{figure}
\\clearpage
EOF

          ivar=`expr ${ivar} + 1`
        done
cat << EOF >> ${otex}
\\clearpage
EOF
      ;;
    esac
  done

  cat << EOF >> ${otex}
\\end{document}
EOF
  otexn=`echo ${filetexn} | tr '.' ' ' | awk '{print $1}'`
  cd ${ofold}
  pdflatex ${otexn}
  pdflatex ${otexn}
  pdflatex ${otexn}
  pdflatex ${otexn}
  evince ${otexn}.pdf &
  cd ${rootsh}
  fi
fi

