# -*- coding: iso-8859-15 -*-
# 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
import numpy.ma as ma

## 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_time -f ERAI_pl201507_130.nc -S 'ta~lon|52,lat|30,time|76@100~lev~time~auto~rainbow,auto,vertical~200.,310.~data,data~ta|in|valley|from|ERA-Interim~png~transpose~time|hours!since!2015-07-01!00:00:00|exct,12,h|$%d^{%H}$|date!($[DD]^{[HH]}$)~True' -v t
## e.g. #drawing.py -o draw_2D_shad_time -f ERAI_pl201507_130.nc -S 'ta~lon|52,lat|30,time|76@100~lev~time~auto~rainbow,auto,vertical~200.,310.~data,fixpixel~ta|in|valley|from|ERA-Interim~png~transpose~time|hours!since!2015-07-01!00:00:00|exct,12,h|$%d^{%H}$|date!($[DD]^{[HH]}$)~True' -v t
## 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: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_lines_time -f 'TRMM_1999-2010_prec_mm-year_hydyearsum_sellonlatbox2005_fldmean.nc%time|-1;lon|0;lat|0,CRUNCEP_1999-2010_prec_mm-year_hydyearsum_sellonlatbox2005_fldmean.nc%time|-1;lon|0;lat|0,WFDEIgpcc_1999-2010_prec_mm-year_hydyearsum_sellonlatbox2005_fldmean.nc%time|-1;lon|0;lat|0' -S 'time;y;time;auto;TRMM,CRUNCEP,WFDEIgpcc;prec;prec|hydrological|year;auto,auto;time|exct,1,y|%Y;0|auto;png;-;k,b,g;.;2;2;all;-1;True' -v prec
## 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_WindRose -S 'lon|7;lat|2:anglespeedfreq;16;8;40.;auto;auto:November!ERA-I!daily!mean!wind!at!850!hPa:png:cardinals:False:WindRose:True' -v u,v -f reg1_daymean_mon11_lev850_kmh.nc
## e.g. # drawing.py -o draw_WindRose -S 'lon|7;lat|2:linepoint;multicoltime;time;auto;auto;auto;auto;exct,5,d;%m/%d;date!([DD]/[MM]):November!ERA-I!daily!mean!wind!at!850!hPa:png:cardinals:False:WindRose:True' -v u,v -f reg1_daymean_mon11_lev850_kmh.nc 
## e.g. # drawing.py -o draw_Taylor -f 'file0.nc@var,file1.nc@var,file2.nc@var,file3.nc@var' -S '$10.\sin(0.05t2\pi)$:x:8:k,b,r,g,#FFBB00:$10.25\sin(0.025+0.05t2\pi)$,$10.25\sin(0.025+0.05125t2\pi)$,$10.5\sin(0.05+0.05t2\pi)$,$10.\sin(0.05+0.0525t2\pi)$:legend,0,8:norm:sinus!Taylor!diagram:png:yes:True' -v reffile.nc,var
## e.g. # drawing.py -o draw_timeSeries -f ~/PY/ERAI_pl199501_131-132.nc -S 'lon|240,lat|120,time|-1,lev|0:Srange,Srange:ua:date|($[MM]^{[DD]}$):exct,15,d:$%m^{%d}$:January|1995|ERA-Interim|x-wind|at|i=240,|j=120,|k=0:ua:0|12:png:r:-:2:x:2:20:yes' -v var131,time
## e.g. # drawing.py -o draw_trajectories -f 'medic950116/control/trajectory.dat@-1@etudes/domains/WL_HyMeX_HighRes_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdza/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdzb/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdzb_cyc/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000' -S 'spaghetti_date@-@None@1@o@1@$%d^{%H}$@8@6@4@4|$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|15,28,26,39|medicane trajectories|png|cyl,i|0@8|yes' -v 'medic950116/obs/trajectory.dat,satellite,-1,0.9999998779E+03,t-step|1800.|19950115000000@auto'
## e.g. # drawing.py -o draw_2D_shad_2cont -f hur_157_100000_20051214000000-20051218000000.nc,z_129_100000_20051214000000-20051218000000.nc,ta_130_100000_20051214000000-20051218000000.nc -S 'hur@100000,z@100000,ta@100000:time|0,lev|0,lat|-1,lon|-1:time|0,lev|0,lat|-1,lon|-1:time|0,lev|0,lat|-1,lon|-1:lon:lat:auto:BuPu,auto,auto:fixc,green:None:fixc,red:None:60.,100.:-700.,4000.,8:265.,300.,8:hur|z|ta|@100000|on|20051214000000:png:flip@y:cyl,l:yes' -v hur,z,ta
## e.g. # drawing.py -o draw_ptZvals -f MountainPeaks.nc -S 'height:lon,lat:auto:x:5.:-180.,-90.,180.,90.:0,9000.:ptlabel,name,8,0,4:Mountain!peaks:rainbow,auto,auto:cyl,l:png:yes' -v height
## e.g. # drawing.py -o draw_vectors -f wrfout_d01_1995-01-01_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:auto:3@3,wind@rainbow@Srange|Srange,9:10m wind,ms-1:cyl,l:WRF!10!m!winds!on!Dec.!1st!1995!06!UTC:png:winds:yes' -v U10,V10
## e.g.# drawing.py -o draw_vertical_levels -f wrfout_d01_1995-01-01_00:00:00 -S 'true,true:false,false:wrfout!vertical!levels!(LUPA):png:4|12:yes' -v WRFz
## e.g. # drawing.py -o draw_subbasin -f Caceres_subbasin.nc -S 'Caceres:None:cyl,l:2:True:Parana!subbasins!from!Cáceres:png:0:Caceres_subbasin:True:True'
## e.g. # drawing.py -o draw_basins -f routing.nc -S '-5,5,42.,52.:l:rainbow,auto,auto:1,1000:True:True:True:ORCDHIEE|river-basins:png:basins_named:True' -v nav_lon,nav_lat,trip,basins
## e.g. # drawing.py -o draw_river_desc -f river_desc.nc -S 'Y|lat|lat|-1,X|lon|lon|-1:red,green:Blues:cyl,l:ORCDHIEE|rivers:png:0:or_rivers:True' -v Amazon,Parana
## e.g. # drawing.py -f forcing_Amazonia.nc,forcing_Amazonia.nc -o draw_2lines_time -S 'tstep:Excts:Excts:exct,5,y;%Y:x:tas,wss:r,b:2.:-,-:None:,;,:WFD!forcing!evolution!at!Amazonia:year:0|12:../LaTeX/figs/forcing_Amazonia_tas-wss:png:yes' -v Tair,Wind
## e.g. # drawing.py -o draw_bar -f 'Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm' -S 'Stringlist,%s,January@Feburary@March@Arpil@May@June@July@August@September@October@November@December,25,pretty,auto,auto,auto:time!since!1958-01-01:pr:y:seconds:mmd-1:SESA,SACZ:#AA0000,#0000AA:1000000.:normalized!evolution!of!precipitaion!with!CRU-NCEP!forcing:0|10:png:bar_rain_CRU-NCEP_norm:yes'
## e.g. # drawing.py -o draw_bar_time -f 'Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm' -S 'auto;pr;1;y;None;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ;#AA0000,#0000AA;10000000.;normalized!evolution!of!DJFmean!of!precipitaion!with!CRU-NCEP!forcing;0|10;png;bar_time_rain_CRU-NCEP_DJFmean_norm;yes'
## e.g. # drawing.py -o draw_bar_line -f 'Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm;bar:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,12@24@1;time_counter;rainnorm;bar:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm;line:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,12@24@1;time_counter;rainnorm;line' -S 'Stringlist,%s,January@Feburary@March@April@May@June@July@August@September@October@November@December@Jan@Feb@Mar@Apr@May@Jun@Jul@Aug@Sept@Oct@Nov@Dec,25,pretty,auto,auto,auto:time!since!1958-01-01:pr:x:-4.,4.:seconds:1:$SESA_{1958}$,$SESA_{1959}$,$SACZ_{1958}$,$SACZ_{1959}$:#AA0000,#0000AA:1000000.:#00AA00,#AAAA00:-.:,:2.:2.:all:normalized!evolution!of!precipitation!with!CRU-NCEP!forcing:0|10:png:bar-line_rain_CRU-NCEP_norm:yes'
## e.g. # drawing.py -o draw_bar_line_time -f 'Forcing_rainstats_OKstomate_SESA_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm;bar:Forcing_rainstats_OKstomate_SACZ_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm;bar:DiPolo_evapstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evap_stats;line:DiPolo_evapnustats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evapnu_stats;line:DiPolo_evspsblvegstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evspsblveg_stats;line:DiPolo_transpirstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;transpir_stats;line:DiPolo_evapstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evap_stats;line:DiPolo_evapnustats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evapnu_stats;line:DiPolo_evspsblvegstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evspsblveg_stats;line:DiPolo_transpirstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;transpir_stats;line' -S 'auto;pr;y;None;1;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ,SESA!evap,evapnu,evspblveg,transpir,SACZ!evap,None,None,None;#AA0000,#0000AA;10000000.;#AAAA00,#00AAAA,#AA00AA,#AAAAAA,#AAAA00,#00AAAA,#AA00AA,#AAAAAA;-,-,-,-,--,--,--,--;,;2.;2.;all;normalized!evolution!of!DJFmean!with!WFD3!forcing;0|10;png;bar_time_rain_CRU-NCEP_DJFmean_norm;yes'
## e.g. # drawing.py -o draw_time_lag -f 'Forcing_rainstats_OKstomate_SESA_norm_meanstd_stat2.nc;time_centered,-1;time_counter;rainnorm%DiPolo_evapstats_SESA_norm_meanstd_OKstomate.nc;time_counter,-1|stats,2;time_counter;evapnorm:Forcing_rainstats_OKstomate_SACZ_norm_meanstd_stat2.nc;time_centered,-1;time_counter;rainnorm%DiPolo_evapstats_SACZ_norm_meanstd_OKstomate.nc;time_counter,-1|stats,2;time_counter;evapnorm' -S 'auto;centered;pr;1;evap;1;-5,5;-2,2;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ;simplepts,1,#AA0000@#0000AA,x,2.;1-month!time-lag!at!SACZ!between!pr!&!evap!normalized!by!mean/stddev;0|12;png;mon1_timelag_pr-evap_SACZ;yes'
## e.g. # drawing.py -o draw_ensembles_time -f 'Forcing_rain_SESA.nc;time_counter,-1|stats,0;time_centered;rain_stats;ensemble#Forcing_rain_SESA.nc;time_counter,-1|stats,1;time_centered;rain_stats;ensemble#Forcing_rain_SESA.nc;time_counter,-1|stats,2;time_centered;rain_stats;data' -S 'auto;y;tas;mm/d;auto,auto;#0000FF:-:2.:,:2.;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;FromFile;$pr_{space-mean}^{SESA}$;cloud,#AAAADD,auto;$pr_{space-mean}$!evolution!at!SESA;0|10;png;Forcing_pr_spacemean;no;yes'
## e.g. # drawing.py -o draw_cycle -f 'Forcing_tairstats_OKstomate_CRUNCEP_spinup_SESA.nc;time_counter,-1|stats,2;time_centered;tair_stats' -S 'auto;y;centered;tair;K;None;12,3;lines,rainbow,horizontal,auto,-,2.;1,3,5@Sep/Nov,Jan/Jul,Mar/May;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA;year-evolution!of!CRUNCEP!tair!forcing!at!SESA;0|10;png;cycle_tair_CRUNCEP_spinup_SESA;yes'
## e.g. # drawing.py -o draw_multi_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|0;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|1;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|2;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|3' -S 'tas:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:0!UTC,1!UTC,2!UTC,3!UTC:2:2:tas!at!2001-11-11:True'
# movie_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00' -S 'tas:west_east|-1,south_north|-1,Time|-1:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:Time,Times:WRFdate,$%d^{%H}$:15:mp4' -v T2
## e.g. # drawing.py -o draw_SkewT -f UWyoming_snd_87576.nc -S 'time|0:auto:auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes' -v ta,tda,pres
## e.g. # drawing.py -o draw_multi_SkewT -f 'UWyoming_snd_87576.nc:pres|-1,time|0:ta,pres;UWyoming_snd_87576.nc:pres|-1,time|0:tda,pres' -S 'auto:auto:multilines!ta,tda!#6464FF,#FF6464!-!,!2:0,auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes'
## e.g. # drawing.py -o draw_2D_shad_contdisc -f 'simout_snddiags.nc;ta;time;pres;time|-1,pres|-1@UWyoming_snd_87576.nc;ta;time;pres;time|-1,pres|-1' -S 'ta:time,bottom_top:Vfix,auto,3600.,auto,Vfix,auto,50.,auto:auto:Srange,Srange:auto:obs!&!sim!Ezeiza!airport!sounding:pdf:flip@y:None:yes'
## e.g. # drawing.py -o draw_2D_shad_contdisc_time -f 'simout_snddiags.nc;ta;time;pres;time|-1,pres|-1@UWyoming_snd_87576.nc;ta;time;pres;time|-1,pres|-1' -S 'ta;y;auto|exct,12,h|%d$^{%H}$|time!($[DD]^{[HH]}$);Vfix,auto,50.,auto;auto;Srange,Srange;auto;obs!&!sim!Ezeiza!airport!sounding;pdf;flip@y;None;yes'
## e.g. # drawing.py -o draw_2D_shad_contdisc -f 'simout_sfcdiags.nc;tdas;XLONG;XLAT;Time|0,time|0,west_east|-1,south_north|-1@all_single-stations.nc;tdas;stslon;stslat;time|0,lon|-1,lat|-1' -S 'tdas:west_east,south_north:auto:YlGnBu,auto,auto:286.,298.:auto:obs!&!sim!tdas!on!1995/01/01!00!UTC:png:None:cyl,f:sponge,0.1,0.1:yes'
## e.g. # drawing.py -o draw_multiWindRose -f '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/sounding_uava_10868.nc@pres|-1;time|1@ua,va#/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_38lev.nc@bottom_top|-1;time|0@ua,va#/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_50lev.nc@bottom_top|-1;time|0@ua,va#/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_50lev_assigned.nc@bottom_top|-1;time|0@ua,va#/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_80lev.nc@bottom_top|-1;time|0@ua,va#/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_120lev.nc@bottom_top|-1;time|0@ua,va#/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_NOaerosol.nc@bottom_top|-1;time|0@ua,va' -S 'linepoint;multicol;pres;-;auto;spectral;auto:obs,38lev,50lev,50leva,80lev,120lev:WindRose!obs!sim!comparison!on!2012/10/23!00!UTC:png:auto:True'
## e.g. # drawing.py -o draw_stations_map -f stations.inf -S 'snd|x|#FFAAAA|2|8@sfc|x|#AAFFAA|2|8:cyl,l:1.,20.,35.,49.:FPS!Alps!stations:pdf:true'
## e.g. # drawing.py -o draw_WRFeta_levels -f 120lev/simin_vars.nc,80lev/simin_vars.nc,50lev/simin_vars.nc,50lev_assigned/simin_vars.nc,38lev/simin_vars.nc -f '120lev,80lev,50lev,50leva,38lev:auto:auto:0|6|2:FPS!Alps!vert!levels:pdf:no:true'
## e.g. # drawing.py -o draw_2Dshad_map -S 'orog;$conv^{ini}$;lat|-1,lon|-1;lon;lat;auto;rainbow#auto#auto#time@minutes!since!1949-12-01!00:00:00|exct,6,h|%d$^{%H}$|date!([DD]$^{[HH]}$);Srange,Srange;convini|Case1|1a;pdf;binary|shadow,NW,auto|-70.,-36,-62.,-30.;cyl,c;yes' -v convini -f UBA_ERA-I_1a_2D.nc

#######
# 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_contdisc: plotting one continuous fields with shading and another discrete one with points
# draw_2D_shad_contdisc_time: plotting one continuous fields with shading and another discrete one with 
#   points with a time-axis
# draw_2D_shad_2cont: plotting three fields, one with shading and the other two 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_2Dshad_map: plotting a shadow field with a background map
# 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_bar: Function to plot a bar char figure with multiple sources
# draw_bar_line: Function to plot a bar char and line figure with multiple sources
# draw_bar_line_time: Function to plot a bar char and line figure with multiple sources with a time-axis
# draw_bar_time: Function to plot a bar char figure with multiple sources and time axis
# 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_cycle: Function to plot a variale with a circular cycle
# draw_ensembles_time: Function to plot an ensembles of data following an axis-time
# 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_multi_2D_shad: plotting multiple 2D fields with same projection with shading and sharing colorbar
# draw_multi_SkewT: creation of a SkewT-logP diagram with multiple lines using matplotlib's API example
# draw_multiWindRose: Function to plot multiple wind rose (from where the dinw blows)
# 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 by their Z value and a colorbar
# draw_SkewT: creation of a SkewT-logP diagram using matplotlib's API example  
# draw_stations_map: Function to plot a map with the stations
# draw_time_lag: Function to plot a time-lag figure with multiple sources (x, previous values; y, future 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 prode 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_Taylor: Function to draw a Taylor diagram (Taylor 2001)
# draw_vertical_levels: plotting vertical levels distribution
# draw_WindRose: Function to plot a wind rose (from where the dinw blows)
# draw_WRFeta_levels: Function to plot vertical levels from WRF wrfinput_d[nn] file
# movie_2D_shad: creation of a movie with shading

mainn = 'drawing.py'

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

namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2Dshad_map',                   \
  'draw_2D_shad_time',                                                               \
  'draw_2D_shad_cont', 'draw_2D_shad_contdisc', 'draw_2D_shad_contdisc_time',        \
  'draw_2D_shad_2cont', 'draw_2D_shad_cont_time',                                    \
  'draw_2D_shad_line',                                                               \
  'draw_2D_shad_line_time', 'draw_bar', 'draw_bar_line', 'draw_bar_line_time',       \
  'draw_bar_time', 'draw_barbs', 'draw_basins', 'draw_cycle', 'draw_ensembles_time', \
  'draw_2lines', 'draw_2lines_time',                                                 \
  'draw_lines', 'draw_lines_time',                                                   \
  'draw_multi_2D_shad', 'draw_multi_SkewT', 'draw_multiWindRose',                    \
  'draw_Neighbourghood_evol',                                                        \
  'draw_points', 'draw_points_lonlat',                                               \
  'draw_ptZvals', 'draw_river_desc', 'draw_SkewT', 'draw_subbasin',                  \
  'draw_stations_map', 'draw_Taylor',                                                \
  'draw_time_lag', 'draw_timeSeries', 'draw_topo_geogrid',                           \
  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'draw_WindRose',         \
  'draw_WRFeta_levels', 'movie_2D_shad', '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 + '" !!'
        varns = sorted(objsf.variables.keys())
        print '    available ones:', 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]~[gridkind]~[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)
        [gridkind]= [gridxk],[gridyk] kind of grid along x and y axis
          'data': size pixel along the given axis change according to the values along the axis
          'fixpixel': size pixel along the given axis does not change 
        [figt]: title of the figure ('|' for spaces)
        [kindfig]: kind of figure
        [reverse]: '|' list of transformations to apply to 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]~[gridkind]~[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]
    gridkind = 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
    
    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:
        odimtv = odxv
        odimtu = timelabel
        timeaxis = 'x'
        odimvv = odyv
        odimvu = objdimy.getncattr('units')
    elif vdimyn == timename:
        odimtv = odyv
        odimtu = timelabel
        timeaxis = 'y'
        odimvv = odxv
        odimvu = objdimx.getncattr('units')
    else:
        print errormsg
        print '  ' + fname + ": time variable '" + timename + "' not found!!"
        quit(-1)
    timepos, timelabels = drw.CFtimes_plot(odimtv, timeunit, timekind, timefmt)

    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]

    # kind of grid-pixels
    [gridxk, gridyk] = gridkind.split(',')

    if revals == 'None':
        revals = None

    drw.plot_2D_shadow_time(valshad, vnamesfig, odimvv, odimtv, odimvu, dimnamesv,   \
      vaxis, colormapv, shading_nx, varunits, gridxk, gridyk, 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)

    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]:
        [transform]:[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)
        [transform]: 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]:[dimxyfmt]:[transform]:[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]:[vrange]:[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 ('|' 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)
        [vrange]=[ymin],[ymax] range for the plot ('auto' for current range of values)
        [leglabels]: ',' separated list of names for the legend ('!' for spaces, '*' for no label)
        [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]:[vrange]:[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].replace('|', ' ')
    dimxyfmt = values.split(':')[3]
    vrange = values.split(':')[4]
    leglabels = gen.latex_text(values.split(':')[5].replace('!',' '))
    vartit = values.split(':')[6]
    title = values.split(':')[7].replace('|',' ')
    legvals = values.split(':')[8]
    colns = gen.str_list(values.split(':')[9], ',')
    lines = gen.str_list(values.split(':')[10], ',')
    points = gen.str_list(values.split(':')[11], '@')
    lwdths = gen.str_list_k(values.split(':')[12], ',', 'R')
    psizes = gen.str_list_k(values.split(':')[13], ',', 'R')
    freqv0 = values.split(':')[14]
    figname = values.split(':')[15]
    graphk = values.split(':')[16]
    close = gen.Str_Bool(values.split(':')[17])

    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]

    # range
    if vrange == 'auto':
        rng = None
    else:
        rng = np.array(vrange.split(','), dtype=np.float)

    drw.plot_lines(dimvalues, varvalues, valuesaxis, dimtit, xaxis, yaxis, rng,      \
      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]%[dimval] ',' separated list of netCDF files and the 'slice' 
        along the dimensions of the file
          [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
      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 the values of the common dimension for all lines ('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, '*' for no label)
        [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]|[kind]|[tfmt] time labels characteristics
           [timen]; name of the time variable
           [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]|[Ncols]
          [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)
          [Ncols]: number of columns in the legend
        [graphk]: kind of the output of the graphic ('png', 'pdf', 'eps', ...)
        [lines]: ',' list of type of lines (matplotlib syntax), 'None' for automatic,
          providing a single value will be used the same for all the lines
        [collines]: ',' list of colors for the lines (matplotlib syntax), 'None' for 
          automatic, single value all the same
        [points]: '@' list of type of points (matplotlib syntax ',' no 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 (every given number of values), 
          'all' to plot all values using all time steps
          'runmean',[Nsteps]: computing a running mean of [Nsteps] along all values
        [period]: which period of the data to plot:
          '-1': all period of data
          [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
        consecutively). With a single value will be used for all files
      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,';')

    ncfiledims = 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(ncfiledims)

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

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

# 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]
    timekind = timevals.split('|')[1]
    timefmt = timevals.split('|')[2]

    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, Ncols = drw.legend_values(legvals,'|')
    legconf = [locleg, legfontsize, Ncols]

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

    ifn = 0
    mintval = 1.e20
    maxtval = -1.e20

    for ifile in ncfiledims:

        filen = ifile.split('%')[0]
        dims = ifile.split('%')[1]

        print '    filen:', filen, 'section:', dims

        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
                timeunit = 'minutes since 1949-12-01 00:00:00'
                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, "' !!"
            print '    available variables:', objfile.variables.keys()
            quit(-1)

        foundvar = False
        for var in varname:
            if objfile.variables.has_key(var):
                foundvar = True
                vvobj0 = objfile.variables[var]

                # Slicing variables
                dictslice = {}
                for dnv in dims.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)

                slicev, ddv = ncvar.SliceVarDict(vvobj0, dictslice)
                vvobj = vvobj0[tuple(slicev)]

                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:
            timeunit = tunits0
            reftvals = timevals0

        dimt = len(vdvals[:])

        if period == '-1':
            if pointfreq0[0:7] == 'runmean':
                Nstps = int(pointfreq0.split(',')[1])
                print '  Running mean of ', Nstps, 'time steps !!'
                varvalues.append(gen.running_mean(vvobj[:], Nstps, 'vals'))
            else:
                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)

            if pointfreq0[0:7] == 'runmean':
                Nstps = int(pointfreq0.split(',')[1])
                print '  Running mean of ', Nstps, 'time steps !!'
                varvalues.append(gen.runnig_mean(vvobj[ibeg:iend], Nstps, 'vals'))
            else:
                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(vvobj0.units)
        else:
            if varunits != drw.units_lunits(vvobj0.units):
                print errormsg
                print '  ' + fname + ': wrong units:', vvobj0.units, " of " +        \
                  "variable '" + var +  "' with respect first variable '", varunits, \
                  "' !!"
                quit(-1)

        objfile.close()

        ifn = ifn + 1

# Times
    ranget = [mintval, maxtval]

    dtvals = (maxtval - mintval)/dimt
#    dti = mintval-dtvals/2. 
#    dte = maxtval+dtvals/2. 
    dti = mintval
    dte = maxtval
    tvals = np.arange(dti, dte+dtvals, 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' or pointfreq0[0:7] == 'runmean':
        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, legconf, ranget,        \
      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],[txtbckgcol]: points with the names and size, color of text and background 
            color ('None' for without)
        [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]:[legvals]:[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('!',' ')
    legvalues = 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

    # legend
    locleg, sizeleg = drw.legend_values(legvalues, '|')

    drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, xaxis,    \
      yaxis, mapV, kindfigure, pointcolor, ptlabels, locleg, sizeleg, 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]:
          [figclose]
        [lonvarname]: name of the variable longitude
        [latvarname]: name of the variable latitude
        [gkind]: kind of graphical output (pdf, png, ps)
        [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
        [figclose]: whether figures should be closed or not
    """
    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]:[figclose]'
 
    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]
    legvals = values.split(':')[8]
    figureK = values.split(':')[9]
    figclose = gen.Str_Bool(values.split(':')[10])

    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(',')

    locleg, sizeleg = drw.legend_values(legvals,'|')

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

    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= [dimvalues]:[sminv],[smaxv]:[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[leglabs]:[legvals]:
          [gkind]:[colorlines]:[typelines]:[widthlines]:[pointtype]:[pointfreq]:[figclose]
        [dimvalues]= ',' separated list of [dimname]|[slice] no given dimension takes all values
          [dimname]: name of dimension
          [slice]: value to take for the given dimension
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * [beg]@[end]@[freq] slice from [beg] to [end] every [freq]
            * -9: last value of the dimension
       [sminv],[smaxv]: minimum and maximum value for the lines or one value for each extreme:
          '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)
        [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 (C-like)
        [title]: title of the graphic ('|' for spaces)
        [leglabs]: ',' separated list of labels for the lines
        [legvals]=[locleg]|[fontsize]: legend values
          [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
        [typelines]: ',' list of types for the lines, 'None' for automatic, single
          value all the same
        [widthlines]: ',' list of width 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
        [pointsizee]: ',' list of size of points for the lines, 'None' for automatic, single
          value all the same
        [pointfreq]: frequency of point plotting, 'all' for all time steps
        [figclose]: whether figure should be closed or not
      variables= [varname],[timename] names of variable and variable with times
    """

    fname = 'draw_timeSeries'

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

    expectargs= '[dimvalues]:[sminv],[smaxv]:[gvarname]:[timetit]:[tkind]:' +        \
      '[timefmt]:[title]:[leglabs]:[legvals]:[gkind]:[colorlines]:[typelines]:' +    \
      '[widthlines]:[pointtype]:[pointsize]:[pointfreq]:[figclose]'
 
    drw.check_arguments(fname,values,expectargs,':')

    dimvalues = values.split(':')[0]
    sminmaxv = values.split(':')[1]
    gvarname = gen.latex_text(values.split(':')[2])
    timetit = values.split(':')[3].replace('|',' ')
    tkind = values.split(':')[4]
    timefmt = values.split(':')[5]
    title = gen.latex_text(values.split(':')[6].replace('|',' '))
    leglabs = gen.str_list(values.split(':')[7], ',')
    legvals = values.split(':')[8]
    gkind = values.split(':')[9]
    colorlines = values.split(':')[10]
    typelines = values.split(':')[11]
    widthlines = values.split(':')[12]
    pointtype = values.split(':')[13]
    pointsize = values.split(':')[14]
    pointfreq0 = values.split(':')[15]
    figclose = gen.Str_Bool(values.split(':')[16])
    
    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]

    # Slicing variables
    dictslice = {}
    for dnv in dimvalues.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)

    slicet, ddt = ncvar.SliceVarDict(timeobj, dictslice)
    timevals = timeobj[tuple(slicet)]
    dimt = len(timevals)

    varattrs = varobj.ncattrs()
    if not gen.searchInlist(varattrs,'units'):
        print '  ' + fname + ": variable '" + variable + "' does not have units !!"
        print "    using name in figure to search for them in 'variable_values.dat'"
        varvals = drw.variables_values(gvarname)
        gunits = varvals[5]
        print "   getting units of '" + gvarname + "' as: '" + gunits + "'"
    else:
        gunits = varobj.getncattr('units')
    tunits = timeobj.getncattr('units')

    slicev, ddv = ncvar.SliceVarDict(varobj, dictslice)
    varvalues = varobj[tuple(slicev)]
    matvarvals = np.array(varvalues)
    if len(matvarvals.shape) != 1:
        print errormsg
        print '  ' + fname + ': wrong rank of values to plot!!'
        print '    resultant values to plot have a shape:', matvarvals.shape,        \
          'it mast be of rank 1D'
        print '    provided slice:', slicev
        quit(-1)

    varvals = np.zeros((2,dimt), dtype=np.float)
    varvals[0,:], valpot, newgunits, Spot = drw.pot_values(varvalues.flatten(), gunits)
    varvals[1,:] = timeobj[:]

    # Min/max values in plot
    line_nx = []
    if sminmaxv.split(',')[0][0:1] != 'S':
        line_nx.append(np.float(sminmaxv.split(',')[0]))
    else:
        line_nx.append(sminmaxv.split(',')[0])

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

    tseriesvals = []
    tseriesvals.append(varvals)

    collines = gen.str_list(colorlines, ',')
    typlines = gen.str_list(typelines, ',')
    wdthlines = gen.str_list(widthlines, ',')
    pttype = gen.str_list(pointtype, ',')
    ptsize = gen.str_list(pointsize, ',')

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

    locleg, sizleg = drw.legend_values(legvals, '|')

    drw.plot_TimeSeries(tseriesvals, line_nx, Spot + gunits, tunits, 'TimeSeries',   \
      gvarname,timetit, tkind, timefmt, title, leglabs, locleg, sizleg, gkind,       \
      collines, typlines, pttype, wdthlines, ptsize, pointfreq, figclose)

    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
      Trajectories are readed from ASCII files with a pair of i,j grid points for each position of the trajectory
        i,j couples of trajectories for all files are referred to a netcdf file with a respective projection
      A complemtary file for observations is also added separately
      trjfilens= [filen]@[Tint]@[map]@[Ttrj] ',' separated list of ASCII 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) with values as:
          [t-step] [x] [y]
        [Tint]: interval of time-steps to get from the file as [Tbeg]@[Tend] or -1 for all the interval
        [map]: [file]#[lonname]#[latname] common projection data
          [file]; netcdf file with the [lon],[lat] projection for the trajectory
          [lonname],[latname]; names of the longitudes and latitudes variables in [file]
        [Ttrj]|[val1]|[val2]|[...|[valN]]: kind of associated time values to the trajectory
          't-step'|[dtime]|[idate]: each line corresponds to a consecutive time-step with the same deltatime
             [dtime]: length of time-step in seconds
             [idate]: date of the first time-step (in [YYYY][MM][DD][HH][MI][SS] format)
          'CF-step'|[units]|[refdate]: each line corresponds to a consecutive CF time-step
             [units]: any of standard temporal CF units: weeks, days, hours, minutes, seconds, ...
             [refdate]: reference date of the CF time-units
          'fulldate': each line provides the correspondance date (in [YYYY][MM][DD][HH][MI][SS] format)
      values= [plotkind]|[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]|[legvals]|[figclose]
        [plotkind],[val1],[...,[valN]]: kind of plot to generate
          'spaghetti'@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@[trjpsiz]: line-marker for each trajectory
            [trjltype]: ',' list of type of lines for each trajectory (single value same for all, 'None' for auto)
            [trjlcol]: ',' list of color of lines for each trajectory (single value same for all, 'None' for auto)
            [trjlwdth]: ',' list of width of lines for each trajectory (single value same for all, 'None' for auto)
            [trjptyp]: ',' list of type of points for each trajectory (single value same for all, 'None' for auto)
            [trjpsiz]: ',' list of size of points for each trajectory (single value same for all, 'None' for auto)
          'spaghetti_date'@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@[trjpsiz]@[datefmt]@[datefontsize]
              @[datefreq]@[xoffset]@[yoffset]: line-marker 
              for each trajectory with a given date format at each point
            [trjltype]: ',' list of type of lines for each trajectory (single value same for all, 'None' for auto)
            [trjlcol]: ',' list of color of lines for each trajectory (single value same for all, 'None' for auto)
            [trjlwdth]: ',' list of width of lines for each trajectory (single value same for all, 'None' for auto)
            [trjptyp]: ',' list of type of points for each trajectory (single value same for all, 'None' for auto)
            [trjpsiz]: ',' list of size of points for each trajectory (single value same for all, 'None' for auto)
            [datefmt]: format of the date to show (C-like mixed with LaTeX commands)
            [datefontsize]: font-size of the time-labels
            [datefreq]: frequency of time-labels
            [xoffset]: x-axis offset in pixels of the time-lables respect trajectory
            [yoffset]: y-axis offset in pixels of the time-lables respect trajectory
        [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 output of the graphic (png, pdf, ...)
        [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
        [legvals]=[locleg]@[fontsize]: legend values
          [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)
        [figclose]: whether figure should be closed or not
      observations= [obsfile],[obsname],[Tint],[null],[obstrjvals] ('None' for no observational/reference trajectory)
        [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
        [obstrjvals] = [Ttrj]@[obsltype]@[obslcol]@[obslwdth]@[obsptyp]@[obspsiz] values for the observational/reference
          trajectory in the plot
             [Ttrj]|[val1]|[val2]|[...|[valN]]: kind of associated time values to the trajectory
              't-step'|[dtime]|[idate]: each line corresponds to a consecutive time-step with the same deltatime
                 [dtime]: length of time-step in seconds
                 [idate]: date of the first time-step (in [YYYY][MM][DD][HH][MI][SS] format)
              'CF-step'|[units]|[refdate]: each line corresponds to a consecutive CF time-step
                 [units]: any of standard temporal CF units: weeks, days, hours, minutes, seconds, ...
                 [refdate]: reference date of the CF time-units
              'fulldate': each line provides the correspondance date (in [YYYY][MM][DD][HH][MI][SS] format)
            [obsltype]: type of line for the observations/reference trajectory (single 'auto' for '-', 'k', 2, 'x', 2)
            [obslcol]: color of line for the observations/reference trajectory
            [obslwdth]: width of line for the observations/reference trajectory
            [obsptyp]: type of point for the observations/reference trajectory
            [obspsiz]: size of point for the observations/reference trajectory
    """
    import datetime as dt
    fname = 'draw_trajectories'

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

    expectargs = '[plotkind]|[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]|' + \
      '[legvals]|[figclose]'
    drw.check_arguments(fname,values,expectargs,'|')

    expectargs = '[obsfile],[obsname],[Tint],[null],[obstrjvals]'
    drw.check_arguments('obstraj',observations,expectargs,',')

    trjfiles = trjfilens.split(',')
    plotkind = values.split('|')[0]
    leglabels = values.split('|')[1]
    lonlatlims = values.split('|')[2]
    title = gen.latex_text(values.split('|')[3].replace('!',' '))
    graphk = values.split('|')[4]
    mapkind = values.split('|')[5]
    legvals = values.split('|')[6]
    figclose = gen.Str_Bool(values.split('|')[7])

    Nfiles = len(trjfiles)

    # plot kind
    plotkindv = plotkind.split('@')
    if plotkindv[0] == 'spaghetti':
        expectargs = 'spaghetti@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@[trjpsiz]'
        drw.check_arguments(plotkindv[0],plotkind,expectargs,'@')

        trjltype = gen.str_list(plotkindv[1], ',')
        trjlcol = gen.str_list(plotkindv[2], ',')
        trjlwdth = gen.str_list(plotkindv[3], ',')
        trjptyp = gen.str_list(plotkindv[4], ',')
        trjpsiz = gen.str_list(plotkindv[5], ',')
    elif plotkindv[0] == 'spaghetti_date':
        expectargs = 'spaghetti_date@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@' +   \
          '[trjpsiz]@[datefmt]@[datefontsize]@[datefreq]@[xoffset]@[yoffset]'
        drw.check_arguments(plotkindv[0],plotkind,expectargs,'@')

        trjltype = gen.str_list(plotkindv[1], ',')
        trjlcol = gen.str_list(plotkindv[2], ',')
        trjlwdth = gen.str_list(plotkindv[3], ',')
        trjptyp = gen.str_list(plotkindv[4], ',')
        trjpsiz = gen.str_list(plotkindv[5], ',')
        datefmt = gen.str_list(plotkindv[6], ',')
        datefsize = gen.str_list(plotkindv[7], ',')
        datefreq = int(plotkindv[8])
        xoffset = int(plotkindv[9])
        yoffset = int(plotkindv[10])
    else:
        print errormsg
        print '  ' + fname + ": kind of plot '" + plotkindv[0] + "' not ready !!"
        print '    accepted ones:', ['spaghetti', 'spaghetti_date']
        quit(-1)

# Getting trajectotries 
##
    lontrjvalues = []
    lattrjvalues = []
    timetrjvalues = []

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

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

        print '    ', ifn+1, "trajectory'" + filen + "'"

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

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

        #Time-values
        Tkindv = Tkind.split('|')
        datesTtrj = []
        if Tkindv[0] == 'CF-step':
            tunits = Tkindv[1]
            refdate = Tkindv[2]

            if tunits == 'weeks': dtime = tunis*7.*24.*3600.
            elif tunits == 'days': dtime = tunis*24.*3600.
            elif tunits == 'hours': dtime = tunis*3600.
            elif tunits == 'minutes': dtime = tunis*60.
            elif tunits == 'seconds': dtime = tunis
            else:
                print erromsg
                print ' '+ fname + ": time-units of CF time-trajectory '" + tunits + \
                  "' not ready !!"
                print '    available ones:', ['weeks', 'days', 'hours', 'minutes',   \
                  'seconds']
                quit(-1)
            refdateT = gen.DateTimeStr_date(refdate)
            for it in trjtimev:
                datesTtrj.append(refdateT + dt.timedelta(seconds=it))
        elif Tkindv[0] == 'fulldate':
            for it in trjtimev:
                datesTtrj.append(gen.DateTimeStr_date(it))            
        elif Tkindv[0] == 't-step':
            dtime = np.float(Tkindv[1])
            idate = Tkindv[2]
            print '  ' + fname + ': idate:', idate
            refdateT = gen.DateTimeStr_date(idate)
            for it in range(len(trjtimev)):
                datesTtrj.append(refdateT + dt.timedelta(seconds=dtime*it))
        else:
            print errormsg
            print '  ' +fname+ ": associated time kind of trajectory '" + Tkind[0] + \
              "' not ready!!"
            print '    accepted ones:', ['t-step', 'CF-step']

        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]])
            timetrjvalues.append(datesTtrj[Tint:Tend+1])
        else:
            lontrjvalues.append(lonvals[trjyv[:], trjxv[:]])
            lattrjvalues.append(latvals[trjyv[:], trjxv[:]])
            timetrjvalues.append(datesTtrj[:])

# 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])
        obstrajvals = observations.split(',')[4]

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

        print '  ' + fname + ": observational trajectory in file: '" + obsfile + "'"

        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(None)
                    obstrjxv.append(None)
                    obstrjyv.append(None)

        objfile.close()
        #Time-values
        Tkind = obstrajvals.split('@')[0]

        Tkindv = Tkind.split('|')
        datesTtrj = []
        if Tkindv[0] == 'CF-step':
            tunits = Tkindv[1]
            refdate = Tkindv[2]

            if tunits == 'weeks': dtime = tunis*7.*24.*3600.
            elif tunits == 'days': dtime = tunis*24.*3600.
            elif tunits == 'hours': dtime = tunis*3600.
            elif tunits == 'minutes': dtime = tunis*60.
            elif tunits == 'seconds': dtime = tunis
            else:
                print erromsg
                print ' '+ fname + ": time-units of CF time-trajectory '" + tunits + \
                  "' not ready !!"
                print '    available ones:', ['weeks', 'days', 'hours', 'minutes',   \
                  'seconds']
                quit(-1)
            refdateT = gen.DateTimeStr_date(refdate)
            for it in obstrjtimev:
                datesTtrj.append(refdateT + dt.timedelta(seconds=it))
        elif Tkindv[0] == 'fulldate':
            for it in obstrjtimev:
                datesTtrj.append(gen.DateTimeStr_date(it))     
        elif Tkindv[0] == 't-step':
            dtime = np.float(Tkindv[1])
            idate = Tkindv[2]
            refdateT = gen.DateTimeStr_date(idate)
            for it in range(len(obstrjtimev)):
                datesTtrj.append(refdateT + dt.timedelta(seconds=dtime*it))
        else:
            print errormsg
            print '  ' +fname+ ": associated time kind of trajectory '" + Tkindv[0]+ \
              "' not ready!!"
            print '    accepted ones:', ['t-step', 'CF-step']

        # Parameters observational/reference trajectory 
        obslv = obstrajvals.split('@')[1:6]
        if obslv[0] == 'auto':
            obslt = '-'
            obslc = 'k'
            obslw = '2'
            obspt = 'x'
            obsps = '2'
        else:
            obslt = obslv[0]
            obslc = obslv[1]
            obslw = np.float(obslv[2])
            obspt = obslv[3]
            obsps = np.float(obslv[4])

        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])
            timetrjvalues.append(datesTtrj[Tint:Tend+1])
        else:
            lontrjvalues.append(obstrjxv[:])
            lattrjvalues.append(obstrjyv[:])
            timetrjvalues.append(datesTtrj[:])

    locleg, sizleg = drw.legend_values(legvals, '@')

    drw.plot_Trajectories(lontrjvalues, lattrjvalues, timetrjvalues, plotkindv,      \
      leglabels.split(','), trjltype, trjlcol, trjlwdth, trjptyp, trjpsiz, lonobj,   \
      latobj, [obslt, obslc, obslw, obspt, obsps], lonlatlimsv, title, graphk,       \
      mapkindv, obsname, locleg, sizleg, figclose)

    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]:[sminv],[smaxv]:[Tint]:[labels]:[legvals]:[gvarname]:[timetit]:[tkind]:
          [timefmt]:[title]:[gkind]:[colorlines]:[typelines]:[widthlines]:[pointtype]:[pointsizee]:[pointfreq]:[figclose]
        [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
        [sminv],[smaxv]: minimum and maximum value for the lines or one value for each extreme:
          '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)
        [Tint]: [Tbeg]@[Tend] or None, interval of time to plot or -1 for all the times
        [leglabels]: ',' 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
        [colorlines]: ',' list of colors for the lines, 'None' for automatic, single
          value all the same
        [typelines]: ',' list of types for the lines, 'None' for automatic, single
          value all the same
        [widthlines]: ',' list of width 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
        [pointsizee]: ',' list of size of points for the lines, 'None' for automatic, single
          value all the same
        [pointfreq]: frequency of point plotting, 'all' for all time steps
        [figclose]: whether figure should be close or not
      variable= variable to use
    """
    fname = 'draw_vals_trajectories'

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

    expectargs = '[statisticskind]:[sminv],[smaxv]:[Tint]:[leglabels]:[legvals]:' +  \
      '[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[gkind]:[colorlines]:' +       \
      '[typelines]:[widthlines]:[pointtype]:[pointsizee]:[pointfreq]:[figclose]'
    drw.check_arguments(fname,values,expectargs,':')

    sims = ncfile.split(',')

    statisticskind = values.split(':')[0]
    sminmaxv = values.split(':')[1]
    Tint = values.split(':')[2]
    leglabels = values.split(':')[3].split(',')
    legvals = values.split(':')[4]
    gvarname = values.split(':')[5]
    timetit = values.split(':')[6].replace('|',' ')
    tkind = values.split(':')[7]
    timefmt = values.split(':')[8]
    title = values.split(':')[9].replace('|',' ')
    gkind = values.split(':')[10]
    colorlines = values.split(':')[11]
    typelines = values.split(':')[12]
    widthlines = values.split(':')[13]
    pointtype = values.split(':')[14]
    pointsize = values.split(':')[15]
    pointfreq0 = values.split(':')[16]
    figclose = gen.Str_Bool(values.split(':')[17])

    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()

    # Min/max values in plot
    line_nx = []
    if sminmaxv.split(',')[0][0:1] != 'S':
        line_nx.append(np.float(sminmaxv.split(',')[0]))
    else:
        line_nx.append(sminmaxv.split(',')[0])

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

    locleg, fsizeleg = drw.legend_values(legvals, '|')

    collines = gen.str_list(colorlines, ',')
    typlines = gen.str_list(typelines, ',')
    wdthlines = gen.str_list(widthlines, ',')
    pttype = gen.str_list(pointtype, ',')
    ptsize = gen.str_list(pointsize, ',')

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

    figname = 'val_trajectories_' + statisticskind

    drw.plot_TimeSeries(vartimetrjv, line_nx, gunits, tunits, figname, gvarname,     \
      timetit, tkind, timefmt, title, leglabels, locleg, fsizeleg, gkind,            \
      collines, typlines, pttype, wdthlines, ptsize, pointfreq, figclose)

    return

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 by their Z values according to a colorbar
      ncfile= netCDF file to use
      values= [fvname]:[XYvar]:[dimxyfmt]:[pointype]:[pointsize]:[graphlimits]:[nxtype]:
          [legend]:[figuretitle]:[cbarv]:[mapvalue]:[kindfig]:[figclose]
        [fvname]: name of the variable in the graph
        [XYvar]: [x],[y] variable names
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each axis ('auto', for 
           'pretty' at both axes)
          [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)
        [ptype]: type of the point
        [ptsize]: size of the point
        [graphlimits]: minX,minY,maxX,maxY 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
        [legend]: kind of legend
          'None': no legend
          'ptlabel',[varlabels],[fontsize],[xoffset],[yoffset]: label at the side of the point
             [varlabels]: variable in file with the labels for the points
             [fontsize]: font-size of the label
             [xoffset]: x-offset of the label respect the point in pixels
             [yoffset]: y-offset of the label respect the point in pixels
          'legend',[varlabels],[location],[fontsize]: standard legend
             [varlabels]: variable in file with the labels for the points
             [location]: location of the legend ('0', for automatic)
               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]: size of the font for the legend ('auto' for 12)
        [figtitle]: title of the figure ('!' for spaces)
        [colorbarv]: list with the parameters of the color bar [colorbar, cbarfmt, cbaror]
          colorbar= name of the color bar to use
          cbarfmt= format of the numbers in the colorbar ('auto' for %6g)
          cbaror= orientation of the colorbar ('auto' for vertical)
        [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
        [closefig]: boolean value whether figure should be close (finish) or not
      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]:[dimxyfmt]:[pointype]:[pointsize]:[graphlmits]:'+ \
      '[nxtype]:[legend]:[figuretit]:[colorbarv]:[mapvalue]:[kindfig]:[closefig]'
 
    drw.check_arguments(fname,values,expectargs,':')

    fvname = values.split(':')[0]
    XYvar = values.split(':')[1]
    dimxyfmt = values.split(':')[2]
    pointype = values.split(':')[3]
    pointsize = np.float(values.split(':')[4])
    graphlimits = values.split(':')[5]
    nxtype = values.split(':')[6]
    legend = values.split(':')[7]
    figuretitle = values.split(':')[8].replace('!',' ')
    colorbarv = values.split(':')[9]
    mapvalue = values.split(':')[10]
    kindfig = values.split(':')[11]
    closefig = gen.Str_Bool(values.split(':')[12])

    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
    xvarn = XYvar.split(',')[0]
    yvarn = XYvar.split(',')[1]

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

    oxvar = onc.variables[xvarn]
    oyvar = onc.variables[yvarn]
    ovarvar = onc.variables[variable]

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

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

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

    varattrs = oxvar.ncattrs()
    if drw.searchInlist(varattrs, 'units'):
        xvunits = oxvar.getncattr('units')
    else:
        xvunits = drw.variables_values(xvarn)[5]
    varattrs = oyvar.ncattrs()
    if drw.searchInlist(varattrs, 'units'):
        yvunits = oxvar.getncattr('units')
    else:
        yvunits = drw.variables_values(yvarn)[5]

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

    # legend
    if legend.find(',') == -1:
        legvals = ['None']
    else:
        legvals = legend.split(',')
        if not onc.variables.has_key(legvals[1]):
            print errormsg
            print '  ' + fname + ": file '" + ncfile + "' does not have labels " +   \
              "variable '" + legvals[1] + "' !!"
            quit(-1)
        ovarleg = onc.variables[legvals[1]]
        Lchar = ovarleg.shape[1]
        labs = ncvar.get_str_nc(ovarleg, Lchar)

    if legvals[0] == 'None':
        legendv = None
    elif legvals[0] == 'ptlabel':
        legendv = [legvals[0]]
        legendv.append(legvals[2])
        legendv.append(np.float(legvals[3]))
        legendv.append(np.float(legvals[4]))
        legendv = legendv + labs
    elif legvals[0] == 'legend':
        legendv = [legvals[0]]
        legendv.append(int(legvals[2]))
        legendv.append(int(legvals[3]))
        legendv = legendv + labs
    else:
        print errormsg
        print '  ' + fname + ": kind of legend '" + legvals[0] + "' not ready !!"
        print '    available ones:', ['None', 'ptlabel', 'legend']
        quit(-1)

    # colorbar values
    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarv,',')

    # 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[1],          \
          graphlts[3])
    else:
        graphlts = None

    drw.plot_ptZvals(fvname, fvunits, xvarn, yvarn, xvunits, yvunits, pointvalues,   \
      xaxis, yaxis, pointype, pointsize, graphlts, nxtype, figuretitle, [colbarn,    \
      fmtcolbar, colbaror], legendv, mapvalue, kindfig, closefig)

    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]:[dimxyfmt]:[vecvals]:[windlabs]:[mapvalues]:[gtit]:[kindfig]:[figuren]:
          [closefig]
        '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
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each axis ('auto', for 
           'pretty' at both axes)
          [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)
        [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') and lengths according to wind's module
            'wind'@[colorbar]@[sminv]|[smaxv]: color of the vectors according to wind speed sqrt(u^2+v^2) 
              and given [colorbar] all vectors the same length
              [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) 
            '3rdvar'@[colorbar]@[varn]@[units]@[sminv]|[smaxv]: color of the vectors according to a 3rd variable 
              (to be added at -v) and given [colorbar] all vectors the same length
              [colorbar]: name of the colornbar to use
              [varn]: name of the variable to pick up values
              [units]: units of the variable
              [sminv]|[smaxv]: 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)
          [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
        closefig= whether the figure should be closed
      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]:[dimxyfmt]:[vecvals]:' +  \
      '[windlabs]:[mapvalues]:[gtit]:[kindfig]:[figuren]:[closefig]'
 
    drw.check_arguments(fname,values,expectargs,':')

    dimvals = values.split(':')[0]
    dimxyfmt = values.split(':')[1]
    vecvals = values.split(':')[2]
    windlabels = values.split(':')[3]
    mapvalues = values.split(':')[4]
    gtit = values.split(':')[5].replace('!',' ')
    kindfig = values.split(':')[6]
    figuren = values.split(':')[7]
    closefig = gen.Str_Bool(values.split(':')[8])

    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]])
            xaxisvn = dims[dn][1]
        elif dn == 'Y':
            varNs.append(dims[dn][1])
            dimy = len(of.dimensions[dims[dn][0]])
            yaxisvn = dims[dn][1]

    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)])
            xaxisu = ncvar.get_varunits(ovarN)
        elif varN == dims['Y'][1]:
            latvals0 = np.squeeze(ovarN[tuple(varslice)])
            yaxisu = ncvar.get_varunits(ovarN)
        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
        shading_nx = None
    elif coln == 'wind':
        colorv = np.sqrt(uwvals**2 + vwvals**2)
        # Min/Max colorbar
        shadminmax = colorvals.split('@')[2]
        shading_nx = shadminmax.split('|')
    elif coln == '3rdvar':
        if len(varns.split(',')) != 3:
            print errormsg
            print '  ' + fname + ": color of vectors should be according to '" +     \
              coln + "' but a third varibale is not provided !!"
            print '    values provided:', varns.split(',')
            quit(-1)
        ocolvec = of.variables[varns.split(',')[2]]
        colorv = ocolvec[:]
        stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
        colorvals = colorvals + '@' + stdvn + '@' + unitsvn
        # Min/Max colorbar
        shadminmax = colorvals.split('@')[4]
        shading_nx = shadminmax.split('|')
    else:
        print errormsg
        print '  ' + fname + ": color type '" + coln + "' not ready !!"
        quit(-1)

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

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

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

    drw.plot_vector(lonvals, latvals, uwvals, vwvals, xaxisvn, yaxisvn, xaxisu,      \
      yaxisu, freqv, xaxis, yaxis, colorvals, colorv, lengthv, shading_nx, windname, \
      windunits, mapvalues, gtit, kindfig, figuren)

    of.close()

    return

def draw_basins(ncfile, values):
    """ Function to plot river basins with their discharge vector and basins id (from 'routing.nc' - ORCHIDEE routing output)
      values= [lonlatbox]:[mapres]:[colorbarvals]:[xtrmbasin]:[mapdraw]:[veclength]:[plotcountry]:[basinidn]:
          [gtit]:[kindfig]:[figuren]
        [lonlatbox]= [lonSW],[lonNE],[latSW],[latNE] coordinates of the lon/lat box
        [mapres]= resolution of the mapping information to lon/lat
          * 'c': cure
          * 'l': low
          * 'i': intermediate
          * 'h': high
          * 'f': full
        [colorbarvals] = [cbarname],[fmtcolorbar],[orientation]
          [cbarname]: colorbar name for the colors
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto', 'horizontal')
        [xtrmbasin]= [minbasin],[maxbasin] minimum and maximum basin numbers to define color range
        [mapdraw]= whether to draw the map (and project the data) or not ('True/False')
        [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
        [closefig]= whether figure should be closed or not
      ncfile= file to use
    """
    fname = 'draw_basins'

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

    expectargs = '[lonlatbox]:[mapres]:[cbarname]:[xtrmbasin]:[mapdraw]:' +          \
      '[plotcountry]:[basinidn]:[gtit]:[kindfig]:[figuren]:[closefig]'
 
    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]
    colorbarvals = 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])
    plotcountry = gen.Str_Bool(values.split(':')[5])
    plotbasinid = gen.Str_Bool(values.split(':')[6])
    gtit = values.split(':')[7].replace('|',' ')
    kindfig = values.split(':')[8]
    figuren = values.split(':')[9]
    closefig = gen.Str_Bool(values.split(':')[10])

    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)
    
    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')

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

    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 file ('river_desc.nc')
      values= [dimname]|[vardimname]|[value]:[basinvals]:[upstreamvals]:[mapvalues]:
        [gtit]:[kindfig]:[legvals]:[figuren]:[closefig]
        'X/Y'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
          [dimname]= name of the dimension in the file for 'X' and 'Y' axis
          [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] colors for the border line of each basin
          [basincolor]: ',' list of colors of the line to use to mark the basins contours (single value also possible)
        [upstreamvals]= [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 (png, ps, pdf)
        [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
        [closefig]= whether figure should be closed or not
      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]:[closefig]'
 
    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].replace('|',' ')
    kindfig = values.split(':')[5]
    legloc = int(values.split(':')[6])
    figuren = values.split(':')[7]
    closefig = gen.Str_Bool(values.split(':')[8])

    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, closefig)

    of.close()

def draw_vertical_levels(ncfile, values, varn):
    """ plotting distribution of vertical levels
    draw_vertical_levels(ncfile, values, varn)
      ncfile= file to use
      values= [zlogs]:[plogs]:[title]:[graphic_kind]:[legvals]:[closefig]
        [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)
        [closefig]= whether figures should be closed or not
      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]:[closefig]'
 
    drw.check_arguments(fname,values,expectargs,':')

    zlogv = gen.Str_Bool(values.split(':')[0].split(',')[0])
    dzlogv = gen.Str_Bool(values.split(':')[0].split(',')[1])
    plogv = gen.Str_Bool(values.split(':')[1].split(',')[0])
    dplogv = gen.Str_Bool(values.split(':')[1].split(',')[1])
    title = values.split(':')[2].replace('!',' ')
    kindfig = values.split(':')[3]
    legvals = values.split(':')[4]
    closefig = gen.Str_Bool(values.split(':')[5])

    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[:]


    # Legend values
    legloc, legsize = drw.legend_values(legvals,'|')

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

    objf.close()

    return

def draw_subbasin(ncfile, values):
    """ Function to plot subbasin from a given point of its discharge from 'routing.nc' ORCDHIEE file
        Each river is composed of different subbasins. Grouped up-flow. This function use a different color
        for the first level of suubbasins, and a different degree of color for the sub-subbasins of the first level
        It takes output from `subbasin' function from 'nc_var.py'
      ncfile= file to use produced with nc_var.py#subbasin function
      values= [subasiname]:[rangecolors]:[mapv]:[basinlinewidth]:[drawsubid]:[gtit]:[figkind]:[legvals]:[figurename]:
          [drawrivers]:[closefig]
        [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
        [drawrivers]= whether rivers from pythons' data-based have to be added or not
        [closefig]= whether figures should be closed or not
    """
    fname = 'draw_subbasin'

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

    expectargs = '[subasiname]:[rangecolors]:[mapv]:[basinlinewidth]:[drawsubid]:' + \
      '[gtit]:[figkind]:[legloc]:[figurename]:[drawrivers]:[closefig]'
 
    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]
    drawrivers = gen.Str_Bool(values.split(':')[9])
    closefig = gen.Str_Bool(values.split(':')[10])

    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, \
      drawrivers, closefig)

    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 from
          'variable_values.dat'; single 'Extrs' from values extremes)
        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic from
          'variable_values.dat'; single '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)

    valsA = gen.variables_values(invarns[0])
    if gen.searchInlist(objvA.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvA.getncattr('units')))
    else:
        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)

    valsB = gen.variables_values(invarns[1])
    if gen.searchInlist(objvB.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvB.getncattr('units')))
    else:
        varunits.append(drw.units_lunits(valsB[5]))
    if varangeB0 == 'None':
        varangeB = [valsB[2], valsB[3]]
    elif varangeB0 == 'Extrs':
        varangeB = [np.min(varvalsB), np.max(varvalsB)]
    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 from 'variables_values'; 'Extrs' from values extremes)
        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic from 'variables_values'; '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', for 2.,2.)
        [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]:[legvals]:[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)

    valsA = gen.variables_values(invarns[0])
    if gen.searchInlist(objvA.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvA.getncattr('units')))
    else:
        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')

    valsB = gen.variables_values(invarns[1])
    if gen.searchInlist(objvB.ncattrs(), 'units'):
        varunits.append(drw.units_lunits(objvB.getncattr('units')))
    else:
        varunits.append(drw.units_lunits(valsB[5]))
    if varangeB0 == 'None':
        varangeB = [valsB[2], valsB[3]]
    elif varangeB0 == 'Extrs':
        varangeB = [np.min(varvalsB), np.max(varvalsB)]
    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)

def draw_WindRose(ncfile, values, varnames):
    """ Function to plot a wind rose (from where the dinw blows)
      values=[dimvariables][kindRose]:[imgtit]:[imgkind]:[kindlabelsangle]:[freqfileout]:[fname]:[close]
        [dimvariables]: ';' list of [dimn]|[dvalue] dimension and slice along dimension to retrieve the winds
          [dimn]: name of the dimension
          [dvalue]: value for the slice in the given dimension
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg],[end],[freq] slice from [beg] to [end] every [freq]
            * NOTE, no dim name all the dimension size
          No value takes all the range of the dimension
        [kindRose]: [kind];[value1];[...[valueN]] Kind of rose to plot and values of the kind
          'fill': filling the area since the center of the rose
          'anglespeedfreq': grid of frequencies of each angle and speed following a given discretization
            values: ;[Nang];[Nspeed];[maxspeed];[cbar];[maxfreq]
          'linepoint': consecutive (time, height, level, ...) line-point angle and speed values. Three different species
            'multicol': line-marker color changing according to a third variable [extravarn]
               values: [extravarn];[line];[marker];[colbar];[Nang]
            'multicoltime': line-marker color changing according to a temporal variable [extravarn]
               values: [extravarn];[line];[marker];[colbar];[Nang];[timekind];[timefmt];[timelabel]
            'singlecol': same color for the line-marker
               values: [line];[marker];[col];[Nang]
          'scatter': a marker for each wind at different values (time, height, level, ...). Three different species
            'multicol':marker color changing according to a third variable [extravarn]
               values: [extravarn];[marker];[colbar];[Nang]
            'multicoltime': marker color changing according to a temporal variable [extravarn]
               values: [extravarn];[line];[marker];[colbar];[Nang];[timekind];[timefmt];[timelabel]
            'singlecol': same color for all the markers
              values: [marker];[col];[Nang]
           meaning (where apply):
             [extravarn]: name of the extra variable 
             [line]: type of the line to draw
             [marker]: type of marker to use 
             [colbar]: name of the colorbar ('auto' for 'spectral_r')
             [Nang]: number of angles to divide the rose ('auto' for 8)
             [Nspeed]: number of speeds to divide the wind speed distribution ('auto' for 8)
             [maxspeed]: maximum wind speed used to compute the frequency of distributions ('auto' for 40.)
             [timekind]; time computation of ticks
               '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]; desired format of time labels (C-like)
             [timelabel]; label of time colorbar at the graph ('!' for spaces)
        imgtit: title of the image ('!' for spaces)
        imgkind: kind of output of the image
        kindlabelsangle: kind of labels for the angles of the wind Rose
          'cardianals': Following combinations of 'N', 'E', 'S', 'W' according to Nang
        freqfileout: whether the file with the frequencies of wind angle and speeds should be created (only working
          for 'anglespeedfreq')
        fname: name of the figure
        close: whether figure should be closed or not
      ncfile= netCDF file with the winds and extra variable (if required)
      varnames= [windun],[windvn] variables' name
    """
    fname = 'draw_WindRose'

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

    expectargs = '[dimvariables]:[kindRose]:[imgtit]:[imgkind]:[kindlabelsangle]:' + \
      '[freqfileout]:[fname]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    dimvariables = values.split(':')[0]
    KindRose = values.split(':')[1]
    imgtit = values.split(':')[2].replace('!',' ')
    imgkind = values.split(':')[3]
    kindlabelsangle = values.split(':')[4]
    freqfileout = gen.Str_Bool(values.split(':')[5])
    fname = values.split(':')[6]
    close = gen.Str_Bool(values.split(':')[7])
    
    uvarn = varnames.split(',')[0]
    vvarn = varnames.split(',')[1]

    windrosekinds = ['fill', 'linepoint', 'scatter']

    if KindRose.find(';') == -1:
        print errormsg
        print '  ' + fname + ": all types '" + KindRose + "' require extra values !!"
        print "    'anglespeedfreq';[Nang];[Nspeed];[maxspeed];[freqcbar];[maxfreq]"
        print "    'linepoint';'singlecol';[line];[marker];[col];[Nang]"
        print "    'linepoint';'multiecoltime';[extravar];[line];[marker];[colbar];"+\
          "[Nang];[timekind];[timefmt];[timelabel]"
        print "    'linepoint';'multiecol';[extravar];[line];[marker];[colbar];[Nang]"
        print "    'scatter';'multiecol';[extravar];[marker];[colbar]"
        print "    'scatter';'multiecoltime';[extravar];[marker];[colbar];[Nang];" + \
          "[timekind];[timefmt];[timelabel]"
        print "    'scatter';'singlecol';[marker];[col];[Nang]"
        print "  values provided: '" + KindRose + "'" 
        quit(-1)

    lpvals = KindRose.split(';')
    lkind = lpvals[1]

    extravarn = None

    if lpvals[0] == 'anglespeedfreq':
        if len(lpvals) != 6:
            print errormsg
            print '  ' + fname + ": 'anglespeedfreq' requires 6 values !!"
            print "    'anglespeedfreq';[Nang];[Nspeed];[maxspeed];[freqcbar];[maxfreq]"
            print '    provided:', lpvals
            quit(-1)     
    elif lpvals[0] == 'linepoint':
        if lkind == 'multicol':
            if len(lpvals) != 7:
                print errormsg
                print '  ' + fname + ": line-point kind '" + lkind + "' requires " + \
                  "6 values !!"
                print "    'multiecol';[extravarn];[line];[marker];[colbar];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
        elif lkind == 'multicoltime':
            if len(lpvals) != 10:
                print errormsg
                print '  '+fname + ": scatter kind '"+lkind+ "' requires 9 values !!"
                print "    'multicol';[extravarn];[line];[marker];[colbar];[Nang];"+ \
                  "[timekind];[timefmt];[timelabel]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
            timekind = lpvals[6]
            timefmt = lpvals[7]
        elif lkind == 'singlecol':
            if len(lpvals) != 6:
                print errormsg
                print '  '+fname+": line-point kind '"+lkind+ "' requires 5 values !!"
                print "    'singlecol';[line];[marker];[col];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
        else:
            print errormsg
            print '  ' + fname + ": line-point kind '" + lkind + "' not ready !!"
            print '    ready ones: multicol, multicoltime, singlecol '
            quit(-1)

    elif lpvals[0] == 'scatter':
        if lkind == 'multicol':
            if len(lpvals) != 6:
                print errormsg
                print '  '+fname+": scatter kind '"+lkind+"' requires 5 values !!"
                print "    'multicol';[extravarn];[marker];[colbar];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
        elif lkind == 'multicoltime':
            if len(lpvals) != 9:
                print errormsg
                print '  ' + fname + ": scatter kind '"+lkind+"' requires 8 values !!"
                print "    'multicol';[extravarn];[marker];[colbar];[Nang];" +       \
                  "[timekind];[timefmt];[timelabel]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
            timekind = lpvals[5]
            timefmt = lpvals[6]
        elif lkind == 'singlecol':
            if len(lpvals) != 5:
                print errormsg
                print '  '+fname + ": scatter kind '"+lkind+ "' requires 4 values !!"
                print "    'singlecol';[marker];[col];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
        else:
            print errormsg
            print '  ' + fname + ": scatter kind '" + lkind + "' not ready !!"
            print '    ready ones: multicol, multicoltime, singlecol '
            quit(-1)

    else:
        print gen.errormsg
        print '  ' +  fname + ": kind of WindRose '" + lpvals[0] + "' not ready !!"
        print '    available ones:', windrosekinds
        quit(-1)

    onc = NetCDFFile(ncfile,'r')
    oncvars = onc.variables.keys()

    if not gen.searchInlist(oncvars,uvarn):
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not have variable " +     \
          "u_wind '" + uvarn + "' !!"
        print '    available variables:', oncvars
        quit(-1)
    if not gen.searchInlist(oncvars,vvarn):
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not have variable " +     \
          "v_wind '" + vvarn + "' !!"
        print '    available variables:', oncvars
        quit(-1)

    if extravarn is not None:
        if not gen.searchInlist(oncvars,extravarn):
            print errormsg
            print '  ' + fname + ": file '" + ncfile + "' does not have extra " +    \
              "variable '" + extravarn + "' !!"
            print '    available variables:', oncvars
            quit(-1)

    # Getting the slice
    dictslice = {}
    for dnv in dimvariables.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)

    # Getting variables
    ou = onc.variables[uvarn]
    sliceu, du = ncvar.SliceVarDict(ou, dictslice)
    uv = ou[tuple(sliceu)]
    ov = onc.variables[vvarn]
    slicev, dv = ncvar.SliceVarDict(ov, dictslice)
    vv = ov[tuple(slicev)]
    wunit = ov.getncattr('units')
    if extravarn is not None:
        oe = onc.variables[extravarn]
        slicee, de = ncvar.SliceVarDict(oe, dictslice)
        extrav = oe[tuple(slicee)]
        dime = extrav.shape[0]
        extraunit = oe.getncattr('units')
    else:
        dime = uv.shape[0]
        extrav = None
        extraunit = None

    onc.close()

    # Wind Rose is with the winds from where they come from!
    ang = np.arctan2(-vv, -uv)
    speed = np.sqrt(uv*uv + vv*vv)

    # re-setting to [0, 2pi]
    ang = np.where(ang <= 0., 2.*np.pi+ang, ang)
    ang = np.where(np.mod(ang,2.*np.pi) == 0., 0., ang)

    drw.plot_WindRose(ang, speed, dime, lpvals, kindlabelsangle, wunit, imgtit,      \
      imgkind, fname, close, ncfile, outputfile=freqfileout, ev=extrav,              \
      eunit=extraunit)

    return

def draw_Taylor(ncfile, values, varname):
    """ Function to draw a Taylor diagram (Taylor 2001)
     From script:
     # Copyright: This document has been placed in the public domain.

     Taylor diagram (Taylor, 2001) test implementation.

     https://gist.github.com/ycopin/3342888

     __version__ = "Time-stamp: <2012-02-17 20:59:35 ycopin>"
     __author__ = "Yannick Copin <yannick.copin@laposte.net>"

      ncfile= ',' list of netCDF file and vartiable to use ([ncfile1]@[var1], [...[nmcvileN]@[varN]])
      values=[reflabel]:[mark]:[col]:[size]:[labels]:[[kindlabels]:[taylorkind]:[imgtit]:[figkind]:[outputfile]:[close]
        [reflabel]: label of the reference values in the graph
        [mark]: ',' list of kind of markers (single value for the same for all values)
        [col]: ',' list of color of markers (single value for the same for all values)
        [size]: ',' list of sizes of markers (single value for the same for all values)
        [labels]: ',' list of label of markers ('None' for without)
        [kindlabels]: kind of labels in plot
          'markfollow': on top of the mark of each pair of stddev, corr
          'legend',[loc],[charsize]: as a traditional legend and [loc] position [charsize] (size of labels, 'auto' for 12)
            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' 
        [taylorkind]: kind of Taylor plot
          'direct': direct values
          'norm': normalized to the stdandard deviation of reference
        [imgtit]: title of the image ('!' for spaces)
        [figkind]: kind of the figure
        [outputfile]: Whether is required to create a netcdf file with the information used in the Taylor diagram
        [close]: whether the figure has to be closed
      varname= [refncfile],[refvn] name of the reference faile and name of the variables within to use as reference
    """
    from scipy import stats as sts

    fname = 'draw_Taylor'

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

    expectargs = '[reflabel]:[mark]:[size]:[col]:[labels]:[kindlabels]:' +           \
      '[taylorkind]:[imgtit]:[figkind]:[outputfile]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    reflabel = values.split(':')[0]
    mark = values.split(':')[1]
    col = values.split(':')[2]
    size = values.split(':')[3]
    labels = values.split(':')[4]
    kindlabels = values.split(':')[5]
    taylorkind = values.split(':')[6]
    imgtit = values.split(':')[7].replace('!', ' ')
    figkind = values.split(':')[8]
    outputfile = gen.Str_Bool(values.split(':')[9])
    close = gen.Str_Bool(values.split(':')[10])

    # Reference parameters
    refncfile = varname.split(',')[0]
    refvn = varname.split(',')[1]

    # Marker types
    if mark.find(',') != -1:
        marktyp = mark.split(',')
    else:
        marktyp = [mark]

    # Marker sizes
    if size.find(',') != -1:
        marksize = size.split(',')
    else:
        marksize = [size]

    # Marker Colors
    if col.find(',') != -1:
        markcol = col.split(',')
    else:
        markcol = [col]

    # Marker Labels
    if labels != 'None':
        marklabs = [reflabel] + labels.split(',')
    else:
        marklabs = None

    # Getting reference values
    if not os.path.isfile(refncfile):
        print errormsg
        print '  ' + fname + ": reference file '" + refncfile + "' does not exist !!"
        quit(-1)

    # List of used files
    usedfilens = []
    # List of used variables
    usedvarns = []

    usedfilens.append(refncfile)
    usedvarns.append(refvn)

    oref = NetCDFFile(refncfile, 'r')
    refvars = oref.variables.keys()
    if not gen.searchInlist(refvars, refvn):
        print errormsg
        print '  ' + fname + ": reference file '" + refncfile + "' does not have " + \
          "variable '" + refvn + "' !!"
        quit(-1)
    orefv = oref.variables[refvn]
    refvals = orefv[:]
    varunits = orefv.units
    oref.close()
        
    # Statistics values
    filevars = ncfile.split(',')
    Nfiles = len(filevars)
    meanvalues = []
    stdvalues = []
    corrvalues = []
    corrpvalues = []
    biasvalues = []
    maevalues = []
    rmsevalues = []

    meanref = refvals.mean()
    stdref = refvals.std()

    if taylorkind == 'norm':
        print '  ' + fname + ': normalizing diagram'
        stdvalues.append(1.)
    else:
        stdvalues.append(stdref)

    meanvalues.append(meanref)
    corrvalues.append(1.)
    corrpvalues.append(1.)
    biasvalues.append(0.)
    maevalues.append(0.)
    rmsevalues.append(0.)

    print '  ' + fname + ': File statistics _______'
    for filevar in filevars:
        filen = filevar.split('@')[0]
        varn = filevar.split('@')[1]
        if not os.path.isfile(refncfile):
            print errormsg
            print '  ' + fname + ": file '" + filen + "' does not exist !!"
            quit(-1)
        ovalf = NetCDFFile(filen, 'r')
        valvars = ovalf.variables.keys()
        if not gen.searchInlist(valvars, varn):
            print errormsg
            print '  ' + fname + ": file '" + filen + "' does not have variable '" + \
              varn + "' !!"
            quit(-1)
        oval = ovalf.variables[varn]
        vals = oval[:]
        ovalf.close()

        usedfilens.append(filen)
        usedvarns.append(varn)

        gen.same_shape(refvals,vals)

        if taylorkind == 'norm':
            valstdv = vals.std()/stdref
        else:
            valstdv = vals.std()
        corrv, corrp = sts.pearsonr(refvals, vals)

        diff = vals - refvals
        meanvalues.append(vals.mean())
        stdvalues.append(valstdv)
        corrvalues.append(corrv)
        corrpvalues.append(corrp)
        biasvalues.append(diff.mean())
        maevalues.append(np.abs(diff).mean())
        rmsevalues.append(diff.std())
        print '    ', filen, 'val bias:', diff.mean(), 'std:', valstdv, 'corr:',     \
          corrv, 'rmse:', diff.std()

    drw.plot_Taylor(stdvalues, corrvalues, corrpvalues, varunits, marktyp, marksize, \
      markcol, marklabs, kindlabels, taylorkind, imgtit, figkind, close)

    if outputfile:
        ofilen = 'Taylor.nc'
        print '  ' + fname + ": creation of oputput file '" + ofilen + "' "
        outnc = NetCDFFile(ofilen, 'w')

        # create dimensions
        newdim = outnc.createDimension('file',Nfiles)
        newdim = outnc.createDimension('Lstring',256)

        # create variable-dimension
        newvar = outnc.createVariable('file', 'c', ('file','Lstring'))
        ncvar.writing_str_nc(newvar,usedfilens[1:-1],256)
        ncvar.basicvardef(newvar,'used_files','files used in Taylor plot','-')

        # Variables
        newvar = outnc.createVariable('refvar', 'c', ('Lstring'))
        ncvar.writing_1str_nc(newvar, 'refvarn', 256)
        ncvar.basicvardef(newvar,'refvar','reference variable', varunits)
        ncvar.set_attributek(newvar,'file',refncfile,'S')
        ncvar.set_attributek(newvar,'mean',meanref,'R')
        ncvar.set_attributek(newvar,'standard_deviation',stdref,'R')

        newvar = outnc.createVariable('varn', 'c', ('file','Lstring'))
        ncvar.writing_str_nc(newvar,usedvarns[1:-1],256)
        ncvar.basicvardef(newvar,'used_variables','variables used in Taylor plot','-')

        newvar = outnc.createVariable('stddev','f4',('file'))
        newvar[:] = stdvalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'standard_deviation','standard deviation',varunits)

        newvar = outnc.createVariable('corr','f4',('file'))
        newvar[:] = corrvalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'correlation','correlation with reference values', \
          '-')

        newvar = outnc.createVariable('corrp','f4',('file'))
        newvar[:] = corrpvalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'p_value_correlations','p-value of the correlation'+\
          ' with reference values', '-')

        newvar = outnc.createVariable('mean','f4',('file'))
        newvar[:] = meanvalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'mean','mean of values', varunits)

        newvar = outnc.createVariable('bias','f4',('file'))
        newvar[:] = biasvalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'bias','bias with reference values',varunits)

        newvar = outnc.createVariable('mae','f4',('file'))
        newvar[:] = maevalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'mae','Mean Absolute Error with reference values',varunits)

        newvar = outnc.createVariable('rmse','f4',('file'))
        newvar[:] = rmsevalues[1:Nfiles+1]
        ncvar.basicvardef(newvar,'rmse','Root Mean Square Error with reference values',varunits)

        # Global values
        outnc.setncattr('original_source_script', 'test_taylor_4panel.py')
        outnc.setncattr('authors_source_script', 'Yannick Copin')
        outnc.setncattr('url_source_script', 'http://www-pcmdi.llnl.gov/about/' +    \
          'staff/Taylor/CV/Taylor_diagram_primer.htm')
        ncvar.add_global_PyNCplot(outnc, 'drawing.py', fname, '1.0')

        outnc.sync()
        outnc.close()
        print fname + ": succesful writting of file '" + ofilen + "' !!"

    return

def draw_2D_shad_2cont(ncfile, values, varn):
    """ plotting three fields, one with shading and the other two with contour lines
    draw_2D_shad_2cont(ncfile, values, varn)
      ncfile= [ncfilevars],[ncfilevarc1],[ncfilevarc2] files to use (one value, same file)
      values=[vnamefs],[vnamefc1],[vnamefc2]:[dimvals]:[dimvalc1]:[dimvalc2]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:
          [ckind1]:[clabfmt1]:[ckind2]:[clabfmt2]:[sminv],[smaxv]:[sminc1],[smaxc1],[Nlev1]:[sminc2],[smaxc2],[Nlev2]:
          [figt]:[kindfig]:[reverse]:[mapv]:[close]
        [vnamefs],[vnamefc1],[vnamefc2]: Name in the figure of the shaded and the contour variable1 and contour variable2
        [dimvals/c1/c2]: ',' 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')
        [ckind1/2]: kind of contours for variable 1 andf variable 2
          'cmap': as it gets from colorbar
          'fixc,[colname]': fixed color [colname], all stright lines
          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
        [clabfmt1/2]: format of the labels in the contour 1 and 2 (C-like, '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)
        [sminc1/2]:[smaxv1/2]:[Nlev1/2]: minimum, maximum and number of values for the contour 1 and 2
        [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
      varn= [varsn],[varcn1],[varcn2] name of the variable to plot with shading variable with contour 1 and contour 2
    """
    fname = 'draw_2D_shad_2cont'

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

    expectargs = '[vnamefs],[vnamefc1],[vnamefc2]:[dimvals]:[dimvalc1]:[dimvalc2]:'+ \
      '[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[ckind1]:[clabfmt1]:[ckind2]:' +  \
      '[clabfmt2]:[sminv],[smaxv]:[sminc1],[smaxc1],[Nlev1]:[sminc2],[smaxc2],' +    \
      '[Nlev2]:[figt]:[kindfig]:[reverse]:[mapv]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    vnamesfig = values.split(':')[0].split(',')
    dimvals= values.split(':')[1].replace('|',':')
    dimvalc1= values.split(':')[2].replace('|',':')
    dimvalc2= values.split(':')[3].replace('|',':')
    vdimxn = values.split(':')[4]
    vdimyn = values.split(':')[5]
    dimxyf = values.split(':')[6]
    colorbarvals = values.split(':')[7]
    countkind1 = values.split(':')[8]
    countlabelfmt1 = values.split(':')[9]
    countkind2 = values.split(':')[10]
    countlabelfmt2 = values.split(':')[11]
    shadminmax = values.split(':')[12].split(',')
    contlevels1 = values.split(':')[13]
    contlevels2 = values.split(':')[14]
    figtitle = values.split(':')[15].replace('|',' ')
    figkind = values.split(':')[16]
    revals = values.split(':')[17]
    mapvalue = values.split(':')[18]
    close = gen.Str_Bool(values.split(':')[19])

    if2filenames = ncfile.find(',')

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

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

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

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

    objsf = NetCDFFile(ncfiles, 'r')
    objcf1 = NetCDFFile(ncfilec1, 'r')
    objcf2 = NetCDFFile(ncfilec2, 'r')
    
    VarNs = varn.split(',')
    if len(VarNs) != 3:
        print errormsg
        print '  ' + fname + ': 3 variables are required and there are:', len(VarNs),\
          'with names:', VarNs, '!!'
        print '    excpected vames for:', ['[varshad]', '[varcont1]', '[varcont2]'] 
        quit(-1)

    varns = varn.split(',')[0]
    varnc1 = varn.split(',')[1]
    varnc2 = varn.split(',')[2]

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

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

    if  not objcf2.variables.has_key(varnc2):
        print errormsg
        print '  ' + fname + ': contour file 2 "' + ncfilec2 +                       \
          '" does not have variable "' +  varnc2 + '" !!'
        quit(-1)

    # Variables' values
    objvars = objsf.variables[varns]
    objvarc1 = objcf1.variables[varnc1]
    objvarc2 = objcf2.variables[varnc2]

    print dimvals.replace('|',':').replace(',','|')
    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace('|',':').replace(',','|'))
    valcont1, dimscont1 = drw.slice_variable(objvarc1, dimvalc1.replace('|',':').replace(',','|'))
    valcont2, dimscont2 = drw.slice_variable(objvarc2, dimvalc2.replace('|',':').replace(',','|'))

    # Checking consistency of matrices
    gen.same_shape(valshad, valcont1)
    gen.same_shape(valshad, valcont2)

    dimnamesv = [vdimxn, vdimyn]

    varunits = []
    varunits.append(objvars.getncattr('units'))
    varunits.append(objvarc1.getncattr('units'))
    varunits.append(objvarc2.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(','))

    # Contour formats
    if countlabelfmt1 == 'None': 
        countlfmt1 = None
    else:
        countlfmt1 = countlabelfmt1
    if countlabelfmt2 == 'None': 
        countlfmt2 = None
    else:
        countlfmt2 = countlabelfmt2

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

    # Contour limits
    c1levmin = np.float(contlevels1.split(',')[0])
    c1levmax = np.float(contlevels1.split(',')[1])
    Nc1levels = int(contlevels1.split(',')[2])
    c2levmin = np.float(contlevels2.split(',')[0])
    c2levmax = np.float(contlevels2.split(',')[1])
    Nc2levels = int(contlevels2.split(',')[2])

    levels_cont1 = gen.pretty_int(c1levmin, c1levmax, Nc1levels)
    levels_cont2 = gen.pretty_int(c2levmin, c2levmax, Nc2levels)

    # Checking range of contours
    if c1levmin > np.min(valcont1) or c1levmax < np.max(valcont1):
        print warnmsg
        print '  ' + fname + " variable '" + varnc1 + "' range contour 1:",          \
          np.min(valcont1), ',', np.max(valcont1), 'beyond provided range:',         \
          c1levmin, ',', c1levmax
    if c2levmin > np.min(valcont2) or c2levmax < np.max(valcont2):
        print warnmsg
        print '  ' + fname + " variable '" + varnc2 + "' range contour 2:",          \
          np.min(valcont2), ',', np.max(valcont2), 'beyond provided range:',         \
          c2levmin, ',', c2levmax

    if len(levels_cont1) <= 1: 
        print warnmsg
        print '  ' + fname + ': wrong contour 1 levels:', levels_cont1, ' !!'
        del(levels_cont1)
        levels_cont1 = np.zeros((Nclevels1), dtype=np.float)
        levels_cont1 = np.arange(7)*(clevmax1 - clevmin1)/(Nclevels1-1)
        print '    generating default ones: ',levels_cont1
    if len(levels_cont2) <= 1: 
        print warnmsg
        print '  ' + fname + ': wrong contour 2 levels:', levels_cont2, ' !!'
        del(levels_cont2)
        levels_cont2 = np.zeros((Nclevels2), dtype=np.float)
        levels_cont2 = np.arange(7)*(clevmax2 - clevmin2)/(Nclevels2-1)
        print '    generating default ones: ',levels_cont2

    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_2contour(valshad, valcont1, valcont2, vnamesfig, odimxv,      \
      odimyv, odimxu, odimyu, xaxis, yaxis, dimnamesv, [colbarn,fmtcolbar,colbaror], \
      countkind1, countlfmt1, countkind2, countlfmt2, shading_nx, levels_cont1,      \
      levels_cont2, varunits, figtitle, figkind, revals,  mapvalue, close)

    return

def draw_bar(ncfile, values):
    """ Function to plot a bar char figure with multiple sources
      ncfile = '#' list of [filen];[dimslice];[xvarn];[yvarn]
        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [xvarn]: name of the variable to use for the x-positions
        [yvarn]: name of the variable to use for the values
      values = [dimxyfmt]:[xaxislab]:[yaxislab]:[xunits]:[yunits]:[aval]:[labels]:[colors]:[wdth]:[graphtit]:
          [legvalues]:[kindfig]:[fign]:[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [xaxislab]: Label for the x-axis ('!' for spaces)
        [yaxislab]: Label for the y-axis ('!' for spaces)
        [xunits]: units of the x-label ('None' for no units)
        [yunits]: units of the y-label
        [aval]: which acis should be used for the values ('x' or 'y')
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [colors]: ',' list of colors (single value same color, 'auto' automatic)
        [wdth]: width of the bars
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [close]: whether figure should be close or not
    """
    fname = 'draw_bar'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_bar.__doc__
        quit()

    expectargs = '[dimxyfmt]:[xaxislab]:[yaxislab]:[aval]:[xunits]:[yunits]:' +      \
      '[labels]:[colors]:[wdth]:[graphtit]:[legvalues]:[kindfig]:[fign]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    dimxyfmt = values.split(':')[0]
    xaxislab = values.split(':')[1].replace('!',' ')
    yaxislab = values.split(':')[2].replace('!',' ')
    aval = values.split(':')[3]
    xunits = values.split(':')[4]
    yunits = values.split(':')[5]
    labels = gen.str_list(values.split(':')[6].replace('!', ' '), ',')
    colors = gen.str_list(values.split(':')[7], ',')
    wdth = np.float(values.split(':')[8])
    graphtit = values.split(':')[9].replace('!',' ')
    legvalues = values.split(':')[10]
    kindfig = values.split(':')[11]
    fign = values.split(':')[12]
    close = gen.Str_Bool(values.split(':')[13])

    # files and values
    filedvs = ncfile.split('#')
    xvals = []
    yvals = []

    for fdv in filedvs:
        filen = fdv.split(';')[0]
        dimrange = fdv.split(';')[1]
        xvarn = fdv.split(';')[2]
        yvarn = fdv.split(';')[3]

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

        onc = NetCDFFile(filen, 'r')
        if not onc.variables.has_key(xvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              xvarn + "' for the x-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)
        if not onc.variables.has_key(yvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              yvarn + "' for the y-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)

        oxvar = onc.variables[xvarn]
        oyvar = onc.variables[yvarn]
        xvs, xdims = ncvar.slice_variable(oxvar, dimrange.replace(',',':'))
        yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
        if len(xvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              xvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', xvs.shape, 'dimensions:', xdims, 'fix it!!'
            quit(-1)
        if len(yvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              yvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', yvs.shape, 'dimensions:', ydims, 'fix it!!'
            quit(-1)
        xvals.append(list(xvs))
        yvals.append(list(yvs))

        onc.close()

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

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    # units
    if xunits == 'None': dxu = None
    else: dxu = xunits
    dyu = yunits

    drw.plot_bars(xvals, yvals, xaxis, yaxis, dxu, dyu, aval, xaxislab, yaxislab,    \
     labels, colors, wdth, graphtit, legloc, legsiz, kindfig, fign, close)

    return

def draw_bar_time(ncfile, values):
    """ Function to plot a bar char figure with multiple sources and time-axis
      ncfile = '#' list of [filen];[dimslice];[tvarn];[yvarn]
        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [tvarn]: name of the variable time
        [yvarn]: name of the variable to use for the values
      values = [dimxyfmt];[yaxislab];[yunits];[aval];[rangevals];[timevals];
          [labels];[colors];[wdth];[graphtit];[legvalues];[kindfig];[fign];[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [yaxislab]: Label for the y-axis ('!' for spaces)
        [yunits]: units of the y-label
        [aval]: which acis should be used for the values ('x' or 'y')
        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
         [vmin],[vmax]: minimum and maximum values
           '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
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [colors]: ',' list of colors (single value same color, 'auto' automatic)
        [wdth]: width of the bars
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [close]: whether figure should be close or not
    """
    fname = 'draw_bar_time'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_bar_time.__doc__
        quit()

    expectargs = '[dimxyfmt];[yaxislab];[yunits];[aval];[rangevals];[timevals];' +   \
      '[labels];[colors];[wdth];[graphtit];[legvalues];[kindfig];[fign];[close]'
    drw.check_arguments(fname,values,expectargs,';')

    dimxyfmt = values.split(';')[0]
    yaxislab = values.split(';')[1].replace('!',' ')
    yunits = values.split(';')[2]
    aval = values.split(';')[3]
    rangevals = values.split(';')[4]
    timevals = values.split(';')[5]
    labels = gen.str_list(values.split(';')[6].replace('!', ' '), ',')
    colors = gen.str_list(values.split(';')[7], ',')
    wdth = np.float(values.split(';')[8])
    graphtit = values.split(';')[9].replace('!',' ')
    legvalues = values.split(';')[10]
    kindfig = values.split(';')[11]
    fign = values.split(';')[12]
    close = gen.Str_Bool(values.split(';')[13])

    # files and values
    filedvs = ncfile.split('#')
    tvals = []
    yvals = []

    # time-values
    expectargs = '[timen]|[units]|[kind]|[tfmt]'
    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')

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

    for fdv in filedvs:
        filen = fdv.split(';')[0]
        dimrange = fdv.split(';')[1]
        tvarn = fdv.split(';')[2]
        yvarn = fdv.split(';')[3]

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

        onc = NetCDFFile(filen, 'r')
        if not onc.variables.has_key(tvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              tvarn + "' for the time-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)
        if not onc.variables.has_key(yvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              yvarn + "' for the y-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)

        otvar = onc.variables[tvarn]
        oyvar = onc.variables[yvarn]
        tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
        yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
        tunitsvar = otvar.units

        if len(tvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              tvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', tvs.shape, 'dimensions:', tdims, 'fix it!!'
            quit(-1)
        if len(yvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              yvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', yvs.shape, 'dimensions:', ydims, 'fix it!!'
            quit(-1)

        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]
        # Referring all times to the same reference time!
        reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)

        tvals.append(list(reftvals))
        yvals.append(list(yvs))

        onc.close()

    # Times
    mintval = np.min(tvals)
    maxtval = np.max(tvals)

    dtvals = (maxtval - mintval)/10
    dti = mintval
    dte = maxtval
    tvalsticks = np.arange(dti, dte+dtvals, 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(tvalsticks, timeunit, timekind, timefmt)

    # ranges
    valmin = np.min(yvals)
    valmax = np.max(yvals)
    if rangevals == 'None':
        valmin = np.min(yvals)
        valmax = np.max(yvals)
    else:
        if rangevals.split(',')[0] != 'auto': 
            valmin = np.float(rangevals.split(',')[0])
        if rangevals.split(',')[1] != 'auto': 
            valmax = np.float(rangevals.split(',')[1])
    yrange = [valmin, valmax]

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

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    dyu = yunits

    drw.plot_bars_time(tvals, yvals, timepos, timelabels, yaxis, dyu, aval, yrange,  \
     timen, yaxislab, labels, colors, wdth, graphtit, legloc, legsiz, kindfig, fign, \
     close)

    return

def draw_bar_line(ncfile, values):
    """ Function to plot a bar char and lines plot figure with multiple sources
      ncfile = '#' list of [filen];[dimslice];[xvarn];[yvarn];[kind]
        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [xvarn]: name of the variable to use for the x-positions
        [yvarn]: name of the variable to use for the values
        [kind]: Kind of plotting
          'bar': for bar-plot
          'line': for line-plot
      values = [dimxyfmt]:[xaxislab]:[yaxislab]:[xunits]:[yunits]:[aval]:[rangevals]:[labels]:
          [colors]:[wdth]:[colns]:[lines]:[points]:[lwdths]:[psizes]:[freqv]:[graphtit]:[legvalues]:
          [kindfig]:[fign]:[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [xaxislab]: Label for the x-axis ('!' for spaces)
        [yaxislab]: Label for the y-axis ('!' for spaces)
        [xunits]: units of the x-label ('None' for no units)
        [yunits]: units of the y-label
        [aval]: which acis should be used for the values ('x' or 'y')
        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
         [vmin],[vmax]: minimum and maximum values
           'auto': the computed minimumm or maximum of the values  
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [colors]: ',' list of colors (single value same color, 'auto' automatic)
        [wdth]: width of the bars
        [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)
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [close]: whether figure should be close or not
    """
    fname = 'draw_bar_line'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_bar_line.__doc__
        quit()

    expectargs = '[dimxyfmt]:[xaxislab]:[yaxislab]:[aval]:[rangevals]:[xunits]:' +   \
      '[yunits]:[labels]:[colors]:[wdth]:[colns]:[lines]:[points]:[lwdths]:' +       \
      '[psizes]:[freqv]:[graphtit]:[legvalues]:[kindfig]:[fign]:' + \
      '[close]'
    drw.check_arguments(fname,values,expectargs,':')

    dimxyfmt = values.split(':')[0]
    xaxislab = values.split(':')[1].replace('!',' ')
    yaxislab = values.split(':')[2].replace('!',' ')
    aval = values.split(':')[3]
    rangevals = values.split(':')[4]
    xunits = values.split(':')[5]
    yunits = values.split(':')[6]
    labels = gen.str_list(values.split(':')[7].replace('!', ' '), ',')
    colors = gen.str_list(values.split(':')[8], ',')
    wdth = np.float(values.split(':')[9])
    colns = gen.str_list(values.split(':')[10], ',')
    lines = gen.str_list(values.split(':')[11], ',')
    points = gen.str_list(values.split(':')[12], '@')
    lwdths = gen.str_list_k(values.split(':')[13], ',', 'R')
    psizes = gen.str_list_k(values.split(':')[14], ',', 'R')
    freqv0 = values.split(':')[15]
    graphtit = values.split(':')[16].replace('!',' ')
    legvalues = values.split(':')[17]
    kindfig = values.split(':')[18]
    fign = values.split(':')[19]
    close = gen.Str_Bool(values.split(':')[20])

    # files and values
    filedvs = ncfile.split('#')
    barxvals = []
    baryvals = []
    linexvals = []
    lineyvals = []
    namebars = []
    namelines = []

    valmin = gen.fillValueF
    valmax = -gen.fillValueF
    print '  ' + fname + 'plotting _______'
    il = 0
    for fdv in filedvs:
        filen = fdv.split(';')[0]
        dimrange = fdv.split(';')[1]
        xvarn = fdv.split(';')[2]
        yvarn = fdv.split(';')[3]
        plotk = fdv.split(';')[4]
        print '  ', filen, 'with', plotk

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

        onc = NetCDFFile(filen, 'r')
        if not onc.variables.has_key(xvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              xvarn + "' for the x-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)
        if not onc.variables.has_key(yvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              yvarn + "' for the y-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)

        oxvar = onc.variables[xvarn]
        oyvar = onc.variables[yvarn]
        xvs, xdims = ncvar.slice_variable(oxvar, dimrange.replace(',',':'))
        yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
        if len(xvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              xvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', xvs.shape, 'dimensions:', xdims, 'fix it!!'
            quit(-1)
        if len(yvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              yvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', yvs.shape, 'dimensions:', ydims, 'fix it!!'
            quit(-1)

        # Location of each kind
        if plotk == 'bar':
            barxvals.append(list(xvs))
            baryvals.append(list(yvs))
            if labels is not None: namebars.append(labels[il])
        elif plotk == 'line':
            linexvals.append(list(xvs))
            lineyvals.append(list(yvs))
            if labels is not None: namelines.append(labels[il])
        else:
            print errormsg
            print '  ' + fname + ": kind of input '" + plotk + "' not ready!!"
            print '    available ones:', ['bar', 'line']
            quit(-1)

        yvsn = np.min(yvs)
        yvsx = np.max(yvs)
        if yvsn < valmin: valmin = yvsn
        if yvsx > valmax: valmax = yvsx

        onc.close()
        il = il + 1

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

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

    # Frequqnecy for lines
    if freqv0 == 'all':
        freqv = None
    else:
        freqv = int(freqv0)

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    # units
    if xunits == 'None': dxu = None
    else: dxu = xunits
    dyu = yunits

    drw.plot_bars_line(barxvals, baryvals, linexvals, lineyvals, xaxis, yaxis, dxu,  \
     dyu, aval, yrange, xaxislab, yaxislab, namebars, namelines, colors, wdth, colns,\
     lines, points, lwdths, psizes, freqv, graphtit, legloc, legsiz, kindfig, fign,  \
     close)

    return

def draw_bar_line_time(ncfile, values):
    """ Function to plot a bar char and lines plot figure with multiple sources and time-axis
      ncfile = '#' list of [filen];[dimslice];[xvarn];[yvarn];[kind]
        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [tvarn]: name of the variable time
        [yvarn]: name of the variable to use for the values
        [kind]: Kind of plotting
          'bar': for bar-plot
          'line': for line-plot
      values = [dimxyfmt];[yaxislab];[yunits];[aval];[rangevals];[timevals];[labels];
          [colors];[wdth];[colns];[lines];[points];[lwdths];[psizes];[freqv];[graphtit];[legvalues];
          [kindfig];[fign];[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [yaxislab]: Label for the y-axis ('!' for spaces)
        [yunits]: units of the y-label
        [aval]: which acis should be used for the values ('x' or 'y')
        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
         [vmin],[vmax]: minimum and maximum values
           '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
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [colors]: ',' list of colors (single value same color, 'auto' automatic)
        [wdth]: width of the bars
        [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)
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [close]: whether figure should be close or not
    """
    fname = 'draw_bar_line_time'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_bar_line_time.__doc__
        quit()

    expectargs = '[dimxyfmt];[yaxislab];[aval];[rangevals];[yunits];' +   \
      '[timevals];[labels];[colors];[wdth];[colns];[lines];[points];' +   \
      '[lwdths];[psizes];[freqv];[graphtit];[legvalues];[kindfig];' +     \
      '[fign];[close]'
    drw.check_arguments(fname,values,expectargs,';')

    dimxyfmt = values.split(';')[0]
    yaxislab = values.split(';')[1].replace('!',' ')
    aval = values.split(';')[2]
    rangevals = values.split(';')[3]
    yunits = values.split(';')[4]
    timevals = values.split(';')[5]
    labels = gen.str_list(values.split(';')[6].replace('!', ' '), ',')
    colors = gen.str_list(values.split(';')[7], ',')
    wdth = np.float(values.split(';')[8])
    colns = gen.str_list(values.split(';')[9], ',')
    lines = gen.str_list(values.split(';')[10], ',')
    points = gen.str_list(values.split(';')[11], '@')
    lwdths = gen.str_list_k(values.split(';')[12], ',', 'R')
    psizes = gen.str_list_k(values.split(';')[13], ',', 'R')
    freqv0 = values.split(';')[14]
    graphtit = values.split(';')[15].replace('!',' ')
    legvalues = values.split(';')[16]
    kindfig = values.split(';')[17]
    fign = values.split(';')[18]
    close = gen.Str_Bool(values.split(';')[19])

    # files and values
    filedvs = ncfile.split('#')
    bartvals = []
    baryvals = []
    linetvals = []
    lineyvals = []
    namebars = []
    namelines = []

    # time-values
    expectargs = '[timen]|[units]|[kind]|[tfmt]'
    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')

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

    valmin = gen.fillValueF
    valmax = -gen.fillValueF
    print '  ' + fname + 'plotting _______'
    il = 0
    for fdv in filedvs:
        filen = fdv.split(';')[0]
        dimrange = fdv.split(';')[1]
        tvarn = fdv.split(';')[2]
        yvarn = fdv.split(';')[3]
        plotk = fdv.split(';')[4]
        print '  ', filen, 'with', plotk

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

        onc = NetCDFFile(filen, 'r')
        if not onc.variables.has_key(tvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              xvarn + "' for the time-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)
        if not onc.variables.has_key(yvarn):
            print errormsg
            print '  ' + fname + ': file "' + filen + "' does not have variable '" + \
              yvarn + "' for the y-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)

        otvar = onc.variables[tvarn]
        oyvar = onc.variables[yvarn]
        tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
        yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
        tunitsvar = otvar.units

        if len(tvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              tvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', tvs.shape, 'dimensions:', tdims, 'fix it!!'
            quit(-1)
        if len(yvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': provided slice:', dimrange, "for variable '" +   \
              yvarn + "' does not provide a rank-1 value !!"
            print '    resultant shape:', yvs.shape, 'dimensions:', ydims, 'fix it!!'
            quit(-1)

        # time-values
        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]
        # Referring all times to the same reference time!
        reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)

        # Location of each kind
        if plotk == 'bar':
            bartvals.append(list(reftvals))
            baryvals.append(list(yvs))
            if labels is not None: namebars.append(labels[il])
        elif plotk == 'line':
            linetvals.append(list(reftvals))
            lineyvals.append(list(yvs))
            if labels is not None: namelines.append(labels[il])
        else:
            print errormsg
            print '  ' + fname + ": kind of input '" + plotk + "' not ready!!"
            print '    available ones:', ['bar', 'line']
            quit(-1)

        yvsn = np.min(yvs)
        yvsx = np.max(yvs)
        if yvsn < valmin: valmin = yvsn
        if yvsx > valmax: valmax = yvsx

        onc.close()
        il = il + 1

    # Times
    mintval = np.min(bartvals + linetvals)
    maxtval = np.max(bartvals + linetvals)

    dtvals = (maxtval - mintval)/10.
    dti = mintval
    dte = maxtval
    tvalsticks = np.arange(dti, dte+dtvals, 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(tvalsticks, timeunit, timekind, timefmt)

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

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

    # Frequqnecy for lines
    if freqv0 == 'all':
        freqv = None
    else:
        freqv = int(freqv0)

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    # units
    dyu = yunits

    drw.plot_bars_line_time(bartvals, baryvals, linetvals, lineyvals, timepos,       \
     timelabels, yaxis, dyu, aval, yrange, timen, yaxislab, namebars, namelines,     \
     colors, wdth, colns, lines, points, lwdths, psizes, freqv, graphtit, legloc,    \
     legsiz, kindfig, fign, close)

    return

def draw_time_lag(ncfile, values):
    """ Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)
      ncfile = '#' list of couples ('%' formed) [prefilen];[predslice];[pretvarn];[prevarn]%[futfilen];
          [futdslice];[futtvarn];[futvarn]
        'pre': values to act as previous values
        'fut': values to act as future values

        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [tvarn]: name of the variable time
        [yvarn]: name of the variable to use for the values
      values = [dimxyfmt];[axeskind];[preaxislab];[preunits];[futaxislab];[futunits];[prerangevals];
          [futrangevals];[timevals];[labels];[figlagkind];[graphtit];[legvalues];[kindfig];[fign];[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [axeskind]: type of axes to be plotted
          'centered': crossed at 0,0 at the center of the figure
          'box': around the figure
        [preaxislab]: Label for the future-axis ('!' for spaces)
        [preunits]: units of the future-label
        [futaxislab]: Label for the future-axis ('!' for spaces)
        [futunits]: units of the future-label
        [prerangevals]: Range of the previous axis with the values (single 'None' for 'auto','auto')
          [val1],[val2]: tacking the provided ',' separated list of desired [val1] and [val2]
          'auto': automatically set up range using minv and maxv
          'extremescentered': extremes automatically centered on zero by computing from data -absmax, absmax; 
            absmax=max(abs(minval),maxval)
          'meancentered': extremes automatically centered on mean by computing from data minv+meanv, maxv-meanv; 
            meanv=(minval + maxval)/2.
        [futrangevals]: Range of the future axis with the values (single 'None' for 'auto','auto')
          [val1],[val2]: tacking the provided ',' separated list of desired [val1] and [val2]
          'auto': automatically set up range using minv and maxv
          'extremescentered': extremes automatically centered on zero by computing from data -absmax, absmax; 
            absmax=max(abs(minval),maxval)
          'meancentered': extremes automatically centered on mean by computing from data minv+meanv, maxv-meanv; 
            meanv=(minval + maxval)/2.
        [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
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [figlagkind]=[kindname],[valueskind] kind of time-lag plot
          'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: 
              time-lag for a given repeating sub-period, Line-conected points following a colorbar and time-values
            [Nlag]: number of time steps as lag
            [period]: period to be repeated allover the time-data
            [colorbar]: name of the color bar to use ('auto' for rainbow)
            [cbarfmt]: format of the numbers in the colorbar
            [cbaror]: orientation of the colorbar ('auto' for vertical)
            [ltype]: type of the lines (single value for the same, or 'auto')
            [lsize]: width of the lines (single value for the same, or 'auto')
            [mtype]: type of the markers (single value for the same, or 'auto')
            [msize]: size of the markers (single value for the same, or 'auto')
          'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: Line-conected 
              points following a colorbar and time-values
            [Nlag]: number of time steps as lag
            [colorbar]: name of the color bar to use ('auto' for rainbow)
            [cbarfmt]: format of the numbers in the colorbar
            [cbaror]: orientation of the colorbar ('auto' for vertical)
            [ltype]: type of the lines (single value for the same, or 'auto')
            [lsize]: width of the lines (single value for the same, or 'auto')
            [mtype]: type of the markers (single value for the same, or 'auto')
            [msize]: size of the markers (single value for the same, or 'auto')
          'simplepts',[Nlag],[col],[type],[size]: Simple points assuming that values have all the same times
            [Nlag]: number of time steps as lag
            [col]: '@' list of colors of the points (single value for the same, or 'auto')
            [type]:types of the points (single value for the same, or 'auto')
            [size]: sizes of the points kind of lag-time figure (single value for the same, or 'auto')
      labels= list of labels for legend (None for no legend, and 'None' for no specific label)
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [close]: whether figure should be close or not
    """
    fname = 'draw_time_lag'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_time_lag.__doc__
        quit()

    expectargs = '[dimxyfmt];[axeskind];[preaxislab];[preunits];[futaxislab];' +     \
      '[futunits];[prerangevals];[futrangevals];[timevals];[labels];[figlagkind];' + \
      '[graphtit];[legvalues];[kindfig];[fign];[close]'
    drw.check_arguments(fname,values,expectargs,';')

    dimxyfmt = values.split(';')[0]
    axeskind = values.split(';')[1]
    preaxislab = values.split(';')[2].replace('!',' ')
    preunits = values.split(';')[3]
    futaxislab = values.split(';')[4].replace('!',' ')
    futunits = values.split(';')[5]
    prerangevals = values.split(';')[6]
    futrangevals = values.split(';')[7]
    timevals = values.split(';')[8]
    labels = gen.str_list(values.split(';')[9].replace('!', ' '), ',')
    figlagkind = values.split(';')[10]
    graphtit = values.split(';')[11].replace('!',' ')
    legvalues = values.split(';')[12]
    kindfig = values.split(';')[13]
    fign = values.split(';')[14]
    close = gen.Str_Bool(values.split(';')[15])

    # files and values
    filedvs = ncfile.split('#')
    timevalues = []
    prevalues = []
    futvalues = []

    # time-values
    expectargs = '[timen]|[units]|[kind]|[tfmt]'
    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')

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

    preminval = gen.fillValue
    premaxval = -gen.fillValue
    futminval = gen.fillValue
    futmaxval = -gen.fillValue
    mintval = gen.fillValue
    maxtval = -gen.fillValue

    for fdvprefut in filedvs:
        prefutdv = fdvprefut.split('%')
        ifile=0
        for fdv in prefutdv:
            expectargs = '[pre/fut]filen;[pre/fut]dslice;[pre/fut]tvarn;[pre/fut]varn'
            drw.check_arguments('filevalues: '+fname, fdv, expectargs,';')
            
            filen = fdv.split(';')[0]
            dimrange = fdv.split(';')[1]
            tvarn = fdv.split(';')[2]
            yvarn = fdv.split(';')[3]
            futfdv = fdvprefut.split('%')[1]

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

            onc = NetCDFFile(filen, 'r')
            if not onc.variables.has_key(tvarn):
                print errormsg
                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
                  tvarn + "' for the time-values !!"
                print '    available ones:', onc.variables.keys()
                onc.close()
                quit(-1)
            if not onc.variables.has_key(yvarn):
                print errormsg
                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
                  yvarn + "' for the y-values !!"
                print '    available ones:', onc.variables.keys()
                onc.close()
                quit(-1)

            otvar = onc.variables[tvarn]
            oyvar = onc.variables[yvarn]
            tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
            yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
            tunitsvar = otvar.units

            if len(tvs.shape) != 1:
                print errormsg
                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" + \
                  tvarn + "' does not provide a rank-1 value !!"
                print '    resultant shape:', tvs.shape, 'dimensions:',tdims,'fix it!!'
                quit(-1)
            if len(yvs.shape) != 1:
                print errormsg
                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" + \
                  yvarn + "' does not provide a rank-1 value !!"
                print '    resultant shape:',yvs.shape, 'dimensions:',ydims,'fix it!!'
                quit(-1)
    
            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]
            # Referring all times to the same reference time!
            reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)
      
            onc.close()

            reftn = reftvals.min()
            reftx = reftvals.max()
            if reftn < mintval: mintval = reftn
            if reftx > maxtval: maxtval = reftx

            if ifile == 0:
                timevalues.append(reftvals)
                prevalues.append(yvs)
                pren = yvs.min()
                prex = yvs.max()
                if pren < preminval: preminval = pren
                if prex > premaxval: premaxval = prex
            else:
                timevalues.append(reftvals)
                futvalues.append(yvs)
                futn = yvs.min()
                futx = yvs.max()
                if futn < futminval: futminval = futn
                if futx > futmaxval: futmaxval = futx
            ifile = ifile + 1

    # Times
    if figlagkind[0:12] == 'repeatPeriod':
        per=int(figlagkind.split(',')[2])
        dtvals = (maxtval - mintval)/10/per
    else:
        dtvals = (maxtval - mintval)/10
    dti = mintval
    dte = maxtval
    tvalsticks = np.arange(dti, dte+dtvals, 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(tvalsticks, timeunit, timekind, timefmt)

    # ranges
    prerng = gen.minmax_range(preminval, premaxval, prerangevals)
    futrng = gen.minmax_range(futminval, futmaxval, futrangevals)

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

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    drw.plot_time_lag(prevalues, futvalues, timevalues, xaxis, yaxis, axeskind,      \
      preaxislab, futaxislab, preunits, futunits, prerng, futrng, figlagkind, labels,\
      timen, timepos, timelabels, graphtit, legloc, legsiz, kindfig, fign, close)

    return

def draw_ensembles_time(ncfile, values):
    """ Function to plot an ensembles of data following an axis-time
      ncfile = '#' list of files [filen];[slice];[tvarn];[varn];[kinddata]
        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [tvarn]: name of the variable time ('WRFtime', for times from WRF)
        [varn]: name of the variable to use for the values
        [kinddata]: which kind of use should be done:
          'data': to be plot as data
          'ensemble': to be used as a member of the ensemble
      values = [dimxyfmt];[valaxis];[axislab];[axisunits];[rangevals];[datavals];[timevals];[valskind];
          [labels];[figenskind];[graphtit];[legvalues];[kindfig];[fign];[outfile];[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [valaxis]: which axes should be used for the data
        [axislab]: Label for the values-axis ('!' for spaces)
        [axisunits]: units of the values-label
        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
         [vmin],[vmax]: minimum and maximum values
           'auto': the computed minimumm or maximum of the values
        [datavals]: [color]:[linetype]:[linewidht]:[markertype]:[markersize] values for the data-lines
          [color]: '@' list of colors of the lines (single value for the same, or 'auto')
          [linetype]: '@' list of type of the lines (single value for the same, or 'auto')
          [linewidht]: '@' list of width of the lines (single value for the same, or 'auto')
          [markertype]: '@' list of type of the markers (single value for the same, or 'auto')
          [markersize]: '@' list of size of the markers (single value for the same, or 'auto')
        [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
        [valskind]: way to compute the values to be plotted
          'FromFile': from the files with the 'data' flag
          'FromEns',[usedims],[stats]: from all the files with the 'ensemble' flag with statistics [stats], 
              throughout dimensions [usedims]
            [usedims]= '@' list of dimensions to take to compute the statistics
            [stats]= statistics to use
              'direct': without statistics
              'mean': mean value of all files with ensemble flag
              'median': median value of all files with ensemble flag
              'weightedmean,[stats],[weights]': weighted mean value all files with ensemble flag
                [stats] = statistics to use from each member: 'direct', 'mean', 'median'
                [weights] = '@' list of weights [0,1]
          'FromIndivEns',[usedims],[stats]: from each files with the 'ensemble' flag with statistics [stats], 
              throughout dimensions [usedims]
            [usedims]= '@' list of dimensions to take to compute the statistics
            [stats]= statistics to use: 
              'mean': mean value of each file with ensemble flag
              'median': median value of each file with ensemble flag
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [figenskind]=[kindname],[valueskind] kind of ensemble plot
          'cloud',[color],[limits]: ensembles values as a cloud 
            [color]: name of the color to use ('auto' for '#DDDDDD')
            [limits]: which stadistics to use for the plot ('auto' for extremes)
              '5quantile': 5quantile,95quantile of the values 
              'direct': below and up values are tacking directly from the provided data
              'extremes': min,max of the values
              'stddev': standard deviation fo the values (only available if there is one line)
          'spaghetti',[color],[width],[type]: a line for each member
            [color]: name of the color to use for all lines ('auto' for '#DDDDDD')
            [width]: width of the line to use for all lines ('auto' for 0.5)
            [type]: type of the line to use for all lines ('auto' for '-')
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [outfile]: wehter or not a file with the result of the computation of the ensemble should be 
          written or not (labelled 'ensemble_ofile.nc')
        [close]: whether figure should be close or not
    """
    fname = 'draw_ensembles_time'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_ensembles_time.__doc__
        quit()

    expectargs = '[dimxyfmt];[axeskind];[axislab];[axisunits];[rangevals];' +        \
      '[datavals];[timevals];[valskind];[labels];[figenskind];[graphtit];' +         \
      '[legvalues];[kindfig];[fign];[outfile];[close]'
    drw.check_arguments(fname,values,expectargs,';')

    dimxyfmt = values.split(';')[0]
    valaxis = values.split(';')[1]
    axislab = values.split(';')[2].replace('!',' ')
    axisunits = values.split(';')[3]
    rangevals = values.split(';')[4]
    datavals = values.split(';')[5]
    timevals = values.split(';')[6]
    valskind = values.split(';')[7]
    labels = gen.str_list(values.split(';')[8].replace('!', ' '), ',')
    figenskind = values.split(';')[9]
    graphtit = values.split(';')[10].replace('!',' ')
    legvalues = values.split(';')[11]
    kindfig = values.split(';')[12]
    fign = values.split(';')[13]
    outfile = gen.Str_Bool(values.split(';')[14])
    close = gen.Str_Bool(values.split(';')[15])

    ofilen = 'ensemble_ofile.nc'

    # files
    valfiles = gen.str_list(ncfile, '#')

    # time-values
    expectargs = '[timen]|[units]|[kind]|[tfmt]'
    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')

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

    linevals = []
    ltimevals = []
    ensvals = []
    etimevals = []

    # List of files used for the ensemble
    ensfilens = []
    # List of files used for the ensemble with its dimension and variable name
    edv_filens = []
    # Dictionary with the dimensions of the values from a given file
    dimsfile = {}

    mintval = gen.fillValueF
    maxtval = -gen.fillValueF
    minvval = gen.fillValueF
    maxvval = -gen.fillValueF

    ensfilens = []
    ifile = 0
    dimt = -gen.fillValueF
    for fdv in valfiles:
        fvals = fdv.split(';')
        expectedargs = '[filen];[slice];[tvarn];[varn];[kinddata]'
        gen.check_arguments('filevals: '+fname, fdv, expectedargs, ';')
        filen = fvals[0]
        dimrange = fvals[1]
        tvarn = fvals[2]
        yvarn = fvals[3]
        datatype = fvals[4]

        edv = filen + '#' + dimrange + '#' + yvarn

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

        onc = NetCDFFile(filen, 'r')
        if tvarn == 'WRFtime':
            datesv = []
            if tvarn == 'WRFtime':
                fdates = onc.variables['Times'][:]
                for it in range(fdates.shape[0]):
                    datesv.append(gen.datetimeStr_conversion(fdates[it,:],           \
                      'WRFdatetime','cfTime,' + timeunit))
            tvs = np.array(datesv, dtype=np.float)
            tunitsvar = timeunit
        else:
            if not onc.variables.has_key(tvarn):
                print errormsg
                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
                  tvarn + "' for the time-values !!"
                print '    available ones:', onc.variables.keys()
                onc.close()
                quit(-1)
            otvar = onc.variables[tvarn]
            tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
            tunitsvar = otvar.units

        if not onc.variables.has_key(yvarn):
            print errormsg
            print '  ' +fname+ ': file "' +filen+ "' does not have variable '" +     \
              yvarn + "' for the y-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)

        oyvar = onc.variables[yvarn]
        yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
        dimsfile[edv] = ydims

        # Referring all times to the same reference time!
        reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)

        onc.close()

        if len(reftvals) > dimt: dimt = len(reftvals)

        reftn = reftvals.min()
        reftx = reftvals.max()
        if reftn < mintval: mintval = reftn
        if reftx > maxtval: maxtval = reftx
        refvn = yvs.min()
        refvx = yvs.max()
        if refvn < minvval: minvval = refvn
        if refvx > maxvval: maxvval = refvx

        if datatype == 'data':
            if len(tvs.shape) != 1:
                print errormsg
                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" +     \
                 tvarn + "' and '" + datatype + "' does not provide a rank-1 value !!"
                print '    resultant shape:', tvs.shape, 'dimensions:',tdims,'fix it !!'
                quit(-1)
            if len(yvs.shape) != 1:
                print errormsg
                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" +     \
                  yvarn + "' and '" + datatype + "'does not provide a rank-1 value !!"
                print '    resultant shape:',yvs.shape, 'dimensions:',ydims,'fix it !!'
                quit(-1)
            linevals.append(yvs)
            ltimevals.append(reftvals)
        else:
            ensfilens.append(filen)
            edv_filens.append(edv)
            ensvals.append(yvs)
            etimevals.append(reftvals)

        ifile = ifile + 1

    Nens = len(ensvals)

    valskindn = gen.str_list(valskind, ',')[0]

    ENSvals = []
    TENSvals = []

    # Getting values to draw as lines
    if valskindn == 'FromFile':
        if len(linevals) == 0:
            print errormsg
            print '  ' + fname + ": you asked to get data '" + valskind +            \
              "' but no file with flag 'data' was provided !!"
            print '    provided file characteristics _______'
            for fdv in prefutdv:
                print fdv.split(';')
            quit(-1)
        ENSvals = list(ensvals)
        TENSvals = list(etimevals)
    elif valskindn == 'FromEns':
        eSvals = valskind.split(',')

        expectedargs='FromEns,[usedims],[stats]'
        gen.check_arguments('FromEns: '+fname, valskind, expectedargs, ',')

        ensdims = eSvals[1].split('@')
        ensn = eSvals[2]
        iedv = 0
        # Temporal slices for each file/variable
        Tslices = {}
        for edv in edv_filens:
            vvalues = ensvals[iedv]
            edv_dims = dimsfile[edv]
            idim = []
            for dsts in ensdims:
                idim.append(edv_dims.index(dsts))
            # Adding each running value as a new member of the ensemble
            NOTusedim = []
            for dn in dimsfile[edv]: 
                if not gen.searchInlist(ensdims, dn): NOTusedim.append(dn)
            varslices = gen.provide_slices(dimsfile[edv], vvalues.shape, NOTusedim)
            Tslices[edv] = varslices

            if iedv == 0: dimt = len(varslices)
            else: 
                if dimt != len(varslices):
                    print errormsg
                    print '  ' + fname + ': this is too complicated !!'
                    print '    for file:', iedv, ' with ', len(varslices),           \
                      'and initial dimt:', dimt 
                    print '    not ready to deal with files with different number '+ \
                      'of time-steps!!'
                    quit(-1)
            # Adding each not runnuning grid-point as a new ensemble member
            varslices = gen.provide_slices(dimsfile[edv], vvalues.shape, ensdims)
            for slc in varslices:
                ENSvals.append(np.squeeze(vvalues[tuple(slc)]))
                TENSvals.append(np.squeeze(np.array(etimevals[iedv])))

            iedv = iedv + 1

        lvals = np.zeros((dimt), dtype=np.float)
        for it in range(dimt):
            iedv = 0     
            Tvals = []
            Tvalse = {}
            for edv in edv_filens:
                vvalues = ensvals[iedv]
                varslics = Tslices[edv]
                Tvals = Tvals + list(np.squeeze(vvalues[tuple(varslics[dimt-it-1])]).flatten())
                Tvalse[edv] = np.squeeze(vvalues[tuple(varslics[dimt-it-1])])

            aTvals = np.array(Tvals)
            if ensn == 'mean':
                lvals[it] = np.mean(aTvals)
            elif ensn == 'median':
                lvals[it] = np.median(aTvals)
            elif ensn[0:12] == 'weightedmean':
                expectedargs='FromEns,[usedims],weightedmean,[stats],[weights]'
                gen.check_arguments('FromEns: '+fname, valskind, expectedargs, ',')

                stats = eSvals[3]
                wgths = eSvals[4].split('@')
                wghtvs = np.array(wgths, dtype=np.float)
                if len(wgths) != Nens:
                    print errormsg
                    print '  ' + fname + ': the number of members of the ensemble:', \
                      Nens, 'and the number of provided weights:', len(wghts),       \
                      'do not coincide !!'
                    print '    provided weights:', wgths
                    print '    provided file characteristics _______'
                    for fdv in prefutdv:
                        print fdv.split(';')
                    quit(-1)
                wgthvals = np.zeros((Nens), dtype=np.float)
                iedv = 0
                for edv in edv_filens:
                    if stats == 'mean':
                        wgthvals[iedv] = np.mean(Tvalse[edv])
                    elif stats == 'median':
                        wgthvals[iedv] = np.median(Tvalse[edv])
                    else:
                        print errormsg
                        print '  ' +fname+ ": statistics '" + eSvals[2] + "' not ready !!"
                        print '    available ones:', ['mean', 'median']
                        quit(-1)
                lvals[it] = np.sum(wghtvals*wghtvs)/np.sum(wghtvs)
            else:
                print errormsg
                print '  ' + fname + ": for '" + valskindn + "'statistics '" +       \
                  eSvals[2] + "' not ready !!"
                print '    available ones:', ['mean', 'median', 'weightedmean']
                quit(-1)
            iedv = iedv + 1
        linevals.append(lvals)
        ltimevals.append(np.squeeze(np.array(etimevals[0], dtype=np.float)))
    elif valskindn == 'FromIndivEns':
        indenfns = []
        eSvals = valskind.split(',')

        expectedargs='FromIndivEns,[usedims],[stats]'
        gen.check_arguments('FromEns: '+fname, valskind, expectedargs, ',')

        ensdims = eSvals[1].split('@')
        ensn = eSvals[2]
        iedv = 0
        evals = np.zeros((dimt, Nens), dtype=np.float)
        for edv in edv_filens:
            vvalues = ensvals[iedv]
            edv_dims = dimsfile[edv]
            filen = edv.split('#')[0]
            indenfns.append(filen)

            idim = []
            for dsts in ensdims:
                idim.append(edv_dims.index(dsts))
            # Adding each running value as a new member of the ensemble
            NOTusedim = []
            for dn in dimsfile[edv]: 
                if not gen.searchInlist(ensdims, dn): NOTusedim.append(dn)
            varslices = gen.provide_slices(dimsfile[edv], vvalues.shape, ensdims)
            for varslc in varslices:
                ENSvals.append(np.squeeze(vvalues[tuple(varslc)]))
                TENSvals.append(np.squeeze(np.array(etimevals[iedv], dtype=np.float)))
                # No need to repeat File name len(varslices)0 times
                # ensfilens.append(filen)
            if ensn == 'mean':
                linevals.append(np.mean(vvalues, axis=tuple(idim)))
            elif ensn == 'median':
                linevals.append(np.median(vvalues, axis=tuple(idim)))
            elif ensn == 'direct':
                if len(values.shape) != 1:
                    print errormsg
                    print '  ' +fname+ ': provided slice:', dimrange,                \
                      "for variable '" + yvarn + "' and '" + datatype +              \
                      "'does not provide a rank-1 value !!"
                    print '    resultant shape:', yvs.shape, 'dimensions:', ydims,   \
                      'fix it !!'
                    quit(-1)
                linevals.append(vvalues)
            else:
                print errormsg
                print '  ' + fname + ": for '" + valskindn + "' statistics '" +      \
                  eSvals[2] + "' not ready !!"
                print '    available ones:', ['mean', 'median']
                quit(-1)
            ltimevals.append(np.squeeze(np.array(etimevals[iedv], dtype=np.float)))
            iedv = iedv + 1
    else:
        print errormsg
        print '  ' + fname + ": kind of values '" + valskindn + "' not ready !!"
        print '    available ones:', ['FromFile', 'FromEns', 'FromIndivEns']
        quit(-1)

    Ndata = len(linevals)
    Nens = len(ENSvals)

    # Times
    dtvals = (maxtval - mintval)/10
    dti = mintval
    dte = maxtval
    tvalsticks = np.arange(dti, dte+dtvals, 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(tvalsticks, timeunit, timekind, timefmt)

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

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

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    valuesvals = [valaxis, axislab, axisunits, [valmin, valmax]]

    # line-characteristics
    expectargs = '[color]:[linetype]:[linewidht]:[markertype]:[markersize]'
    Lvals = datavals.split(':')
    gen.check_arguments('data-line characterisitcs: '+fname,datavals,expectargs,':')

    Lcol = Lvals[0]
    Ltype = Lvals[1]
    Lwidth = Lvals[2]
    Lmarker = Lvals[3]
    Lsizem = Lvals[4]

    if len(labels) != len(linevals):
        print errormsg
        print '  ' + fname + ': There are', len(linevals), 'lines to plot but',      \
          len(labels), 'labels provided !!'
        print '    provided labels:', labels
        quit(-1)

    if outfile:
        onew = NetCDFFile(ofilen, 'w')
        Lstr = 250
    
        # Dimensions
        newdim = onew.createDimension('data', Ndata)
        newdim = onew.createDimension('ensemble', Nens)
        newdim = onew.createDimension('time', dimt)
        newdim = onew.createDimension('Lstring', Lstr)
    
        # Dimension variables
        newvar = onew.createVariable('time', 'f8', ('time'))
        ncvar.basicvardef(newvar, 'time', 'Time', timeunit)
        newvar.setncattr('axis', 'T')
        newvar.setncattr('_CoordinateAxisType', 'Time')
        newvar.setncattr('calendar', 'gregorian')
        newvar[:] = etimevals[0]

        newvar = onew.createVariable('ensfilen', 'c', ('ensemble', 'Lstring'))
        ncvar.basicvardef(newvar, 'ensfilen', 'name of files of the ensemble data',  \
          '-')
        newvals = ncvar.writing_str_nc(newvar, ensfilens, Lstr)
        onew.sync()
    
        # Global attributes
        ncvar.add_global_PyNCplot(onew, mainn, fname, '1.0')

    else:
        onew = None

    drw.plot_TimeEnsembles(linevals, ENSvals, ltimevals, TENSvals, xaxis, yaxis,     \
      valuesvals, Lcol, Ltype, Lwidth, Lmarker, Lsizem, labels, figenskind, timen,   \
      timepos, timelabels, graphtit, legloc, legsiz, kindfig, fign, onew, close)

    if onew is not None:
        ovals = onew.variables['vals']
        if valskindn == 'FromEns':
            eSvals = valskind.split(',')
            ensdims = eSvals[1].split('@')
            ensn = eSvals[2]

            if ensn != 'weightedmean':
                txt = 'values retrieved from all ensembles file as ' + ensn +        \
                  ' along dimensions ' + ','.join(ensdims)
            else:
                newvar = onew.createVariable('weight', 'f', ('ensemble'))
                ncvar.basicvardef(newvar, 'weight', 'weights for the weighted mean', \
                  '-')
                newvar[:] = wghtvs
                txt = 'values retrieved from all ensembles file as weighted mean' +  \
                  ' along dimensions ' + ','.join(ensdims)

            newattr = ncvar.set_attribute(ovals, 'data_origin', txt)

            onew.sync()

        elif valskindn == 'FromIndivEns':
            eSvals = valskind.split(',')
            ensdims = eSvals[1].split('@')
            ensn = eSvals[2]

            txt = 'values retrieved from each ensembles file as ' + ensn +           \
              ' along dimensions ' + ','.join(ensdims)
            newattr = ncvar.set_attribute(ovals, 'data_origin', txt)

            newvar = onew.createVariable('datafilen', 'c', ('data', 'Lstring'))
            ncvar.basicvardef(newvar, 'datafilen', 'name of files for the ensemble ',\
              'data', '-')
            newvals = ncvar.writing_str_nc(newvar, indenfns, Lstr)
            onew.sync()

        onew.sync()
        onew.close()

        print fname + ": succesful writting of output file '" + ofilen + "' !!"

    return

def draw_cycle(ncfile, values):
    """ Function to plot a variale with a circular cycle
      ncfile = '#' list of files [filen];[slice];[tvarn];[varn]
        [filen]: name of the file
        [dimslice]: '|' list of [dimn],[dimrange]
          [dimn]: name of the dimension
          [dimrange]: range for the slice
            * [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
        [tvarn]: name of the variable time ('WRFtime', for times from WRF)
        [varn]: name of the variable to use for the values
      values = [dimxyfmt];[valaxis];[axeskind];[axislab];[axisunits];[rangevals];[cyclevals];[figcyckind];
          [cycticks];[timevals];[labels];[graphtit];[legvalues];[kindfig];[fign];[outfile];[close]
        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each 
            axis (or single 'auto' for 'auto','auto')
          [dxs]: style of x-axis ('auto' for 'pretty')
            'Nfix', values computed at even 'Ndx'
            'Stringlist', a given list of strings
            '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 (for 'Stringlist', '@' list of labels)
          [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)
        [valaxis]: which axes should be used for the data
        [axeskind]: type of axes to be plotted
          'centered': crossed at 0,0 at the center of the figure
          'box': around the figure
        [axislab]: Label for the values-axis ('!' for spaces)
        [axisunits]: units of the values-label
        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
          [val1],[val2]: tacking the provided ',' separated list of desired [val1] and [val2]
          'auto': automatically set up range using minv and maxv
          'extremescentered': extremes automatically centered on zero by computing from data -absmax, absmax; 
            absmax=max(abs(minval),maxval)
          'meancentered': extremes automatically centered on mean by computing from data minv+meanv, maxv-meanv; 
            meanv=(minval + maxval)/2.
        [cyclevals] = [cycle],[cycle0]
          [cycle]= numbers of time steps to use for the cycle
          [cycle0]= initial position of time steps whithin the cycle
        [figcyckind]=[kindname],[valueskind] kind of cycle plot
          'cloud',[color]: values as a cloud of points
            [color]: name of the colorbar to use changing after the end of each cycle ('auto' for 'rainbow')
          'lines',[color],[width],[type]: values a continuous line 
            [color]: name of the colorbar to use changing after the end of each cycle ('auto' for 'rainbow')
            [width]: width of the line to use for all lines ('auto' for 0.5)
            [type]: type of the line to use for all lines ('auto' for '-')
        [cycticks]= [cycpos]@[cyclab] characteristics of the ticks for the cycle
          [cycpos]: ',' list of positions for the ticks (less than cycle/2)
          [cyclab]: ',' list of labels for the ticks (less than cycle/2)
        [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
        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
        [graphtit]: title of the figure '!' for spaces
        [legvalues]=[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)
        [kindfig]: kind of output figure (png, pdf, ps)
        [fign]: name of the figure (without extension)
        [close]: whether figure should be close or not
    """
    fname = 'draw_cycle'

    if values == 'h':
        print fname + '____________________________________________________________'
        print draw_cycle.__doc__
        quit()

    expectargs = '[dimxyfmt];[valaxis];[axeskind];[axislab];[axisunits];' +          \
      '[rangevals];[cyclevals];[figcyckind];[cycticks];[timevals];[labels];'+ \
      '[graphtit];[legvalues];[kindfig];[fign];[close]'
    drw.check_arguments(fname,values,expectargs,';')

    dimxyfmt = values.split(';')[0]
    valaxis = values.split(';')[1]
    axiskind = values.split(';')[2]
    axislab = values.split(';')[3].replace('!',' ')
    axisunits = values.split(';')[4]
    rangevals = values.split(';')[5]
    cyclevals = values.split(';')[6]
    figcyckind = values.split(';')[7]
    cycticks = values.split(';')[8].split('@')
    timevals = values.split(';')[9]
    labels = gen.str_list(values.split(';')[10].replace('!', ' '), ',')
    graphtit = values.split(';')[11].replace('!',' ')
    legvalues = values.split(';')[12]
    kindfig = values.split(';')[13]
    fign = values.split(';')[14]
    close = gen.Str_Bool(values.split(';')[15])

    # cycle
    cycle = int(cyclevals.split(',')[0])
    cycle0 = int(cyclevals.split(',')[1])

    # time-values
    expectargs = '[timen]|[units]|[kind]|[tfmt]'
    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')

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

    # files
    valfiles = gen.str_list(ncfile, '#')

    values = []
    timevalues = []

    mintval = gen.fillValueF
    maxtval = -gen.fillValueF
    minvval = gen.fillValueF
    maxvval = -gen.fillValueF

    ifile = 0
    dimt = -gen.fillValueF
    for fdv in valfiles:
        fvals = fdv.split(';')
        expectedargs = '[filen];[slice];[tvarn];[varn]'
        gen.check_arguments('filevals: '+fname, fdv, expectedargs, ';')
        filen = fvals[0]
        dimrange = fvals[1]
        tvarn = fvals[2]
        yvarn = fvals[3]

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

        onc = NetCDFFile(filen, 'r')
        if tvarn == 'WRFtime':
            datesv = []
            if tvarn == 'WRFtime':
                fdates = onc.variables['Times'][:]
                for it in range(fdates.shape[0]):
                    datesv.append(gen.datetimeStr_conversion(fdates[it,:],           \
                      'WRFdatetime','cfTime,' + timeunit))
            tvs = np.array(datesv, dtype=np.float)
            tunitsvar = timeunit
        else:
            if not onc.variables.has_key(tvarn):
                print errormsg
                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
                  tvarn + "' for the time-values !!"
                print '    available ones:', onc.variables.keys()
                onc.close()
                quit(-1)
            otvar = onc.variables[tvarn]
            tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
            tunitsvar = otvar.units

        if not onc.variables.has_key(yvarn):
            print errormsg
            print '  ' +fname+ ': file "' +filen+ "' does not have variable '" +     \
              yvarn + "' for the y-values !!"
            print '    available ones:', onc.variables.keys()
            onc.close()
            quit(-1)

        oyvar = onc.variables[yvarn]
        yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
        if len(yvs.shape) != 1:
            print errormsg
            print '  ' + fname + ': Wrong slice. There must be a 1D variable!!'
            print '    current shape:', yvs.shape
            quit(-1)

        # Referring all times to the same reference time!
        reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)

        onc.close()

        if len(reftvals) > dimt: dimt = len(reftvals)

        reftn = reftvals.min()
        reftx = reftvals.max()
        if reftn < mintval: mintval = reftn
        if reftx > maxtval: maxtval = reftx
        refvn = yvs.min()
        refvx = yvs.max()
        if refvn < minvval: minvval = refvn
        if refvx > maxvval: maxvval = refvx

        values.append(yvs)
        timevalues.append(reftvals)

        ifile = ifile + 1

    # cycle ticks
    pos=cycticks[0].split(',')
    ll=cycticks[1].split(',')
    ctick = []
    clab = []
    for ip in range(len(pos)):
        ctick.append(np.float(pos[ip]))
        clab.append(gen.latex_text(ll[ip]))

    # Times
    dtvals = (maxtval - mintval)/10
    dti = mintval
    dte = maxtval
    tvalsticks = np.arange(dti, dte+dtvals, 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(tvalsticks, timeunit, timekind, timefmt)

    # ranges
    rng = gen.minmax_range(minvval, maxvval, rangevals)

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

    # Legend 
    legloc, legsiz = drw.legend_values(legvalues,'|')

    drw.plot_cycle(values, timevalues, xaxis, yaxis, valaxis, axiskind, axislab,     \
      axisunits, rng, cycle, cycle0, figcyckind, labels, ctick, clab, timen, timepos,\
      timelabels, graphtit, legloc, legsiz, kindfig, fign, close)

    return

def draw_multi_2D_shad(ncfiles, values, axfig=None, fig=None):
    """ plotting multiple 2D fields with same projection with shading and sharing colorbar
    draw_multi_2D_shad(ncfile, values, varn)
      ncfiles= ';' list of files to use as [filen]@[varn]@[dimvals]
        [filen]: name of the file
        [varn]: name of the variable in the file 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
      values=[vnamefs]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[sminv],[smaxv]:
       [kindfig]:[reverse]:[mapv]:[labels]:[Nrow]:[Ncol]:[globaltitle]:[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [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)
        [kindfig]: kind of figure output file: png, pdf, ...
        [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
        [labels]: ',' list of consecutive labels for each individual panel ('!' for spaces)
        [Nrow]: number of rows in the figure
        [Ncol]: number of columns in the figure
        [globaltitle]: global title of the figure ('!' for spaces)
        [close]: Whether figure should be finished or not
    """

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

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

    vnamesfig = values.split(':')[0]
    vdimxn = values.split(':')[1]
    vdimyn = values.split(':')[2]
    dimxyf = values.split(':')[3]
    colorbarvals = values.split(':')[4]
    shadminmax = values.split(':')[5]
    figkind = values.split(':')[6]
    revals = values.split(':')[7]
    mapvalue = values.split(':')[8]
    labels = values.split(':')[9].split(',')
    Nrow = int(values.split(':')[10])
    Ncol = int(values.split(':')[11])
    globaltitle = values.split(':')[12].replace('!', ' ')
    close = gen.Str_Bool(values.split(':')[13])

    fvds = ncfiles.split(';')
    lvalshad = []

    for fvd in fvds:
        ncfile = fvd.split('@')[0]
        varn = fvd.split('@')[1]
        dimvals = fvd.split('@')[2]

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

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

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

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

        valshad, dimsshad = drw.slice_variable(objvars,                              \
          dimvals.replace('|',':').replace(',','|'))
        lvalshad.append(valshad)

        # Getting variable information from first file
        if fvd == fvds[0]:
            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.multi_plot_2D_shadow(lvalshad, odimxv, odimyv, odimxu, odimyu, xaxis, yaxis, \
      dimnamesv, colormapv, shading_nx, varunits, figkind, revals, mapvalue, labels, \
      Nrow, Ncol, globaltitle, close)

    return
#python drawing.py -o draw_multi_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|0;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|1;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|2;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|3' -S 'tas:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:0!UTC,1!UTC,2!UTC,3!UTC:2:2:tas!at!2001-11-11:True'

def movie_2D_shad(ncfile, values, varn, axfig=None, fig=None):
    """ creation of a movie with shading
    movie_2D_shad(ncfile, values, varn)
      ncfile= file to use
      values=[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[sminv],[smaxv]:[figt]:
       [kindfig]:[reverse]:[mapv]:[moviedim]:[fps]:[kmov]
        [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)
        [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
        [movievals] = [moviedim],[movivar] way to get values for the movie
          [moviedime]: name of the dimension to get the movie (following outcome from [dimvals])
          [movievar]: name of the variable to get the values
        [framelabels]: values for the production of the labels of each frame
          * 'varVal',[HeadTit],[TailTit],[fmt]: Following direct values from variable as:
            [HeadTit] + ' ' + [varValue] + ' ' + [TailTit]
              [HeadTit]: Head of title ('!', for spaces)
              [TailTit]: title of title ('!', for spaces)
              [fmt]: format of the values of the variable in the title (C-like and LaTeX-like combined)
          * 'listtit',[Ftitles]: Providing manually title for each frame
              [Ftitle]: '@' separated list of titles ('!', for titles)
          * 'CFdate',[datefmt]: Just title with the date (assuming CF-time compilant variable)
              [tfmt]: format of the date (C-like and LaTeX-like combined)
          * 'WRFdate',[datefmt]: Just title with the date (assuming WRF time variable)
              [tfmt]: format of the date (C-like and LaTeX-like combined)
        [fps]: frames per second of the output movie
        [kmov]: kind of movie (mp4, ....)
      varn= [varsn] name of the variable to plot with shading
    """
    fname = 'movie_2D_shad'
    if values == 'h':
        print fname + '_____________________________________________________________'
        print movie_2D_shad.__doc__
        quit()

    expectargs = '[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyf]:[colbarvals]:' +    \
      '[sminv],[smaxv]:[kindfig]:[reverse]:[mapv]:[movidime]:[framelabels]:[fps]' +  \
      ':[kmov]'
 
    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]
    figkind = values.split(':')[7]
    revals = values.split(':')[8]
    mapvalue = values.split(':')[9]
    movievals = values.split(':')[10].split(',')
    framelabelS = values.split(':')[11]
    fps = int(values.split(':')[12])
    kmov = values.split(':')[13]

    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 + '" !!'
        varns = sorted(objsf.variables.keys())
        print '    available ones:', varns
        quit(-1)

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

    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
    dimnamesv = [vdimxn, vdimyn]

    # Movie variable
    moviedim = movievals[0]
    movievar = movievals[1]
    idd = 0
    for dn in objvars.dimensions:
        if dn == moviedim: 
            NumDimT = idd
        break
        idd = idd + 1 

    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

    if not objsf.variables.has_key(movievar):
        oncvars = objsf.variables.keys()
        oncvars.sort()
        print errormsg
        print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +    \
          movievar + "' to get from the values for the frames!!"
        print '    available ones:', oncvars
        quit(-1)
    omovievar = objsf.variables[movievar]
    movievarv, dimsmov = drw.slice_variable(omovievar, dimvals.replace(',','|'))

    # Labels for frames
    framelabels = []
    if framelabelS[0:6] == 'varVal':
        HeadTit = framelabelS.split(',')[1]
        TailTit = framelabelS.split(',')[2]
        fmt = framelabelS.split(',')[3]

        if len(movievarv.shape) != 1:
            print errormsg
            print '  ' + fname + ": for frame labels type 'varVal' is required a " + \
              " rank 1 variable !!"
            print "    variable '" + movievar + "' shape:", vn.shape
            quit(-1)
        dimt = movievarv.shape[0]
        for it in range(dimt):
            framelabels.append(gen.latex_tex(HeadTit) + ' ' +                        \
              '{}'.format(movievarv[it]) + ' ' + gen.latex_tex(TailTit))

    elif framelabelS[0:7] == 'listtit':
        frameS = framelabelS.split(',')[1].split('@')
        dimt = len(frameS)
        for it in range(dimt):
            framelabels.append(gen.latex_tex(frameS[it].replace('!', ' ')))

    elif framelabelS[0:6] == 'CFdate':
        import datetime as dt
        tfmt = framelabelS.split(',')[1]
        if len(movievarv.shape) != 1:
            print errormsg
            print '  ' + fname + ": for frame labels type 'CFdate' is required a " + \
              " rank 1 variable !!"
            print "    variable '" + movievar + "' shape:", movievarv.shape
            quit(-1)
        tunits = omovievar.getncattr('units')
        tcalendar = omovievar.getncattr('calendar')
        datesv = gen.netCDFdatetime_realdatetime(tunits, tcalendar, movievarv[:])
        dimt = omovievar.shape[0]
        for it in range(dimt):
            dateV = dt.datetime(datesv[it][0], datesv[it][1], datesv[it][2],         \
              datesv[it][3], datesv[it][4], datesv[it][5])
            framelabels.append(dateV.strftime(tfmt))

    elif framelabelS[0:7] == 'WRFdate':
        import datetime as dt
        tfmt = framelabelS.split(',')[1]
        if len(movievarv.shape) != 2:
            print errormsg
            print '  ' + fname + ": for frame labels type 'WRFtime' is required a "+ \
              " rank 2 variable !!"
            print "    variable '" + movievar + "' shape:", movievarv.shape
            quit(-1)
        timev, tunits = ncvar.compute_WRFtime(movievarv[:])
        datesv = gen.netCDFdatetime_realdatetime(tunits, 'standard', timev)
        dimt = omovievar.shape[0]
        for it in range(dimt):
            dateV = dt.datetime(datesv[it][0], datesv[it][1], datesv[it][2],         \
              datesv[it][3], datesv[it][4], datesv[it][5])
            framelabels.append(dateV.strftime(tfmt))

    drw.movie_2D_shadow(valshad, NumDimT, vnamesfig, odimxv, odimyv, odimxu, odimyu, \
      xaxis, yaxis, dimnamesv, colormapv, shading_nx, varunits, framelabels,         \
      figkind, revals, mapvalue, fps, kmov)

    return

#python drawing.py -o movie_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00' -S 'tas:west_east|-1,south_north|-1,Time|-1:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:Time,Times:WRFdate,$%d^{%H}$:15:mp4' -v T2

def draw_SkewT(ncfile, values, varname):
    """ creation of a SkewT-logP diagram using matplotlib's API example  
      https://matplotlib.org/examples/api/skewt.html (skewt.py, included as external python)
    draw_SkewT(ncfile, values, varn)
      ncfile= file to use
      values = [dimvals]:[taminv],[tamaxv]:[presminv],[presmaxv]:[figt]:[kindfig]:
        [close]
        [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
        [taminv],[tamaxv]: minimum and maximum of temperatures to plot [C] 
          ('auto' for -50,50)
        [presminv],[presmaxv]: minimum and maximum of pressures to plot [hPa]
          ('auto' for 100.,1020.)
        [figt]: title of figure ('!' for spaces)
        [kindfig]: kind of graphical output (ps, png, pdf)
        [close]: wether figure should be closed or not
      varn= [tavarn],[tdavarn],[presvarn]
    """
    fname = 'draw_SkewT'

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

    expectargs = '[dimvals]:[taminv],[tamaxv]:[presminv],[presmaxv]:[figt]:' +       \
      '[kindfig]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    # Variables
    varns = varname.split(',')
    if len(varns) != 3:
        print errormsg
        print '  ' +fname+ ": requires 3 name of variables as '[tavarn],[tdavarn]" + \
          ",[presvarn]' !!"
        print "    variables provided: '" + varname + "' "
        quit(-1)

    dimvals= values.split(':')[0].replace('|',':')
    if values.split(':')[1] != 'auto':
        tanx = gen.str_list_k(values.split(':')[1], ',', 'np.float')
    else:
        tanx = [-50.,50.]
    if values.split(':')[2] != 'auto':
        presnx = gen.str_list_k(values.split(':')[2], ',', 'np.float')
    else:
        presnx = [100.,1020.]
    figt = values.split(':')[3].replace('!',' ')
    kindfig = values.split(':')[4]
    close = gen.Str_Bool(values.split(':')[5])

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

    ota = onc.variables[varns[0]]
    otda = onc.variables[varns[1]]
    opres = onc.variables[varns[2]]

    # Getting values
    tavals, tadims = drw.slice_variable(ota, dimvals.replace(',','|'))
    tdavals, tdadims = drw.slice_variable(otda, dimvals.replace(',','|'))
    presvals, presdims = drw.slice_variable(opres, dimvals.replace(',','|'))

    # Expected masked values
    if type(tavals) != type(gen.mamat):
        tavals = ma.masked_array(tavals)
    if type(tdavals) != type(gen.mamat):
        tdavals = ma.masked_array(tdavals)
    if type(presvals) != type(gen.mamat):
        presvals = ma.masked_array(presvals)

    drw.plot_SkewT(tavals, tdavals, presvals, tanx, presnx, figt, kindfig, close)

    onc.close()

    return

#filen='/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc'
#values='time|0:auto:auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes'
#varn='ta,tda,pres'
#draw_SkewT(filen, values, varn)


def draw_multi_SkewT(ncfiles, values):
    """ creation of a SkewT-logP diagram with multiple lines using matplotlib's API example
      https://matplotlib.org/examples/api/skewt.html (skewt.py, included as external python)
    draw_SkewT(ncfile, values, varn)
      ncfiles = ';' list of [filen]:[dimvals]:[varn],[presvarn] file and variables to use 
        from each file
        [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
        [varn]: name of the variable to plot [C]
        [presvarn]: name of the variable with the pressures of [varn] [Pa]
      values = [taminv],[tamaxv]:[presminv],[presmaxv]:[kindgraph]:[legvals]:[figt]:
        [kindfig]:[close]
        [taminv],[tamaxv]: minimum and maximum of temperatures to plot [C] 
          ('auto' for -50,50)
        [presminv],[presmaxv]: minimum and maximum of pressures to plot [hPa]
          ('auto' for 100.,1020.)
        [kindgraph]: kind of graphic to produce. To select from:
          'multilines'![labels]![collines]![kindlines]![kindmarkers]![widthlines]
            [labels] = ',' separated list of labels for each file ('None' for no 
              label)
            [collines] = ',' separated list of colors ('#RRGGBB' values) of lines for
              each file (1 value for all the lines the same)
            [kindmarkers] = ';' separated list of marker types (matplolib values) for
              each file (1 value for all the lines the same)
            [kindlines] = ';' separated list of line types (matplolib values) of 
              lines for each file (1 value for all the lines the same)
            [widthlines] = ';' separated list of line widths (matplolib values) of 
              lines for each file (1 value for all the lines the same)
        [legvals]=[loclegend],[fonstsize] values for the legend
          [locleg]: location of the legend (0, automatic)
            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)
        [figt]: title of figure ('!' for spaces)
        [kindfig]: kind of graphical output (ps, png, pdf)
        [close]: wether figure should be closed or not
    """
    fname = 'draw_SkewT'

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

    availgraph = ['multilines']

    expectargs = '[taminv],[tamaxv]:[presminv],[presmaxv]:[figt]:[kindgraph]:' +     \
      '[legvals]:[kindfig]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    if values.split(':')[0] != 'auto':
        tanx = gen.str_list_k(values.split(':')[0], ',', 'np.float')
    else:
        tanx = [-50.,50.]
    if values.split(':')[1] != 'auto':
        presnx = gen.str_list_k(values.split(':')[1], ',', 'np.float')
    else:
        presnx = [100.,1020.]
    kindgraph = values.split(':')[2]
    legv = drw.legend_values(values.split(':')[3], ',')
    figt = values.split(':')[4].replace('!',' ')
    kindfig = values.split(':')[5]
    close = gen.Str_Bool(values.split(':')[6])

    filevals = ncfiles.split(';')
    Nfiles = len(filevals)

    # Getting graphic parameters
    kindgraphv = kindgraph.split('!')
    kgraphS = kindgraphv[0]
    kgraphv = {}
    if kgraphS == 'multilines':
        kgraphv['labels'] = kindgraphv[1].split(',')
        kgraphv['collines'] = gen.str_list_rep(kindgraphv[2], ',', Nfiles)
        kgraphv['kindlines'] = gen.str_list_rep(kindgraphv[3], ',', Nfiles)
        kgraphv['kindmarkers'] = gen.str_list_rep(kindgraphv[4], ';', Nfiles)
        kgraphv['widthlines'] = gen.str_list_rep(kindgraphv[5], ',', Nfiles)
    else:
        print errormsg
        print '  ' + fname + ": graphic type '" + kindgraphv[0] + "' not ready !!"
        print '    available ones:', availgraph
        quit(-1)

    vavals = {}
    presvals = {}
    ifile = 0
    # Getting values to plot
    for fileval in filevals:
        ncfile = fileval.split(':')[0]
        dimvals= fileval.split(':')[1].replace('|',':')
        varname = fileval.split(':')[2]

        # Variables
        varns = varname.split(',')
        if len(varns) != 2:
            print errormsg
            print '  ' +fname+ ": requires 2 name of variables as '[varn]," +      \
              "[presvarn]' !!"
            print "    variables provided: '" + varname + "' "
            quit(-1)

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

        onc = NetCDFFile(ncfile, 'r')
        print '  ' + fname + ": getting from file '" + ncfile + "' variables:" ,     \
          varns, 'with slice:', dimvals
        for varn in varns:
            if not onc.variables.has_key(varn):
                print errormsg
                print ' ' + fname + ": file '" + ncfile + "' does not have " +       \
                  "variable '" + varn + "' !!"
                print '    available ones:', onc.variables.keys()
                quit(-1)

        ov = onc.variables[varns[0]]
        opres = onc.variables[varns[1]]
        otime = onc.variables['time']

        # Getting values
        vals, valdims = drw.slice_variable(ov, dimvals.replace(',','|'))
        pvals, presdims = drw.slice_variable(opres, dimvals.replace(',','|'))
        tvals, tdims = drw.slice_variable(otime, dimvals.replace(',','|'))

        # Expected masked values
        if type(vals) != type(gen.mamat):
            vavals[ifile] = ma.masked_array(vals)
        else:
            vavals[ifile] = vals
        if type(pvals) != type(gen.mamat):
            presvals[ifile] = ma.masked_array(pvals)
        else:
            presvals[ifile] = pvals
        ifile = ifile + 1

    drw.plot_multi_SkewT(vavals, presvals, tanx, presnx, kgraphS, kgraphv, legv,     \
      figt, kindfig, close)

    onc.close()

    return

#filen='/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc:pres|-1,time|0:ta,pres;' + \
#  '/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc:pres|-1,time|0:tda,pres'
#values='auto:auto:multilines!ta,tda!#6464FF,#FF6464!-!,!2:0,auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes'
#draw_multi_SkewT(filen, values)

def draw_2D_shad_contdisc(ncfiles, values, axfig=None, fig=None):
    """ plotting one continuous fields with shading and another discrete one with points
    draw_2D_shad_contdisc(ncfile, values)
      ncfiles= [contfilen];[contvarn];[dimxvarn];[dimyvarn];[dimvals]@[discfilen];
          [discvarn];[dimxvarn];[dimyvarn];[dimvals] files and variables to use
        [contfilen]: name of the file with the continuous varible
        [contvarn]: name of the continuos variable
        [dimxvarn]: name of the variable with values for the x-dimension
        [dimyvarn]: name of the variable with values for the y-dimension
        [dimvals]: ',' list of [dimname]|[value] values to slice the variable:
            * [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
        [discfilen]: name of the file with the discrete varible
        [discvarn]: name of the discrete variable
        * NOTE: limits of the graph will be computed from the continuous variable
      values=[vnamefs]:[dvarxn],[dvaryn]:[dimxyfmt]:[colorbarvals]:[sminv],[smaxv]:
       [discvals]:[figt]:[kindfig]:[reverse]:[mapv]:[plotrange]:[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [dvarxn],[dvaryn]: name of the dimensions for the final x-axis and y-axis at 
          the figure (from contfilen)
        [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' ['auto'], 'horizontal')
          * NOTE: single 'auto' for 'rainbow,%6g,vertical'
        [smin/axv]: minimum and maximum values for the shading or string for each for:
          '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)
        [discvals]= [type],[size],[lwidth],[lcol] characteristics of the points for the discrete field
          [type]: type of point. Any marker from matoplib must be filled !
          [size]: size of point 
          [lwidth]: width of the line around the point
          [lcol]: color of the line around the point
          'auto': for [type]='o', [size]=5, [lwdith]=0.25, [lcol]='#000000'
        [figt]: title of the figure ('!' for spaces)
        [kindfig]: kind of figure output (ps, png, pdf)
        [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
        [plotrange]: range of the plot
          'strict': map covers only the minimum and maximum lon,lats from the 
            locations of the discrtete points
          'sponge,'[dlon],[dlat]: map covers an extended [dlon],[dlat] from the 
            minimum and maximum lon,lats from the locations of the discrtete points
          'fullcontinuous': map covers all the shadding area
          'lonlatbox,[lonSW],[latSW],[lonNE],[latNE]': plotted map only covers a lon,lat box
        [close]: Whether figure should be finished or not
    """

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

    expectargs = '[vnamefs]:[dvarxn],[dvaryn]:[dimxyfmt]:[colorbarvals]:[sminv],' +  \
      '[smaxv]:[discvals]:[figt]:[kindfig]:[reverse]:[mapv]:[plotrange]:[close]'
 
    drw.check_arguments(fname,values,expectargs,':')

    vnamesfig = values.split(':')[0]
    [dvarxn, dvaryn] = values.split(':')[1].split(',')
    dimxyf = values.split(':')[2]
    colorbarvals = values.split(':')[3]
    shadminmax = values.split(':')[4]
    discvals = values.split(':')[5]
    figt = values.split(':')[6].replace('!',' ')
    kindfig = values.split(':')[7]
    revals = values.split(':')[8]
    mapvalue = values.split(':')[9]
    plotrange = values.split(':')[10]
    close = gen.Str_Bool(values.split(':')[11])

    ncs = ncfiles.split('@')
    filesinf = {}
    ifile = 0
    for nc in ncs:
        if ifile == 0:
            hfn = 'cont'
        else:
            hfn = 'disc'

        filesinf[hfn + 'filen'] = nc.split(';')[0]
        filesinf[hfn + 'varn'] = nc.split(';')[1]
        filesinf[hfn + 'dimxvn'] = nc.split(';')[2]
        filesinf[hfn + 'dimyvn'] = nc.split(';')[3]
        filesinf[hfn + 'dimvals'] = nc.split(';')[4].replace('|',':')
        ifile = ifile + 1

    for hfn in ['cont', 'disc']:
        ncfilen = filesinf[hfn + 'filen']
        varn = filesinf[hfn + 'varn']
        vdimxn = filesinf[hfn + 'dimxvn']
        vdimyn = filesinf[hfn + 'dimyvn']
        dimvals = filesinf[hfn + 'dimvals']

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

        onc = NetCDFFile(ncfilen, 'r')

        if  not onc.variables.has_key(varn):
            print errormsg
            print '  ' + fname + ": '" + hfn + "' file '" + ncfilen +                \
              "' does not have variable '" + varn + "' !!"
            varns = sorted(onc.variables.keys())
            print '    available ones:', varns
            quit(-1)

        # Variables' values
        ovar = onc.variables[varn]
        vals, dims = drw.slice_variable(ovar, dimvals.replace(',','|'))

        # Values have to be 2D
        if hfn == 'cont' and len(vals.shape) != 2:
            print errormsg
            print '  ' + fname + ": values have to be 2D !!"
            print '    provided shape:', vals.shape, 'for slice:', dimvals
            quit(-1)

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

        # dimensions
        dimnamesv = [vdimxn, vdimyn]
        if  not onc.variables.has_key(vdimxn):
            print errormsg
            print '  ' + fname + ": '" + hfn + "' file '" + ncfilen +                \
              "' does not have x-dimension variable '" +  vdimxn + "' !!"
            varns = sorted(onc.variables.keys())
            print '    available ones:', varns
            quit(-1)
        if  not onc.variables.has_key(vdimyn):
            print errormsg
            print '  ' + fname + ": '" + hfn + "' file '" + ncfilen +                \
              "' does not have y-dimension variable '" +  vdimyn + "' !!"
            varns = sorted(onc.variables.keys())
            print '    available ones:', varns
            quit(-1)

        objdimx = onc.variables[vdimxn]
        objdimy = onc.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 = '-'

        odimxv0, odimyv0 = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:],                \
          objdimx.dimensions, objdimy.dimensions, dimvals.replace(':','|').split(','),\
          False)

        # Some statistics
        vn = np.min(vals)
        vx = np.max(vals)
        dxn = np.min(odimxv0)
        dxx = np.max(odimxv0)
        dyn = np.min(odimyv0)
        dyx = np.max(odimyv0)

        print gen.infmsg
        print '  ' + fname + ": for '" + hfn + "' ________"
        print '    values min:', vn, 'max:', vx
        print '    dimx min:', dxn, 'max:', dxx
        print '    dimy min:', dyn, 'max:', dyx
        if dxn == 0. and dxx == 0. and dyn == 0. and dyx == 0.:
            print errormsg
            print '  ' + fname + ': wrong boundaries from continuos field !!'
            print '    all are zero !!'
            quit(-1)

        if hfn == 'cont':
            if not gen.searchInlist(onc.dimensions, dvarxn):
                print errormsg
                print '  ' + fname + ": file '" + ncfilen + "' does not have " +     \
                  "dimension '" + dvarxn + "' for final x-axis in figure !!"
                print '     available ones: ', onc.dimensions.keys()
                quit(-1)
            if not gen.searchInlist(onc.dimensions, dvaryn):
                print errormsg
                print '  ' + fname + ": file '" + ncfilen + "' does not have " +     \
                  "dimension '" + dvaryn + "' for final y-axis in figure !!"
                print '     available ones: ', onc.dimensions.keys()
                quit(-1)

            # Getting the right shape of dimensions
            gdimx = len(onc.dimensions[dvarxn])
            gdimy = len(onc.dimensions[dvaryn])

            if vals.shape[1] == gdimx: contv = vals[:]
            else: contv = vals[:].transpose()

            odxv = np.zeros((gdimy,gdimx), dtype=np.float)
            odyv = np.zeros((gdimy,gdimx), dtype=np.float)

            if len(odimxv0.shape) == 2:
                if odimxv0.shape[1] == gdimx: odxv = odimxv0[:]
                else: odxv = odimxv0.transpose()
            else:
                for k in range(gdimy):
                    odxv[k,:] = odimxv0[:]

            if len(odimyv0.shape) == 2:
                if odimyv0.shape[0] == gdimy: odyv = odimyv0[:]
                else: odyv = odimyv0.transpose()
            else:
                for k in range(gdimx):
                    odyv[:,k] = odimyv0[:]

            diminfo = {}
            diminfo['units'] = [odimxu, odimyu]
            diminfo['names'] = [gen.variables_values(vdimxn)[0],                     \
              gen.variables_values(vdimyn)[1]]
            varinfo = {}
            varinfo['units'] = varunits
            varinfo['name'] = vnamesfig

            # Absolute xtremes for the plot
            absxn = dxn
            absxx = dxx
            absyn = dyn
            absyx = dyx
            contxynx = [dxn, dxx, dyn, dyx]

        else:
            discvarv = []
            discx = []
            discy = []
            # Assuming that discrete values are masked
            if type(vals) != type(gen.mamat):
                madiscvarv = ma.masked_array(vals)
            else:
                madiscvarv = vals

            if len(vals.shape) == 1:
                if type(madiscvarv.mask) == type(np.True_):
                    discvarv = list(madiscvarv[:])
                    discx = list(odimxv0[:])
                    discy = list(odimyv0[:])
                else:
                    for i in range(vals.shape[0]):
                        if not madiscvarv.mask[i]:
                            discvarv.append(madiscvarv[i])
                            discx.append(odimxv0[i])
                            discy.append(odimyv0[i])

            elif len(vals.shape) == 2:
                # Getting 2D dimensions
                [d2Dx, d2Dy] = np.meshgrid(odimxv0, odimyv0)

                # Checking for flipping axis?
                if d2Dx.shape[0] == vals.shape[1] and d2Dx.shape[1] == vals.shape[0]:
                    print '  rotating values !'
                    #madiscvarv = madiscvarv.transpose()
                    d2Dx = d2Dx.transpose()
                    d2Dy = d2Dy.transpose()

                # vals have to be 2D otherwise... ?
                dx = madiscvarv.shape[1]
                dy = madiscvarv.shape[0]
                for j in range(dy):
                    for i in range(dx):
                        if not madiscvarv.mask[j,i]:
                            discvarv.append(madiscvarv[j,i])
                            discx.append(d2Dx[j,i])
                            discy.append(d2Dy[j,i])
            else:
                # Values have to be 1D or 2D
                print errormsg
                print '  ' + fname + ": disc. values have to be 1D or 2D !!"
                print '    provided shape:', vals.shape, 'for slice:', dimvals
                quit(-1)

            Ndiscvals = len(discvarv)
            print '    getting:', Ndiscvals, 'discrete values'
            discv = np.zeros((Ndiscvals,3), dtype=np.float)
            discv[:,0] = discx[:]
            discv[:,1] = discy[:]
            discv[:,2] = discvarv[:]

            # Absolute xtremes for the plot
            absxn = np.max([absxn,dxn])
            absxx = np.min([absxx,dxx])
            absyn = np.max([absyn,dyn])
            absyx = np.min([absyx,dyx])

        onc.close()

    availplotrng = ['strict', 'sponge', 'fullcontinuous']
    if plotrange[0:6] == 'strict': 
        graphnx = [absxn, absxx, absyn, absyx]
    elif plotrange[0:6] == 'sponge':
        dlon = np.float(plotrange.split(',')[1])
        dlat = np.float(plotrange.split(',')[2])
        graphnx = [absxn-dlon, absxx+dlon, absyn-dlat, absyx+dlat]
    elif plotrange[0:14] == 'fullcontinuous':
        graphnx = contxynx
    elif plotrange[0:9] == 'lonlatbox':
        lonSW = np.float(plotrange.split(',')[1])
        latSW = np.float(plotrange.split(',')[2])
        lonNE = np.float(plotrange.split(',')[3])
        latNE = np.float(plotrange.split(',')[4])
        graphnx = [lonSW, lonNE, latSW, latNE]
    else:
        print errormsg
        print '  ' + fname + ": plot range '" + plotrange + "' not ready !!"
        print '    available ones:', availplotrng
        quit(-1)

    print "  '" + plotrange + "' limits of the graphic:", graphnx

    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 discvals == 'auto':
        discinfo = ['o', 5., 0.25, '#000000']
    else:
        discinfo = [discvals.split(',')[0], np.float(discvals.split(',')[1]),        \
          np.float(discvals.split(',')[2]), discvals.split(',')[3]]

    if mapvalue == 'None': mapvalue = None

    if colorbarvals == 'auto': colorbarvals = 'rainbow,auto,auto'
    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_2Dshad_obssim(discv, contv, odxv, odyv, revals, diminfo, xaxis, yaxis,  \
      colormapv, shading_nx, varinfo, discinfo, mapvalue, graphnx, figt, kindfig,    \
      close)

    return

#contfilen = '/home/lluis/estudios/ChemGBsAs/tests/199501/simout_snddiags.nc;ta;time;pres;time|-1,pres|-1'
#discfilen = '/home/lluis/estudios/ChemGBsAs/tests/199501/obs/snd/UWyoming_snd_87576.nc;ta;time;pres;time|-1,pres|-1'

#values = 'ta:time,bottom_top:Vfix,auto,3600.,auto,Vfix,auto,50.,auto:auto:Srange,Srange:o,5.:obs!&!sim!Ezeiza!airport!sounding:pdf:flip@y:None:yes'

#draw_2D_shad_contdisc(contfilen+'@'+discfilen, values, axfig=None, fig=None)
    
def draw_2D_shad_contdisc_time(ncfiles, values, axfig=None, fig=None):
    """ plotting one continuous fields with shading and another discrete one with 
    points with a time-axis
    draw_2D_shad_contdisc_time(ncfile, values)
      ncfiles= [contfilen];[contvarn];[dimtvarn];[dimvvarn];[dimvals]@[discfilen];
          [discvarn];[dimtvarn];[dimvvarn];[dimvals] files and variables to use
        [contfilen]: name of the file with the continuous varible
        [contvarn]: name of the continuos variable
        [dimtvarn]: name of the variable with values for the time-dimension
        [dimvvarn]: name of the variable with values for the variable-dimension
        [dimvals]: ',' list of [dimname]|[value] values to slice the variable:
            * [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
        [discfilen]: name of the file with the discrete varible
        [discvarn]: name of the discrete variable
        * NOTE: limits of the graph will be computed from the continuous variable
      values=[vnamefs];[varaxis];[timevals];[dimvfmt];[colorbarvals];[sminv],[smaxv];
       [discvals];[figt];[kindfig];[reverse];[mapv];[close]
        [vnamefs]: Name in the figure of the variable to be shaded
        [varaxis]: axis in the figure for the variable-axis ('x' or 'y')
        [timevals]: [units]|[kind]|[tfmt]|[label] time labels characteristics
          [units]: units string according to CF conventions ([tunits] since 
            [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces), 
            'auto' for minutes!since!1949-12-01!00:00:00
          [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 (combination of 'C'-style values and LaTeX)
          [label]: label at the graph ('!' for spaces, combination of 'C'-style 
            values and LaTeX)
        [dimvfmt]=[[dvs],[dvf],[Ndv],[ordv]: format of the values at variable-axis 
          (or 'auto')
          [dvs]: style of variable-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 var-axis ('auto' for '%5g')
          [Ndv]: Number of ticks at the var-axis ('auto' for 5)
          [ordv]: angle of orientation of ticks at the var-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' ['auto'], 'horizontal')
          * NOTE: single 'auto' for 'rainbow,%6g,vertical'
        [smin/axv]: minimum and maximum values for the shading or string for each for:
          '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)
        [discvals]= [type],[size],[lwidth],[lcol] characteristics of the points for the discrete field
          [type]: type of point. Any marker from matoplib must be filled !
          [size]: size of point 
          [lwidth]: width of the line around the point
          [lcol]: color of the line around the point
          'auto': for [type]='o', [size]=5, [lwdith]=0.25, [lcol]='#000000'
        [figt]: title of the figure ('!' for spaces)
        [kindfig]: kind of figure output (ps, png, pdf)
        [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
    """

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

    expectargs = '[vnamefs];[varaxis];[timevals];[dimvfmt];[colorbarvals];' +       \
       '[sminv],[smaxv];[discvals];[figt];[kindfig];[reverse];[mapv];[close]'

    drw.check_arguments(fname,values,expectargs,';')

    vnamesfig = values.split(';')[0]
    varaxis = values.split(';')[1]
    timevals = values.split(';')[2].split('|')
    dimvfmt = values.split(';')[3]
    colorbarvals = values.split(';')[4]
    shadminmax = values.split(';')[5]
    discvals = values.split(';')[6]
    figt = values.split(';')[7].replace('!',' ')
    kindfig = values.split(';')[8]
    revals = values.split(';')[9]
    mapvalue = values.split(';')[10]
    close = gen.Str_Bool(values.split(';')[11])

    if timevals[0] == 'auto':
        timevals[0] = 'minutes since 1949-12-01 00:00:00'
    else:
        timevals[0] = timevals[0].replace('!',' ')

    ncs = ncfiles.split('@')
    filesinf = {}
    ifile = 0
    for nc in ncs:
        if ifile == 0:
            hfn = 'cont'
        else:
            hfn = 'disc'

        filesinf[hfn + 'filen'] = nc.split(';')[0]
        filesinf[hfn + 'varn'] = nc.split(';')[1]
        filesinf[hfn + 'dimtvn'] = nc.split(';')[2]
        filesinf[hfn + 'dimvvn'] = nc.split(';')[3]
        filesinf[hfn + 'dimvals'] = nc.split(';')[4].replace('|',':')
        ifile = ifile + 1

    for hfn in ['cont', 'disc']:
        ncfilen = filesinf[hfn + 'filen']
        varn = filesinf[hfn + 'varn']
        vdimtn = filesinf[hfn + 'dimtvn']
        vdimvn = filesinf[hfn + 'dimvvn']
        dimvals = filesinf[hfn + 'dimvals']

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

        onc = NetCDFFile(ncfilen, 'r')

        if  not onc.variables.has_key(varn):
            print errormsg
            print '  ' + fname + ": '" + hfn + "' file '" + ncfilen +                \
              "' does not have variable '" + varn + "' !!"
            varns = sorted(onc.variables.keys())
            print '    available ones:', varns
            quit(-1)

        # Variables' values
        ovar = onc.variables[varn]
        vals, dims = drw.slice_variable(ovar, dimvals.replace(',','|'))

        # Values have to be 2D (might not be true for disc?)
        if len(vals.shape) != 2:
            print errormsg
            print '  ' + fname + ": values have to be 2D !!"
            print '    provided shape:', vals.shape, 'for slice:', dimvals
            quit(-1)

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

        # dimensions
        dimnamesv = [vdimtn, vdimvn]
        if  not onc.variables.has_key(vdimtn):
            print errormsg
            print '  ' + fname + ": '" + hfn + "' file '" + ncfile +                 \
              "' does not have time-dimension variable '" +  vdimtn + "' !!"
            varns = sorted(onc.variables.keys())
            print '    available ones:', varns
            quit(-1)
        if  not onc.variables.has_key(vdimvn):
            print errormsg
            print '  ' + fname + ": '" + hfn + "' file '" + ncfile +                 \
              "' does not have var-dimension variable '" +  vdimvn + "' !!"
            varns = sorted(onc.variables.keys())
            print '    available ones:', varns
            quit(-1)

        if vdimtn != 'WRFtime':
            objdimt = onc.variables[vdimtn]
            if drw.searchInlist(objdimt.ncattrs(),'units'):
                odimxu = objdimt.getncattr('units')
            else:
                print erormsg
                print '  ' +fname+": variable dimension '" + vdimxn + "' without units!!"
                quit(-1)
        else:
            objdimt = onc.variables['Times']
            timev, odimxv = ncvar.compute_WRFtime(objdimt[:])
            odimxv0 = ncvar.nericNCvariable_Dict({'time':timev.shape[0]}, ['time'],  \
              'time', 'time', 'Time', tunits, timev)

        objdimv = onc.variables[vdimvn]
        if drw.searchInlist(objdimv.ncattrs(),'units'):
            odimvu = objdimv.getncattr('units')
        else:
            print warnmsg
            print '  ' +fname+": variable dimension '" + vdimvn + "' without units!!"
            odimvu = '-'

        odimxv0, odimyv0 = drw.dxdy_lonlatDIMS(objdimt[:], objdimv[:],                \
          objdimt.dimensions, objdimv.dimensions, dimvals.replace(':','|').split(','),\
          False)
        # Getting same times
        odimxv0 = gen.coincident_CFtimes(odimxv0, timevals[0], odimxu)

        # Some statistics
        vn = np.min(vals)
        vx = np.max(vals)
        dxn = np.min(odimxv0)
        dxx = np.max(odimxv0)
        dyn = np.min(odimyv0)
        dyx = np.max(odimyv0)

        print gen.infmsg
        print '  ' + fname + ": for '" + hfn + "' ________"
        print '    values min:', vn, 'max:', vx
        print '    dimx min:', dxn, 'max:', dxx
        print '    dimy min:', dyn, 'max:', dyx

        if hfn == 'cont':

            # Getting time initialy as x-axis the right shape of dimensions
            gdimx = odimxv0.shape[0]
            if vals.shape[0] != gdimx: gdimy = vals.shape[0]
            else: gdimy = vals.shape[1]

            if vals.shape[1] == gdimx: contv = vals[:]
            else: contv = vals[:].transpose()

            odxv = np.zeros((gdimy,gdimx), dtype=np.float)
            odyv = np.zeros((gdimy,gdimx), dtype=np.float)

            if len(odimxv0.shape) == 2:
                if odimxv0.shape[1] == gdimx: odxv = odimxv0[:]
                else: odxv = odimxv0.transpose()
            else:
                for k in range(gdimy):
                    odxv[k,:] = odimxv0[:]

            if len(odimyv0.shape) == 2:
                if odimyv0.shape[0] == gdimy: odyv = odimyv0[:]
                else: odyv = odimyv0.transpose()
            else:
                for k in range(gdimx):
                    odyv[:,k] = odimyv0[:]

            diminfo = {}
            diminfo['units'] = [timevals[0], odimvu]
            diminfo['names'] = [gen.variables_values(vdimtn)[0],                     \
              gen.variables_values(vdimvn)[1]]
            varinfo = {}
            varinfo['units'] = varunits
            varinfo['name'] = vnamesfig

            # Absolute xtremes for the plot
            absxn = dxn
            absxx = dxx
            absyn = dyn
            absyx = dyx

        else:
            discvarv = []
            discx = []
            discy = []
            # Assuming that discrete values are masked
            if type(vals) != type(gen.mamat):
                madiscvarv = ma.masked_array(vals)
            else:
                madiscvarv = vals

            # Getting 2D dimensions
            [d2Dx, d2Dy] = np.meshgrid(odimxv0, odimyv0)

            # Checking for flipping axis?
            if d2Dx.shape[0] == vals.shape[1] and d2Dx.shape[1] == vals.shape[0]:
                print '  rotating values !'
                #madiscvarv = madiscvarv.transpose()
                d2Dx = d2Dx.transpose()
                d2Dy = d2Dy.transpose()

            # vals have to be 2D otherwise... ?
            dx = madiscvarv.shape[1]
            dy = madiscvarv.shape[0]
            for j in range(dy):
                for i in range(dx):
                    if not madiscvarv.mask[j,i]:
                        discvarv.append(madiscvarv[j,i])
                        discx.append(d2Dx[j,i])
                        discy.append(d2Dy[j,i])

            Ndiscvals = len(discvarv)
            print '    getting:', Ndiscvals, 'discrete values'
            discv = np.zeros((Ndiscvals,3), dtype=np.float)
            discv[:,0] = discx[:]
            discv[:,1] = discy[:]
            discv[:,2] = discvarv[:]

            # Absolute xtremes for the plot
            absxn = np.max([absxn,dxn])
            absxx = np.min([absxx,dxx])
            absyn = np.max([absyn,dyn])
            absyx = np.min([absyx,dyx])

        onc.close()

    graphnx = [absxn, absxx, absyn, absyx]
    print 'limits of the graphic:', graphnx

    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 discvals == 'auto':
        discinfo = ['o', 5., 0.25, '#000000']
    else:
        discinfo = [discvals.split(',')[0], np.float(discvals.split(',')[1]),        \
          np.float(discvals.split(',')[2]), discvals.split(',')[3]]

    if mapvalue == 'None': mapvalue = None

    if colorbarvals == 'auto': colorbarvals = 'rainbow,auto,auto'
    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
    colormapv = [colbarn, fmtcolbar, colbaror]

    # format axes
    if dimvfmt == 'auto': axfmt = 'auto,auto,auto,auto,auto,auto,auto,auto'
    else: axfmt = 'auto,auto,auto,auto,' + dimvfmt
    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(axfmt, ',')
    valaxis = [ystyl, yaxf, Nyax, yaxor]

    if revals == 'None':
        revals = None

    # time values
    timeinfo = {}
    timeinfo['units'] = timevals[0]
    timeinfo['name'] = timevals[3].replace('!', ' ')
    timeinfo['tpos'], timeinfo['tlabs'] = drw.CFtimes_plot([dxn, dxx], timevals[0],  \
      timevals[1], timevals[2])

    drw.plot_2Dshad_obssim_time(discv, contv, odxv, odyv, varaxis, revals, diminfo,  \
      valaxis, timeinfo, colormapv, shading_nx, varinfo, discinfo, mapvalue, graphnx,\
      figt, kindfig, close)

    return

#contfilen = '/home/lluis/estudios/ChemGBsAs/tests/199501/simout_snddiags.nc;ta;time;pres;time|-1,pres|-1'
#discfilen = '/home/lluis/estudios/ChemGBsAs/tests/199501/obs/snd/UWyoming_snd_87576.nc;ta;time;pres;time|-1,pres|-1'
#values = 'ta;y;auto|exct,12,h|%d$^{%H}$|time!($[DD]^{[HH]}$);Vfix,auto,50.,auto;auto;Srange,Srange;auto;obs!&!sim!Ezeiza!airport!sounding;pdf;flip@y;None;yes'

#draw_2D_shad_contdisc_time(contfilen+'@'+discfilen, values, axfig=None, fig=None)

def draw_multiWindRose(ncfiles, values):
    """ Function to plot multiple wind rose (from where the dinw blows)
      ncfiles='#' separated list of [filen]@[dimvals]@[uvarn],[vvarn]
        [filen]: name of the file
        [dimvals]: ';' list of [dimn]|[dvalue] dimension and slice along dimension to retrieve the winds
          [dimn]: name of the dimension
          [dvalue]: value for the slice in the given dimension
            * [integer]: which value of the dimension
            * -1: all along the dimension
            * -9: last value of the dimension
            * [beg],[end],[freq] slice from [beg] to [end] every [freq]
            * NOTE, no dim name all the dimension size
          No value takes all the range of the dimension
        [uvarn],[vvarn]: name of the x and y wind components
      values=[kindRose]:[labels]:[imgtit]:[imgkind]:[kindlabelsangle]:[close]
        [kindRose]: [kind];[value1];[...[valueN]] Kind of rose to plot and values of the kind
          'linepoint': consecutive (time, height, level, ...) line-point angle and speed values. Three different species
            'multicol': line-marker color changing according to a third variable [extravarn]
               values: [extravarn];[lines];[markers];[freqmarkers];[colbar];[Nang]
            'multicoltime': line-marker color changing according to a temporal variable [extravarn]
               values: [extravarn];[lines];[markers];[colbar];[Nang];[timekind];[timefmt];[timelabel]
            'singlecol': same color for the line-marker
               values: [lines];[markers];[cols];[Nang]
          'scatter': a marker for each wind at different values (time, height, level, ...). Three different species
            'multicol':marker color changing according to a third variable [extravarn]
               values: [extravarn];[markers];[colbar];[Nang]
            'multicoltime': marker color changing according to a temporal variable [extravarn]
               values: [extravarn];[lines];[markers];[colbar];[Nang];[timekind];[timefmt];[timelabel]
            'singlecol': same color for all the markers
              values: [markers];[cols];[Nang]
           meaning (where apply):
             [extravarn]: name of the extra variable 
             [lines]: '@' separated list of type of lines (matplotlib ref)
             [markers]: '@' separated list of type of markers to use (matplotlib ref)
             [freqmarkers]: '@' separated list of frequency of drawing markers ('auto' for every 10)
             [cols] = '@' separated list of colors ('#[RR][GG][BB])
             [colbar]: name of the colorbar ('auto' for 'spectral_r')
             [Nang]: number of angles to divide the rose ('auto' for 8)
             [Nspeed]: number of speeds to divide the wind speed distribution ('auto' for 8)
             [maxspeed]: maximum wind speed used to compute the frequency of distributions ('auto' for 40.)
             [timekind]; time computation of ticks
               '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]; desired format of time labels (C-like)
             [timelabel]; label of time colorbar at the graph ('!' for spaces)
        labels: ',' separated list of labels for the legend ('None' for no label)
        imgtit: title of the image ('!' for spaces)
        imgkind: kind of file output of the image (ps, pns, pdf, ...)
        kindlabelsangle: kind of labels for the angles of the wind Rose
          'cardianals': Following combinations of 'N', 'E', 'S', 'W' according to Nang
        close: whether figure should be closed or not
    """
    fname = 'draw_multiWindRose'

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

    expectargs = '[kindRose]:[labels]:[imgtit]:[imgkind]:[kindlabelsangle]:' + \
      '[close]'
    drw.check_arguments(fname,values,expectargs,':')

    dimvariables = values.split(':')[0]

    KindRose = values.split(':')[0]
    labels = values.split(':')[1].split(',')
    imgtit = values.split(':')[2].replace('!',' ')
    imgkind = values.split(':')[3]
    kindlabelsangle = values.split(':')[4]
    close = gen.Str_Bool(values.split(':')[5])
    
    windrosekinds = ['linepoint', 'scatter']

    if KindRose.find(';') == -1:
        print errormsg
        print '  ' + fname + ": all types '" + KindRose + "' require extra values !!"
        print "    'linepoint';'singlecol';[line];[marker];[col];[Nang]"
        print "    'linepoint';'multiecoltime';[extravar];[line];[marker];[colbar];"+\
          "[Nang];[timekind];[timefmt];[timelabel]"
        print "    'linepoint';'multiecol';[extravar];[line];[marker];[colbar];[Nang]"
        print "    'scatter';'multiecol';[extravar];[marker];[colbar]"
        print "    'scatter';'multiecoltime';[extravar];[marker];[colbar];[Nang];" + \
          "[timekind];[timefmt];[timelabel]"
        print "    'scatter';'singlecol';[marker];[col];[Nang]"
        print "  values provided: '" + KindRose + "'" 
        quit(-1)

    lpvals = KindRose.split(';')
    lkind = lpvals[1]

    extravarn = None

    if lpvals[0] == 'linepoint':
        if lkind == 'multicol':
            if len(lpvals) != 8:
                print errormsg
                print '  ' + fname + ": line-point kind '" + lkind + "' requires " + \
                  "6 values !!"
                print "    'multiecol';[extravarn];[line];[marker];[freqmarker];" +  \
                  "[colbar];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
        elif lkind == 'multicoltime':
            if len(lpvals) != 10:
                print errormsg
                print '  '+fname + ": scatter kind '"+lkind+ "' requires 9 values !!"
                print "    'multicol';[extravarn];[line];[marker];[colbar];[Nang];"+ \
                  "[timekind];[timefmt];[timelabel]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
            timekind = lpvals[6]
            timefmt = lpvals[7]
        elif lkind == 'singlecol':
            if len(lpvals) != 6:
                print errormsg
                print '  '+fname+": line-point kind '"+lkind+ "' requires 5 values !!"
                print "    'singlecol';[line];[marker];[col];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
        else:
            print errormsg
            print '  ' + fname + ": line-point kind '" + lkind + "' not ready !!"
            print '    ready ones: multicol, multicoltime, singlecol '
            quit(-1)

    elif lpvals[0] == 'scatter':
        if lkind == 'multicol':
            if len(lpvals) != 6:
                print errormsg
                print '  '+fname+": scatter kind '"+lkind+"' requires 5 values !!"
                print "    'multicol';[extravarn];[marker];[colbar];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
        elif lkind == 'multicoltime':
            if len(lpvals) != 9:
                print errormsg
                print '  ' + fname + ": scatter kind '"+lkind+"' requires 8 values !!"
                print "    'multicol';[extravarn];[marker];[colbar];[Nang];" +       \
                  "[timekind];[timefmt];[timelabel]"
                print '    provided:', lpvals
                quit(-1)     
            extravarn = lpvals[2]
            timekind = lpvals[5]
            timefmt = lpvals[6]
        elif lkind == 'singlecol':
            if len(lpvals) != 5:
                print errormsg
                print '  '+fname + ": scatter kind '"+lkind+ "' requires 4 values !!"
                print "    'singlecol';[marker];[col];[Nang]"
                print '    provided:', lpvals
                quit(-1)     
        else:
            print errormsg
            print '  ' + fname + ": scatter kind '" + lkind + "' not ready !!"
            print '    ready ones: multicol, multicoltime, singlecol '
            quit(-1)

    else:
        print gen.errormsg
        print '  ' +  fname + ": kind of WindRose '" + lpvals[0] + "' not ready !!"
        print '    available ones:', windrosekinds
        quit(-1)

    angles = []
    speeds = []
    extravs = []
    fvarns = ncfiles.split('#')
    for fvn in fvarns:
        ncfile = fvn.split('@')[0]
        dimvariables = fvn.split('@')[1]
        uvarn = fvn.split('@')[2].split(',')[0]
        vvarn = fvn.split('@')[2].split(',')[1]

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

        onc = NetCDFFile(ncfile,'r')
        oncvars0 = onc.variables.keys()
        oncvars = oncvars0 + []
        oncvars.sort()

        if not gen.searchInlist(oncvars,uvarn):
            print errormsg
            print '  ' + fname + ": file '" + ncfile + "' does not have variable " +     \
              "u_wind '" + uvarn + "' !!"
            print '    available variables:', oncvars
            quit(-1)
        if not gen.searchInlist(oncvars,vvarn):
            print errormsg
            print '  ' + fname + ": file '" + ncfile + "' does not have variable " +     \
              "v_wind '" + vvarn + "' !!"
            print '    available variables:', oncvars
            quit(-1)
        if extravarn is not None:
            if not gen.searchInlist(oncvars,extravarn):
                print errormsg
                print '  ' + fname + ": file '" + ncfile + "' does not have extra " +    \
                  "variable '" + extravarn + "' !!"
                print '    available variables:', oncvars
                quit(-1)

        # Getting the slice
        dictslice = {}
        for dnv in dimvariables.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)

        # Getting variables
        ou = onc.variables[uvarn]
        sliceu, du = ncvar.SliceVarDict(ou, dictslice)
        uv = ou[tuple(sliceu)]
        ov = onc.variables[vvarn]
        slicev, dv = ncvar.SliceVarDict(ov, dictslice)
        vv = ov[tuple(slicev)]
        wunit = ov.getncattr('units')
        if extravarn is not None:
            oe = onc.variables[extravarn]
            slicee, de = ncvar.SliceVarDict(oe, dictslice)
            extrav = oe[tuple(slicee)]
            dime = extrav.shape[0]
            extraunit = oe.getncattr('units')
        else:
            dime = uv.shape[0]
            extrav = None
            extraunit = None
    
        onc.close()

        # Wind Rose is with the winds from where they come from!
        ang = np.arctan2(-vv, -uv)
        speed = np.sqrt(uv*uv + vv*vv)

        # re-setting to [0, 2pi]
        ang = np.where(ang <= 0., 2.*np.pi+ang, ang)
        ang = np.where(np.mod(ang,2.*np.pi) == 0., 0., ang)

        angles.append(ang)
        speeds.append(speed)
        if extrav is not None: extravs.append(extrav)

    drw.plot_multiWindRose(angles, speeds, dime, lpvals, kindlabelsangle, wunit,     \
      labels, imgtit, imgkind, 'multi_WindRose', close, evs=extravs, eunit=extraunit)

    return

#filenames='/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/sounding_uava_10868.nc@pres|-1;time|1@ua,va#' + \
#  '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_38lev.nc@bottom_top|-1;time|12@ua,va#' +  \
#  '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_50lev.nc@bottom_top|-1;time|12@ua,va#' +  \
#  '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_50lev_assigned.nc@bottom_top|-1;time|12@ua,va#' +  \
#  '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_80lev.nc@bottom_top|-1;time|12@ua,va#' +  \
#  '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_120lev.nc@bottom_top|-1;time|12@ua,va#' + \
#  '/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out/simout_vars_sndpt_10868_NOaerosol.nc@bottom_top|-1;time|12@ua,va'
#wrkind='linepoint;multicol;pres;-;x;spectral;auto'
#figvalues=wrkind + ':obs,38lev,50lev,50leva,80lev,120lev:WindRose!obs!,!sim!comparison!on!2012/10/23!12!UTC:png:auto:True'

#draw_multiWindRose(filenames, figvalues)

def draw_stations_map(filename, values):
    """ Function to plot a map with the stations
      filename= name of ASCII file with the values of the stations as: ('#' comments)
        [sttype],[label],[lon],[lat],[height]
          [sttype]: type of the station
          [label]: label of the station (LaTeX format, 'None' for no label)
          [lon]: longitude of the station
          [lat]: latitude of the station
          [height]: height of the station
      values=[stypevals]:[mapvals]:[SWNEbox]:[imgtit]:[imgkind]:[close]
        stypevals='@' separated list of [sttype]|[marker]|[color]|[size]|[fontsize]
          [sttype]: label of the type of the marker
          [marker]: type of the marker
          [color]: color of the marker
          [size]: size of the marker
        mapvals= 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
        SWNEbox: ',' list of the vertexs of the map [SWlon, NElon, SWlat, NElat]
          'lonlatxtrms': to use the extremes of the lon,lat stations
        imgtit: title of the image ('!' for spaces)
        imgkind: kind of file output of the image (ps, pns, pdf, ...)
        close: whether figure should be closed or not
    """
    fname = 'draw_stations_map'

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

    expectargs = '[stypevals]:[mapvals]:[SWNEbox]:[imgtit]:[imgkind]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    stypevals = values.split(':')[0].split('@')
    mapvals = values.split(':')[1]
    SWNEboxS = values.split(':')[2]
    imgtit = values.split(':')[3].replace('!', ' ')
    imgkind = values.split(':')[4]
    close = gen.Str_Bool(values.split(':')[5])

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

    # Getting stations values
    styypes = {}
    sttyps = []
    for stvs in stypevals:
        stv = stvs.split('|')
        styp = stv[0]
        smk = stv[1]
        scol = stv[2]
        ssz = np.float(stv[3])
        fsz = stv[4]
        styypes[styp] = [smk, scol, ssz, fsz]
        sttyps.append(styp)

    ofile = open(filename, 'r')
    dicstations = {}
    nlonst = 100000.
    xlonst = -100000.
    nlatst = 100000.
    xlatst = -100000.

    for line in ofile:
        if line[0:1] != '#' and len(line) > 1: 
            linev = line.replace('\n','').replace('\r','').split(',')
            ltyp = linev[0]
            lid = linev[1]
            llon = np.float(linev[2])
            llat = np.float(linev[3])
            lhgt = np.float(linev[4])
            if nlonst > llon: nlonst=llon
            if xlonst < llon: xlonst=llon
            if nlatst > llat: nlatst=llat
            if xlatst < llat: xlatst=llat

            if not gen.searchInlist(sttyps, ltyp):
                print errormsg
                print '  ' + fname + ": station type '" + ltyp + "' not ready !!"
                print '    available ones:', sttyps
                quit(-1)
            
            typsv = styypes[ltyp]
            dicstations[lid] = [llon, llat, lhgt, lid, typsv[0], typsv[1], typsv[2], \
              typsv[3]]

    ofile.close()

    if SWNEboxS == 'lonlatxtrms':
        SWNEbox = [nlonst, xlonst, nlatst, xlatst]
    else:
        SWNEbox = gen.str_list_k(SWNEboxS, ',', 'F')

    Nd = 100
    nlon = SWNEbox[0]
    xlon = SWNEbox[1]
    nlat = SWNEbox[2]
    xlat = SWNEbox[3]

    ddlon = (xlon - nlon)/Nd
    ddlat = (xlat - nlat)/Nd

    if SWNEboxS == 'lonlatxtrms':
        SWNEbox = [nlonst-ddlon, xlonst+ddlon, nlatst-ddlat, xlatst+ddlat]
        nlon = SWNEbox[0]
        xlon = SWNEbox[1]
        nlat = SWNEbox[2]
        xlat = SWNEbox[3]

    lon1D = np.arange(nlon, xlon+ddlon, ddlon)
    lat1D = np.arange(nlat, xlat+ddlat, ddlat)
   
    drw.plot_stations_map(dicstations, lon1D, lat1D, mapvals, SWNEbox, ddlon, imgtit,\
      imgkind, close)

    return

def draw_WRFeta_levels(filenames, values):
    """ Function to plot vertical levels from WRF wrfinput_d[nn] file
      filenames= ',' list of name of files to use
      values = [labs]:[colors]:[markers]:[legvals]:[imgtit]:[imgkind]:[newfile]:[close]
        [labs]= ',' list of labels for the plot (LaTeX like)
        [colors]= ',' list of colors for the lines ('auto' for automatic)
        [markers]= '@' list of markers for the lines ('auto' for automatic)
        [legvals]=[loclegend]|[fonstsize]|[ncol] values for the legend
          [locleg]: location of the legend (0, automatic)
            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)
          [ncol]: number of columns ('auto' for 1)
        [imgtit]= title of the image ('!' for spaces)
        [imgkind]= kind of file output of the image (ps, pns, pdf, ...)
        [newfile]= whether the possible pre-existing file with the required data be 
          should removed or not ('yes/no')
        [close]= whether figure should be closed or not
      * NOTE: A multi-panel plot will be drawn called `WRFeta_levels.png', and also 
        an individual plot for each panel will be produced
    """
    import subprocess as sub

    fname = 'draw_WRFeta_levels'

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

    expectargs = '[labs]:[colors]:[markers]:[legvals]:[imgtit]:[imgkind]:' +         \
      '[newfile]:[close]'
    drw.check_arguments(fname,values,expectargs,':')

    labs = values.split(':')[0].split(',')
    colors = gen.auto_val_list(values.split(':')[1].split(','), len(labs),           \
      drw.colorsauto)
    markers = gen.auto_val_list(values.split(':')[2].split('@'), len(labs),          \
      drw.pointkindsauto)
    legvals = values.split(':')[3]
    imgtit = values.split(':')[4].replace('!', ' ')
    imgkind = values.split(':')[5]
    newfile = gen.Str_Bool(values.split(':')[6])
    close = gen.Str_Bool(values.split(':')[7])
    
    files = filenames.split(',')
    Nfiles = len(files)

    allhgtsea = []
    allxhgt = []
    allpsea = []
    allpxhgt = []
    allhgtxhgt = []
    alldhgtsea = []
    alldhgtxhgt = []
    alldpsea = []
    alldpxhgt = []
    alletaw = []
    alletau = []
    alldimz = []

    # Creation of a file with the data
    titS = imgtit.replace(' ','-')
    ofilen = 'WRFeta_levels_' + titS + '.nc'

    # Removing pre-existing file
    if newfile:
        if os.path.isfile(ofilen):
            print '  ' + fname + ": removing pre-existing file with required '" +    \
              "data '" + ofilen + "' !!"
            sub.call('rm ' + ofilen, shell=True)

    if not os.path.isfile(ofilen):

        maxdz = -10
        for filen in files:
            if not os.path.isfile(filen):
                print errormsg
                print '  ' + fname + ": file '" + filen + "' does not exist !!"
                quit(-1)

            onc = NetCDFFile(filen, 'r')
            ophb = onc.variables['PHB']
            opb = onc.variables['PB']
            olandseamask = onc.variables['LANDMASK']
            ohgt = onc.variables['HGT']
            oznw = onc.variables['ZNW']
            oznu = onc.variables['ZNU']
    
            dimx = ophb.shape[3]
            dimy = ophb.shape[2]
            dimz = ophb.shape[1]
            dimt = ophb.shape[0]
            dimzp = opb.shape[1]

            if maxdz < dimz: maxdz = dimz

            for j in range(10,dimy):
                for i in range(10,dimx):
                    if olandseamask[0,j,i] == 0:
                        hgtssea = ophb[0,:,j,i]/9.8
                        pssea = opb[0,:,j,i]
                        break

            maxhgt = np.max(ohgt[0,:,:])
            ijxhgt = gen.index_mat(ohgt[0,:,:], maxhgt)
            hgtsxhgt = ophb[0,:, ijxhgt[0], ijxhgt[1]]/9.8
            psxhgt = opb[0,:, ijxhgt[0], ijxhgt[1]]

            allhgtsea.append(hgtssea)
            allxhgt.append(maxhgt)
            allhgtxhgt.append(hgtsxhgt)
            allpsea.append(pssea)
            allpxhgt.append(psxhgt)
            alldhgtsea.append(hgtssea[1:dimz]-hgtssea[0:dimz-1])
            alldhgtxhgt.append(hgtsxhgt[1:dimz]-hgtsxhgt[0:dimz-1])
            alldpsea.append(pssea[0:dimzp-1]-pssea[1:dimzp])
            alldpxhgt.append(psxhgt[0:dimzp-1]-psxhgt[1:dimzp])
            alletaw.append(oznw[0,:])
            alletau.append(oznu[0,:])
            alldimz.append(dimz)

            onc.close()

        print infmsg
        print '  ' + fname + ": creation of file '" + ofilen + "' to keep required"+ \
          "values to plot !!"
        onewnc = NetCDFFile(ofilen, 'w')

        # Dimensions
        newdim = onewnc.createDimension('Nfiles', Nfiles)
        newdim = onewnc.createDimension('Lstring', 250)
        newdim = onewnc.createDimension('evert', maxdz)

        # Variabledimensions
        newvar = onewnc.createVariable('Nfiles', 'c', ('Nfiles', 'Lstring'))
        ncvar.writing_str_nc(newvar, files, 250)
        ncvar.basicvardef(newvar,'files','Files used to retrieve data','-')

        newvar = onewnc.createVariable('evert_file', 'i', ('Nfiles'))
        ncvar.basicvardef(newvar,'evert_file','number vertical layers per file','-')
        newvar[:] = alldimz

        # Variables
        newvar = onewnc.createVariable('hgtsea', 'f', ('Nfiles', 'evert'),           \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'hgtsea','heights above sea point', 'm')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]] = allhgtsea[iff]

        newvar = onewnc.createVariable('pressea', 'f', ('Nfiles', 'evert'),          \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'pressea','pressures above sea point', 'Pa')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-1] = allpsea[iff]

        newvar = onewnc.createVariable('hgtmax', 'f', ('Nfiles'))
        ncvar.basicvardef(newvar,'hgtmax','maximum height', 'm')
        newvar[:] = allxhgt

        newvar = onewnc.createVariable('hgtxhgt', 'f', ('Nfiles', 'evert'),          \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'hgtxhgt','heights above maximum height', 'm')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]] = allhgtxhgt[iff]

        newvar = onewnc.createVariable('presxhgt', 'f', ('Nfiles', 'evert'),         \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'presxhgt','pressures above maximum height', 'Pa')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-1] = allpxhgt[iff]

        onewnc.sync()

        newvar = onewnc.createVariable('dhgtsea', 'f', ('Nfiles', 'evert'),          \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'dhgtsea','delta heights above sea point', 'm')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-1] = alldhgtsea[iff]

        newvar = onewnc.createVariable('dhgtxhgt', 'f', ('Nfiles', 'evert'),         \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'dhgtxhgt','delta heights above maximum height', 'm')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-1] = alldhgtxhgt[iff]

        newvar = onewnc.createVariable('dpressea', 'f', ('Nfiles', 'evert'),         \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'dpressea','delta pressures above sea point', 'Pa')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-2] = alldpsea[iff]

        newvar = onewnc.createVariable('dpresxhgt', 'f', ('Nfiles', 'evert'),        \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'dpresxhgt','delta pressures above maximum height', \
         'Pa')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-2] = alldpxhgt[iff]

        newvar = onewnc.createVariable('eta_full', 'f', ('Nfiles', 'evert'),         \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'eta_full','full eta layers', '-')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]] = alletaw[iff]

        newvar = onewnc.createVariable('eta_half', 'f', ('Nfiles', 'evert'),         \
          fill_value=gen.fillValueF)
        ncvar.basicvardef(newvar,'eta_half','half eta layers', '-')
        for iff in range(Nfiles): newvar[iff,0:alldimz[iff]-1] = alletau[iff]

        onewnc.sync()
        onewnc.close()
        print fname + ": succesfull written of file '" + ofilen + "' with all data !!"

    else:
        print fname + ": readding existing file '" + ofilen + "' with all data !!"
        print "    if a new file is required set variable 'newfile' to 'yes'" 
        onc = NetCDFFile(ofilen, 'r')

        ovar = onc.variables['hgtsea']
        allhgtseav = ovar[:]
        ovar = onc.variables['pressea']
        allpseav = ovar[:]
        ovar = onc.variables['hgtmax']
        allxhgtv = ovar[:]
        ovar = onc.variables['hgtxhgt']
        allhgtxhgtv = ovar[:]
        ovar = onc.variables['presxhgt']
        allpxhgtv = ovar[:]
        ovar = onc.variables['dhgtsea']
        alldhgtseav = ovar[:]
        ovar = onc.variables['dhgtxhgt']
        alldhgtxhgtv = ovar[:]
        ovar = onc.variables['dpressea']
        alldpseav = ovar[:]
        ovar = onc.variables['dpresxhgt']
        alldpxhgtv = ovar[:]
        ovar = onc.variables['eta_full']
        alletawv = ovar[:]
        ovar = onc.variables['eta_half']
        alletauv = ovar[:]
 
        onc.close()

        for iff in range(Nfiles):
            allhgtsea.append(allhgtseav[iff,:].compressed())
            allxhgt.append(allxhgtv[iff])
            allhgtxhgt.append(allhgtxhgtv[iff,:].compressed())
            allpsea.append(allpseav[iff,:].compressed())
            allpxhgt.append(allpxhgtv[iff,:].compressed())
            alldhgtsea.append(alldhgtseav[iff,:].compressed())
            alldhgtxhgt.append(alldhgtxhgtv[iff,:].compressed())
            alldpsea.append(alldpseav[iff,:].compressed())
            alldpxhgt.append(alldpxhgtv[iff,:].compressed())
            alletaw.append(alletawv[iff,:].compressed())
            alletau.append(alletauv[iff,:].compressed())

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

    drw.plot_WRFeta_levels(allhgtsea, allpsea, allxhgt, allhgtxhgt, allpxhgt,        \
      alldhgtsea, alldhgtxhgt, alldpsea, alldpxhgt, alletaw, alletau, labs, colors,  \
      markers, [locleg, legfontsize, legncol], imgtit, imgkind, close)

    # Individual plots
    drw.plot_indiv_WRFeta_levels(allhgtsea, allpsea, allxhgt, allhgtxhgt, allpxhgt,  \
      alldhgtsea, alldhgtxhgt, alldpsea, alldpxhgt, alletaw, alletau, labs, colors,  \
      markers, [locleg, legfontsize, legncol], imgtit, imgkind, close)

    return
#
foldn='/media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/sims/wrfinput_select/'
#fils=foldn + '120lev_cdxwrf2/simin_vars.nc,' + foldn + '120lev_assigned/simin_vars.nc,' + foldn +      \
#  '80lev_cdxwrf2/simin_vars.nc,' + foldn + '80lev_assigned/simin_vars.nc,' + foldn +                   \
#  '50lev_cdxwrf2/simin_vars.nc,' + foldn + '50lev_assigned/simin_vars.nc,' + foldn +                   \
#  '38lev_cdxwrf2/simin_vars.nc,' + foldn + '38lev_assigned/simin_vars.nc'
#vals='120lev,120leva,80lev,8leva,50lev,50leva,38lev,38leva:auto:auto:0|4|2:FPS!Alps!vertical!levels:png:no:true'
#print fils
#draw_WRFeta_levels(fils, vals)

def draw_2Dshad_map(ncfile, values, varn, axfig=None, fig=None):
    """ plotting a shadow field with a background map
    draw_2Dshad_map(ncfile, values, varn)
      ncfile= file to use
      values=[vnamemap];[vnamefs];[dimvals];[dimxvn];[dimyvn];[dimxyfmt];
       [colorbarvals];[sminv],[smaxv];[figt];[kindfig];[mapkind];[mapv];[close]
        [vnamemap]: Name of the variable to be used for map
        [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]#[colorbarticks]
          [colorbarn]: name of the color bar for the values to plot
          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
          [colorbarticks]: kind of colorbarticks
            'direct': direct values
            'time'@[units]|[kind]|[tfmt]|[label] time labels characteristics
              [units]: units string according to CF conventions ([tunits] since 
                [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces), 
                'auto' for minutes!since!1949-12-01!00:00:00
              [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 (combination of 'C'-style values and LaTeX)
              [label]: label at the graph ('!' for spaces, combination of 'C'-style 
                values and LaTeX)
        [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 file for the figure output (ps, eps, png, pdf, ...)
        [mapfmt] = [cbarmap]|[mapkind]|[lonlatbox] values for the map 
          cbarmap: name of the colorbar for the map
          mapkind: kind of map to use in the plot
            'direct': values are they come
            'shadow',[pos],[enhance]: pseudo-shadding from a given location of the sun
              [pos]: 'N', 'NW'
              [enhance]: enhance factor for the shading ('auto' for 1./5.)
          lonlatbox: [lonSW],[latSW],[lonNE],[latNE] to plot only a lon,lat box
            'full': for the whole domain
        [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
      varn= [varsn] name of the variable to plot with shading
    """

    fname = 'draw_2Dshad_map'

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

    availmapkind = ['direct', 'shadow']
    availsunpos = ['N', 'NW']

    expectargs = '[vnamemap];[vnamefs];[dimvals];[dimxvn];[dimyvn];[dimxyfmt];' +    \
      '[colorbarvals];[sminv],[smaxv];[figt];[kindfig];[mapfmt];[mapv];[close]'

    drw.check_arguments(fname,values,expectargs,';')

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

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

    objsf = NetCDFFile(ncfiles, 'r')
    
    # Map values
    if not objsf.variables.has_key(vnamemap):
        print errormsg
        print '  ' + fname + ": file does not have map variable '" + vnamemap + "' !!"
        varns = list(objsf.variables.keys())
        varns.sort()
        print '    available ones:', varns
        quit(-1)

    omap = objsf.variables[vnamemap]
    valsmap, dimsmap = drw.slice_variable(omap, dimvals.replace(',','|'))
    if len(valsmap.shape) != 2:
        print errormsg
        print '  ' + fname + ': map values have to be 2-rank and they are:',         \
          len(valsmap.shape), '!!'
        quit(-1)

    dx = valsmap.shape[1]
    dy = valsmap.shape[0]

    mapkind = mapfmt[1]
    if mapfmt[2] == 'full':
        lonlatbox = None
    elif len(mapfmt[2].split(',')) == 4:
        lonlatbox = []
        for lL in mapfmt[2].split(','):
            lonlatbox.append(np.float(lL))
    else:
        print errormsg
        print '  ' + fname + ": lonlatbox value '" + mapfmt[2] + "' not ready !!"
        print '    for a lonlatbox 4 values are required. Values passed:',           \
          mapfmt[2].splot(',')
        quit(-1)
    

    if mapkind == 'direct':
        mapv = valsmap[:]
    elif mapkind[0:6] == 'shadow':
        mapv = np.zeros((dy,dx), dtype=np.float)
        sunpos = mapkind.split(',')[1]
        enhance = gen.auto_val(mapkind.split(',')[2], 1./5.)
        if sunpos == 'N':
            ## Linear shadow from N
            mapv[0:dy-1,:] = valsmap[1:dy,:] - valsmap[0:dy-1,:]
        elif sunpos == 'NW':
            ## Diagonal shadow from NW
            for i in range(dx-1):
                for j in range(dy-1):
                    if (i-1 >= 0) and (j+1 <= dy-1): 
                        mapv[j,i] = valsmap[j+1,i-1] - valsmap[j,i]
        else:
            print errormsg
            print '  ' + fname + ": sun location for map sahdding '" + sunpos +      \
              "' not ready !!"
            print '    available ones:', availsunpos
            quit(-1)
        xmapv = np.max(mapv)*enhance
        mapv = np.where(mapv > xmapv, xmapv, mapv)
        mapv = ma.masked_less(mapv, 0.)
    else:
        print errormsg
        print '  ' + fname + ": kind of map '" + mapkind + "' not ready !!"
        print '    available ones:', availmapkind
        quit(-1)

    if  not objsf.variables.has_key(varn):
        print errormsg
        print '  ' + fname + ': shading file "' + ncfiles +                          \
          '" does not have variable "' +  varn + '" !!'
        varns = list(objsf.variables.keys())
        varns.sort()
        print '    available ones:', varns
        quit(-1)

    # Variables' values
    objvars = objsf.variables[varn]
    if type(objvars[:]) != type(gen.mamat):
        print errormsg
        print '  ' + fname + ": drawing variable is not masked !!"
        quit(-1)

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

    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

    colorbarv = colorbarvals.split('#')
    colorbarvalsS = ','.join(colorbarv[0:3])

    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvalsS, ',')
    nbarv = np.min(valshad)
    xbarv = np.max(valshad)
    rbarv = xbarv - nbarv
    dbarv = rbarv/5.

    if colorbarv[3] == 'direct':
        cbarpos = gen.pretty_int(nbarv,xbarv+dbarv,5)
        cbarlab = []
        for cpos in cbarpos:
            cbarlab.append('{:6g}'.format(cpos))
    elif colorbarv[3][0:4] == 'time':
        timevals = colorbarv[3].split('@')[1]
        timeunit = timevals.split('|')[0].replace('!',' ')
        timekind = timevals.split('|')[1]
        timefmt = timevals.split('|')[2]
        timelabel = timevals.split('|')[3].replace('!',' ')
        cbarpos, cbarlab = drw.CFtimes_plot([nbarv, xbarv], timeunit, timekind, timefmt)
        vnamesfig = timelabel
        varunits = None
        fmtcolbar = '%s'

    colormapv = [vnamesfig, varunits, colbarn, fmtcolbar, colbaror, cbarpos, cbarlab]

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

    drw.plot_2Dshad_map(mapv, valshad, mapfmt[0], colormapv, xaxis, yaxis, odimxv,   \
      odimyv, lonlatbox, mapvalue, shading_nx, figtitle, figkind, close)

    return

#ncfile = '/home/lluis/sandbox/get/UBA_ERA-I_1a_2D.nc'
##values='orog;$conv^{ini}$;lat|-1,lon|-1;lon;lat;auto;rainbow#auto#auto#direct;' +    \
##  'Srange,Srange;Case1|1a;pdf;binary|shadow,NW;cyl,c;yes'
#values='orog;$conv^{ini}$;lat|-1,lon|-1;lon;lat;auto;rainbow#auto#auto#' +     \
#  'time@minutes!since!1949-12-01!00:00:00|exct,12,h|%d$^{%H}$|date!'+          \
#  '([DD]$^{[HH]}$);Srange,Srange;Case1|1a;pdf;binary|shadow,NW,auto|' +        \
#  '-70.,-36,-62.,-30.;cyl,c;yes'
#draw_2Dshad_map(ncfile, values, 'convini', axfig=None, fig=None)

#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_contdisc',                     \
  'draw_2D_shad_contdisc_time', 'draw_2D_shad_2cont', 'draw_2D_shad_cont_time',      \
  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
  'draw_bar', 'draw_bar_line', 'draw_bar_line_time', 'draw_bar_time',                \
  'draw_cycle', 'draw_ensembles_time', 'draw_multi_2D_shad', 'draw_multi_SkewT',     \
  'draw_lines',                                                                      \
  'draw_lines_time', 'draw_multiWindRose', 'draw_points', 'draw_Taylor',             \
  'draw_time_lag', 'draw_topo_geogrid_boxes',                                        \
  'draw_trajectories', 'draw_vals_trajectories', 'draw_WRFeta_levels',               \
  '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 None and not gen.searchInlist(Notcheckingfile, oper) and       \
      opts.values != 'h':
        print errormsg
        print '  ' + mainn + ": you must provide a file as '-f [filename]'!!"
        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_2Dshad_map':
        draw_2Dshad_map(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_contdisc':
        draw_2D_shad_contdisc(opts.ncfile, opts.values)
    elif oper == 'draw_2D_shad_contdisc_time':
        draw_2D_shad_contdisc_time(opts.ncfile, opts.values)
    elif oper == 'draw_2D_shad_2cont':
        draw_2D_shad_2cont(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_bar':
        draw_bar(opts.ncfile, opts.values)
    elif oper == 'draw_bar_line':
        draw_bar_line(opts.ncfile, opts.values)
    elif oper == 'draw_bar_line_time':
        draw_bar_line_time(opts.ncfile, opts.values)
    elif oper == 'draw_bar_time':
        draw_bar_time(opts.ncfile, opts.values)
    elif oper == 'draw_barbs':
        draw_barbs(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_basins':
        draw_basins(opts.ncfile, opts.values)
    elif oper == 'draw_cycle':
        draw_cycle(opts.ncfile, opts.values)
    elif oper == 'draw_ensembles_time':
        draw_ensembles_time(opts.ncfile, opts.values)
    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_multi_2D_shad':
        draw_multi_2D_shad(opts.ncfile, opts.values)
    elif oper == 'draw_multi_SkewT':
        draw_multi_SkewT(opts.ncfile, opts.values)
    elif oper == 'draw_multiWindRose':
        draw_multiWindRose(opts.ncfile, opts.values)
    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_SkewT':
        draw_SkewT(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_stations_map':
        draw_stations_map(opts.ncfile, opts.values)
    elif oper == 'draw_Taylor':
        draw_Taylor(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_time_lag':
        draw_time_lag(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 == 'draw_WindRose':
        draw_WindRose(opts.ncfile, opts.values, opts.varname)
    elif oper == 'draw_WRFeta_levels':
        draw_WRFeta_levels(opts.ncfile, opts.values)
    elif oper == 'movie_2D_shad':
        movie_2D_shad(opts.ncfile, opts.values, opts.varname)
    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()

