# Python to manage plot data in netCDF files.
# From L. Fita work in different places: LMD (France)
# More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot
#
# pyNCplot and its component drawing.py comes with ABSOLUTELY NO WARRANTY. 
# This work is licendes under a Creative Commons 
#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
#
import numpy as np
import os
from netCDF4 import Dataset as NetCDFFile
import nc_var_tools as ncvar
import drawing_tools as drw
import generic_tools as gen
from optparse import OptionParser
import sys
from cStringIO import StringIO

## e.g. # drawing.py -f /media/data2/etudes/WRF_LMDZ/WL_HyMeX/IIphase/medic950116/wlmdza/wrfout/wrfout_d01_1995-01-13_00:00:00 -o create_movie -S 'draw_2D_shad#Time@WRFTimes@10@95@191@1#tas:East_West|-1,North_South|-1,Time|2:longitude:latitude:Summer:270.,300.:tas|at|t=0:pdf:None:None' -v T2
## e.g. # drawing.py -o draw_2D_shad -f wrfout_d01_2001-11-11_00:00:00 -S 'tas:west_east|-1,south_north|-1,Time|2:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:tas|at|2001-11-11|02|UTC:png:None:cyl,l:True' -v T2
## e.g. # drawing.py -o draw_2D_shad_time -f wrfout_d01_2001-11-11_00:00:00 -S 'hurs~west_east|-1,south_north|27,Time|-1~XLONG~WRFtime~auto~Blues,auto,auto~Srange,Srange~tas|evolution|at|south_north=27~png~None~WRFtime|hours!since!1949-12-01|exct,1,h|$%d^{%H}$|date!($[DD]^{[HH]}$)~True' -v Q2
## e.g. # drawing.py -o draw_2D_shad_cont -f wrfout_d01_2001-11-11_00:00:00 -S 'huss,tas:west_east|-1,south_north|-1,Time|2:Time|2:XLONG:XLAT:auto:Blues,auto,auto:fixc,r:%3g:Srange,Srange:260,300,9:huss|&|tas|at|2001-11-11|02|UTC:png:None:cyl,c:True' -v Q2,T2 
## e.g. # drawing.py -o draw_2D_shad_cont_time -f wrfout_d01_2001-11-11_00:00:00 -S 'hfls,tas;west_east|-1,south_north|27,Time|-1;south_north|27;XLONG;WRFtime;auto;BuPu,auto,auto;fixc,y;%3g;Srange,Srange;260,300,9;huss|&|tas|evolution|at|south_north=27;png;None;WRFtime|hours!since!1949-12-01|exct,1,h|$%d^{%H}$|date!($[DD]^{[HH]}$);True' -v LH,T2
## e.g. # drawing.py -o draw_2D_shad_line -f wrfout_d01_2001-11-11_00:00:00,wrfout_d01_2001-11-11_00:00:00 -S 'hus,hgt:west_east|-1,south_north|96,Time|2,bottom_top|-1:XLONG:ZNU:auto:rainbow,auto,horizontal:Srange,Srange:k,0.,4000.,auto,auto,auto,45.:vert.|sec.|hus|at|y=96|on|2001-11-11|02|UTC:png:flip@y:None:True' -v QVAPOR,HGT
## e.g. # drawing.py -o draw_barbs -f wrfout_d01_2001-11-11_00:00:00 -S 'west_east|XLONG|-1,west_east_stag|XLONG|0@239@1,south_north|XLAT|15,bottom_top|ZNU|-1,bottom_top_stag|ZNW|0@39@1,Time|WRFtime|3:10@2,colormap@rainbow,7.:uw,ms-1:XLONG:ZNW:None:auto:flip@y:vertical|cross|section|wind|speed|at|y=15|on|2001-11-10|03|UTC:png:wind_barbs_2001111003_uw:True' -v U,W 
## e.g. # drawing.py -f geo_em.d02.nc -o draw_topo_geogrid -S '0.,1500.:None:2km!domain!centered!at!SIRTA:png:cyl,i:True' 
## e.g. # python ../drawing.py -f ~/etudes/domains/SIRTA/geo_em.d01.nc,/home/lluis/etudes/domains/SIRTA/geo_em.d02.nc -o draw_topo_geogrid_boxes -S '0.,1500.:None:WRF!domain!centered!at!SIRTA:png:cyl,i:d01$_{15k}$,d02$_{3k}$:0|10:True' 
## e.g. # drawing.py -f ~/etudes/domains/MEDCORDEX/geo_em.d01.nc -o draw_2D_shad_cont -S 'height,landmask:Time|0:Time|0:XLONG_M:XLAT_M:terrain:fixc,k:None:0.,3000.:0,1,10:MEDCORDEX height & landmask:pdf:False:lcc,i' -v HGT_M,LANDMASK
## e.g. # $ drawing.py -f WRF/current/hurs_wrfout_tturb_xmean_last.nc,WRF/micro1/hurs_wrfout_tturb_xmean_last.nc,WRF/micro2/hurs_wrfout_tturb_xmean_last.nc,WRF_LMDZ/AR40/hurs_wrfout_tturb_xmean_last.nc,WRF_LMDZ/NPv31/hurs_wrfout_tturb_xmean_last.nc,LMDZ/AR40/hurs_reproj-histins_tturb_xmean_last.nc,LMDZ/NPv31/hurs_reproj-histins_tturb_xmean_last.nc -o draw_lines -S 'lat:x:lat ($degrees\ North$):auto:wcurr,wmp1,wmp2,wlmdza,wlmdzb,lmdza,lmdzb:hurs:all model-experiments meridional hurs$_{[tturb\ xmean\ last]}$:0|auto:None:-:,:2.:2.:all:Nlines_hurs_wrfout_tturb-xmean-last:png:True' -v hursturbmean
## e.g. # drawing.py -o draw_lines_time -f wrfout_d01_2001-11-11_00:00:00_west_east_B20-E20-I1_south_north_B20-E20-I1.nc,wrfout_d01_2001-11-11_00:00:00_west_east_B25-E25-I1_south_north_B25-E25-I1.nc,wrfout_d01_2001-11-11_00:00:00_west_east_B35-E35-I1_south_north_B35-E35-I1.nc -S 'WRFtime;y;time ([DD]${[HH]}$);auto;we=20$\times$sn=20,we=25$\times$sn=25,we=35$\times$sn=35;tas;tas|evolution|at|3|different|grid|points;None;time|hours!since!1949-12-01_00:00:00|exct,3,h|%d$^{%H}$;0|12;pdf;-;r,g,b;.;2.;2.;all;-1;True' -v T2
## e.g. # drawing.py -o draw_Neighbourghood_evol -S 'vas:Time|-1|WRFtime,south_north|44|XLAT,west_east|88|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,1,h|exct,3,h:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution|on|2001|Nov.|at|x=88,|y=44:0.0,20.:rainbow,auto,auto:auto:png:vas_Neigh_evol:True' -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -v V10
## e.g. # drawing.py -o draw_points -S 'SuperStorm/tslist.dat,#,3,2,1:SuperStorm|sfc|stations:auto:cyl,i:labelled,10,r:auto:None:0:png:stations_loc:True' -f 'geo_em.d02.nc,XLONG_M,XLAT_M,HGT_M,Time|0@west_east|30;180;1@south_north|175;255;1,height,0.,1500.,terrain,auto,auto,m'

## e.g. # drawing.py -o draw_trajectories -f 'WRF/control/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_HighRes_C/geo_em.d03.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdza/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb_ii/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M' -S '$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|None|medicane trajectories|pdf|cyl,i' -v obs/trajectory.dat,satellite,-1
## e.g. # drawing.py -o draw_vals_trajectories -f WRF_LMDZ/wlmdza/tevolboxtraj_T2.nc,WRF_LMDZ/wlmdzb/tevolboxtraj_T2.nc,WRF/control/tevolboxtraj_T2.nc -S 'mean:-1:$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$@4:tas:time|($[DD]^[HH]$):exct,6,h:$%d^{%H}$:trajectory|following|mean:pdf' -v T2
## e.g. # drawing.py -o draw_2D_shad_time -f 'netcdf_concatenated.nc' -S 'dtcon:Time|-1,bottom_top|-1:presmean:time:seismic:-3.e-6,3.e-6:monthly|dtcon:pdf:transpose:time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])|x:True' -v 'dtconmean'
## e.g. # drawing.py -o variable_values -S PSFC
## e.g. # drawing.py -o draw_timeSeries -f wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc -S 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf' -v 'LDQCON,time'
## e.g. # drawing.py -f wrfout_d01_1979-12-01_00:00:00 -o draw_Neighbourghood_evol -S 'q:Time|-1|Times,bottom_top|6|ZNU,south_north|3|XLAT,west_east|26|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,2,h|exct,1,d:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution:0.0,0.004:BuPu:pdf:True' -v QVAPOR
## e.g. # drawing.py -o draw_lines_time -f wrfout_d01_1980-03-01_00:00:00_Time_B0-E48-I1_south_north_B15-E15-I1_west_east_B15-E15-I1.nc -S 'time;y;time ([DD]${[HH]}$);file1;tas;evolution;time|hours!since!1949-12-01_00:00:00|exct,12,h|%d$^{%H}$;pdf' -v T2
## e.g. # drawing.py -o draw_barbs -f ERAI_pl199501_131-132.nc -S 'X|lon|lon|-1,Y|lat|lat|-1,Z|lev|lev|4,T|time|time|0:auto,auto,auto:wind,ms-1:cyl,c:ERA-Interim|winds|at|1000|hPa|on|1996|January|1st|at|00|UTC:pdf:ERAI_pl199501_131-132' -v var131,var132
## e.g. # ~/etudes/WRF_LMDZ/svn/LMDZ_WRF/tools/drawing.py -o draw_points -S 'tslist.dat,#,3,2,1:SuperStorm|sfc|stations:cyl,i:legend:auto:None:0:png:stations_loc' -f $HOME'/etudes/domains/WRFdynamicoSENS_SuperStorm/geo_em.d02.nc,XLONG_M,XLAT_M,HGT_M,Time|0,height,0.,3000.,terrain,m'
## e.g. # drawing.py -o draw_points -S 'tslist.dat,#,3,2,1:SuperStorm|sfc|stations:cyl,i:labelled,8,black:auto:None:0:png:stations_loc' -f $HOME'/etudes/domains/WRFdynamicoSENS_SuperStorm/geo_em_west_east_B25-E180-I1_south_north_B160-E262-I1.nc,XLONG_M,XLAT_M,HGT_M,Time|0,height,0.,1500.,terrain,m'
## e.g. # drawing.py -o draw_ptZvals -f geo_v2_2012102123_RR1.nc -S 'pracc:lon,lat:o:80:2,42,7,47,:values!of!values:Blues:cyl,l:pdf' -v pr
## e.g. # drawing.py -f carteveg5km.nc -o draw_points_lonlat -S 'longitude:latitude:pdf:points!veget|type:green:.:0.5:None:0:legend'
## e.g. # drawing.py -o draw_vectors -f wrfout_d01_2001-11-11_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:3@3,wind@rainbow,9:10m wind,ms-1:cyl,l:WRF 10 m winds:pdf:winds' -v U10,V10
## e.g. # drawing.py -o draw_basins -f routing.py -S 'Y|y|nav_lat|-1,X|x|nav_lon|-1:1@1,rainbow,9:basins,-:cyl,l:ORCDHIEE river-basins:pdf:basins_named' -v nav_lon,nav_lat,trip,basins
## e.g. # drawing.py -o draw_river_desc -f diver_desc.nc -S 'Y|lat|lat|-1,X|lon|lon|-1:red,green:Blues:cyl,l:ORCDHIEE rivers:pdf:0:or_rivers -v Amazon
## e.g. # drawing.py -o draw_vertical_levels -f wrfout_d01_2001-11-11_00:00:00 -S 'true:false:wrfout!vertical!levels!(standard!40):png:4' -v WRFz
## e.g. # drawing.py -o draw_subbasin -f Caceres_subbasin.nc -S 'Caceres:None:cyl,l:2,True:Caceres:pdf:0:Caceres_subbasin'
## e.g. # drawing.py -o draw_2lines -f /home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/wss_wrfout_tvar_xmean.nc,/home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/tas_wrfout_tvar_xmean.nc -v wssvarmean,tasvarmean -S 'lat:0.,20.:0.,4.:-90.,90.:y:wss,tas:red,blue:2.,2.:-:2.,2.:,:wss!tas!mean!meridional!tvar:lon:0:wss_tas_wrfout_tvar_xmean:pdf'
## e.g. # drawing.py -o draw_2lines_time -f /home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/wss_wrfout_xvar_ymean.nc,/home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/tas_wrfout_xvar_ymean.nc -v wssvarmean,tasvarmean -S 'time:0.,20.:0.,4.:exct,1,d;%d:x:wss,tas:red,blue:2.,2.:-:2.,2.:,:wss!tas!mean!longitudinal!xvar:time!($[DD]$):0:wss_tas_wrfout_xvar_ymean:pdf'

#######
# create_movie: Function to create a movie assuming ImageMagick installed!
# draw_2D_shad: plotting a fields with shading
# draw_2D_shad_cont: plotting two fields, one with shading and the other with contour lines
# draw_2D_shad_cont_time: plotting two fields, one with shading and the other with contour lines being 
#   one of the dimensions of time characteristics
# draw_2D_shad_line: plotting a fields with shading and another with line
# draw_2D_shad_line_time: plotting a fields with shading and a line with time values
# draw_2D_shad_time: plotting a fields with shading with time values
# draw_2lines: Fucntion to plot two lines in different axes (x/x2 or y/y2)
# draw_2lines_time: Function to plot two time-lines in different axes (x/x2 or y/y2)
# draw_barbs: Function to plot wind barbs
# draw_basins: Function to plot river basins with their discharge vector and basins id (from 'routing.nc')
# draw_lines: Function to draw different lines at the same time from different files
# draw_lines_time: Function to draw different lines at the same time from different files with times
# draw_Neighbourghood_evol: Function to draw the temporal evolution of a neighbourghood around a point
# draw_points: Function to plot a series of points
# draw_points_lonlat: Function to plot a series of lon/lat points
# draw_ptZvals: Function to plot a given list of points and values 
# draw_timeSeries: Function to draw a time-series
# draw_topo_geogrid: plotting geo_em.d[nn].nc topography from WPS files
# draw_topo_geogrid_boxes: plotting different geo_em.d[nn].nc topography from WPS files
# draw_trajectories: Function to draw different trajectories at the same time
# draw_vals_trajectories: Function to draw values from the outputs from 'compute_tevolboxtraj'
# draw_vectors: Function to plot wind vectors
# movievalslice: Function to provide variable slice according to a geneation of a movie
# variable_values: Function to give back values for a given variable
# draw_river_desc: Function to plot rivers' description from ORCHIDEE's routing scheme
# draw_subbasin: Function to plot subbasin from 'routnig.nc' ORCDHIEE
# draw_vertical_levels: plotting vertical levels distribution

mainn = 'drawing.py'

errormsg = 'ERROR -- error -- ERROR -- error'
warnmsg = 'WARNING -- waring -- WARNING -- warning'
fillValue=1.e20

namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2D_shad_time',                 \
  'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line',                \
  'draw_2D_shad_line_time', 'draw_barbs', 'draw_basins',                             \
  'draw_2lines', 'draw_2lines_time', 'draw_lines', 'draw_lines_time',                \
  'draw_Neighbourghood_evol',                                                        \
  'draw_points', 'draw_points_lonlat',                                               \
  'draw_ptZvals', 'draw_river_desc', 'draw_subbasin', 'draw_timeSeries',             \
  'draw_topo_geogrid',                                                               \
  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'variable_values']

def draw_2D_shad(ncfile, values, varn, axfig=None, fig=None):
    """ plotting a fields with shading
    draw_2D_shad(ncfile, values, varn)
      ncfile= file to use
      values=[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[sminv],[smaxv]:[figt]:
       [kindfig]:[reverse]:[mapv]:[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the 
          variable a given value is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
            * NOTE, no dim name all the dimension size
        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [smin/axv]: minimum and maximum value for the shading or:
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: Transformation of the values
          * 'transpose': reverse the axes (x-->y, y-->x)
          * 'flip'@[x/y]: flip the axis x or y
        [mapv]: map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        [close]: Whether figure should be finished or not
      valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
      varn= [varsn] name of the variable to plot with shading
    """

    fname = 'draw_2D_shad'
    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2D_shad.__doc__
        quit()

    expectargs = '[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyf]:[colbarvals]:' +    \
      '[sminv],[smaxv]:[figt]:[kindfig]:[reverse]:[mapv]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    vnamesfig = values.split(':')[0]
    dimvals= values.split(':')[1].replace('|',':')
    vdimxn = values.split(':')[2]
    vdimyn = values.split(':')[3]
    dimxyf = values.split(':')[4]
    colorbarvals = values.split(':')[5]
    shadminmax = values.split(':')[6]
    figtitle = values.split(':')[7].replace('|',' ')
    figkind = values.split(':')[8]
    revals = values.split(':')[9]
    mapvalue = values.split(':')[10]
    close = gen.Str_Bool(values.split(':')[11])

    ncfiles = ncfile
    
    if not os.path.isfile(ncfiles):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
        quit(-1)    

    objsf = NetCDFFile(ncfiles, 'r')
    
    varns = varn.split(',')[0]

    if  not objsf.variables.has_key(varns):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varns + '" !!'
        quit(-1)

# Variables' values
    objvars = objsf.variables[varns]

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))

# Dimensions names
##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
##    dimnamesv = []
##    for idd in range(len(objvars.dimensions)):
##        cutdim = False
##        for idc in range(len(dimvals.split(','))):
##            dimcutn = dimvals.split(',')[idc].split(':')[0]
##            print objvars.dimensions[idd], dimcutn
##            if objvars.dimensions[idd] == dimcutn: 
##                cutdim = True
##                break
##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
    dimnamesv = [vdimxn, vdimyn]

    if drw.searchInlist(objvars.ncattrs(),'units'):
        varunits = objvars.getncattr('units')
    else:
        print warnmsg
        print '  ' + fname + ": variable '" + varn + "' without units!!"
        varunits = '-'

    if  not objsf.variables.has_key(vdimxn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimxn + '" !!'
        quit(-1)
    if  not objsf.variables.has_key(vdimyn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimyn + '" !!'
        quit(-1)

    objdimx = objsf.variables[vdimxn]
    objdimy = objsf.variables[vdimyn]
    if drw.searchInlist(objdimx.ncattrs(),'units'):
        odimxu = objdimx.getncattr('units')
    else:
        print warnmsg
        print '  ' + fname + ": variable dimension '" + vdimxn + "' without units!!"
        odimxu = '-'

    if drw.searchInlist(objdimy.ncattrs(),'units'):
        odimyu = objdimy.getncattr('units')
    else:
        print warnmsg
        print '  ' + fname + ": variable dimension '" + vdimyn + "' without units!!"
        odimyu = '-'

    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
      objdimy.dimensions, dimvals.replace(':','|').split(','))

    shading_nx = []
    if shadminmax.split(',')[0][0:1] != 'S':
            shading_nx.append(np.float(shadminmax.split(',')[0]))
    else:
        shading_nx.append(shadminmax.split(',')[0])

    if shadminmax.split(',')[1][0:1] != 'S':
        shading_nx.append(np.float(shadminmax.split(',')[1]))
    else:
        shading_nx.append(shadminmax.split(',')[1])

    if mapvalue == 'None': mapvalue = None

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
    colormapv = [colbarn, fmtcolbar, colbaror]

    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if revals == 'None':
        revals = None

    drw.plot_2D_shadow(valshad, vnamesfig, odimxv, odimyv, odimxu, odimyu, xaxis,    \
      yaxis, dimnamesv, colormapv, shading_nx, varunits, figtitle, figkind, revals,  \
      mapvalue, close)

    return

def draw_2D_shad_time(ncfile, values, varn):
    """ plotting a fields with shading with time values
    draw_2D_shad_time(ncfile, values, varn)
      ncfile= file to use
      values=[vnamefs]~[dimvals]~[dimxvn]~[dimyvn]~[dimvfmt]~[colorbarvals]~[sminv],[smaxv]~[figt]~
       [kindfig]~[reverse]~[timevals]~[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the 
          variable a given value is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
            * NOTE, no dim name all the dimension size
        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)  ('WRFtime' for WRF times)
        [dimvfmt]=[dvs],[dvf],[Ndv],[ordv]: format of the values for the non-temporal axis (or 'auto')
          [dvs]: style of non-temporal axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dvf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndv]: Number of ticks at the x-axis ('auto' for 5)
          [ordv]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [smin/axv]: minimum and maximum value for the shading or:
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: Transformation of the values
          * 'transpose': reverse the axes (x-->y, y-->x)
          * 'flip'@[x/y]: flip the axis x or y
        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label]|[timeaxis] time labels characteristics
           [timen]; name of the time variable ('WRFtime' for WRF times)
           [units]; units string according to CF conventions ([tunits] since 
             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
           [kind]; kind of output
             'Nval': according to a given number of values as 'Nval',[Nval]
             'exct': according to an exact time unit as 'exct',[tunit]; 
               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
                'l': milisecond
           [tfmt]; desired format
           [label]; label at the graph ('!' for spaces)
        [close]: should figure be closed (finished)
      values='dtcon~Time|-1,bottom_top|-1~presmean~time~auto~seismic,auto,auto~-3.e-6,3.e-6~monthly|'
        'dtcon~pdf~transpose~time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])~True
      varn= [varsn] name of the variable to plot with shading
    """
    fname = 'draw_2D_shad_time'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2D_shad_time.__doc__
        quit()

    farguments = '[vnamefs]~[dimvals]~[dimxvn]~[dimyvn]~[dimvfmt]~[colorbarvals]~' + \
      '[sminv],[smaxv]~[figt]~[kindfig]~[reverse]~[timevals]~[close]'
    drw.check_arguments(fname,values,farguments,'~')

    vnamesfig = values.split('~')[0]
    dimvals= values.split('~')[1].replace('|',':')
    vdimxn = values.split('~')[2]
    vdimyn = values.split('~')[3]
    dimvfmt = values.split('~')[4]    
    colorbarvals = values.split('~')[5]
    shadminmax = values.split('~')[6]
    figtitle = values.split('~')[7].replace('|',' ')
    figkind = values.split('~')[8]
    revals = values.split('~')[9]
    timevals = values.split('~')[10]
    close = gen.Str_Bool(values.split('~')[11])

    ncfiles = ncfile
    
    if not os.path.isfile(ncfiles):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
        quit(-1)    

    objsf = NetCDFFile(ncfiles, 'r')
    
    varns = varn.split(',')[0]

    if  not objsf.variables.has_key(varns):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varns + '" !!'
        quit(-1)

# Variables' values
    objvars = objsf.variables[varns]

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))

    dimnamesv = [vdimxn, vdimyn]

    varunits = objvars.getncattr('units')

    if vdimxn != 'WRFtime' and not objsf.variables.has_key(vdimxn):
        print errormsg
        print '  ' + fname + ": shading file '" + ncfiles +                          \
          "' does not have dimension variable '" +  vdimxn + "' !!"
        quit(-1)
    if vdimyn != 'WRFtime' and not objsf.variables.has_key(vdimyn):
        print errormsg
        print '  ' + fname + ": shading file '" + ncfiles +                          \
          "' does not have dimension variable '" +  vdimyn + " !!'"
        quit(-1)

    timename = timevals.split('|')[0]
    timeunit = timevals.split('|')[1].replace('!',' ')
    timekind = timevals.split('|')[2]
    timefmt = timevals.split('|')[3]
    timelabel = timevals.split('|')[4].replace('!',' ')

    if vdimxn == 'WRFtime' or vdimyn == 'WRFtime':
        tunitsec = timeunit.split(' ')
        if len(tunitsec) == 4:
            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +          \
              tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
        else:
            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10]+ '000000'
        tunitsval = tunitsec[0]
            
        timewrfv = objsf.variables['Times']
        dt = timewrfv.shape[0]
        cftimes = np.zeros((dt), dtype=np.float)

        for it in range(dt):
            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime',      \
              'matYmdHMS')
            cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)

    if vdimxn != 'WRFtime':
        objdimx = objsf.variables[vdimxn]
        objdimxv = objdimx[:]
        odimxu = objdimx.getncattr('units')
    else:
        objdimxv = cftimes
        odimxu = timeunit

    if vdimyn != 'WRFtime':
        objdimy = objsf.variables[vdimyn]
        objdimyv = objdimy[:]
        odimyu = objdimy.getncattr('units')
    else:
        objdimyv = cftimes
        odimyu = timeunit

    if len(objdimxv.shape) <= 2:
        odimxv0 = objdimxv[:]
    elif len(objdimxv.shape) == 3:
        odimxv0 = objdimxv[0,:]
    else:
        print errormsg
        print '  ' + fname + ': shape of dimension variable:', objdimxv.shape,       \
          ' not ready!!'
        quit(-1)
    if len(objdimyv.shape) <= 2:
        odimyv0 = objdimyv[:]
    elif len(objdimyv.shape) == 3:
        odimyv0 = objdimyv[0,:]
    else:
        print errormsg
        print '  ' + fname + ': shape of dimension variable:', objdimyv.shape,       \
          ' not ready!!'
        quit(-1)

# Dimensional values
    if vdimxn != 'WRFtime':
        odxv, dimsdxv = drw.slice_variable(objsf.variables[vdimxn], dimvals.replace(',','|'))
    else:
        odxv = cftimes
        dimsdxv = ['Time']

    if vdimyn != 'WRFtime':
        odyv, dimsdyv = drw.slice_variable(objsf.variables[vdimyn], dimvals.replace(',','|'))
    else:
        odyv = cftimes
        dimsdyv = ['Time']

    if vdimxn == timename:
        odimxv = odxv
        odimxu = timelabel
        timeaxis = 'x'
        odimyv = odyv
        odimyu = objdimy.getncattr('units')
        timepos, timelabels = drw.CFtimes_plot(odxv, timeunit, timekind, timefmt)
    elif vdimyn == timename:
        odimyv = odyv
        odimyu = timelabel
        timeaxis = 'y'
        odimxv = odxv
        odimxu = objdimx.getncattr('units')
        timepos, timelabels = drw.CFtimes_plot(odyv, timeunit, timekind, timefmt)
    else:
        print errormsg
        print '  ' + fname + ": time variable '" + timename + "' not found!!"
        quit(-1)

    shading_nx = []
    if shadminmax.split(',')[0][0:1] != 'S':
        shading_nx.append(np.float(shadminmax.split(',')[0]))
    else:
        shading_nx.append(shadminmax.split(',')[0])

    if shadminmax.split(',')[1][0:1] != 'S':
        shading_nx.append(np.float(shadminmax.split(',')[1]))
    else:
        shading_nx.append(shadminmax.split(',')[1])

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
    colormapv = [colbarn, fmtcolbar, colbaror]

    if dimvfmt != 'auto': dimvfmt = dimvfmt + 'auto,auto,auto,auto'
    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimvfmt,',')
    vaxis = [xstyl, xaxf, Nxax, xaxor]

    if revals == 'None':
        revals = None

    drw.plot_2D_shadow_time(valshad, vnamesfig, odxv, odyv, odimxu, odimyu,          \
      dimnamesv, vaxis, colormapv, shading_nx, varunits, figtitle, figkind, revals,  \
      timeaxis, timepos, timelabels, close)

    return

def draw_2D_shad_cont(ncfile, values, varn):
    """ plotting two fields, one with shading and the other with contour lines
    draw_2D_shad_cont(ncfile, values, varn)
      ncfile= [ncfilevars],[ncfilevarc] files to use (one value, same file)
      values=[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:[figt]:[kindfig]:[reverse]:[mapv]:[close]
        [vnamefs],[vnamefc]: Name in the figure of the shaded and the contour variables
        [dimvals/c]: list of [dimname]|[value] telling at which dimension of the 
          variable a given value is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
            * NOTE, no dim name all the dimension size
        [dimx/yvn]: names of the variables with the values of the dimensions for the plot
        [dimxyfmt]=[dxf],[Ndx],[dyf],[Ndy]: format of the values at each axis
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis
          [Ndx]: Number of ticks at the x-axis
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis
          [Ndy]: Number of ticks at the y-axis
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [ckind]: kind of contours 
          'cmap': as it gets from colorbar
          'fixc,[colname]': fixed color [colname], all stright lines
          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
        [clabfmt]: format of the labels in the contour (None, also possible)
        [smin/axv]: minimum and maximum value for the shading or
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [sminc]:[smaxv]:[Nlev]: minimum, maximum and number of values for the contour
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: does the values be transposed? 'True/False', 
        [mapv]: map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lamvbert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        [close]: Whether figure should be finished or not
      valules= 'rh,ta:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:fixsigc,black:%d:0.,100.:195.,305.,7:Meridonal|average|of|rh|&|ta:pdf:flip@y:None'
      varn= [varsn],[varcn] name of the variable to plot with shading variable with contour
    """

    fname = 'draw_2D_shad_cont'
    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2D_shad_cont.__doc__
        quit()

    expectargs = '[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[dimxyf]:' +       \
      '[colorbarvals]:[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:' +   \
      '[figt]:[kindfig]:[reverse]:[mapv]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    vnamesfig = values.split(':')[0].split(',')
    dimvals= values.split(':')[1].replace('|',':')
    dimvalc= values.split(':')[2].replace('|',':')
    vdimxn = values.split(':')[3]
    vdimyn = values.split(':')[4]
    dimxyf = values.split(':')[5]
    colorbarvals = values.split(':')[6]
    countkind = values.split(':')[7]
    countlabelfmt = values.split(':')[8]
    shadminmax = values.split(':')[9].split(',')
    contlevels = values.split(':')[10]
    figtitle = values.split(':')[11].replace('|',' ')
    figkind = values.split(':')[12]
    revals = values.split(':')[13]
    mapvalue = values.split(':')[14]
    close = gen.Str_Bool(values.split(':')[15])

    if2filenames = ncfile.find(',')

    if if2filenames != -1:
        ncfiles = ncfile.split(',')[0]
        ncfilec = ncfile.split(',')[1]
    else:
        ncfiles = ncfile
        ncfilec = ncfile

    if not os.path.isfile(ncfiles):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
        quit(-1)    

    if not os.path.isfile(ncfilec):
        print errormsg
        print '  ' + fname + ': contour file "' + ncfilec + '" does not exist !!'
        quit(-1)    

    objsf = NetCDFFile(ncfiles, 'r')
    objcf = NetCDFFile(ncfilec, 'r')
    
    varns = varn.split(',')[0]
    varnc = varn.split(',')[1]

    if  not objsf.variables.has_key(varns):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varns + '" !!'
        quit(-1)

    if  not objcf.variables.has_key(varnc):
        print errormsg
        print '  ' + fname + ': contour file "' + ncfilec +                          \
          '" does not have variable "' +  varnc + '" !!'
        quit(-1)

# Variables' values
    objvars = objsf.variables[varns]
    objvarc = objcf.variables[varnc]

    if len(objvars.shape) != len(objvarc.shape):
        print errormsg
        print '  ' + fname + ': shading variable "' + varns + '" has a shape: ',     \
          objvars.shape,  'different than contour variable "' +  varnc + '": ',      \
          objvarc.shape,' !!!'
        quit(-1)

    for idim in range(len(objvars.shape)):
        if objvars.shape[idim] != objvarc.shape[idim]:
            print errormsg
            print '  ' + fname + ': shading variable "' + varns + '" has a shape: ', \
              objvars.shape,  'different than contour variable "' +  varnc + '": ',  \
              objvarc.shape,' !!!'
            quit(-1)

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
    valcont, dimscont = drw.slice_variable(objvarc, dimvalc.replace(',','|'))

# Dimensions names
##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
##    dimnamesv = []
##    for idd in range(len(objvars.dimensions)):
##        cutdim = False
##        for idc in range(len(dimvals.split(','))):
##            dimcutn = dimvals.split(',')[idc].split(':')[0]
##            print objvars.dimensions[idd], dimcutn
##            if objvars.dimensions[idd] == dimcutn: 
##                cutdim = True
##                break
##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
    dimnamesv = [vdimxn, vdimyn]

    varunits = []
    varunits.append(objvars.getncattr('units'))
    varunits.append(objvarc.getncattr('units'))

    if  not objsf.variables.has_key(vdimxn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimxn + '" !!'
        quit(-1)
    if  not objsf.variables.has_key(vdimyn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimyn + '" !!'
        quit(-1)

    objdimx = objsf.variables[vdimxn]
    objdimy = objsf.variables[vdimyn]
    odimxu = objdimx.getncattr('units')
    odimyu = objdimy.getncattr('units')

# Getting only that dimensions with coincident names
    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
      objdimy.dimensions, dimvals.replace(':','|').split(','))

#    dimnvx = objdimx.dimensions
#    cutslice = []
#    for idimn in objdimx.dimensions:
#        found = False
#        for dimsn in dimsshad:
#            if idimn == dimsn:
#                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
#                found = True
#        if not found: cutslice.append(0)
#
#    odimxv = objdimx[tuple(cutslice)]
#
#    dimnvy = objdimy.dimensions
#    cutslice = []
#    for idimn in objdimy.dimensions:
#        found = False
#        for dimsn in dimsshad:
#            if idimn == dimsn:
#                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
#                found = True
#        if not found: cutslice.append(0)
#
#    odimyv = objdimy[tuple(cutslice)]

#    if len(objdimx.shape) <= 2:
#        odimxv = objdimx[:]
#        odimyv = objdimy[:]
#    elif len(objdimx.shape) == 3:
#        odimxv = objdimx[0,:]
#        odimyv = objdimy[0,:]
#    else:
#        print errormsg
#        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
#          ' not ready!!'
#        quit(-1)

    if countlabelfmt == 'None': 
        countlfmt = None
    else:
        countlfmt = countlabelfmt

    # Shading limits
    shading_nx = drw.graphic_range(shadminmax,valshad)

    # Contour limits
    clevmin = np.float(contlevels.split(',')[0])
    clevmax = np.float(contlevels.split(',')[1])
    Nclevels = int(contlevels.split(',')[2])

    levels_cont = gen.pretty_int(clevmin, clevmax, Nclevels)

    if len(levels_cont) <= 1: 
        print warnmsg
        print '  ' + fname + ': wrong contour levels:', levels_cont,' !!'
        del(levels_cont)
        levels_cont = np.zeros((Nclevels), dtype=np.float)
        levels_cont = np.arange(7)*(clevmax - clevmin)/(Nclevels-1)
        print '    generating default ones: ',levels_cont

    if mapvalue == 'None': mapvalue = None

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')

    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if revals == 'None': revals = None

    drw.plot_2D_shadow_contour(valshad, valcont, vnamesfig, odimxv, odimyv, odimxu,  \
      odimyu, xaxis, yaxis, dimnamesv, [colbarn, fmtcolbar, colbaror], countkind,    \
      countlfmt, shading_nx, levels_cont, varunits, figtitle, figkind, revals,       \
      mapvalue, close)

    return

def draw_2D_shad_cont_time(ncfile, values, varn):
    """ plotting two fields, one with shading and the other with contour lines being
    one of the dimensions of time characteristics
    draw_2D_shad_cont_time(ncfile, values, varn)
      ncfile= [ncfilevars],[ncfilevarc] files to use (one value, same file)
      values=[vnamefs];[dimvals];[dimvalc];[dimxvn];[dimyvn];[dimxyf];[colorbarvals];[ckind];[clabfmt];[sminv],[smaxv];[sminc],[smaxv],[Nlev];[figt];[kindfig];[reverse];[timevals];[close]
        [vnamefs],[vnamefc]: Name in the figure of the shaded and the contour variables
        [dimvals/c]: list of [dimname]|[value] telling at which dimension of the 
          variable a given value is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
            * NOTE, no dim name all the dimension size
        [dimxvn]: name of the variables with the values of the dimension of the x-axis ('WRFtime' for WRF times)
        [dimyvn]: name of the variables with the values of the dimension of the y-axis ('WRFtime' for WRF times)
        [dimxyf]=[dxf],[Ndx],[dyf],[Ndy]: format of the values at each axis
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx' (unique map plotted with constant pixel size)
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis
          [Ndx]: Number of ticks at the x-axis
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis
          [Ndy]: Number of ticks at the y-axis
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [ckind]: kind of contours 
          'cmap': as it gets from colorbar
          'fixc,[colname]': fixed color [colname], all stright lines
          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
        [clabfmt]: format of the labels in the contour (None, also possible)
        [smin/axv]: minimum and maximum value for the shading or:
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [sminc]:[smaxv]:[Nlev]: minimum, maximum and number of values for the contour
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: modification to the dimensions:
          'transposed': transpose matrices
          'flip',[x/y]: flip only the dimension [x] or [y]
        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label] time labels characteristics
          [timen]; name of the time variable ('WRFtime' for WRF times)
          [units]; units string according to CF conventions ([tunits] since 
            [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
          [kind]; kind of output
            'Nval': according to a given number of values as 'Nval',[Nval]
            'exct': according to an exact time unit as 'exct',[tunit]; 
              tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
               'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
               'l': milisecond
          [tfmt]; desired format
          [label]; label at the graph ('!' for spaces)
        [close]: Whether figure should be finished or not
      valules= 'rh,ta;z|-1,x|-1;z|-1,x|-1;lat;pressure;BuPu;fixsigc,black;%d;0.,100.;195.,305.,7;Meridonal|average|of|rh|&|ta;pdf;flip@y;time!hours!since!1949/12/01|exct,5d|%d|date!([DD])' 
      varn= [varsn],[varcn] name of the variable to plot with shading variable with contour
    """

    fname = 'draw_2D_shad_cont_time'
    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2D_shad_cont_time.__doc__
        quit()

    expectargs = '[vnamefs];[dimvals];[dimvalc];[dimxvn];[dimyvn];[dimxyf];' +       \
      '[colorbarvals];[ckind];[clabfmt];[sminv],[smaxv];[sminc],[smaxv],[Nlev];' +   \
      '[figt];[kindfig];[reverse];[timevals];[close]'
 
    drw.check_arguments(fname,values,expectargs,';')

    vnamesfig = values.split(';')[0].split(',')
    dimvals= values.split(';')[1].replace('|',':')
    dimvalc= values.split(';')[2].replace('|',':')
    vdimxn = values.split(';')[3]
    vdimyn = values.split(';')[4]
    dimxyf = values.split(';')[5]
    colorbarvals = values.split(';')[6]
    countkind = values.split(';')[7]
    countlabelfmt = values.split(';')[8]
    shadminmax = values.split(';')[9]
    contlevels = values.split(';')[10]
    figtitle = values.split(';')[11].replace('|',' ')
    figkind = values.split(';')[12]
    revals = values.split(';')[13]
    timevals = values.split(';')[14]
    close = gen.Str_Bool(values.split(';')[15])

    if2filenames = ncfile.find(',')

    if if2filenames != -1:
        ncfiles = ncfile.split(',')[0]
        ncfilec = ncfile.split(',')[1]
    else:
        ncfiles = ncfile
        ncfilec = ncfile

    if not os.path.isfile(ncfiles):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
        quit(-1)    

    if not os.path.isfile(ncfilec):
        print errormsg
        print '  ' + fname + ': contour file "' + ncfilec + '" does not exist !!'
        quit(-1)    

    objsf = NetCDFFile(ncfiles, 'r')
    objcf = NetCDFFile(ncfilec, 'r')
    
    varns = varn.split(',')[0]
    varnc = varn.split(',')[1]

    if  not objsf.variables.has_key(varns):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varns + '" !!'
        quit(-1)

    if  not objcf.variables.has_key(varnc):
        print errormsg
        print '  ' + fname + ': contour file "' + ncfilec +                          \
          '" does not have variable "' +  varnc + '" !!'
        quit(-1)

# Variables' values
    objvars = objsf.variables[varns]
    objvarc = objcf.variables[varnc]

    if len(objvars.shape) != len(objvarc.shape):
        print errormsg
        print '  ' + fname + ': shading variable "' + varns + '" has a shape: ',     \
          objvars.shape,  'different than contour variable "' +  varnc + '": ',      \
          objvarc.shape,' !!!'
        quit(-1)

    for idim in range(len(objvars.shape)):
        if objvars.shape[idim] != objvarc.shape[idim]:
            print errormsg
            print '  ' + fname + ': shading variable "' + varns + '" has a shape: ', \
              objvars.shape,  'different than contour variable "' +  varnc + '": ',  \
              objvarc.shape,' !!!'
            quit(-1)

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
    valcont, dimscont = drw.slice_variable(objvarc, dimvalc.replace(',','|'))

    dimnamesv = [vdimxn, vdimyn]

    varunits = []
    varunits.append(objvars.getncattr('units'))
    varunits.append(objvarc.getncattr('units'))

    if vdimxn != 'WRFtime' and not objsf.variables.has_key(vdimxn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimxn + '" !!'
        quit(-1)
    if vdimyn != 'WRFtime' and not objsf.variables.has_key(vdimyn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimyn + '" !!'
        quit(-1)

    timename = timevals.split('|')[0]
    timeunit = timevals.split('|')[1].replace('!',' ')
    timekind = timevals.split('|')[2]
    timefmt = timevals.split('|')[3]
    timelabel = timevals.split('|')[4].replace('!',' ')

    if vdimxn == 'WRFtime' or vdimyn == 'WRFtime':
        tunitsec = timeunit.split(' ')
        if len(tunitsec) == 4:
            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +          \
              tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
        else:
            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10]+ '000000'
        tunitsval = tunitsec[0]

        timewrfv = objsf.variables['Times']
        dt = timewrfv.shape[0]
        cftimes = np.zeros((dt), dtype=np.float)

        for it in range(dt):
            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime',      \
              'matYmdHMS')
            cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)

    if vdimxn == timename:
        if vdimxn == 'WRFtime':
            timevals = cftimes
            timedims = ['Time']
        else:
            timevals = objsf.variables[vdimxn][:]
            timedims = objsf.variables[vdimxn].dimensions
        dimt = 'x'
        ovalaxis = objsf.variables[vdimyn]
        ovalu = ovalaxis.getncattr('units')
    elif vdimyn == timename:
        if vdimyn == 'WRFtime':
            timevals = cftimes
            timedims = ['Time']
        else:
            timevals = objsf.variables[vdimyn][:]
            timedims = objsf.variables[vdimyn].dimensions
        dimt = 'y'
        ovalaxis = objsf.variables[vdimxn]
        ovalu = ovalaxis.getncattr('units')
    else:
        print errormsg
        print '  ' + fname + ": time variable '" + timename + "' not found!!"
        quit(-1)

    timepos, timelabels = drw.CFtimes_plot(timevals, timeunit, timekind, timefmt)

# Getting only that dimensions with coincident names
    dimnvx = ovalaxis.dimensions
    dimsliceaxis = []
    for dimv in dimvals.split(','):
        adimvn = dimv.split(':')[0]
        adimval = dimv.split(':')[1]
        found = False
        for dimtn in timedims:
            if adimvn == dimtn:
                dimsliceaxis.append(adimvn + ':0')
                found = True
                break
        if not found:
            dimsliceaxis.append(dimv)

    dimsliceaxisS = '|'.join(dimsliceaxis)

    ovalaxisv, odimaxisv = drw.slice_variable(ovalaxis,dimsliceaxisS)
    print fname + '; Lluis odimaxisv:', odimaxisv, timedims[0]+':0'

    if countlabelfmt == 'None': 
        countlfmt = None
    else:
        countlfmt = countlabelfmt

    shading_nx = []
    if shadminmax.split(',')[0][0:1] != 'S':
            shading_nx.append(np.float(shadminmax.split(',')[0]))
    else:
        shading_nx.append(shadminmax.split(',')[0])

    if shadminmax.split(',')[1][0:1] != 'S':
        shading_nx.append(np.float(shadminmax.split(',')[1]))
    else:
        shading_nx.append(shadminmax.split(',')[1])

    clevmin = np.float(contlevels.split(',')[0])
    clevmax = np.float(contlevels.split(',')[1])
    Nclevels = int(contlevels.split(',')[2])

    levels_cont = gen.pretty_int(clevmin, clevmax, Nclevels)

    if len(levels_cont) <= 1: 
        print warnmsg
        print '  ' + fname + ': wrong contour levels:', levels_cont,' !!'
        del(levels_cont)
        levels_cont = np.zeros((Nclevels), dtype=np.float)
        levels_cont = np.arange(7)*(clevmax - clevmin)/(Nclevels-1)
        print '    generating default ones: ',levels_cont

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')

    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if revals == 'None': revals = None

    drw.plot_2D_shadow_contour_time(valshad, valcont, vnamesfig, ovalaxisv,         \
      timevals, timepos, timelabels, ovalu, timelabel, dimt, xaxis, yaxis,          \
      dimnamesv, [colbarn, fmtcolbar, colbaror], countkind, countlfmt, shading_nx,  \
      levels_cont, varunits, figtitle, figkind, revals, close)

    return

def draw_2D_shad_line(ncfile, values, varn):
    """ plotting a fields with shading and another with line
    draw_2D_shad_line(ncfile, values, varn)
      ncfile= [ncfiles],[ncfilel] file to use for the shading and for the line
      values=[vnamefs],[vnamefl]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[smin/axv]:[linevalues]:[figt]:
       [kindfig]:[reverse]:[mapv]:[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [vnamefl]: Name in the figure of the variable to be lined
        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the 
          variable a given value is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
            * NOTE, no dim name all the dimension size
        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [smin/axv]: minimum and maximum value for the shading or:
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [linevalues]=[colline],[sminl],[smaxl],[dls],[dlf],[Ndl],[ordl]
          [colline]: name of the color for the line
          [smin/axv]: minimum and maximum value for the line or:
            'Srange': for full range
             'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
            'Saroundminmax@val': for min*val,max*val
            'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
              percentile_(100-val)-median)
            'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
            'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
            'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
               percentile_(100-val)-median)
          [dls]: style of line-axis ('auto' for 'pretty')
          [dlf]: format of the labels at the line-axis ('auto' for '%5g')
          [Ndl]: Number of ticks at the line-axis ('auto' for 5)
          [ordl]: angle of orientation of ticks at the line-axis ('auto' for horizontal)
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: Transformation of the values
          * 'transpose': reverse the axes (x-->y, y-->x)
          * 'flip'@[x/y]: flip the axis x or y
        [mapv]: map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lamvbert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        [close]: Whether figure should be finished or not
      valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
      varn= [varsn],[varnl] name of the variable to plot with shading and with line
    """

    fname = 'draw_2D_shad_line'
    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2D_shad_line.__doc__
        quit()

    farguments = '[vnamefs],[vnamefl]:[dimvals]:[dimxvn]:[dimyvn]:' +                \
      '[dimxyfmt]:[colorbarvals]:[smin/axv]:[linevalues]:[figt]:[kindfig]:' +        \
      '[reverse]:[mapv]:[close]'
    drw.check_arguments(fname,values,farguments,':')

    vnamesfig = values.split(':')[0].split(',')[0]
    dimvals= values.split(':')[1].replace('|',':')
    vdimxn = values.split(':')[2]
    vdimyn = values.split(':')[3]
    dimxyf = values.split(':')[4]
    colorbarvals = values.split(':')[5]
    shadminmax = values.split(':')[6]
    linevalues = values.split(':')[7]
    figtitle = values.split(':')[8].replace('|',' ')
    figkind = values.split(':')[9]
    revals = values.split(':')[10]
    mapvalue = values.split(':')[11]
    close = gen.Str_Bool(values.split(':')[12])

    ncfiles = ncfile.split(',')[0]
    
    if not os.path.isfile(ncfiles):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
        quit(-1)    

    objsf = NetCDFFile(ncfiles, 'r')
    
    varns = varn.split(',')[0]

    if  not objsf.variables.has_key(varns):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varns + '" !!'
        quit(-1)

# Variables' values
    objvars = objsf.variables[varns]

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))

# Dimensions names
    dimnamesv = [vdimxn, vdimyn]

    varunits = objvars.getncattr('units')

    if  not objsf.variables.has_key(vdimxn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimxn + '" !!'
        quit(-1)
    if  not objsf.variables.has_key(vdimyn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimyn + '" !!'
        quit(-1)

    objdimx = objsf.variables[vdimxn]
    objdimy = objsf.variables[vdimyn]
    if drw.searchInlist(objdimx.ncattrs(),'units'):
        odimxu = objdimx.getncattr('units')
    else:
        print warnmsg
        print '  ' + fname + ": variable dimension '" + vdimxn + "' without units!!"
        odimxu = '-'

    if drw.searchInlist(objdimy.ncattrs(),'units'):
        odimyu = objdimy.getncattr('units')
    else:
        print warnmsg
        print '  ' + fname + ": variable dimension '" + vdimyn + "' without units!!"
        odimyu = '-'

    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
      objdimy.dimensions, dimvals.replace(':','|').split(','))

    shading_nx = []
    if shadminmax.split(',')[0][0:1] != 'S':
            shading_nx.append(np.float(shadminmax.split(',')[0]))
    else:
        shading_nx.append(shadminmax.split(',')[0])

    if shadminmax.split(',')[1][0:1] != 'S':
        shading_nx.append(np.float(shadminmax.split(',')[1]))
    else:
        shading_nx.append(shadminmax.split(',')[1])

# line plot
##
    linearg = linevalues.split(',')
    if linevalues.split(',')[1][0:1] != 'S':
        linearg[1] = np.float(linevalues.split(',')[1])
    if linevalues.split(',')[2][0:1] != 'S':
        linearg[2] = np.float(linevalues.split(',')[2])
    if linearg[3] == 'auto': linearg[3] = 'pretty'
    if linearg[4] == 'auto': linearg[4] = '5g'
    if linearg[5] == 'auto': linearg[5] = 5
    if linearg[6] == 'auto': linearg[6] = 0.

    ncfilel = ncfile.split(',')[1]
    vnamelfig = values.split(':')[0].split(',')[1]
    varnl = varn.split(',')[1]

    if not os.path.isfile(ncfilel):
        print errormsg
        print '  ' + fname + ': file for line "' + ncfilel + '" does not exist !!'
        quit(-1)
    objlf = NetCDFFile(ncfilel,'r')

    if  not objlf.variables.has_key(varnl):
        print errormsg
        print '  ' + fname + ': line file "' + ncfilel +                            \
          '" does not have variable "' +  varnl + '" !!'
        quit(-1)
    objlvar = objlf.variables[varnl]
    linevals, dimsline = drw.slice_variable(objlvar, dimvals.replace(',','|'))
    varlunits = objlvar.units

    if mapvalue == 'None': mapvalue = None

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
    colormapv = [colbarn, fmtcolbar, colbaror]

    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if revals == 'None':
        revals = None

    drw.plot_2D_shadow_line(valshad, linevals, vnamesfig, vnamelfig, odimxv, odimyv, \
      odimxu, odimyu, dimnamesv, xaxis, yaxis, colormapv, linearg, shading_nx,       \
      varunits, varlunits, figtitle, figkind, revals, mapvalue, close)

    objsf.close()
    objlf.close()

    return

def draw_2D_shad_line_time(ncfile, values, varn):
    """ plotting a fields with shading and a line with time values
    draw_2D_shad_line(ncfile, values, varn)
      ncfile= [ncfiles],[ncfilel] files to use to draw with shading and the line
      values= [vnamefs],[vanemefl];[dimvals];[dimxvn];[dimyvn];[dimxyfmt];[colorbarvals];[sminv],[smaxv];
        [figt];[kindfig];[reverse];[timevals];[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [vnamefl]: Name in the figure of the variable to be lined
        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the 
          variable a given value is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
            * NOTE, no dim name all the dimension size
        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [smin/axv]: minimum and maximum value for the shading or:
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [linevalues]=[colline],[sminl],[smaxl],[dls],[dlf],[Ndl],[ordl]
          [colline]: name of the color for the line
          [smin/axv]: minimum and maximum value for the line or:
            'Srange': for full range
             'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
            'Saroundminmax@val': for min*val,max*val
            'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
              percentile_(100-val)-median)
            'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
            'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
            'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
               percentile_(100-val)-median)
          [dls]: style of line-axis ('auto' for 'pretty')
          [dlf]: format of the labels at the line-axis ('auto' for '%5g')
          [Ndl]: Number of ticks at the line-axis ('auto' for 5)
          [ordl]: angle of orientation of ticks at the line-axis ('auto' for horizontal)
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: Transformation of the values
          * 'transpose': reverse the axes (x-->y, y-->x)
          * 'flip'@[x/y]: flip the axis x or y
        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label]|[timeaxis] time labels characteristics
           [timen]; name of the time variable
           [units]; units string according to CF conventions ([tunits] since 
             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
           [kind]; kind of output
             'Nval': according to a given number of values as 'Nval',[Nval]
             'exct': according to an exact time unit as 'exct',[tunit]; 
               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
                'l': milisecond
           [tfmt]; desired format
           [label]; label at the graph ('!' for spaces)
        [close]: should figure be closed (finished)
      values='dtcon,prc:Time|-1,bottom_top|-1:presmean:time:seismic:-3.e-6,3.e-6:monthly|'
        'dtcon:pdf:transpose:time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])|x:True
      varn= [varsn].[varln] name of the variable to plot with shading and to plot with line
    """
    fname = 'draw_2D_shad_line_time'
    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2D_shad__line_time.__doc__
        quit()

    farguments = '[vnamefs],[vanemefl];[dimvals];[dimxvn];[dimyvn];[dimxyfmt];' +    \
      '[colorbarvals];[sminv],[smaxv];[linevalues];[figt];[kindfig];[reverse];[timevals];[close]'
    drw.check_arguments(fname,values,farguments,';')

    vnamesfig = values.split(';')[0]
    dimvals= values.split(';')[1].replace('|',':')
    vdimxn = values.split(';')[2]
    vdimyn = values.split(';')[3]
    dimxyfmt = values.split(';')[4]
    colorbarvals = values.split(';')[5]
    shadminmax = values.split(';')[6]
    linevalues = values.split(';')[7]
    figtitle = values.split(';')[8].replace('|',' ')
    figkind = values.split(';')[9]
    revals = values.split(';')[10]
    timevals = values.split(';')[11]
    close = gen.Str_Bool(values.split(';')[12])

    ncfiles = ncfile.split(',')[0]
    ncfilel = ncfile.split(',')[1]

    vshadn = vnamesfig.split(',')[0]
    vlinen = vnamesfig.split(',')[1]
    
    if not os.path.isfile(ncfiles):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
        quit(-1)    
    if not os.path.isfile(ncfilel):
        print errormsg
        print '  ' + fname + ': line file "' + ncfilel + '" does not exist !!'
        quit(-1)    

    objsf = NetCDFFile(ncfiles, 'r')
    
    varns = varn.split(',')[0]

    if  not objsf.variables.has_key(varns):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varns + '" !!'
        quit(-1)

# Variables' values
    objvars = objsf.variables[varns]

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))

    dimnamesv = [vdimxn, vdimyn]

    varunits = objvars.getncattr('units')

    if vdimxn != 'WRFtime' and not objsf.variables.has_key(vdimxn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimxn + '" !!'
        quit(-1)
    if vdimyn != 'WRFtime' and not objsf.variables.has_key(vdimyn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have dimension variable "' +  vdimyn + '" !!'
        quit(-1)

    timename = timevals.split('|')[0]
    timeunit = timevals.split('|')[1].replace('!',' ')
    timekind = timevals.split('|')[2]
    timefmt = timevals.split('|')[3]
    timelabel = timevals.split('|')[4].replace('!',' ')

    # Getting time as WRF Times
    if timename == 'WRFtime':
        dictslice = {}
        for dnv in dimvals.split(','):
            dimn = dnv.split(':')[0]
            dimv = dnv.split(':')[1]
            if dimv.find(',') != -1: 
                dictslice[dimn] = list(np.array(dimv.split(','), dtype=int))
            else:
                dictslice[dimn] = int(dimv)

        wrft = objsf.variables['Times']
        slicewrft, dwrfd = ncvar.SliceVarDict(wrft, dictslice)
        timewrfv = wrft[tuple(slicewrft)]
        if len(timeunit.split(' ')) > 3:
            refdateS = timeunit.split(' ')[2] + ' ' + timeunit.split(' ')[3]
        else:
            refdateS = timeunit.split(' ')[2] + ' 00:00:00'
        tunitsval = timeunit.split(' ')[0]

        yrref=refdateS[0:4]
        monref=refdateS[5:7]
        dayref=refdateS[8:10]
        horref=refdateS[11:13]
        minref=refdateS[14:16]
        secref=refdateS[17:19]

        refdate = yrref + monref + dayref + horref + minref + secref

        dt = timewrfv.shape[0]
        cftimes = np.zeros((dt), dtype=np.float)
        for it in range(dt):
            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],        \
              'WRFdatetime', 'matYmdHMS')
            cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates,        \
              refdate, tunitsval)
        tunits = tunitsval + ' since ' + refdateS

    if vdimxn == timename:
        if timename != 'WRFtime':
            odimxv = objsf.variables[vdimxn][:]
        else:
            odimxv = cftimes
        odimxu = timelabel
        timeaxis = 'x'
        objdimyv = objsf.variables[vdimyn]
        odimyv = objdimyv[:]
        odimyu = objdimyv.getncattr('units')
        timepos, timelabels = drw.CFtimes_plot(odimxv, timeunit, timekind, timefmt)
    elif vdimyn == timename:
        if timename != 'WRFtime':
            odimyv = objsf.variables[vdimxn][:]
        else:
            odimyv = cftimes
        odimyu = timelabel
        timeaxis = 'y'
        objdimxv = objsf.variables[vdimxn]
        odimxv = objdimxv[:]
        odimxu = objdimxv.getncattr('units')
        timepos, timelabels = drw.CFtimes_plot(odimyv, timeunit, timekind, timefmt)
    else:
        print errormsg
        print '  ' + fname + ": time variable '" + timename + "' not found!!"
        quit(-1)

    shading_nx = shadminmax.split(',')

# Line values
## 
    linearg = linevalues.split(',')
    if linevalues.split(',')[1][0:1] != 'S':
        linearg[1] = np.float(linevalues.split(',')[1])
    if linevalues.split(',')[2][0:1] != 'S':
        linearg[2] = np.float(linevalues.split(',')[2])
    if linearg[3] == 'auto': linearg[3] = 'pretty'
    if linearg[4] == 'auto': linearg[4] = '5g'
    if linearg[5] == 'auto': linearg[5] = 5
    if linearg[6] == 'auto': linearg[6] = 0.

    vnamelfig = values.split(':')[0].split(',')[1]
    varnl = varn.split(',')[1]

    objlf = NetCDFFile(ncfilel,'r')
    objlvar = objlf.variables[varnl]

    linevals, dimsline = drw.slice_variable(objlvar, dimvals.replace(',','|'))
    varlunits = objlvar.units

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
    colormapv = [colbarn, fmtcolbar, colbaror]

    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if revals == 'None':
        revals = None

    drw.plot_2D_shadow_line_time(valshad, linevals, vshadn, vlinen, odimxv, odimyv,  \
      odimxu, odimyu, dimnamesv, xaxis, yaxis, colormapv, linearg, shading_nx,       \
      varunits, varlunits, figtitle, figkind, revals, timeaxis, timepos, timelabels, \
      close)

    objsf.close()
    objlf.close()

    return

def draw_barbs(ncfile, values, varns):
    """ Function to plot wind barbs
      draw_barbs(ncfile, values, varns)
      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[dimxv]:[dimyv]:[mapvalues]:[dimxyfmt]:
        [reverse]:[gtit]:[kindfig]:[figuren]:[close]
        [dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
          [dimname]: name of the dimension in the file
          [vardimname]: name of the variable with the values for the dimension in the file
          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
          No value takes all the range of the dimension
        [vecvals]= [frequency],[color],[length]
          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points; 
            'auto', computed automatically to have 20 vectors along each axis)
          [color]: color of the vectors ('auto', for 'red') two options:
            [colorname]: name of the color fixed for all vectors
            'colormap'@[colormapname]: use colormap to provide the colors tacking wind speed as reference
          [length]: length of the wind barbs ('auto', for 9)
        [windlabs]= [windname],[windunits]
          [windname]: name of the wind variable in the graph
          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
        [dimxvn]: Variables with the final values for the x dimension
        [dimyvn]: Variables with the final values for the y dimension
        [mapvalues]= map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [reverse]: Transformation of the values
          * 'transpose': reverse the axes (x-->y, y-->x)
          * 'flip'@[x/y]: flip the axis x or y
        [gtit]= title of the graph ('|', for spaces)
        [kindfig]= kind of figure
        [figuren]= name of the figure
        [close]= whether figure should be finished or not
      ncfile= file to use
      varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component
    """
    fname = 'draw_barbs'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_barbs.__doc__
        quit()

    expectargs = '[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[dimxv]:' +   \
      '[dimyv]:[mapvalues]:[reverse]:[dimxyfmt]:[gtit]:[kindfig]:[figuren]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    dimvals = values.split(':')[0]
    vecvals = values.split(':')[1]
    windlabels = values.split(':')[2]
    dimxvn = values.split(':')[3]
    dimyvn = values.split(':')[4]
    mapvalues = values.split(':')[5]
    dimxyfmt = values.split(':')[6]
    reverse = values.split(':')[7]
    gtit = values.split(':')[8]
    kindfig = values.split(':')[9]
    figuren = values.split(':')[10]
    close = gen.Str_Bool(values.split(':')[11])

    of = NetCDFFile(ncfile,'r')

    # Dictionary with the dimension name and its associated variable and slice
    dims = {}
    for dimv in dimvals.split(','):
        dns = dimv.split('|')
        dims[dns[0]] = [dns[1], dns[2]]

    varNs = [dimxvn, dimyvn]
    for dn in dims.keys():
        vdn = dims[dn]
        if vdn == dimxvn:
            dimx = len(of.dimensions[dn])
        elif vdn == dimyvn:
            dimy = len(of.dimensions[dn])

    # x-y variable-dimensions' names
    xydimns = [dimxvn, dimyvn]
    # x-y variable-dimensions' units
    xydimus = []
    odimx = of.variables[xydimns[0]]
    odimax = odimx.ncattrs()
    if gen.searchInlist(odimax,'units'):
        xydimus.append(odimx.getncattr('units'))
        odimy = of.variables[xydimns[1]]
        xydimus.append(odimy.getncattr('units'))
    else:
        xydimus= [gen.variable_values(xydimns[0])[4],gen.variable_values(xydimns[1])[4]]

    ivar = 0
    for wvar in varns.split(','):
        if not drw.searchInlist(of.variables.keys(), wvar):
            print errormsg
            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
            quit(-1)
        if ivar == 0:
            varNs.append(wvar)
        else:
            varNs.append(wvar)

    ivar = 0
    for varN in varNs:
        varslice = []

        ovarN = of.variables[varN]
        vard = ovarN.dimensions
        for vdn in vard:
            found = False
            for dd in dims.keys():
                if dd == vdn:
                    if dims[dd][1].find('@') != -1:
                        rvals = dims[dd][1].split('@')
                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
                    elif dims[dd][1] == '-1':
                        varslice.append(slice(0,len(of.dimensions[dd])))
                    else:
                        varslice.append(int(dims[dd][1]))

                    found = True
                    break
            if not found:
                varslice.append(slice(0,len(of.dimensions[vdn])))

        if ivar == 0:
            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
        elif ivar == 1:
            latvals0 = np.squeeze(ovarN[tuple(varslice)])
        elif ivar == 2:
            uwvals = np.squeeze(np.array(ovarN[tuple(varslice)]))
        elif ivar == 3:
            vwvals = np.squeeze(ovarN[tuple(varslice)])            

        ivar = ivar + 1

#    print 'Final shapes:',lonvals0.shape,':',latvals0.shape,':',uwvals.shape,':',
#      vwvals.shape

    if len(uwvals.shape) != 2 or len(vwvals.shape) != 2:
        print errormsg
        print '  ' + fname + ': wrong size of the wind fields! they must be ' +      \
          '2-dimensional!'
        print '    u-winds shape:',uwvals.shape,'dims:',of.variables[varNs[2]]
        print '    v-winds shape:',vwvals.shape,'dims:',of.variables[varNs[3]]
        print '      provide more values for their dimensions!!'
        quit(-1)

    if len(lonvals0.shape) == 1:
        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
    else:
        lonvals = lonvals0
        latvals = latvals0

# Vecor values
    if vecvals.split(',')[0] == 'None':
        freqv = None
    else:
        freqv = vecvals.split(',')[0] 
    colorv = vecvals.split(',')[1]
    lengthv = vecvals.split(',')[2]

# Vector labels
    windname = windlabels.split(',')[0]
    windunits = windlabels.split(',')[1]

    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if mapvalues == 'None':
        mapvs = None
    else:
        mapvs = mapvalues

    if reverse == 'None':
        revs = None
    else:
        revs = reverse

    drw.plot_barbs(lonvals, latvals, uwvals, vwvals, freqv, colorv, lengthv,         \
      windname, windunits, xaxis, yaxis, xydimns, xydimus, mapvs, revs, gtit,        \
      kindfig, figuren, close)

    return
 
def draw_topo_geogrid(ncfile, values):
    """ plotting geo_em.d[nn].nc topography from WPS files
    draw_topo_geogrid(ncfile, values)
      ncfile= geo_em.d[nn].nc file to use
      values= [minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]
        [min/max]Topo: minimum and maximum values of topography to draw
        lonlatL: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] or None
        title: title of the graph ('!' for spaces)
        graphic_kind: kind of figure (jpg, pdf, png)
        mapvalues: map characteristics [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        close: Whether figure should be finished or not
    """
    fname = 'draw_topo_geogrid'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_topo_geogrid.__doc__
        quit()

    expectargs= '[minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:'+ \
      '[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    mintopo = np.float(values.split(':')[0].split(',')[0])
    maxtopo = np.float(values.split(':')[0].split(',')[1])

    lonlatLS = values.split(':')[1]
    lonlatLv = lonlatLS.split(',')[0]

    if lonlatLv == 'None':
        lonlatL = None
    else:
        lonlatL = np.zeros((4), dtype=np.float)
        lonlatL[0] = np.float(lonlatLS.split(',')[0])
        lonlatL[1] = np.float(lonlatLS.split(',')[1])
        lonlatL[2] = np.float(lonlatLS.split(',')[2])
        lonlatL[3] = np.float(lonlatLS.split(',')[3])

    grtit = values.split(':')[2].replace('!',' ')
    kindfig = values.split(':')[3]
    mapvalues = values.split(':')[4]
    close = gen.Str_Bool(values.split(':')[5])

    if not os.path.isfile(ncfile):
        print errormsg
        print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
        quit(-1)    

    objdomf = NetCDFFile(ncfile, 'r')
    
    objhgt = objdomf.variables['HGT_M']
    objlon = objdomf.variables['XLONG_M']
    objlat = objdomf.variables['XLAT_M']

    topography = objhgt[0,:,:]

    drw.plot_topo_geogrid(topography, objlon, objlat, mintopo, maxtopo, lonlatL,     \
      grtit, kindfig, mapvalues, close)

    objdomf.close()

    return

def draw_topo_geogrid_boxes(ncfiles, values):
    """ plotting different geo_em.d[nn].nc topography from WPS files
    draw_topo_geogrid_boxes(ncfiles, values)
      ncfiles= ',' list of geo_em.d[nn].nc files to use (fisrt as topographyc reference)
      values= [minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:[labels]:[legvals]:[close]
        [min/max]Topo: minimum and maximum values of topography to draw
        lonlatL: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] or None
        title: title of the graph ('!' for spaces)
        graphic_kind: kind of figure (jpg, pdf, png)
        mapvalues: map characteristics [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        legvals: [locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        labels: labels to write in the graph ('!' for spaces)
        close: Whether figure should be finished or not
    """
#    import matplotlib as mpl
#    mpl.use('Agg')
    import matplotlib.pyplot as plt

    fname = 'draw_topo_geogrid_boxes'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_topo_geogrid_boxes.__doc__
        quit()

    expectargs = '[minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:'+\
       '[labels]:[legvals]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    mintopo = np.float(values.split(':')[0].split(',')[0])
    maxtopo = np.float(values.split(':')[0].split(',')[1])

    lonlatLS = values.split(':')[1]
    lonlatLv = lonlatLS.split(',')[0]

    if lonlatLv == 'None':
        lonlatL = None
    else:
        lonlatL = np.zeros((4), dtype=np.float)
        lonlatL[0] = np.float(lonlatLS.split(',')[0])
        lonlatL[1] = np.float(lonlatLS.split(',')[1])
        lonlatL[2] = np.float(lonlatLS.split(',')[2])
        lonlatL[3] = np.float(lonlatLS.split(',')[3])

    grtit = values.split(':')[2].replace('!', ' ')
    kindfig = values.split(':')[3]
    mapvalues = values.split(':')[4]
    labels = values.split(':')[5]
    legvals = values.split(':')[6]
    close = gen.Str_Bool(values.split(':')[7])

    ncfile = ncfiles.split(',')[0]
    if not os.path.isfile(ncfile):
        print errormsg
        print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
        quit(-1)    

    objdomf = NetCDFFile(ncfile, 'r')
    
    objhgt = objdomf.variables['HGT_M']
    objlon0 = objdomf.variables['XLONG_M']
    objlat0 = objdomf.variables['XLAT_M']

    topography = objhgt[0,:,:]

    Nfiles = len(ncfiles.split(','))
    boxlabels = labels.split(',')

    Xboxlines = []
    Yboxlines = []

    for ifile in range(Nfiles):
        ncfile = ncfiles.split(',')[ifile]
#        print ifile, ncfile
        if not os.path.isfile(ncfile):
            print errormsg
            print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
            quit(-1)    

        objdomfi = NetCDFFile(ncfile, 'r')
    
        objlon = objdomfi.variables['XLONG_M']
        objlat = objdomfi.variables['XLAT_M']

        dx = objlon.shape[2]
        dy = objlon.shape[1]

        Xboxlines.append(objlon[0,0,:])
        Yboxlines.append(objlat[0,0,:])
        Xboxlines.append(objlon[0,dy-1,:])
        Yboxlines.append(objlat[0,dy-1,:])
        Xboxlines.append(objlon[0,:,0])
        Yboxlines.append(objlat[0,:,0])
        Xboxlines.append(objlon[0,:,dx-1])
        Yboxlines.append(objlat[0,:,dx-1])

        objdomfi.close()

    # Legend
    locleg, legfontsize = drw.legend_values(legvals,'|')

    drw.plot_topo_geogrid_boxes(topography, Xboxlines, Yboxlines, boxlabels,         \
      objlon0, objlat0, mintopo, maxtopo, lonlatL, grtit, kindfig, mapvalues, locleg,\
      legfontsize, close)

    objdomf.close()

    return

def movievalslice(origslice, dimmovien, framenum):
    """ Function to provide variable slice according to a geneation of a movie
    movievals(origslice, dimmovien, framenum)
      [origslice]= slice original as [dimname1]|[val1],[...,[dimnameN]|[valN]] 
        ([val] = -1, full length) 
      [dimmovien]= name of the dimension to produce the movie
      [framenum]= value of the frame to substitue in [origslice] as 
        [dimmovien]|[framenum]
    >>> movievalslice('East_West|-1,North_South|-1,Time|2','Time',0)
    East_West|-1,North_South|-1,Time|0
    """

    fname = 'movievalslice'

    if origslice == 'h':
        print fname + '_____________________________________________________________'
        print movievalslice.__doc__
        quit()
    
    dims = origslice.split(',')

    movieslice = ''
    idim = 0

    for dimn in dims:
        dn = dimn.split('|')[0]
        if dn == dimmovien:
            movieslice = movieslice + dn + '|' + str(framenum)
        else:
            movieslice = movieslice + dimn
        if idim < len(dims)-1: movieslice = movieslice + ','

        idim = idim + 1

    return movieslice

class Capturing(list):
    """ Class to capture function output as a list
    from: http://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
    """
#    from cStringIO import StringIO

    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout

def create_movie(netcdfile, values, variable):
    """ Function to create a movie assuming ImageMagick installed!
      values= [graph]#[movie_dimension]#[graph_values]
        [graph]: which graphic
        [movie_dimension]: [dimnmovie]@[dimvmovie]@[moviedelay]@[interval]
          [dimnmovie]; name of the dimension from which make the movie
          [dimvmovie]; name of the variable with the values of the dimension
          [moviedelay]; delay between frames
          [interval]; [beg]@[end]@[freq] or -1 (all)
        [graph_values]: values to generate the graphic
      netcdfile= netCDF file
      variable= variable to use (when applicable)
    """ 
    fname = 'create_movie'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print create_movie.__doc__
        quit()

    graph = values.split('#')[0]
    movie_dim = values.split('#')[1]
    graph_vals = values.split('#')[2]

    ncobj = NetCDFFile(netcdfile, 'r')

# Movie dimension
##
    dimnmovie = movie_dim.split('@')[0]
    dimvmovie = movie_dim.split('@')[1]
    moviedelay = movie_dim.split('@')[2]
    moviebeg = int(movie_dim.split('@')[3])

    if not drw.searchInlist(ncobj.dimensions.keys(),dimnmovie):
        print errormsg
        print '  ' + fname + ": file '" + netcdfile + "' has not dimension '" +      \
          dimnmovie + "' !!!"
        quit(-1)

    objdmovie = ncobj.dimensions[dimnmovie]
    dmovie = len(objdmovie)
    if moviebeg != -1:
        moviend = int(movie_dim.split('@')[4])
        moviefreq = int(movie_dim.split('@')[5])
    else:
        moviebeg = 0
        moviend = dmovie
        moviefreq = 1

    if dimvmovie == 'WRFTimes':
        objvdmovie = ncobj.variables['Times']
        vdmovieunits = ''
        valsdmovie = []
        for it in range(objvdmovie.shape[0]):
            valsdmovie.append(drw.datetimeStr_conversion(objvdmovie[it,:],           \
              'WRFdatetime', 'Y/m/d H-M-S'))
    elif dimvmovie == 'CFtime':
        objvdmovie = ncobj.variables['time']
        vdmovieunits = ''
        print objvdmovie.units
        valsdmovie0 = drw.netCDFdatetime_realdatetime(objvdmovie.units, 'standard',  \
          objvdmovie[:])
        valsdmovie = []
        for it in range(objvdmovie.shape[0]):
            valsdmovie.append(drw.datetimeStr_conversion(valsdmovie0[it,:],          \
              'matYmdHMS', 'Y/m/d H-M-S'))
    else:
        if  not drw.searchInlist(ncobj.variables.keys(),dimvmovie):
            print errormsg
            print '  ' + fname + ": file '" + netcdfile + "' has not variable '" +   \
              dimvmovie + "' !!!"
            quit(-1)
        vdmovieunits = objvdmovie.getncattr('units')
        objvdmovie = ncobj.variables[dimvmovie]
        if len(objvdmovie.shape) == 1:
            vasldmovie = objvdmovie[:]
        else:
            print errormsg
            print '  ' + fname + ': shape', objvdmovie.shape, 'of variable with ' +  \
              'dimension movie values not ready!!!'
            quit(-1)

    ncobj.close()
    os.system('rm frame_*.png > /dev/null')

# graphic
##
    if graph == 'draw_2D_shad':
        graphvals = graph_vals.split(':')

        for iframe in range(moviebeg,moviend,moviefreq):
            iframeS = str(iframe).zfill(4)

            drw.percendone((iframe-moviebeg)/moviefreq,(moviend-moviebeg)/moviefreq, \
              5, 'frames')
            titgraph = dimnmovie + '|=|' + str(valsdmovie[iframe]) + '|' +           \
              vdmovieunits

            graphvals[1] = movievalslice(graphvals[1],dimnmovie,iframe)
            graphvals[6] = titgraph
            graphvals[7] = 'png'

            graphv = drw.numVector_String(graphvals, ":")

            with Capturing() as output:
                draw_2D_shad(netcdfile, graphv, variable)

            os.system('mv 2Dfields_shadow.png frame_' + iframeS + '.png')
    else:
        print errormsg
        print '  ' + fname + ": graphic '" +  graph + "' not defined !!!"
        quit(-1)

    os.system('convert -delay ' + moviedelay + ' -loop 0 frame_*.png create_movie.gif')

    print "Succesfuly creation of movie file 'create_movie.gif' !!!"

    return

def draw_lines(ncfilens, values, varname):
    """ Function to draw different lines at the same time from different files
    draw_lines(ncfilens, values, varname):
      ncfilens= [filen] ',' separated list of netCDF files
      values= [dimvname]:[valuesaxis]:[dimtit]:[dimxyfmt]:[leglabels]:[vtit]:[title]:[legvals]:[colns]:[lines]
       [points]:[lwdths]:[psizes]:[freqv]:[figname]:[graphk]:[close]
        [dimvname]: ',' list of names of the variable with he values of the common dimension
        [valuesaxis]: which axis will be used for the values ('x', or 'y')
        [dimtit]: title for the common dimension
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [leglabels]: ',' separated list of names for the legend ('!' for spaces)
        [vartit]: name of the variable in the graph
        [title]: title of the plot ('|' for spaces)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [colns]= ',' list of color names ('None' for automatic, single value for all the same)
        [lines]= ',' list of style of lines ('None' for automatic, single value for all the same)
        [points]= '@' list of style of points ('None' for automatic, single value for all the same)
        [lwdths]= ',' list of withs of lines ('None' for automatic, single value for all the same)
        [psizes]= ',' list of size of points ('None' for automatic, single value for all the same)
        [freqv]= frequency of values ('all' for all values)
        [figname]= name of the figure
        [graphk]: kind of the graphic
        [close]: should figure be closed (finished)
      varname= variable to plot
      values= 'XLAT:x:latitude:32x32:$wss^{*}$:wss Taylor's turbulence term:pdf'
    """

    fname = 'draw_lines'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_lines.__doc__
        quit()

    expectargs = '[dimvname]:[valuesaxis]:[dimtit]:[dimxyfmt]:[leglabels]:[vtit]:' + \
      '[title]:[legvals]:[colns]:[lines]:[points]:[lwdths]:[psizes]:[freqv]:' +      \
      '[figname]:[graphk]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    ncfiles = ncfilens.split(',')
    dimvnames = values.split(':')[0]
    valuesaxis = values.split(':')[1]
    dimtit = values.split(':')[2]
    dimxyfmt = values.split(':')[3]
    leglabels = gen.latex_text(values.split(':')[4].replace('!',' '))
    vartit = values.split(':')[5]
    title = values.split(':')[6].replace('|',' ')
    legvals = values.split(':')[7]
    colns = gen.str_list(values.split(':')[8], ',')
    lines = gen.str_list(values.split(':')[9], ',')
    points = gen.str_list(values.split(':')[10], '@')
    lwdths = gen.str_list_k(values.split(':')[11], ',', 'R')
    psizes = gen.str_list_k(values.split(':')[12], ',', 'R')
    freqv0 = values.split(':')[13]
    figname = values.split(':')[14]
    graphk = values.split(':')[15]
    close = gen.Str_Bool(values.split(':')[16])

    Nfiles = len(ncfiles)

# Getting trajectotries 
##

    varvalues = []
    dimvalues = []

    print '  ' + fname
    ifn = 0
    for ifile in ncfiles:
        filen = ifile.split('@')[0]

        print '    filen:',filen

        if not os.path.isfile(filen):
            print errormsg
            print '  ' + fname + ": netCDF file '" + filen + "' does not exist !!"
            quit(-1)

        objfile = NetCDFFile(filen, 'r')

        if dimvnames.find(',') != -1:
            dimvname = dimvnames.split(',')
        else:
            dimvname = [dimvnames]
   
        found = False
        for dvn in dimvname:
            if objfile.variables.has_key(dvn):
                found = True
                break
    
        if not found:
            print errormsg
            print '  ' + fname + ": netCDF file '" + filen +                         \
              "' does not have variables '" + dimvnames + "' !!"
            quit(-1)

        if not objfile.variables.has_key(varname):
            print errormsg
            print '  ' + fname + ": netCDF file '" + filen +                         \
              "' does not have variable '" + varname + "' !!"
            quit(-1)

        vvobj = objfile.variables[varname]
        if len(vvobj.shape) != 1:
            print errormsg
            print '  ' + fname + ': wrong shape:',vvobj.shape," of variable '" +     \
              varname +  "' !!"
            quit(-1)

        for dimvn in dimvname:
            if drw.searchInlist(objfile.variables, dimvn):
                vdobj = objfile.variables[dimvn]
                if len(vdobj.shape) != 1:
                    print errormsg
                    print '  ' + fname + ': wrong shape:',vdobj.shape,               \
                      " of variable '" + dimvn +  "' !!"
                    quit(-1)
                break

        varvalues.append(vvobj[:])
        dimvalues.append(vdobj[:])

        if ifn == 0:
            varunits = vvobj.units

        objfile.close()

        ifn = ifn + 1

    if freqv0 == 'all':
        freqv = None
    else:
        freqv = int(freqv0)

    # Legend
    locleg, legfontsize = drw.legend_values(legvals,'|')

    # axis
    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    drw.plot_lines(dimvalues, varvalues, valuesaxis, dimtit, xaxis, yaxis,           \
      leglabels.split(','), vartit, varunits, title, locleg, legfontsize, colns,     \
      lines, points, lwdths, psizes, freqv, figname, graphk, close)

    return

def draw_lines_time(ncfilens, values, varnames):
    """ Function to draw different lines at the same time from different files with times
    draw_lines_time(ncfilens, values, varname):
      ncfilens= [filen] ',' separated list of netCDF files
      values= [dimvname];[valuesaxis];[dimtit];[dimxyfmt];[leglabels];[vtit];[title];[rangevals];[timevals];
        [legvals];[graphk];[collines];[points];[linewidths];[pointsizes];[pointfreq];[period];[close]
        [dimvname]: ',' list of names of the variables with he values of the common dimension ('WRFtime' for WRF Times variable)
        [valuesaxis]: which axis will be used for the values ('x', or 'y')
        [dimtit]: title for the common dimension ('|' for spaces)
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [leglabels]: ',' separated list of names for the legend ('None', no legend '!' for spaces)
        [vartit]: name of the variable in the graph
        [title]: title of the plot ('|' for spaces)
        [rangevals]: Range of the axis with the values ('None' for 'auto','auto')
          [vmin],[vmax]: minimum and maximum values where [vmNN] can also be:
            'auto': the computed minimumm or maximum of the values  
        [timevals]: [timen]|[units]|[kind]|[tfmt] time labels characteristics
           [timen]; name of the time variable
           [units]; units string according to CF conventions ([tunits] since 
             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
           [kind]; kind of output
             'Nval': according to a given number of values as 'Nval',[Nval]
             'exct': according to an exact time unit as 'exct',[tunit]; 
               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
                'l': milisecond
           [tfmt]; desired format
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [graphk]: kind of the graphic
        [lines]: ',' list of type of lines, None for automatic, single value all the same
        [collines]: ',' list of colors for the lines, None for automatic, single 
          value all the same
        [points]: '@' list of type of points for the lines, None for automatic, single
          value all the same
        [linewidths]: ',' list of widths for the lines, None for automatic, single
          value all the same
        [pointsizes]: ',' list of widths for the lines, None for automatic, single
          value all the same
        [pointfreq]: frequency of point plotting, 'all' for all time steps
        [period]: which period to plot
          '-1': all period
          [beg],[end]: beginning and end of the period in reference time-units of first file
        [close]: Whether figure should be finished or not
      varnames= ',' list of variable names to plot (assuming only 1 variable per file)
      values= 'time;y;time ([DD]${[HH]}$);32x32;$wss^{*}$;wss Taylor's turbulence term;time|hours!since!1949-12-01_00:00:00;exct,12,h|%d$^{%H}$;2;pdf'
    """

    fname = 'draw_lines_time'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_lines_time.__doc__
        quit()

    expectargs = '[dimvname];[valuesaxis];[dimtit];[dimxyfmt];[leglabels];[vtit];' + \
      '[title];[rangevals];[timevals];[legvals];[graphk];[lines];[collines];' +      \
      '[points];[linewidths];[pointsizes];[pointfreq];[period];[close]'
    drw.check_arguments(fname,values,expectargs,';')

    ncfiles = ncfilens.split(',')
    dimvname0 = values.split(';')[0]
    valuesaxis = values.split(';')[1]
    dimtit = values.split(';')[2].replace('|',' ')
    dimxyfmt = values.split(';')[3]
    leglabels = gen.latex_text(values.split(';')[4]).replace('!',' ')
    vartit = values.split(';')[5]
    title = values.split(';')[6].replace('|',' ')
    rangevals = values.split(';')[7]
    timevals = values.split(';')[8]
    legvals = values.split(';')[9]
    graphk = values.split(';')[10]
    lines0 = values.split(';')[11]
    collines0 = values.split(';')[12]
    points0 = values.split(';')[13]
    linewidths0 = values.split(';')[14]
    pointsizes0 = values.split(';')[15]
    pointfreq0 = values.split(';')[16]
    period = values.split(';')[17]
    close = gen.Str_Bool(values.split(';')[18])

    Nfiles = len(ncfiles)

# Multiple variable-dimension names?
    if dimvname0.find(',') != -1:
        dimvname = dimvname0.split(',')
    else:
        dimvname = [dimvname0]

# Multiple variables?
    if varname0.find(',') != -1:
        varname = varname0.split(',')
    else:
        varname = [varname0]

# Multiple lines types?
    if lines0.find(',') != -1:
        lines = lines0.split(',')
    elif lines0 == 'None':
        lines = None
    else:
        lines = []
        for il in range(Nfiles):
            lines.append(lines0)

# Multiple color names?
    if collines0.find(',') != -1:
        collines = collines0.split(',')
    elif collines0 == 'None':
        collines = None
    else:
        collines = []
        for ip in range(Nfiles):
            collines.append(collines0)

# Multiple point types?
    if points0.find(',') != -1:
        if len(points0) == 1:
            points = []
            for ip in range(Nfiles):
                points.append(points0)
        else:
            points = points0.split('@')
    elif points0 == 'None':
        points = None
    else:
        points = []
        for ip in range(Nfiles):
            points.append(points0)

# Multiple line sizes?
    if linewidths0.find(',') != -1:
        linewidths = []
        Nlines = len(linewidths0.split(','))
        for il in range(Nlines):
          linewidths.append(np.float(linewidths0.split(',')[il]))
    elif linewidths0 == 'None':
        linewidths = None
    else:
        linewidths = [np.float(linewidths0)]

# Multiple point sizes?
    if pointsizes0.find(',') != -1:
        pointsizes = []
        Npts = len(pointsizes0.split(','))
        for ip in Npts:
          pointsizes.append(np.float(pointsizes0.split(',')[ip]))
    elif pointsizes0 == 'None':
        pointsizes = None
    else:
        pointsizes = [np.float(pointsizes0)]

    timename = timevals.split('|')[0]
    timeunit = timevals.split('|')[1].replace('!',' ')
    timekind = timevals.split('|')[2]
    timefmt = timevals.split('|')[3]

    if rangevals == 'None':
        valmin = 'auto'
        valmax = 'auto'
    else:
        valmin = rangevals.split(',')[0]
        valmax = rangevals.split(',')[1]
        if valmin != 'auto': valmin = np.float(valmin)
        if valmax != 'auto': valmax = np.float(valmax)

    # Legend
    locleg, legfontsize = drw.legend_values(legvals,'|')

# Getting values
##
    varvalues = []
    dimvalues = []
    timvalues = []
    timvals0 = timvalues

    print '  ' + fname
    ifn = 0
    mintval = 1.e20
    maxtval = -1.e20

    for ifile in ncfiles:
        filen = ifile.split('@')[0]

        print '    filen:',filen

        if not os.path.isfile(filen):
            print errormsg
            print '  ' + fname + ": netCDF file '" + filen + "' does not exist !!"
            quit(-1)

        objfile = NetCDFFile(filen, 'r')

        founddvar = False
        for dvar in dimvname:
            if dvar != 'WRFtime' and objfile.variables.has_key(dvar):
                founddvar = True
                vdobj = objfile.variables[dvar]
                uvd = str(vdobj.units)
                if len(vdobj.shape) != 1:
                    print errormsg
                    print '  ' + fname + ': wrong shape:',vdobj.shape," of " +       \
                      "variable '" + dvar +  "' !!"
                    quit(-1)
                vdvals = vdobj[:]
                break
            elif dvar == 'WRFtime' and objfile.variables.has_key('Times'):
                founddvar = True
                uvd = timeunit
                tunitsec = timeunit.split(' ')
                if len(tunitsec) == 4:
                    refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +  \
                      tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
                else:
                    refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +  \
                      '000000'
                tunitsval = tunitsec[0]

                timewrfv = objfile.variables['Times']
                dt = timewrfv.shape[0]
                vdvals = np.zeros((dt), dtype=np.float)

                for it in range(dt):
                    wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],            \
                      'WRFdatetime', 'matYmdHMS')
                    vdvals[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate,    \
                      tunitsval)

        if not founddvar:
            print errormsg
            print '  ' + fname + ": netCDF file '" + filen +                         \
            "' has any variable '", dimvname, "' !!"
            quit(-1)

        foundvar = False
        for var in varname:
            if objfile.variables.has_key(var):
                foundvar = True
                vvobj = objfile.variables[var]
                if len(vvobj.shape) != 1:
                    print errormsg
                    print '  ' + fname + ': wrong shape:',vvobj.shape," of " +       \
                      "variable '" + var +  "' !!"
                    quit(-1)

                break
        if not foundvar:
            print errormsg
            print '  ' + fname + ": netCDF file '" + filen +                         \
              "' has any variable '", varname, "' !!"
            quit(-1)
        if uvd.find('month') != -1:
            print warnmsg
            print '  ' + fname + ": transforming time units from 'months' to 'days'!!"
            timevals0, tunits0 = gen.CFmonthU_daysU(vdvals[:], vdobj.units) 
        else:
            timevals0 = vdvals[:]
            tunits0 = uvd 

# Getting period
        if ifn > 0: 
# Referring all times to the same reference time!
            reftvals = gen.coincident_CFtimes(timevals0, timeunit, tunits0)
        else:
            reftvals = timevals0

        dimt = len(vdvals[:])

        if period == '-1':
            varvalues.append(vvobj[:])
            dimvalues.append(reftvals)
            mindvals = np.min(reftvals)
            maxdvals = np.max(reftvals)
        else:
            ibeg=-1
            iend=-1
            tbeg = np.float(period.split(',')[0])
            tend = np.float(period.split(',')[1])

            for it in range(dimt-1):
                if reftvals[it] <= tbeg and reftvals[it+1] > tbeg: ibeg = it
                if reftvals[it] <= tend and reftvals[it+1] > tend: iend = it + 1
                if ibeg != -1 and iend != -1: break

            if ibeg == -1 and iend == -1:
                print warnmsg
                print '  ' + fname + ': Period:',tbeg,',',tend,'not found!!'
                print '    ibeg:',ibeg,'iend:',iend
                print '    period in file:',np.min(reftvals), np.max(reftvals)
                print '    getting all the period in file !!!'
                ibeg = 0
                iend = dimt
            elif iend == -1:
                iend = dimt
                print warnmsg
                print '  ' + fname + ': end of Period:',tbeg,',',tend,'not found!!'
                print '    getting last available time instead'
                print '    ibeg:',ibeg,'iend:',iend
                print '    period in file:',np.min(reftvals), np.max(reftvals)
            elif ibeg == -1:
                ibeg = 0
                print warnmsg
                print '  ' + fname + ': beginning of Period:',tbeg,',',tend,         \
                  'not found!!'
                print '    getting first available time instead'
                print '    ibeg:',ibeg,'iend:',iend
                print '    period in file:',np.min(reftvals), np.max(reftvals)

            varvalues.append(vvobj[ibeg:iend])
            dimvalues.append(reftvals[ibeg:iend])
            mindvals = np.min(reftvals[ibeg:iend])
            maxdvals = np.max(reftvals[ibeg:iend])

            dimt = iend - ibeg

        if mindvals < mintval: mintval = mindvals
        if maxdvals > maxtval: maxtval = maxdvals
        print '  ' + fname + ": file '" + filen + "' period:", mindvals, '->', maxdvals

        if ifn == 0:
            varunits = drw.units_lunits(vvobj.units)

        objfile.close()

        ifn = ifn + 1

# Times

    dtvals = (maxtval - mintval)/dimt
#    dti = mintval-dtvals/2. 
#    dte = maxtval+dtvals/2. 
    dti = mintval
    dte = maxtval
    tvals = np.arange(dti, dte, dtvals)

    dtiS = drw.datetimeStr_conversion(str(dti) + ',' + timeunit, 'cfTime',           \
      'Y/m/d H-M-S')
    dteS = drw.datetimeStr_conversion(str(dte) + ',' + timeunit, 'cfTime',           \
      'Y/m/d H-M-S')

    print '  ' + fname + ': plotting from: ' + dtiS + ' to ' + dteS

    timepos, timelabels = drw.CFtimes_plot(tvals, timeunit, timekind, timefmt)

#    print 'Lluis min/max tval +/- dtval/2:', mintval-dtvals/2., maxtval+dtvals/2.,'dt:', len(tvals)
#    for it in range(len(timepos)):
#        print timepos[it], timelabels[it]

    if leglabels != 'None':
        legvals = leglabels.split(',')
    else:
        legvals = None

    if pointfreq0 == 'all':
        pointfreq = None
    else:
        pointfreq = int(pointfreq0)

    # axis
    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    drw.plot_lines_time(dimvalues, varvalues, valuesaxis, xaxis, yaxis, dimtit,      \
      legvals, vartit, varunits, timepos, timelabels, title, locleg, legfontsize,    \
      graphk, valmin, valmax, lines, collines, points, linewidths, pointsizes,       \
      pointfreq, close)

    return

def draw_Neighbourghood_evol(filen, values, variable):
    """ Function to draw the temporal evolution of a neighbourghood around a point
    draw_Neighbourghood_evol(filen, values, variable)
      filen= netCDF file name
      values= [gvarname]:[dimsval]:[neigdims]:[Nneig]:[Ncol]:[timetits]:[tkinds]:
       [timefmts]:[gtitle]:[shadxtrms]:[colobarvals]:[neighlinevals]:[gkind]:[ofile]:[close]
        [gvarname]: ':' list of names of the variables in the plot
        [dimsval]: [dimn1]|[val1]|[dimv1],...,[dimnN]|[valN]|[dimvN] dimension names, values to get:
          * [integer]: which value of the dimension
          * -1: all along the dimension
          * NOTE, no dim name all the dimension size
          'WRFtime' for WRF times
          NOTE: when dimsval[X,Y] == neigdims[X,Y], valX,valY --> valX,valY-Nneig/2, valX,valY+Nneig/2
        [neigdims]: [dimnX],[dimnY] dimensions mnames along which the neigbourghood should be defined
        [Nneig]: Number of grid points of the full side of the box (odd value)
        [Ncol]: Number of columns ('auto': square final plot)
        [gvarname]: name of the variable to appear in the graph
        [timetits]: [titX],[titY] titles of the axes ('|' for spaces)
        [tkinds]: [tkindX]|[tkindY] kinds of time to appear in the graph
          'Nval': according to a given number of values as 'Nval',[Nval]
          'exct': according to an exact time unit as 'exct',[tunit]; 
            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
              'l': milisecond
        [timefmts]: [tfmtX],[tfmtY] format of the time labels
        [gtitle]: title of the graphic ('|' for spaces)
        [shadxtrms]: minimum and maximum value for the shading or:
          'Srange': for full range
          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
          'Saroundminmax@val': for min*val,max*val
          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
            percentile_(100-val)-median)
          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
             percentile_(100-val)-median)
        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation] characteristics of the colormap and colorbar
          [colorbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
        [neighlinevals]=[linecol],[linestyle],[linewidth] characterisitcs of the lines to mark the limits of the neighborhood
          ('auto' for: ['#646464', '-', 2.])
          [linecol]: color of the line
          [linestyle]: style of the line
          [linewidth]: width of the line
        [gkind]: kind of graphical output
        [ofile]: True/False whether the netcdf with data should be created or not
        [close]: Whether figure should be finished or not
      variable= name of the variable
      values = 'q:Time|-1|Times,bottom_top|6|ZNU,south_north|3|XLAT,west_east|26|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,2,h|exct,1,d:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution:0.0,0.004:BuPu:pdf:True'
    """ 

    fname = 'draw_Neighbourghood_evol'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_Neighbourghood_evol.__doc__
        quit()

    expectargs = '[gvarname]:[dimsval]:[neigdims]:[Nneig]:[Ncol]:' +                 \
      '[timetits]:[tkinds]:[timefmts]:[gtitle]:[shadxtrms]:[colorbarvals]:' +        \
      '[neighlinevals]:[gkind]:[ofile]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    gvarname = values.split(':')[0]
    dimsval = values.split(':')[1].split(',')
    neigdims = values.split(':')[2].split(',')
    Nneig = int(values.split(':')[3])
    Ncol0 = values.split(':')[4]
    timetits = values.split(':')[5].split(',')
    timekinds = values.split(':')[6].split('|')
    timefmts = values.split(':')[7].split(',')
    gtitle = values.split(':')[8].replace('|',' ')
    shadxtrms = values.split(':')[9].split(',')
    colorbarvals = values.split(':')[10]
    neighlinevals = values.split(':')[11]
    gkind = values.split(':')[12]
    ofile = values.split(':')[13]
    close = gen.Str_Bool(values.split(':')[14])

    if Ncol0 != 'auto': 
        Ncol = int(Ncol0)
    else:
        Ncol = Ncol0

    timetits[0] = timetits[0].replace('|',' ')
    timetits[1] = timetits[1].replace('|',' ')

    if np.mod(Nneig,2) == 0:
        print errormsg
        print '  ' + fname + ": an odd value for 'Nneig':", Nneig, 'is required !!!'
        quit(-1)

    Nneig2 = int(Nneig/2)

# Values to slice the variable
    dimvslice = {}
    dimvvalues = {}
    for dimvs in dimsval:
        dimn = dimvs.split('|')[0]
        dimv = int(dimvs.split('|')[1])
        dimnv = dimvs.split('|')[2]

        dimvvalues[dimn] = dimnv
        dimvslice[dimn] = dimv

    ncobj = NetCDFFile(filen, 'r')

    varobj = ncobj.variables[variable]

    slicevar = []
    newdimn = []
    newdimsvar = {}

    for dimn in varobj.dimensions:
        if not drw.searchInlist(dimvslice.keys(), dimn):
            dimsize = len(ncobj.dimensions[dimn])
            slicevar.append(slice(0, dimsize+1))
            newdimn.append(dimn)
            newdimsvar[dimn] = dimsize

        for dimslicen in dimvslice.keys():
            if dimn == dimslicen:
                if dimvslice[dimn] != -1:
                    if drw.searchInlist(neigdims, dimn):
                        slicevar.append(slice(dimvslice[dimn]-Nneig2,                \
                          dimvslice[dimn]+Nneig2+1))
                        newdimn.append(dimn)
                        newdimsvar[dimn] = Nneig
                        break
                    else:
                        slicevar.append(slice(dimvslice[dimn], dimvslice[dimn]+1))
                        break
                else:
                    dimsize = len(ncobj.dimensions[dimn])
                    slicevar.append(slice(0, dimsize+1))
                    newdimn.append(dimn)
                    newdimsvar[dimn] = dimsize
                    break
 
    varv = varobj[tuple(slicevar)]

    if len(newdimn) != 3:
        print errormsg
        print '  ' + fname + ': sliced variable with shape=', varv.shape,            \
          ' must have three dimensions',len(varv.shape),'given !!'
        quit(-1)

    newdims = []
    for nwdims in newdimn:
        newdims.append(newdimsvar[nwdims])

# The dimension which is not in the neighbourhood dimensions must be time!
    for dim1 in newdimn:
        if not drw.searchInlist(neigdims, dim1):
            dimt = newdimsvar[dim1]
            dimtime = dim1

    # Number of columns and rows
    if Ncol == 'auto':
        dimtsqx = int(np.sqrt(dimt))
    else:
        dimtsqx = int(Ncol)

    dimtsqy = dimt/dimtsqx + 1
    print '  ' + fname + '; plotting ', dimtsqx, 'x', dimtsqy, 'time-windows of:',   \
      Nneig, 'x', Nneig, 'grid-points'

    neighbourghood = np.ones((dimtsqy*Nneig,dimtsqx*Nneig), dtype=np.float)*fillValue

    for it in range(dimt):
        ity = int(it/dimtsqx)
        itx = it-ity*dimtsqx

        itty = (dimtsqy - ity - 1)*Nneig + Nneig2
        ittx = itx*Nneig + Nneig2

        neighbourghood[itty-Nneig2:itty+Nneig2+1,ittx-Nneig2:ittx+Nneig2+1]=         \
          varv[it,::-1,:]

    variablevals = drw.variables_values(variable)
    if drw.searchInlist(varobj.ncattrs(), 'units'):
        vunits = varobj.units
    else:
        vunits = variablevals[5]

# Time values at the X/Y axes
    if dimvvalues[dimtime] == 'WRFtime':
        print '    ' + fname + ": WRF time variable!: 'Times'"
        refdate = '19491201000000'
        tunitsval = 'hours'
        dimtvalues = np.zeros((dimt), dtype=np.float)
        tvals = ncobj.variables['Times']
        yrref=refdate[0:4]
        monref=refdate[4:6]
        dayref=refdate[6:8]
        horref=refdate[8:10]
        minref=refdate[10:12]
        secref=refdate[12:14]

        refdateS = yrref + '/' + monref + '/' + dayref + '_' + horref + ':' +        \
          minref + ':' + secref
        tunits = tunitsval + ' since ' + refdateS
        for it in range(dimt):
            wrfdates = drw.datetimeStr_conversion(tvals[it,:],'WRFdatetime', 'matYmdHMS')
            dimtvalues[it] = drw.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
    else:
        dimtvalues = ncobj.variables[dimvvalues[dimtime]][:]
        tunits = ncobj.variables[newdimsvar[dimtime]].units

    dimxv = dimtvalues[0:dimtsqx]
    dimyv = dimtvalues[0:dimt:dimtsqx]

    dimn = ['time','time']

    if ofile == 'True':
        ofilen = 'Neighbourghood_evol.nc'
        newnc = NetCDFFile(ofilen, 'w')
# Dimensions
        newdim = newnc.createDimension('time',None)
        newdim = newnc.createDimension('y',dimtsqy*Nneig)
        newdim = newnc.createDimension('x',dimtsqx*Nneig)
# Dimension values
        newvar = newnc.createVariable('time','f8',('time'))
        newvar[:] = np.arange(dimt)
        newattr = drw.basicvardef(newvar, 'time','time',tunits)
# Neighbourhghood variable
        newvar = newnc.createVariable(variable + 'neigevol', 'f4', ('y','x'),        \
          fill_value=fillValue)
        newvar[:] = neighbourghood

        newnc.sync()
        newnc.close()
        print fname + ": Successfull generation of file '" + ofilen + "' !!"
# Colorbar values
    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
    colormapv = [colbarn, fmtcolbar, colbaror]

# Neighborhood line values
    if neighlinevals == 'auto':
        neiglinev = ['#646464', '-', 2.]
    else:
        neiglinev = neighlinevals.split(',')

# Time ticks
    timeposX, timelabelsX = drw.CFtimes_plot(dimxv, tunits, timekinds[0], timefmts[0])
    timeposY, timelabelsY = drw.CFtimes_plot(dimyv, tunits, timekinds[1], timefmts[1])

    timepos = [timeposX[0:len(timeposX)], timeposY[len(timeposY):0:-1]]
    timelabels = [timelabelsX[0:len(timeposX)], timelabelsY[0:len(timeposY)]]

    for i in range(2):
        if shadxtrms[i][0:1] != 'S':
            shadxtrms[i] = np.float(shadxtrms[i])

    drw.plot_Neighbourghood_evol(neighbourghood, dimxv, dimyv, gvarname, timetits,   \
      timepos, timelabels, colormapv, neiglinev, Nneig, shadxtrms, vunits, gtitle,   \
      gkind, close)

def draw_points(filen, values):
    """ Function to plot a series of points read from an ASCII file with lon, lat, label
      draw_points(filen, values)
      [values]= [ptasciifile]:[gtit]:[dimxyfmt]:[mapvalues]:[kindfigure]:[pointcolor]:[pointlabels]:
        [legvals]:[figureko]:[figuren]:[close]
        [ptasciifile]:[file],[comchar],[collon],[collat],[lab]
          [file]: column ASCII file with the location of the points
          [comchar]: '|' list of characters for commentaries
          [collon]: number of column with the longitude of the points
          [collat]: number of column with the latitude of the points
          [collab]: number of column with the labels of the points ('None', and will get
            the values from the [pointlabels] variable
        [gtit]: title of the figure ('|' for spaces)
        [dimxyfmt]: [dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Vfix', values computed at even 'Ndx' increments
            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
          [dys]: style of y-axis ('auto' for 'pretty')
          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
        [mapvalues]: drawing coastaline ([proj],[res]) or None
          [proj]: projection
             * 'cyl', cilindric
             * 'lcc', lambert conformal
          [res]: resolution:
             * 'c', crude
             * 'l', low
             * 'i', intermediate
             * 'h', high
             * 'f', full
        [kindfigure]: kind of figure
          'legend': only points in the map with the legend with the names
          'labelled',[txtsize],[txtcol]: points with the names and size, color of text
        [pointcolor]: color for the points ('auto' for "red")
        [pointlabels]: ',' of labels [only used if [collab]='None'] ('None' for no labels, '!' for spaces)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [figureko]: kind of the output file (pdf, png, ...)
        [figuren]: name of the figure
        [close]: Whether figure should be finished or not
      [filen]= [ncfile],[lonvarn],[latvarn][,[varn],[dimvals],[vargn],[min],[max],[colbarn],[fmtcolorbar],[orientation],[varu]]
        [ncfile]: netCDF to use to geolocalize the points
        [lonvarn]: name of the variable with the longitudes
        [latvarn]: name of the variable with the latitudes
        Optional values:
          [varn]: optional variable to add staff into the graph
          [dimval]: '@' list of [dimn]|[dimval] to get the values for [varn]
            [dimn]: name of the dimension
            [dimval]: value of the dimension variable a given value is required:
              * [integer]: which value of the dimension
              * -1: all along the dimension
              * -9: last value of the dimension
              * [beg];[end];[inc] slice from [beg] to [end] every [inc]
              * NOTE, no dim name all the dimension size
          [vargn]: name of the variable in the graph
          [min]: minimum value for the extra variable
          [max]: maximum value for the extra variable
          [colbarn]: name of the color bar
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
          [varu]: units of the variable
    """
    fname = 'draw_points'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_points.__doc__
        quit()

    expectargs = '[ptasciifile]:[gtit]:[dimxyfmt]:[mapvalues]:[kindfigure]:' +       \
      '[pointcolor]:[pointlabels]:[locleg]:[figurek]:[figuren]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    ptasciifile = values.split(':')[0]
    gtit = values.split(':')[1]
    dimxyfmt = values.split(':')[2]
    mapvalues = values.split(':')[3]
    kindfigure = values.split(':')[4]
    pointcolor = values.split(':')[5]
    pointlabels = values.split(':')[6].replace('!',' ')
    locleg = int(values.split(':')[7])
    figureko = values.split(':')[8]
    figuren = values.split(':')[9]
    close = gen.Str_Bool(values.split(':')[10])

# Getting station locations
## 
    filev = ptasciifile.split(',')[0]
    comchar = ptasciifile.split(',')[1].split('|')
    collon = int(ptasciifile.split(',')[2])
    collat = int(ptasciifile.split(',')[3])
    collab = ptasciifile.split(',')[4]

    if not os.path.isfile(filev):
        print errormsg
        print '  ' + fname + ": file '" + filev + "' does not exist!!"
        quit(-1)

# Getting points position and labels
    oascii = open(filev, 'r')
    xptval = []
    yptval = []
    if collab != 'None':
        ptlabels = []
        for line in oascii:
            if not drw.searchInlist(comchar, line[0:1]):
                linevals = drw.reduce_spaces(line)
                xptval.append(np.float(linevals[collon].replace('\n','')))
                yptval.append(np.float(linevals[collat].replace('\n','')))
                ptlabels.append(linevals[int(collab)].replace('\n',''))
    else:
        ptlabels = None
        for line in oascii:
            if  not drw.searchInlist(comchar, line[0:1]):
                linevals = drw.reduce_spaces(line)
                xptval.append(np.float(linevals[collon].replace('\n','')))
                yptval.append(np.float(linevals[collat].replace('\n','')))

    oascii.close()

    if pointlabels != 'None' and collab == 'None':
        ptlabels = pointlabels.split(',')

# Getting localization of the points
##
    filev = filen.split(',')
    Nvals = len(filev)

    ncfile = filev[0]
    lonvarn = filev[1]
    latvarn = filev[2]
    varn = None
    varextrav = None
    if Nvals == 12:
        varn = filev[3]
        dimvals = filev[4]
        varextrav = [filev[5], np.float(filev[6]), np.float(filev[7]), filev[8],     \
          filev[9], filev[10], filev[11]]
        if filev[9] == 'auto': varextrav[4] = '%6g'
        if filev[10] == 'auto': varextrav[5] = 'vertical'
    
    if not os.path.isfile(ncfile):
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not exist!!"
        quit(-1)

    onc = NetCDFFile(ncfile, 'r')
    
    # Slicing lon,lats
    dd = {}
    for dn in dimvals.split('@'):
        ddn = dn.split('|')[0]
        ddv = dn.split('|')[1]
        dd[ddn] = ddv

    objlon = onc.variables[lonvarn]
    vard = objlon.dimensions
    slicevar = []
    for dv in vard:
        found= False
        for dn in dd.keys():
            if dn == dv:
                if dd[dn].find(';') == -1:
                    if dd[dn] == '-1':
                        slicevar.append(slice(0,len(onc.dimensions[dv])))
                    elif dd[dn] == '-9':
                        slicevar.append(len(onc.dimensions[dv]))
                    else:
                        slicevar.append(int(dd[dn]))
                else:
                    islc = int(dd[dn].split(';')[0])
                    eslc = int(dd[dn].split(';')[1])
                    tslc = int(dd[dn].split(';')[2])
                    slicevar.append(slice(islc,eslc,tslc))
                found = True
                break
        if not found:
            slicevar.append(slice(0,len(onc.dimensions[dv])))
    lonvals = np.squeeze(objlon[tuple(slicevar)])

    objlat = onc.variables[latvarn]
    vard = objlat.dimensions
    slicevar = []
    for dv in vard:
        found= False
        for dn in dd.keys():
            if dn == dv:
                if dd[dn].find(';') == -1:
                    if dd[dn] == '-1':
                        slicevar.append(slice(0,len(onc.dimensions[dv])))
                    elif dd[dn] == '-9':
                        slicevar.append(len(onc.dimensions[dv]))
                    else:
                        slicevar.append(int(dd[dn]))
                else:
                    islc = int(dd[dn].split(';')[0])
                    eslc = int(dd[dn].split(';')[1])
                    tslc = int(dd[dn].split(';')[2])
                    slicevar.append(slice(islc,eslc,tslc))
                found = True
                break
        if not found:
            slicevar.append(slice(0,len(onc.dimensions[dv])))
    latvals = np.squeeze(objlat[tuple(slicevar)])

    lonv, latv = drw.lonlat2D(lonvals, latvals)

    if varn is not None:
        objextra = onc.variables[varn]
        vard = objextra.dimensions
        slicevar = []
        for dv in vard:
            found= False
            for dn in dd.keys():
                if dn == dv:
                    if dd[dn].find(';') == -1:
                        if dd[dn] == '-1':
                            slicevar.append(slice(0,len(onc.dimensions[dv])))
                        elif dd[dn] == '-9':
                            slicevar.append(len(onc.dimensions[dv]))
                        else:
                            slicevar.append(int(dd[dn]))
                    else:
                        islc = int(dd[dn].split(';')[0])
                        eslc = int(dd[dn].split(';')[1])
                        tslc = int(dd[dn].split(';')[2])
                        slicevar.append(slice(islc,eslc,tslc))
                    found = True
                    break
            if not found:
                slicevar.append(slice(0,len(onc.dimensions[dv])))

        varextra = np.squeeze(objextra[tuple(slicevar)])

    # Axis values
    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
    xaxis = [xstyl, xaxf, Nxax, xaxor]
    yaxis = [ystyl, yaxf, Nyax, yaxor]

    if mapvalues == 'None':
        mapV = None
    else:
        mapV = mapvalues

    drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, xaxis,    \
      yaxis, mapV, kindfigure, pointcolor, ptlabels, locleg, figureko, figuren, close)

    onc.close()

    return

def draw_points_lonlat(filen, values):
    """ Function to plot a series of lon/lat points
      filen= name of the file
      values= [lonvarname]:[latvarname]:[gkind]:[gtit]:[ptcolor]:[pttype]:[ptsize]:[labels]:[legvals]:[figureK]
        [lonvarname]: name of the variable longitude
        [latvarname]: name of the variable latitude
        [gkind]: kind of graphical output
        [gtit]: graphic title '!' for spaces
        [ptcolor]: color of the points ('auto', for "red")
        [pttype]: type of point
        [ptsize]: size of point
        [labels]: ',' list of labels to use
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [figureK]= kind of figure
          'legend': only points in the map with the legend with the names
          'labelled',[txtsize],[txtcol]: points with the names and size, color of text
    """
    fname = 'draw_points_lonlat'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_points_lonlat.__doc__
        quit()

    expectargs = '[lonvarname]:[latvarname]:[gkind]:[gtit]:[ptcolor]:[pttype]:' +    \
      '[ptsize]:[labels]:[locleg]:[figureK]'
 
    drw.check_arguments(fname,values,expectargs,':')

    lonname = values.split(':')[0]
    latname = values.split(':')[1]
    kindfigure = values.split(':')[2]
    gtit = values.split(':')[3].replace('!',' ')
    pointcolor = values.split(':')[4]
    pointtype = values.split(':')[5]
    pointsize = np.float(values.split(':')[6])
    labelsv = values.split(':')[7]
    loclegend = values.split(':')[8]
    figureK = values.split(':')[9]

    fname = 'points_lonlat'

    onc = NetCDFFile(filen, 'r')
    if not onc.variables.has_key(lonname):
        print errormsg
        print fname + ": file '" + filen + "' does not have longitudes '" + lonname +\
          "' !!"
        quit(-1)
    if not onc.variables.has_key(lonname):
        print errormsg
        print fname + ": file '" + filen + "' does not have longitudes '" + lonname +\
          "' !!"
        quit(-1)
    
    olon = onc.variables[lonname]
    olat = onc.variables[latname]

    Ndimlon = len(olon.shape)
    if Ndimlon == 1:
        dx = olon.shape[0]
        dy = olat.shape[0]
        if dx == dy: 
            lonvals = olon[:]
            latvals = olat[:]
        else: 
            lonvals0 = np.zeros((dy,dx), dtype=np.float)
            latvals0 = np.zeros((dy,dx), dtype=np.float)
            for iL in range(dy):
                lonvals0[iL,:] = olon[:]
            for il in range(dx):
                latvals0[:,il] = olat[:]
            lonvals = lonvals0.flatten()
            latvals = latvals0.flatten()

    elif Ndimlon == 2:
        lonvals = olon[:].flatten()
        latvals = olat[:].flatten()
    elif Ndimlon == 3:
        lonvals = olon[1,:,:].flatten()
        latvals = olat[1,:,:].flatten()
# Playing for Anna
#        lonvals = olon[:].flatten()
#        latvals = olat[:].flatten()
    elif Ndimlon == 4:
        lonvals = olon[1,0,:,:].flatten()
        latvals = olat[1,0,:,:].flatten()
    else:
        print errormsg
        print '  ' + fname + ': longitude size:',len(olon),' not ready!!'
        quit(-1)

    if labelsv == 'None':
        labels = None
    else:
        labels = labelsv.split(',')

    drw.plot_list_points(lonvals, latvals, lonname, latname, gtit, figureK, pointcolor, pointtype,    \
      pointsize, labels, loclegend, kindfigure, fname)

    onc.close()

    return

def draw_timeSeries(filen, values, variables):
    """ Function to draw a time-series
      draw_timeSeries(filen, values, variable):
        filen= name of the file
        values= [gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[legvals]:[gkind]:[colorlines]:[pointtype]:[pointfreq]
        [gvarname]: name of the variable to appear in the graph
        [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
        [tkind]: kind of time to appear in the graph (assumed x-axis)
          'Nval': according to a given number of values as 'Nval',[Nval]
          'exct': according to an exact time unit as 'exct',[tunit]; 
            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
              'l': milisecond
        [timefmt]: format of the time labels
        [title]: title of the graphic ('|' for spaces)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [gkind]: kind of graphical output
        [colorlines]: ',' list of colors for the lines, None for automatic, single
          value all the same
        [pointtype]: ',' list of type of points for the lines, None for automatic, single
          value all the same
        [pointfreq]: frequency of point plotting, 'all' for all time steps
      variables= [varname],[timename] names of variable and variable with times
      draw_timeSeries('wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc', 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf', 'LDQCON,time')
    """

    fname = 'draw_timeSeries'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_timeSeries.__doc__
        quit()

    expectargs = '[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:' +                 \
      '[locleg]:[gkind]:[colorlines]:[pointtype]:[pointfreq]'
 
    drw.check_arguments(fname,values,expectargs,':')

    gvarname = values.split(':')[0]
    timetit = values.split(':')[1].replace('|',' ')
    tkind = values.split(':')[2]
    timefmt = values.split(':')[3]
    title = values.split(':')[4].replace('|',' ')
    locleg = int(values.split(':')[5])
    gkind = values.split(':')[6]
    colorlines = values.split(':')[7]
    pointtype = values.split(':')[8]
    pointfreq0 = values.split(':')[9]
    
    ncobj = NetCDFFile(filen, 'r')

    variable = variables.split(',')[0]
    timevar = variables.split(',')[1]

    if not ncobj.variables.has_key(variable):
        print errormsg
        print '  ' + fname + ": file '" +  filen + "' does not have variable '" +    \
          variable + "' !!"
        quit(-1)

    if not ncobj.variables.has_key(timevar):
        print errormsg
        print '  ' + fname + ": file '" +  filen + "' does not have variable time '" \
          + timevar + "' !!"
        quit(-1)

    varobj = ncobj.variables[variable]
    timeobj = ncobj.variables[timevar]

    dimt = len(timeobj[:])
    varvals = np.zeros((2,dimt), dtype=np.float)

    gunits = varobj.getncattr('units')
    tunits = timeobj.getncattr('units')

    varvals[0,:], valpot, newgunits, Spot = drw.pot_values(varobj[:].flatten(), gunits)
    varvals[1,:] = timeobj[:]

    tseriesvals = []
    tseriesvals.append(varvals)

    if colorlines == 'None': 
        collines = None
    else:
        collines = colorlines.split(',')
    if pointtype == 'None': 
        pttype = None
    else:
        pttype = pointtype.split(',')

    if pointfreq0 == 'all':
        pointfreq = None
    else:
        pointfreq = int(pointfreq0)

    drw.plot_TimeSeries(tseriesvals, Spot + drw.units_lunits(gunits), tunits,        \
      'TimeSeries', gvarname, timetit, tkind, timefmt, title,                        \
      gvarname.replace('_','\_'), locleg, gkind, collines, pttype, pointfreq)

    return

#draw_timeSeries('wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc', 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf:None:None', 'LDQCON,time')

def draw_trajectories(trjfilens, values, observations):
    """ Function to draw different trajectories at the same time
    draw_trajectories(trjfilens, values, observations):
      trjfilens= [filen]@[Tint]@[map] ',' separated list of files with trajectories,
         time intervals and reference maps (first one will be used to plot)
        [filen]: name of the file to use (lines with '#', not readed) as:
          [t-step] [x] [y]
        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
        [map]: [file]#[lonname]#[latname] 
          [file]; with the [lon],[lat] matrices
          [lonname],[latname]; names of the longitudes and latitudes variables
      values=[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]
        [leglabels]: ',' separated list of names for the legend
        [lonlatlims]: ',' list of limits of the map [lonmin, latmin, lonmax, latmax] or None
        [title]: title of the plot ('!' for spaces)
        [graphk]: kind of the graphic
        [mapkind]: drawing coastaline ([proj],[res]) or None
          [proj]: projection
             * 'cyl', cilindric
             * 'lcc', lambert conformal
          [res]: resolution:
             * 'c', crude
             * 'l', low
             * 'i', intermediate
             * 'h', high
             * 'f', full
      obsevations= [obsfile],[obsname],[Tint],[null]
        [obsfile]: name fo the File with the observations as [t-step] [lat] [lon]
        [obsname]: name of the observations in the graph
        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
        [null]: null value for the observed trajectory
    """

    fname = 'draw_trajectories'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_trajectories.__doc__
        quit()

    expectargs = '[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]'
 
    drw.check_arguments(fname,values,expectargs,'|')

    trjfiles = trjfilens.split(',')
    leglabels = values.split('|')[0]
    lonlatlims = values.split('|')[1]
    title = values.split('|')[2].replace('!',' ')
    graphk = values.split('|')[3]
    mapkind = values.split('|')[4]

    Nfiles = len(trjfiles)

# Getting trajectotries 
##

    lontrjvalues = []
    lattrjvalues = []

    print '  ' + fname
    ifn = 0
    for ifile in trjfiles:
        filen = ifile.split('@')[0]
        Tint = ifile.split('@')[1]

        print '    trajectory:',filen

        if Tint != '-1':
            Tbeg = Tint
            Tend = ifile.split('@')[2]
            mapv = ifile.split('@')[3]
        else:
            mapv = ifile.split('@')[2]

        if not os.path.isfile(filen):
            print errormsg
            print '  ' + fname + ": trajectory file '" + filen + "' does not exist !!"
            quit(-1)

# Charging longitude and latitude values
## 
        lonvals, latvals = drw.lonlat_values(mapv.split('#')[0], mapv.split('#')[1], \
          mapv.split('#')[2])

        if ifn == 0: mapref = mapv
        ifn = ifn + 1

        objfile = open(filen, 'r')
        trjtimev = []
        trjxv = []
        trjyv = []

        for line in objfile:
            if line[0:1] != '#':
                trjtimev.append(int(line.split(' ')[0]))
                trjxv.append(int(line.split(' ')[1]))
                trjyv.append(int(line.split(' ')[2]))

        objfile.close()

        if Tint != '-1':
            lontrjvalues.append(lonvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
            lattrjvalues.append(latvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
        else:
            lontrjvalues.append(lonvals[trjyv[:], trjxv[:]])
            lattrjvalues.append(latvals[trjyv[:], trjxv[:]])

# lonlatlimits
##

    if lonlatlims == 'None':
        lonlatlimsv = None
    else:
        lonlatlimsv = np.zeros((4), dtype=np.float)
        lonlatlimsv[0] = np.float(lonlatlims.split(',')[0])
        lonlatlimsv[1] = np.float(lonlatlims.split(',')[1])
        lonlatlimsv[2] = np.float(lonlatlims.split(',')[2])
        lonlatlimsv[3] = np.float(lonlatlims.split(',')[3])

# lon/lat objects
##
    objnc = NetCDFFile(mapref.split('#')[0])
    lonobj = objnc.variables[mapref.split('#')[1]]
    latobj = objnc.variables[mapref.split('#')[2]]

# map
##
    if mapkind == 'None':
        mapkindv = None
    else:
        mapkindv = mapkind

    if observations is None:
        obsname = None
    else:
        obsfile = observations.split(',')[0]
        obsname = observations.split(',')[1]
        Tint = observations.split(',')[2]
        null = np.float(observations.split(',')[3])
        print '    observational trajectory:',obsfile

        if not os.path.isfile(obsfile):
            print errormsg
            print '  ' + fname + ": observations trajectory file '" + obsfile +      \
              "' does not exist !!"
            quit(-1)

        objfile = open(obsfile, 'r')
        obstrjtimev = []
        obstrjxv = []
        obstrjyv = []

        for line in objfile:
            if line[0:1] != '#':
                lon = np.float(line.split(' ')[2])
                lat = np.float(line.split(' ')[1])
                if not lon == null and not lat == null:
                    obstrjtimev.append(int(line.split(' ')[0]))
                    obstrjxv.append(lon)
                    obstrjyv.append(lat)
                else:
                    obstrjtimev.append(int(line.split(' ')[0]))
                    obstrjxv.append(None)
                    obstrjyv.append(None)

        objfile.close()

        if Tint != '-1':
            Tint = int(observations.split(',')[2].split('@')[0])
            Tend = int(observations.split(',')[2].split('@')[1])
            lontrjvalues.append(obstrjxv[Tint:Tend+1])
            lattrjvalues.append(obstrjyv[Tint:Tend+1])
        else:
            lontrjvalues.append(obstrjxv[:])
            lattrjvalues.append(obstrjyv[:])

    drw.plot_Trajectories(lontrjvalues, lattrjvalues, leglabels.split(','),          \
      lonobj, latobj, lonlatlimsv, title, graphk, mapkindv, obsname)

    objnc.close()

    return

def draw_vals_trajectories(ncfile, values, variable):
    """ Function to draw values from the outputs from 'compute_tevolboxtraj'
      draw_vals_trajectories(ncfile, values, variable)
      ncfile= [ncfile] ',' list of files to use
      values= [statisticskind]:[Tint]:[labels]@[legvals]:[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[gkind]
        [statisticskind]=[statistics][kind]
          [statistics]: which statistics to use, from: 'center', 'min', 'max', 'mean', 
            'mean2', 'stdev'
          [kind]: 'box', 'circle' statistics taking the values from a box or a circle
            'trj': value following the trajectory
        [Tint]: [Tbeg]@[Tend] or None, interval of time to plot or -1 for all the times
        [labels]: ',' separated list of labels for the legend
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [gvarname]: name of the variable to appear in the graph
        [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
        [tkind]: kind of time to appear in the graph (assumed x-axis)
          'Nval': according to a given number of values as 'Nval',[Nval]
          'exct': according to an exact time unit as 'exct',[tunit]; 
            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
                'l': milisecond
        [timefmt]: format of the time labels
        [title]: title of the graphic ('|' for spaces)
        [gkind]: kind of graphical output
      variable= variable to use
    """
    fname = 'draw_vals_trajectories'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_vals_trajectories.__doc__
        quit()

    sims = ncfile.split(',')

    if len(values.split(':')) != 9:
        print errormsg
        print '  ' + fname  + ': wrong number of values!', len(values.split(':')),   \
          'given 9 needed!!'
        print '    ',values.split(':')
        quit(-1)

    statisticskind = values.split(':')[0]
    Tint = values.split(':')[1]
    labels = values.split(':')[2]
    gvarname = values.split(':')[3]
    timetit = values.split(':')[4].replace('|',' ')
    tkind = values.split(':')[5]
    timefmt = values.split(':')[6]
    title = values.split(':')[7].replace('|',' ')
    gkind = values.split(':')[8]

    leglabels = labels.split('@')[0].split(',')
    locleg = int(labels.split('@')[1])

    Nsims = len(sims)

    if Tint != '-1':
        tini = np.float(Tint.split('@')[0])
        tend = np.float(Tint.split('@')[1])
    else:
        tini = -1.
        tend = -1.

    vartimetrjv = []

    print '  ' + fname
    for trjfile in sims:
        print '    ' + trjfile + ' ...'
        if not os.path.isfile(trjfile):
            print errormsg
            print '  ' + fname + ": trajectory file: '" + trjfile +                  \
              "' does not exist !!"
            quit(-1)

        trjobj = NetCDFFile(trjfile, 'r')
        otim = trjobj.variables['time']
        if not trjobj.variables.has_key(statisticskind + '_' + variable):
            print errormsg
            print '  ' + fname + ": file '" + trjfile + "' does not have variable '"+\
              statisticskind + '_' + variable + "' !!"
            quit(-1)
        ovar = trjobj.variables[statisticskind + '_' + variable]
        dimt = otim.shape[0]

        if trjfile == sims[0]:
            gunits = ovar.getncattr('units')
            lname = ovar.getncattr('long_name')
            tunits = otim.getncattr('units')

        if tini != -1:
            tiniid = -1
            tendid = -1       
            for itv in range(dimt):
                if otim[itv] <= tini and otim[itv+1] >= tini: tiniid = itv
                if otim[itv] <= tend and otim[itv+1] >= tend: tendid = itv

            if tiniid == -1 or tendid == -1:
                print errormsg
                print '  ' + main + ' time interval ', tini,',',tend,' not found: ',     \
                  tendid, ',', tiniid, ' !!'
                print '    data interval [',otim[0], otim[dimt-1],']'
                quit(-1)
            dimt = tendid - tiniid + 1

        else:
            dimt = otim.shape[0]

        valsv = np.zeros((2,dimt), dtype=np.float)
# Checking for time consistency
        if otim.getncattr('units') != tunits:
            print warnmsg
            print '  ' + fname + ': different time units in the plot!!'
            newtimes = gen.coincident_CFtimes(otim[:], tunits, otim.getncattr('units'))
        else:
            newtimes = otim[:]

        if tini == -1:
            valsv[1,:] = newtimes[:]
            valsv[0,:] = ovar[:]
        else:
            valsv[1,:] = newtimes[tiniid:tendid+1]
            valsv[0,:] = ovar[tiniid:tendid+1]

        vartimetrjv.append(valsv)
        trjobj.close()

    drw.plot_TimeSeries(vartimetrjv, drw.units_lunits(gunits), tunits,               \
      'val_trajectories_' + statisticskind, gvarname, timetit, tkind, timefmt, title,\
      leglabels, locleg, gkind)

def variable_values(values):
    """ Function to give back values for a given variable
      values= [varname] name of the variable
    """

    fname = 'variable_values'

    values = drw.variables_values(values)

    print fname,'values:',values
    print fname,'variable_name:',values[0]
    print fname,'standard_name:',values[1]
    print fname,'min,max:',str(values[2]) + ',' + str(values[3])
    print fname,'long_name:',values[4]
    print fname,'units:',values[5]
    print fname,'shad_colors:',values[6]
    print fname,'all_values:',drw.numVector_String(values,',')

    return

def draw_ptZvals(ncfile, values, variable):
    """ Function to plot a given list of points and values 
      ncfile= netCDF file to use
      values= [fvname]:[XYvar]:[pointype]:[pointsize]:[graphlimits]:[nxtype]:
        [figuretitle]:[colorbar]:[mapvalue]:[kindfig]
        fvname: name of the variable in the graph
        XYvar: [lon],[lat] variable names
        ptype: type of the point
        ptsize: size of the point
        graphlimits: minLON,minLAT,maxLON,maxLAT limits of the graph 'None' for the full size
        nxtype: minimum and maximum type
          'auto': values taken from the extrems of the data
          [min],[max]: given minimum and maximum values
        figtitle: title of the figure
        cbar: color bar
        mapv: map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert-conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        kfig: kind of figure
      variable= name of the variable to plot
    """
    fname = 'draw_ptZvals'
    import numpy.ma as ma

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_ptZvals.__doc__
        quit()

    expectargs = '[fvname]:[XYvar]:[pointype]:[pointsize]:[graphlmits]:[nxtype]:' +  \
      '[figuretit]:[colorbar]:[mapvalue]:[kindfig]'
 
    drw.check_arguments(fname,values,expectargs,':')

    fvname = values.split(':')[0]
    XYvar = values.split(':')[1]
    pointype = values.split(':')[2]
    pointsize = int(values.split(':')[3])
    graphlimits = values.split(':')[4]
    nxtype = values.split(':')[5]
    figuretitle = values.split(':')[6].replace('!',' ')
    colorbar = values.split(':')[7]
    mapvalue = values.split(':')[8]
    kindfig = values.split(':')[9]

    onc = NetCDFFile(ncfile, 'r')
    
    if not onc.variables.has_key(variable):
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +    \
          variable + "' !!"
        quit(-1)

# points
    lonvarn = XYvar.split(',')[0]
    latvarn = XYvar.split(',')[1]

    if not onc.variables.has_key(lonvarn):
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not have longitude " +    \
          "variable '" + lonvarn + "' !!"
        quit(-1)
    
    if not onc.variables.has_key(latvarn):
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not have latitude " +    \
          "variable '" + latvarn + "' !!"
        quit(-1)

    olonvar = onc.variables[lonvarn]
    olatvar = onc.variables[latvarn]
    ovarvar = onc.variables[variable]

    Lpts = len(olonvar[:].flatten())

    pointvalues = ma.masked_array(np.zeros((Lpts,3), dtype=np.float))
    pointvalues[:,0] = olonvar[:].flatten()
    pointvalues[:,1] = olatvar[:].flatten()
    pointvalues[:,2] = ovarvar[:].flatten()

    varattrs = ovarvar.ncattrs()
    if drw.searchInlist(varattrs, 'units'):
        fvunits = ovarvar.getncattr('units')
    else:
        fvunits = drw.variables_values(variable)[5]

# map value
    if mapvalue == 'None': mapvalue = None

# Graph limits
    if graphlimits != 'None':
        graphlts = np.zeros((4), dtype=np.float)
        for il in range(4): graphlts[il] = np.float(graphlimits.split(',')[il])
        pointvalues[:,0] = ma.masked_outside(pointvalues[:,0], graphlts[0],          \
          graphlts[2])
        pointvalues[:,1] = ma.masked_outside(pointvalues[:,1], graphlts[3],          \
          graphlts[2])

#        for ip in range(Lpts):  
#            if pointvalues[ip,0] < graphlts[0] or pointvalues[ip,0] > graphlts[2]    \
#              or pointvalues[ip,1] < graphlts[1] or pointvalues[ip,1] > graphlts[3]:
#                print ip,pointvalues[ip,0:2], graphlts
#                pointvalues[ip,2] = None
    else:
        graphlts = None

    drw.plot_ptZvals(fvname,fvunits,pointvalues,pointype,pointsize,graphlts, nxtype, \
      figuretitle,colorbar,mapvalue,kindfig)

    return

#draw_ptZvals('OBSnetcdf.nc', 'pracc:lon,lat:o:80:2,42,7,47,:values!of!values:Blues:cyl,l:pdf', 'pr')

def draw_vectors(ncfile, values, varns):
    """ Function to plot wind vectors
      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
        [gtit]:[kindfig]:[figuren]
        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
          [dimname]: name of the dimension in the file
          [vardimname]: name of the variable with the values for the dimension in the file
          [value]: which value of the given dimension is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]:[end] slice from [beg] to [end]
            * NOTE, no dim name all the dimension size
          No value takes all the range of the dimension
        [vecvals]= [frequency],[color],[length]
          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points; 
            'auto', computed automatically to have 20 vectors along each axis)
          [color]: color of the vectors
            'singlecol'@[colorn]: all the vectors same color ('auto': for 'red')
            'wind'@[colorbar]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]
              all vectors the same length
            '3rdvar'@[colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
              all vectors the same length
          [length]: length of the wind vectors ('auto', for 9)
        [windlabs]= [windname],[windunits]
          [windname]: name of the wind variable in the graph
          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
        [mapvalues]= map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        gtit= title of the graph ('|', for spaces)
        kindfig= kind of figure
        figuren= name of the figure
      ncfile= file to use
      varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component
    """
    fname = 'draw_vectors'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_vectors.__doc__
        quit()

    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
 
    drw.check_arguments(fname,values,expectargs,':')

    dimvals = values.split(':')[0]
    vecvals = values.split(':')[1]
    windlabels = values.split(':')[2]
    mapvalues = values.split(':')[3]
    gtit = values.split(':')[4]
    kindfig = values.split(':')[5]
    figuren = values.split(':')[6]

    of = NetCDFFile(ncfile,'r')

    dims = {}
    for dimv in dimvals.split(','):
        dns = dimv.split('|')
        dims[dns[0]] = [dns[1], dns[2], dns[3]]

    varNs = []
    for dn in dims.keys():
        if dn == 'X':
            varNs.append(dims[dn][1])
            dimx = len(of.dimensions[dims[dn][0]])
        elif dn == 'Y':
            varNs.append(dims[dn][1])
            dimy = len(of.dimensions[dims[dn][0]])

    ivar = 0
    for wvar in varns.split(','):
        if not drw.searchInlist(of.variables.keys(), wvar):
            print errormsg
            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
            quit(-1)
        if ivar == 0:
            varNs.append(wvar)
        else:
            varNs.append(wvar)

    ivar = 0
    for varN in varNs:
        varslice = []

        ovarN = of.variables[varN]
        vard = ovarN.dimensions
        for vdn in vard:
            found = False
            for dd in dims.keys():
                if dims[dd][0] == vdn:
                    if dims[dd][2].find('@') != -1:
                        rvals = dims[dd][2].split('@')
                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
                    elif dims[dd][2] == '-1':
                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
                    else:
                        varslice.append(int(dims[dd][2]))

                    found = True
                    break
            if not found:
                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))

        if varN == dims['X'][1]:
            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
        elif varN == dims['Y'][1]:
            latvals0 = np.squeeze(ovarN[tuple(varslice)])
        elif ivar == 2:
            uwvals = np.squeeze(np.array(ovarN[tuple(varslice)]))
        elif ivar == 3:
            vwvals = np.squeeze(ovarN[tuple(varslice)])

        ivar = ivar + 1

#    print 'Final shapes:',lonvals0.shape,':',latvals0.shape,':',uwvals.shape,':',
#      vwvals.shape

    if len(uwvals.shape) != 2 or len(vwvals.shape) != 2:
        print errormsg
        print '  ' + fname + ': wrong size of the wind fields! they must be ' +      \
          '2-dimensional!'
        print '    u-winds shape:',uwvals.shape,'dims:',of.variables[varNs[2]]
        print '    v-winds shape:',vwvals.shape,'dims:',of.variables[varNs[3]]
        print '      provide more values for their dimensions!!'
        quit(-1)

    if len(lonvals0.shape) == 1:
        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
    else:
        lonvals = lonvals0
        latvals = latvals0

# Vector values
    if vecvals.split(',')[0] == 'None':
        freqv = None
    else:
        freqv = vecvals.split(',')[0] 
    colorvals = vecvals.split(',')[1]
    coln = colorvals.split('@')[0]
    colv = colorvals.split('@')[1]
    if coln == 'singlecol':
        colorv = colv
    elif coln == 'wind':
        colorv = np.sqrt(uwvals**2 + vwvals**2)
    elif coln == '3rdvar':
        if len(varn.split(',')) != 3:
            print errormsg
            print '  ' + fname + ": color of vectors should be according to '" +     \
              coln + "' but a third varibale is not provided !!"
            quit(-1)
        ocolvec = of.variables[varNs[4]]
        colorv = ocolvec[:]
        stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
        colorvals = colorvals + '@' + stdvn + '@' + unitsvn
    else:
        print errormsg
        print '  ' + fname + ": color type '" + coln + "' not ready !!"
        quit(-1)

    lengthv = vecvals.split(',')[2]

# Vector labels
    windname = windlabels.split(',')[0]
    windunits = windlabels.split(',')[1]

    drw.plot_vector(lonvals, latvals, uwvals, vwvals, freqv, colorvals, colorv,      \
      lengthv, windname, windunits, mapvalues, gtit, kindfig, figuren)

    of.close()

    return

def draw_basins(ncfile, values, varns):
    """ Function to plot river basins with their discharge vector and basins id (from 'routing.nc')
      values= [lonlatbox]:[mapres]:[cbarname]:[xtrmbasin]:[mapdraw]:[veclength]:[freq]:
        [ifreq]:[plotcountry]:[basinidn]:[gtit]:[kindfig]:[figuren]
        [lonlatbox]= [lonSW],[lonNE],[latSW],[latNE] coordinates of the lon/lat box
        [mapres]= resolution of the mapping information
        [cbarname]= colorbar name for the colors
        [xtrmbasin]= [minbasin],[maxbasin] minimum and maximum basin numbers
        [mapdraw]= whether to draw the map (and project the data) or not ('True/False')
        [veclength]= length of the vectors of discharge at each grid cell
        [freq]= frequency of values allong each axis (None, all grid points; 
          'auto', computed automatically to have 20 vectors along each axis)
        [plotcountry]= whether country lines should be plotted or not ('True/False')
        [plotbasinid]= whether id of the basins should be plotted or not ('True/False')
        [gtit]= title of the graph ('|', for spaces)
        [kindfig]= kind of figure
        [figuren]= name of the figure
      ncfile= file to use
    """
    fname = 'draw_basins'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_vectors.__doc__
        quit()

    expectargs = '[lonlatbox]:[mapres]:[cbarname]:[xtrmbasin]:[mapdraw]:' +          \
      '[veclength]:[freq]:[plotcountry]:[basinidn]:[gtit]:[kindfig]:[figuren]'
 
    drw.check_arguments(fname,values,expectargs,':')

    varn='basins'
    lonname = 'nav_lon'
    latname = 'nav_lat'
    flowname = 'trip'

    lonlims =[]
    latlims =[]

    lonlims.append(np.float(values.split(':')[0].split(',')[0]))
    lonlims.append(np.float(values.split(':')[0].split(',')[1]))
    latlims.append(np.float(values.split(':')[0].split(',')[2]))
    latlims.append(np.float(values.split(':')[0].split(',')[3]))
    map_res = values.split(':')[1]
    cbarname = values.split(':')[2]
    vtit = 'basins'
    minbasin = np.int(values.split(':')[3].split(',')[0])
    maxbasin = np.int(values.split(':')[3].split(',')[1])
    mapdraw = gen.Str_Bool(values.split(':')[4])
    veclength = np.float(values.split(':')[5])
    freq0 = values.split(':')[6]
    plotcountry = gen.Str_Bool(values.split(':')[7])
    plotbasinid = gen.Str_Bool(values.split(':')[8])
    gtit = values.split(':')[9].replace('|',' ')
    kindfig = values.split(':')[10]
    figuren = values.split(':')[11]

    if freq0 == 'None': freq = None

    ofile = NetCDFFile(ncfile, 'r')

    obasins = ofile.variables[varn]
    olon = ofile.variables[lonname]
    olat = ofile.variables[latname]
    oflow = ofile.variables[flowname]

    lons = olon[:]
    lats = olat[:]

    lon, lat = drw.lonlat2D(lons, lats)

    nlon = lonlims[0]
    xlon = lonlims[1]
    nlat = latlims[0]
    xlat = latlims[1]

    imin, imax, jmin, jmax = gen.ijlonlat(lon, lat, nlon, xlon, nlat, xlat)

    drw.plot_basins(lon[jmin:jmax,imin:imax], lat[jmin:jmax,imin:imax],              \
      oflow[jmin:jmax,imin:imax], freq, cbarname+'@basin@-',                         \
      obasins[jmin:jmax,imin:imax], veclength, minbasin, maxbasin, 'outflow', '-',   \
      'cyl,'+map_res, plotcountry, plotbasinid, gtit, kindfig, figuren)

    ofile.close()

    return

def draw_basinsold(ncfile, values, varns):
    """ Function to plot wind basins
      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
        [gtit]:[kindfig]:[figuren]
        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
          [dimname]: name of the dimension in the file
          [vardimname]: name of the variable with the values for the dimension in the file
          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
          No value takes all the range of the dimension
        [vecvals]= [frequency],[color],[length]
          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points; 
            'auto', computed automatically to have 20 vectors along each axis)
          [color]: [colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
              all vectors the same length
          [length]: length of the wind vectors ('auto', for 9)
        [windlabs]= [windname],[windunits]
          [windname]: name of the wind variable in the graph
          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
        [mapvalues]= map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        gtit= title of the graph ('|', for spaces)
        kindfig= kind of figure
        figuren= name of the figure
      ncfile= file to use
      varns= [lon],[lat],[outflow],[basinID] ',' list of the name of the variables with the lon,lat, the outflow and the basin ID
    """
    fname = 'draw_basins'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_vectors.__doc__
        quit()

    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
 
    drw.check_arguments(fname,values,expectargs,':')

    dimvals = values.split(':')[0]
    vecvals = values.split(':')[1]
    windlabels = values.split(':')[2]
    mapvalues = values.split(':')[3]
    gtit = values.split(':')[4]
    kindfig = values.split(':')[5]
    figuren = values.split(':')[6]

    of = NetCDFFile(ncfile,'r')

    dims = {}
    for dimv in dimvals.split(','):
        dns = dimv.split('|')
        dims[dns[0]] = [dns[1], dns[2], dns[3]]

    varNs = []
    for dn in dims.keys():
        if dn == 'X':
            varNs.append(dims[dn][1])
            dimx = len(of.dimensions[dims[dn][0]])
        elif dn == 'Y':
            varNs.append(dims[dn][1])
            dimy = len(of.dimensions[dims[dn][0]])

    ivar = 0
    for wvar in varns.split(','):
        if not drw.searchInlist(of.variables.keys(), wvar):
            print errormsg
            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
            quit(-1)
        if ivar == 0:
            varNs.append(wvar)
        else:
            varNs.append(wvar)

    ivar = 0
    for varN in varNs:
        varslice = []

        ovarN = of.variables[varN]
        vard = ovarN.dimensions
        for vdn in vard:
            found = False
            for dd in dims.keys():
                if dims[dd][0] == vdn:
                    if dims[dd][2].find('@') != -1:
                        rvals = dims[dd][2].split('@')
                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
                    elif dims[dd][2] == '-1':
                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
                    else:
                        varslice.append(int(dims[dd][2]))

                    found = True
                    break
            if not found:
                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))

        if varN == dims['X'][1]:
            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
        elif varN == dims['Y'][1]:
            latvals0 = np.squeeze(ovarN[tuple(varslice)])

        ivar = ivar + 1

    if len(lonvals0.shape) == 1:
        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
    else:
        lonvals = lonvals0
        latvals = latvals0

# Vector values
    if vecvals.split(',')[0] == 'None':
        freqv = None
    else:
        freqv = vecvals.split(',')[0] 

    colorvals = vecvals.split(',')[1]
    if len(varn.split(',')) != 3:
        print errormsg
        print '  ' + fname + ": color of vectors should be according to '" +         \
          coln + "' but a third varibale is not provided !!"
        quit(-1)

    ocolvec = of.variables[varNs[3]]
    colorv = ocolvec[:]
    stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
    colorvals = colorvals + '@' + stdvn + '@' + unitsvn

    lengthv = vecvals.split(',')[2]

# Vector labels
    windname = windlabels.split(',')[0]
    windunits = windlabels.split(',')[1]

# Vector angles
    oflow = ofile.variables[varNs[2]]
    angle = (oflow[:] - 1)*np.pi/4
    xflow = np.where(oflow[:] < 9, np.float(lengthv)*np.sin(angle), 0.)
    yflow = np.where(oflow[:] < 9, np.float(lengthv)*np.cos(angle), 0.)

    drw.plot_basins(lonvals, latvals, xflow, yflow, freqv, colorvals, colorv,      \
      lengthv, windname, windunits, mapvalues, gtit, kindfig, figuren)

    of.close()

    return

def draw_river_desc(ncfile, values, riverns):
    """ Function to plot rivers' description from ORCHIDEE's routing scheme
      values= [dimname]|[vardimname]|[value]:[basinvals]:[upstreamvals]:[mapvalues]:
        [gtit]:[kindfig]:[legvals]:[figuren]
        'X/Y'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
          [dimname]: name of the dimension in the file
          [vardimname]: name of the variable with the values for the dimension in the file
          [value]: which value of the given dimension is required:
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg]:[end] slice from [beg] to [end]
            * NOTE, no dim name all the dimension size
          No value takes all the range of the dimension
        [basinsvals]= [colorline]
          [basincolor]: ',' list of colors of the line to use to mark the basins contours (single value also possible)
        [upstreamvals]= [upstreamvarn],[colorbar]
          [upstreamcolor]: colorbar to use to plot the basins upstream values
        [mapvalues]= map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        gtit= title of the graph ('|', for spaces)
        kindfig= kind of figure
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        figuren= name of the figure
      ncfile= file to use
      riverns= ',' list of the name of the rivers to plot
    """
    import numpy.ma as ma
    fname = 'draw_river_desc'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_river_desc.__doc__
        quit()

    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[basinvals]:' +           \
      '[upstreamvals]:[mapvalues]:[gtit]:[kindfig]:[legloc]:[figuren]'
 
    drw.check_arguments(fname,values,expectargs,':')

    dimvals = values.split(':')[0]
    basinvals = values.split(':')[1]
    upstreamvals = values.split(':')[2]
    mapvals = values.split(':')[3]
    gtit = values.split(':')[4]
    kindfig = values.split(':')[5]
    legloc = int(values.split(':')[6])
    figuren = values.split(':')[7]

    basincol = basinvals
    if basincol.find(',') != 1:
        basincolor = basincol.split(',')
    else:
        basincolor = [basincol]

    upstreamcolor = upstreamvals

    of = NetCDFFile(ncfile,'r')

    dims = {}
    for dimv in dimvals.split(','):
        dns = dimv.split('|')
        dims[dns[0]] = [dns[1], dns[2], dns[3]]

    varNs = []
    for dn in dims.keys():
        if dn == 'X':
            varNs.append(dims[dn][1])
            dimx = len(of.dimensions[dims[dn][0]])
        elif dn == 'Y':
            varNs.append(dims[dn][1])
            dimy = len(of.dimensions[dims[dn][0]])

    if riverns.find(',') != -1:
        riverns = riverns.split(',')
    else:
        riverns = [riverns]

    rivers = []
    riversubbasins = {}
    riversupstream = {}
    riversoutflow = {}
    for rivern in riverns:
        print rivern

# subBasins
        basinvar = rivern + '_coding'
        if not drw.searchInlist(of.variables.keys(), basinvar):
            print errormsg
            print '  ' + fname + ": file does not have variable '" + basinvar + "' !!"
            quit(-1)
        rivers.append(rivern)
        obasin = of.variables[basinvar]
        riversubbasins[rivern] = obasin[:]
        if rivern == riverns[0]:
            finalmask = obasin[:].mask
        else:
            finalmask = finalmask * obasin[:].mask

# upstream
        upstreamvar = rivern + '_upstream'
        if not drw.searchInlist(of.variables.keys(), upstreamvar):
            print errormsg
            print '  ' + fname + ": file does not have variable '" + upstreamvar + "' !!"
            quit(-1)
        oupstream = of.variables[upstreamvar]
        riversupstream[rivern] = oupstream[:]
        if rivern == riverns[0]:
            uunits = oupstream.getncattr('units')

# River metadata
        fracvar = rivern + '_frac'
        if not drw.searchInlist(of.variables.keys(), fracvar):
            print errormsg
            print '  ' + fname + ": file does not have variable '" + fracvar + "' !!"
            quit(-1)
        ofrac = of.variables[fracvar]
        riversoutflow[rivern] = [ofrac.getncattr('Longitude_of_outflow_point'),      \
          ofrac.getncattr('Latitude_of_outflow_point')]

    ivar = 0
    for varN in varNs:
        varslice = []

        ovarN = of.variables[varN]
        vard = ovarN.dimensions
        for vdn in vard:
            found = False
            for dd in dims.keys():
                if dims[dd][0] == vdn:
                    if dims[dd][2].find('@') != -1:
                        rvals = dims[dd][2].split('@')
                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
                    elif dims[dd][2] == '-1':
                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
                    else:
                        varslice.append(int(dims[dd][2]))

                    found = True
                    break
            if not found:
                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))

        if varN == dims['X'][1]:
            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
        elif varN == dims['Y'][1]:
            latvals0 = np.squeeze(ovarN[tuple(varslice)])

        ivar = ivar + 1

    if len(lonvals0.shape) == 1:
        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
    else:
        lonvals = lonvals0
        latvals = latvals0

# Masking only the lon,lat with rivers
    malonvals = ma.masked_array(lonvals, mask=finalmask)
    malatvals = ma.masked_array(latvals, mask=finalmask)

    if mapvals == 'None':
        mapvalues = None
    else:
        mapvalues = mapvals

    drw.plot_river_desc(malonvals, malatvals, rivers, riversubbasins, riversupstream, riversoutflow,  \
      basincolor, upstreamcolor, uunits, mapvalues, gtit, kindfig, legloc, figuren)

    of.close()

def draw_vertical_levels(ncfile, values, varn):
    """ plotting vertical levels distribution
    draw_topo_geogrid(ncfile, values, varn)
      ncfile= file to use
      values= [zlogs]:[plogs]:[title]:[graphic_kind]:[legvals]
        zlogs= zlog,dzlog
        zlog: to use logarithmic scale on the height axis ('true/false')
        dzlog: to use logarithmic scale on the difference of height between levels axis ('true/false')
        plogs= plog,dplog
        plog: to use logarithmic scale on the height axis ('true/false')
        dplog: to use logarithmic scale on the difference of height between levels axis ('true/false')
        title: title of the graph ('!' for spaces)
        graphic_kind: kind of figure (jpg, pdf, png)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
      varn= [varnheight],[varnpres]
        varnheight: name of the variable with the height of the vertical levels
          'WRFz': for WRF z-levels (computed as (PH + PHB)/g, from a PHB(0,i,j) = 0)
        varnpres: name of the variable with the pressure of the vertical levels ('None', for no pressure plot)
          'WRFp': for WRF p-levels (computed as P + PB, from a PHB(0,i,j) = 0)
    """
    fname = 'draw_vertical_levels'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_vertical_levels.__doc__
        quit()

    expectargs = '[zlogs]:[plogs]:[title]:[graphic_kind]:[legloc]'
 
    drw.check_arguments(fname,values,expectargs,':')

    zlog = values.split(':')[0].split(',')[0]
    dzlog = values.split(':')[0].split(',')[1]
    plog = values.split(':')[1].split(',')[0]
    dplog = values.split(':')[1].split(',')[1]
    title = values.split(':')[2].replace('!',' ')
    kindfig = values.split(':')[3]
    legloc = int(values.split(':')[4])

    if varn.find(',') == -1:
        varnheight = varn
        varnpres = None
        pvals = None
        print warnmsg
        print '  ' + fname + ': assuming no pressure variable!!'
    else:
        varnheight = varn.split(',')[0]
        varnpres = varn.split(',')[1]
        if varnpres == 'None': 
            varnpres = None
            pvals = None

    if not os.path.isfile(ncfile):
        print errormsg
        print '  ' + fname + ': file "' + ncfile + '" does not exist !!'
        quit(-1)    

    objf = NetCDFFile(ncfile, 'r')

    if varnheight == 'WRFz': 
        if not gen.searchInlist(objf.variables,'PH'):
            print errormsg
            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
              "variable 'PH' !!"
            quit(-1)
        if not gen.searchInlist(objf.variables,'PHB'):
            print errormsg
            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
              "variable 'PHB' !!"
            quit(-1)

        objph = objf.variables['PH']
        objphb = objf.variables['PHB']
        geop = objph[:] + objphb[:]

        ijz0 = gen.index_mat(geop[0,], 0.)
        zvals = geop[0, :, ijz0[0], ijz0[1]] / 9.8
    else:
        if not gen.searchInlist(objf.variables, varnheight):
            print errormsg
            print '  ' + fname + ": file '" + ncfile + "' does not have height " +   \
              " variable '" + varnheight + "' !!"
            quit(-1)
        objvar = objf.variables[varn]
        if len(objvar.shape) == 4:
            print warnmsg
            print '  ' + fname + ": assuming that height variable '" + varnheight +  \
              "' with shape: dt,dz,dy,dx. Tacking first time-step"

            ijz0 = gen.index_mat(objvar[0,0,], 0.)
            zvals = objvar[0, :, ijz0[0], ijz0[1]]
        elif len(objvar.shape) == 3:
            print warnmsg
            print '  ' + fname + ": assuming that height variable '" + varnheight +  \
              "' with shape: dz,dy,dx"

            ijz0 = gen.index_mat(objvar[0,], 0.)
            zvals = objvar[:, ijz0[0], ijz0[1]]
        
        elif len(objvar.shape) == 2:
            print warnmsg
            print '  ' + fname + ": assuming that height variable '" + varnheight +  \
              "' with shape: dz,dyx"

            ijz0 = gen.index_mat(objvar[0,], 0.)
            zvals = objvar[:, ijz0[0]]
        else:
            zvals = objvar[:]

# Pressure
    if varnpres is not None:
        if varnpres == 'WRFp': 
            if not gen.searchInlist(objf.variables,'P'):
                print errormsg
                print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
                  "variable 'P' !!"
                quit(-1)
            if not gen.searchInlist(objf.variables,'PB'):
                print errormsg
                print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
                  "variable 'PB' !!"
                quit(-1)

            objph = objf.variables['P']
            objphb = objf.variables['PB']
            pres = objph[:] + objphb[:]

            pvals = pres[0, :, ijz0[0], ijz0[1]]
        else:
            if not gen.searchInlist(objf.variables, varnpres):
                print errormsg
                print '  ' + fname + ": file '" + ncfile + "' does not have pressure " + \
                  " variable '" + varnpres + "' !!"
                quit(-1)
            objvar = objf.variables[varnpres]
            if len(objvar.shape) == 4:
                print warnmsg
                print '  ' + fname + ": assuming that pressure variable '" + varnpres +  \
                  "' with shape: dt,dz,dy,dx. Tacking first time-step"
    
                pvals = objvar[0, :, ijz0[0], ijz0[1]]
            elif len(objvar.shape) == 3:
                print warnmsg
                print '  ' + fname + ": assuming that pressure variable '" + varnpres +  \
                  "' with shape: dz,dy,dx"
    
                pvals = objvar[:, ijz0[0], ijz0[1]]
            
            elif len(objvar.shape) == 2:
                print warnmsg
                print '  ' + fname + ": assuming that pressure variable '" + varnpres +  \
                  "' with shape: dz,dyx"
    
                pvals = objvar[:, ijz0[0]]
            else:
                pvals = objvar[:]

# Logarithmic axes
    if zlog == 'true':
        zlogv = True
    elif zlog == 'false':
        zlogv = False
    else:
        print errormsg
        print '  ' + fname + ": wrong value for zlog: '" + zlog + "' !!"
        print "    must be either: 'true' or 'false'"
        quit(-1)

    if dzlog == 'true':
        dzlogv = True
    elif dzlog == 'false':
        dzlogv = False
    else:
        print errormsg
        print '  ' + fname + ": wrong value for dzlog: '" + dzlog + "' !!"
        print "    must be either: 'true' or 'false'"
        quit(-1)

    if pvals is not None:
        if plog == 'true':
            plogv = True
        elif plog == 'false':
            plogv = False
        else:
            print errormsg
            print '  ' + fname + ": wrong value for plog: '" + plog + "' !!"
            print "    must be either: 'true' or 'false'"
            quit(-1)
        if dplog == 'true':
            dplogv = True
        elif dplog == 'false':
            dplogv = False
        else:
            print errormsg
            print '  ' + fname + ": wrong value for dplog: '" + dplog + "' !!"
            print "    must be either: 'true' or 'false'"
            quit(-1)

    drw.plot_vertical_lev(zvals, pvals, zlogv, dzlogv, plogv, dplogv, title, kindfig, legloc)

    objf.close()

    return

def draw_subbasin(ncfile, values):
    """ Function to plot subbasin from 'routnig.nc' ORCDHIEE
      ncfile= file to use produced with nc_var.py#subbasin function 
      values= [subasiname]:[rangecolors]:[mapv]:[basinlinewidth]:[drawsubid]:[gtit]:[figkind]:[legvals]:[figurename]
        [subasiname]= name of the subbasin ('!' for spaces)
        [rcolor]= '@', list of 'r|g|b' 1-based colors (as much as first level sub-flow). 'None' for automatic
        [mapv]= map characteristics: [proj],[res]
          see full documentation: http://matplotlib.org/basemap/
          [proj]: projection
            * 'cyl', cilindric
            * 'lcc', lambert conformal
          [res]: resolution:
            * 'c', crude
            * 'l', low
            * 'i', intermediate
            * 'h', high
            * 'f', full
        [basinlinewidth]= with of the line to draw the basin
        [drawsubid]= wehther sub-flow ids should be plot or not
        [graphtit]= title of the graph ('|', for spaces)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [figname]= name of the figure
    """
    fname = 'draw_subbasin'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_subbasin.__doc__
        quit()

    expectargs = '[subasiname]:[rangecolors]:[mapv]:[basinlinewidth]:[drawsubid]:' + \
      '[gtit]:[figkind]:[legloc]:[figurename]'
 
    drw.check_arguments(fname,values,expectargs,':')

    subbasiname = values.split(':')[0].replace('!',' ')
    rangecolors = values.split(':')[1]
    mapv = values.split(':')[2]
    basinlinewidth = np.float(values.split(':')[3])
    drawsubid = gen.Str_Bool(values.split(':')[4])
    gtit = values.split(':')[5].replace('!',' ')
    figkind = values.split(':')[6]
    legloc = int(values.split(':')[7])
    figurename = values.split(':')[8]

    if not os.path.isfile(ncfile):
        print errormsg
        print '  ' + fname + ': file "' + ncfile + '" does not exist !!'
        quit(-1)    

    objf = NetCDFFile(ncfile, 'r')

    searchvars = ['lon', 'lat', 'lonsubflow', 'latsubflow', 'outsubflow']
    for searchvar in searchvars: 
        if not gen.searchInlist(objf.variables,searchvar):
            print errormsg
            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
              "variable '" + searchvar + "' !!"
            quit(-1)
    
# lon,lat
    olon = objf.variables['lon']
    olat = objf.variables['lat']
    lon = olon[:]
    lat = olat[:]

# sub-flow names
    osubnames = objf.variables['subflow']
    subnames = drw.get_str_nc(osubnames, osubnames.shape[1])

# sub-flow lat, lon
    latlonsub = {}
    outflowsub = {}
    osublon = objf.variables['lonsubflow']
    osublat = objf.variables['latsubflow']
    oNsubflow = objf.variables['Nsubflow']
    ooutsubflow = objf.variables['outsubflow']
    Nsubflow = oNsubflow[:]
    isub = 0
    for Ssub in subnames:
        sublatlon = []
        suboutflow = []
        for igrid in range(Nsubflow[isub]):
            sublatlon.append([osublat[isub,igrid], osublon[isub,igrid]])
            suboutflow.append(ooutsubflow[isub,igrid])
        latlonsub[Ssub] = sublatlon
        outflowsub[Ssub] = suboutflow
        isub = isub + 1

# colors
    if rangecolors == 'None':
        rangecols = None
    else:
        cols = rangecolors.split('@')
        Ncols = len(cols)
        rangecols = []
        for icol in range(Ncols):
            cval = cols[icol].split('|')
            rangecols.append([np.float(cval[0]),np.float(cval[1]),np.float(cval[2])])

    drw.plot_subbasin(subbasiname, lon, lat, subnames, latlonsub, outflowsub,        \
      rangecols, mapv, basinlinewidth, drawsubid, gtit, figkind, legloc, figurename)

    objf.close()

    return

def draw_2lines(ncfiles, values, varnames):
    """ Fucntion to plot two lines in different axes (x/x2 or y/y2)
      values= [commonvardim]:[varangeA]:[varangeB]:[varangeaxis]:[axisvals]:[figvarns]:[colors]:
       [widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:[labelaxis]:[legvals]:[figname]:[figkind]:[close]
        [commonvardim]: name of the common variable-dimension
        [varangeA]: ',' separated list of range (min,max) for A values ('None', automatic; 'Extrs' from values extremes)
        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic; 'Extrs' from values extremes)
        [varangeaxis]: ',' separated list of range (min,max) for common axis values ('None', automatic; 'Extrs' from 
          values extremes)
        [axisvals]: which is the axis to plot the values ('x' or 'y')
        [figvarns]: ',' separated list of names of the variables in the  plot
        [colors]: ',' list with color names of the lines for the variables ('None', automatic)
        [widths]: ',' list with widths of the lines for the variables ('None', automatic)
        [styles]: ',' list with the styles of the lines ('None', automatic)
        [sizemarks]: ',' list with the size of the markers of the lines ('None', automatic)
        [marks]: ',' list with the markers of the lines ('None', automatic)
        [graphtitle]: title of the figure ('!' for spaces)
        [labelaxis]: label in the figure of the common axis ('!' for spaces)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [figname]: name of the figure
        [figkind]: kind of figure
        [close]: Whether figure should be finished or not
      ncfiles= ',' separated list of files to use
      varnames=  ',' separated list of variables names in the files to plot
    """
    fname = 'draw_2lines'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2lines.__doc__
        quit()

    expectargs = '[commonvardim]:[varangeA]:[varangeB]:' +           \
     '[varangeaxis]:[axisvals]:[figvarns]:[colors]:[widths]:[styles]:[sizemarks]:' + \
     '[marks]:[graphtitle]:[labelaxis]:[lloc]:[figname]:[figkind]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    commonvardim = values.split(':')[0]
    varangeA0 = values.split(':')[1]
    varangeB0 = values.split(':')[2]
    varangeaxis0 = values.split(':')[3]
    axisvals = values.split(':')[4]
    figvarns = values.split(':')[5].split(',')
    colors = gen.str_list(values.split(':')[6],',')
    widths = gen.str_list_k(values.split(':')[7],',','np.float')
    styles = gen.str_list(values.split(':')[8],',')
    sizemarks = gen.str_list_k(values.split(':')[9],',','np.float')
    marks = gen.str_list(values.split(':')[10],',')
    graphtitle = values.split(':')[11].replace('!',' ')
    labelaxis = values.split(':')[12].replace('!',' ')
    legvals = values.split(':')[13]
    figname = values.split(':')[14]
    figkind = values.split(':')[15]
    close = gen.Str_Bool(values.split(':')[16])

    files = ncfiles.split(',')
    invarns = varnames.split(',')

    varunits = []

    # Values line A
    if not os.path.isfile(files[0]):
        print errormsg
        print '  ' + fname + ": file '" + files[0] + "' does not exist !!"
        quit(-1)

    oncA = NetCDFFile(files[0], 'r')

    if not gen.searchInlist(oncA.variables.keys(), invarns[0]):
        print errormsg
        print '  ' + fname + ": A file '" + files[0] + "' does not have variable '" +\
          invarns[0] + "' !!"
        quit(-1)

    objvA = oncA.variables[invarns[0]]
    varvalsA = objvA[:]
    varangeA = np.zeros((2),dtype=np.float)

    if gen.searchInlist(objvA.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvA.getncattr('units')))
    else:
        valsA = gen.variables_values(invarns[0])
        varunits.append(drw.units_lunits(valsA[5]))
    if varangeA0 == 'None':
        varangeA = [valsA[2], valsA[3]]
    elif varangeA0 == 'Extrs':
        varangeA = [np.min(varvalsA), np.max(varvalsA)]
    else:
        for iv in range(2): varangeA[iv] = np.float(varangeA0.split(',')[iv])

    if not gen.searchInlist(oncA.variables.keys(), commonvardim):
        print errormsg
        print '  ' + fname + ": A file '" + files[0] + "' does not have common " +   \
          "dimvar '" + commonvardim + "' !!"
        quit(-1)
    objvd = oncA.variables[commonvardim]
    varvalsaxisA = objvd[:]    

    oncA.close()

    # Values line B
    if not os.path.isfile(files[1]):
        print errormsg
        print '  ' + fname + ": file '" + files[1] + "' does not exist !!"
        quit(-1)

    oncB = NetCDFFile(files[1], 'r')

    if not gen.searchInlist(oncB.variables.keys(), invarns[1]):
        print errormsg
        print '  ' + fname + ": B file '" + files[1] + "' does not have variable '" +\
          invarns[1] + "' !!"
        quit(-1)

    objvB = oncB.variables[invarns[1]]
    varvalsB = objvB[:]
    varangeB = np.zeros((2),dtype=np.float)

    if gen.searchInlist(objvB.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvB.getncattr('units')))
    else:
        valsB = gen.variables_values(invarns[1])
        varunits.append(drw.units_lunits(valsB[5]))
    if varangeB0 == 'None':
        varangeB = [valsB[2], valsB[3]]
    elif varangeB0 == 'Extrs':
        varangeA = [np.min(varvalsA), np.max(varvalsA)]
    else:
        for iv in range(2): varangeB[iv] = np.float(varangeB0.split(',')[iv])

    # Common vardim
    if not gen.searchInlist(oncB.variables.keys(), commonvardim):
        print errormsg
        print '  ' + fname + ": B file '" + files[1] + "' does not have common " +   \
          "dimvar '" + commonvardim + "' !!"
        quit(-1)
    objvd = oncB.variables[commonvardim]
    varvalsaxisB = objvd[:]

    # Range of the axis
    varangeaxis = np.zeros((2),dtype=np.float)

    valsVD = gen.variables_values(commonvardim)
    if gen.searchInlist(objvd.ncattrs(), 'units'):
        dimvarunits = drw.units_lunits(objvd.getncattr('units'))
    else:
        dimvarunits = drw.units_lunits(valsVD[5])
    if varangeaxis0 == 'None':
        varangeaxis = [valsVD[2], valsVD[3]]
    elif varangeaxis0 == 'Extrs':
        varangeaxis[0] = np.min([np.min(varvalsaxisA), np.min(varvalsaxisB)])
        varangeaxis[1] = np.max([np.max(varvalsaxisA), np.max(varvalsaxisB)])
    else:
        for iv in range(2): varangeaxis[iv] = np.float(varangeaxis0.split(',')[iv])
    
    oncB.close()

    labelaxis = valsVD[0] + ' (' + dimvarunits + ')'

    # Lines characteristics
    colvalues, linekinds, pointkinds, lwidths, psizes = drw.ColorsLinesPointsStyles( \
      2, colors, styles, marks, widths, sizemarks, 'None')

    # legend
    lloc, lsize = drw.legend_values(legvals,'|')

    drw.plot_2lines(varvalsA, varvalsB, varvalsaxisA, varvalsaxisB, varangeA,        \
      varangeB, varangeaxis, axisvals, figvarns, varunits, colvalues, lwidths,       \
      linekinds, psizes, pointkinds, graphtitle, labelaxis, lloc, lsize, figname,    \
      figkind, close)

def draw_2lines_time(ncfiles, values, varnames):
    """ Function to plot two time-lines in different axes (x/x2 or y/y2)
      values= [timevardim]:[varangeA]:[varangeB]:[timeaxisfmt]:[timeaxis]:[figvarns]:[colors]:
       [widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:[labelaxis]:[legvals]:[figname]:[figkind]:[close]
        [timevardim]: name of the common variable-dimension time
        [varangeA]: ',' separated list of range (min,max) for A values ('None', automatic; 'Extrs' from values extremes)
        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic; 'Extrs' from values extremes)
        [timeaxisfmt]=[tkind];[tfmt]: format of the ticks for the time axis:
           [kind]: kind of time to appear in the graph
             'Nval': according to a given number of values as 'Nval',[Nval]
             'exct': according to an exact time unit as 'exct',[tunit]; 
               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second, 
                'l': milisecond
           [tfmt]; desired format
        [timeaxis]: which is the time axis in the plot ('x' or 'y')
        [figvarns]: ',' separated list of names of the variables in the  plot
        [colors]: ',' list with color names of the lines for the variables ('None', automatic)
        [widths]: ',' list with widths of the lines for the variables ('None', automatic)
        [styles]: ',' list with the styles of the lines ('None', automatic)
        [sizemarks]: ',' list with the size of the markers of the lines ('None', automatic)
        [marks]: ',' list with the markers of the lines ('None', automatic)
        [graphtitle]: title of the figure ('!' for spaces)
        [labelaxis]: label in the figure of the common axis ('!' for spaces)
        [legvals]=[locleg]|[fontsize]: 
          [locleg]: location of the legend (0, autmoatic)
            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
            9: 'upper center', 10: 'center'
          [fontsize]: font size for the legend (auto for 12)
        [figname]: name of the figure
        [figkind]: kind of figure
        [close]: Whether figure should be finished or not
      ncfiles= ',' separated list of files to use
      varnames=  ',' separated list of variables names in the files to plot
    """
    fname = 'draw_2lines_time'

    if values == 'h':
        print fname + '_____________________________________________________________'
        print draw_2lines_time.__doc__
        quit()

    expectargs = '[timevardim]:[varangeA]:[varangeB]:[timeaxisfmt]:[timeaxis]:' +    \
     '[figvarns]:[colors]:[widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:' +     \
     '[labelaxis]:[lloc]:[figname]:[figkind]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    timevardim = values.split(':')[0]
    varangeA0 = values.split(':')[1]
    varangeB0 = values.split(':')[2]
    timeaxisfmt = values.split(':')[3]
    timeaxis = values.split(':')[4]
    figvarns = values.split(':')[5].split(',')
    colors = gen.str_list(values.split(':')[6],',')
    widths = gen.str_list_k(values.split(':')[7],',','np.float')
    styles = gen.str_list(values.split(':')[8],',')
    sizemarks = gen.str_list_k(values.split(':')[9],',','np.float')
    marks = gen.str_list(values.split(':')[10],',')
    graphtitle = values.split(':')[11].replace('!',' ')
    labelaxis = values.split(':')[12].replace('!',' ')
    legvals = values.split(':')[13]
    figname = values.split(':')[14]
    figkind = values.split(':')[15]
    close = gen.Str_Bool(values.split(':')[16])

    files = ncfiles.split(',')
    invarns = varnames.split(',')

    varunits = []

    # Values line A
    if not os.path.isfile(files[0]):
        print errormsg
        print '  ' + fname + ": file '" + files[0] + "' does not exist !!"
        quit(-1)

    oncA = NetCDFFile(files[0], 'r')

    if not gen.searchInlist(oncA.variables.keys(), invarns[0]):
        print errormsg
        print '  ' + fname + ": A file '" + files[0] + "' does not have variable '" +\
          invarns[0] + "' !!"
        quit(-1)
    if not gen.searchInlist(oncA.variables.keys(), timevardim):
        print errormsg
        print '  ' + fname + ": A file '" + files[0] + "' does not have time " +     \
          "variable '" + timevardim + "' !!"
        quit(-1)

    objvA = oncA.variables[invarns[0]]
    varvalsA = objvA[:]
    varangeA = np.zeros((2),dtype=np.float)
    objtA = oncA.variables[timevardim]
    timevalsA = objtA[:]
    trangeA = [np.min(timevalsA), np.max(timevalsA)]
    tunitsA = objtA.getncattr('units')

    if len(varvalsA.shape) != 1:
        print errormsg
        print '  ' + fname + ": variable '" + invarns[0] + "' has wrong shape:",     \
          varvalsA.shape, 'it must be 1D !!'
        quit(-1)

    if gen.searchInlist(objvA.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvA.getncattr('units')))
    else:
        valsA = gen.variables_values(invarns[0])
        varunits.append(drw.units_lunits(valsA[5]))
    if varangeA0 == 'None':
        varangeA = [valsA[2], valsA[3]]
    elif varangeA0 == 'Extrs':
        varangeA = [np.min(varvalsA), np.max(varvalsA)]
    else:
        for iv in range(2): varangeA[iv] = np.float(varangeA0.split(',')[iv])

    oncA.close()

    # Values line B
    if not os.path.isfile(files[1]):
        print errormsg
        print '  ' + fname + ": file '" + files[1] + "' does not exist !!"
        quit(-1)

    oncB = NetCDFFile(files[1], 'r')

    if not gen.searchInlist(oncB.variables.keys(), invarns[1]):
        print errormsg
        print '  ' + fname + ": B file '" + files[1] + "' does not have variable '" +\
          invarns[1] + "' !!"
        quit(-1)
    if not gen.searchInlist(oncB.variables.keys(), timevardim):
        print errormsg
        print '  ' + fname + ": B file '" + files[1] + "' does not have time " +     \
          "variable '" + timevardim + "' !!"
        quit(-1)

    objvB = oncB.variables[invarns[1]]
    varvalsB = objvB[:]
    varangeB = np.zeros((2),dtype=np.float)
    objtB = oncB.variables[timevardim]
    timevalsB = objtB[:]
    tunitsB = objtB.getncattr('units')

    if gen.searchInlist(objvB.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvB.getncattr('units')))
    else:
        valsB = gen.variables_values(invarns[1])
        varunits.append(drw.units_lunits(valsB[5]))
    if varangeB0 == 'None':
        varangeB = [valsB[2], valsB[3]]
    elif varangeB0 == 'Extrs':
        varangeA = [np.min(varvalsA), np.max(varvalsA)]
    else:
        for iv in range(2): varangeB[iv] = np.float(varangeB0.split(',')[iv])
    
    oncB.close()

    # Time axis taking time units in line A as reference
    varvalsaxisB = gen.coincident_CFtimes(timevalsB, tunitsA, tunitsB)
    trangeB = [np.min(varvalsaxisB), np.max(varvalsaxisB)]

    varangeaxis = [np.min([trangeA[0],trangeB[0]]), np.max([trangeA[1],trangeB[1]])]

    timevals = np.arange(varangeaxis[0],varangeaxis[1])
    tkind = timeaxisfmt.split(';')[0]
    tformat = timeaxisfmt.split(';')[1]
    tpos, tlabels = drw.CFtimes_plot(timevals, tunitsA, tkind, tformat)

    # Lines characteristics
    colvalues, linekinds, pointkinds, lwidths, psizes = drw.ColorsLinesPointsStyles( \
      2, colors, styles, marks, widths, sizemarks, 'None')

    # legend
    lloc, lsize = drw.legend_values(legvals,'|')

    drw.plot_2lines_time(varvalsA, varvalsB, timevalsA, varvalsaxisB, varangeA,      \
      varangeB, tpos, tlabels, timeaxis, figvarns, varunits, colvalues, lwidths,     \
      linekinds, psizes, pointkinds, graphtitle, labelaxis, lloc, lsize, figname,    \
      figkind, close)

#quit()

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

ngraphics = "'" + drw.numVector_String(namegraphics, "', '") + "'"
  
### Options
##string_operation="operation to make: " + '\n' + " out, output values -S inidim1,[inidim2,...]:enddim1,[enddim2,...]"
string_operation="""operation to make: 
  draw_topo_geogrid, draws topography from a WPS geo_em.d[nn].nc: -S [minTopo],[maxTopo]:[SW_lon],[SW_lat],[NE_lon],[NE_lat]:[title]:[graphic_kind]:[projection],[res_coastline]
  draw_2D_shad_cont, draws two 2D fields, first with shading second with contour lines: -v [varns],[varnc] -S [vnamefs],[vnamefc],[dimxvn],[dimyvn],[colorbar],[ckind],[clabfmt],[sminv]:[smaxv],[sminc]:[smaxv]:[Nlev],[figt],[kindfig],[reverse]
    [ckind]:
      'cmap': as it gets from colorbar
      'fixc,[colname]': fixed color [colname], all stright lines
      'fixsignc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
"""
####### ###### ##### #### ### ## #

# Not checking file operation
Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_cont_time',                    \
  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
  'draw_lines',                                                                      \
  'draw_lines_time', 'draw_points', 'draw_topo_geogrid_boxes', 'draw_trajectories',  \
  'draw_vals_trajectories', 'variable_values']

errormsg='ERROR -- error -- ERROR -- error'

# From: http://stackoverflow.com/questions/4041238/why-use-def-main
def main():
#######    #######
## MAIN
    #######

    parser = OptionParser()
    parser.add_option("-f", "--netCDF_file", dest="ncfile", 
     help="file to use", metavar="FILE")
    parser.add_option("-o", "--operation", type='choice', dest="operation", 
      choices=namegraphics, help="operation to make: " + ngraphics, metavar="OPER")
    parser.add_option("-S", "--valueS", dest="values", 
      help="[WHEN APPLICABLE] values to use according to the operation", 
      metavar="VALUES")
    parser.add_option("-v", "--variable", dest="varname",
      help="[WHEN APPLICABLE] variable to check", metavar="VAR")

    (opts, args) = parser.parse_args()

    varn=opts.varname
    oper=opts.operation

    if opts.operation is None:
        print errormsg
        print '  No operation provided !!'
        print "  an operation must be provided as '-o [operationname]' "
        quit(-1)

    if opts.ncfile is not None and not os.path.isfile(opts.ncfile) and                   \
      not drw.searchInlist(Notcheckingfile, oper):
        print errormsg
        print '  ' + mainn + ': File ' + opts.ncfile + ' does not exist !!'
        quit(-1)

    if oper == 'create_movie':
        create_movie(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2D_shad':
        draw_2D_shad(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2D_shad_time':
        draw_2D_shad_time(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2D_shad_cont':
        draw_2D_shad_cont(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2D_shad_cont_time':
        draw_2D_shad_cont_time(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2D_shad_line':
        draw_2D_shad_line(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2D_shad_line_time':
        draw_2D_shad_line_time(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_barbs':
        draw_barbs(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_basins':
        draw_basins(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_Neighbourghood_evol':
        draw_Neighbourghood_evol(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2lines':
        draw_2lines(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_2lines_time':
        draw_2lines_time(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_lines':
        draw_lines(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_lines_time':
        draw_lines_time(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_points':
        draw_points(opts.ncfile, opts.values)
    elif oper == 'draw_points_lonlat':
        draw_points_lonlat(opts.ncfile, opts.values)
    elif oper == 'draw_ptZvals':
        draw_ptZvals(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_river_desc':
        draw_river_desc(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_subbasin':
        draw_subbasin(opts.ncfile, opts.values)
    elif oper == 'draw_timeSeries':
        draw_timeSeries(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_topo_geogrid':
        draw_topo_geogrid(opts.ncfile, opts.values)
    elif oper == 'draw_topo_geogrid_boxes':
        draw_topo_geogrid_boxes(opts.ncfile, opts.values)
    elif oper == 'draw_trajectories':
        draw_trajectories(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_vals_trajectories':
        draw_vals_trajectories(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_vectors':
        draw_vectors(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_vertical_levels':
        draw_vertical_levels(opts.ncfile, opts.values, opts.varname)
    elif oper == 'list_graphics':
    # From: http://www.diveintopython.net/power_of_introspection/all_together.html
        import drawing as myself
        object = myself
        for opern in namegraphics:
            if  opern != 'list_graphics': 
                print opern + '_______ ______ _____ ____ ___ __ _'
                print getattr(object, opern).__doc__
    elif oper == 'variable_values':
        variable_values(opts.values)
    else:
        print errormsg
        print '  ' + main + ": the graphic '" + oper + "' is not ready !!"
        print errormsg
        quit()

if __name__ == '__main__':
    main()

