#######################
##### PLANETOPLOT #####
#######################

### A. Spiga     -- LMD -- 06~09/2011 -- General building and mapping capabilities
### T. Navarro   -- LMD -- 10~11/2011 -- Improved use for GCM and added sections + 1Dplot capabilities 
### A. Colaitis  -- LMD --    11/2011 -- Mostly minor improvements and inter-plot operation capabilities + zrecast interpolation for gcm
### A. Spiga     -- LMD -- 11~12/2011 -- Extended multivar subplot capabilities + cosmetic changes + general cleaning and tests
### A. Colaitis  -- LMD --    12/2011 -- Added movie capability [mencoder must be installed]
### A. Spiga     -- LMD --    12/2011 -- Added HTML animated page capability + general tests of consistency [winds, etc...] + consistent generic movie loop
### J. Leconte   -- LMD --    02/2012 -- Added area weighted averaging. Compatibility with terrestrial gcm.
### A. Spiga     -- LMD --    03/2012 -- Cleaning and improved comments 
def planetoplot (namefiles,\
           level=0,\
           vertmode=0,\
           proj=None,\
           back=None,\
           target=None,
           stride=3,\
           var=None,\
           colorb="def",\
           winds=False,\
           addchar=None,\
           interv=[0,1],\
           vmin=None,\
           vmax=None,\
           tile=False,\
           zoom=None,\
           display=True,\
           hole=False,\
           save="gui",\
           anomaly=False,\
           var2=None,\
           ndiv=10,\
           mult=1.,\
           zetitle=["fill"],\
           slon=None,\
           slat=None,\
           svert=None,\
           stime=None,\
           outputname=None,\
           resolution=200,\
           ope=None,\
           fileref=None,\
           minop=0.,\
           maxop=0.,\
           titleref="fill",\
           invert_y=False,\
           xaxis=[None,None],\
           yaxis=[None,None],\
           ylog=False,\
           yintegral=False,\
           blat=None,\
           blon=None,\
           tsat=False,\
           flagnolow=False,\
           mrate=None,\
           mquality=False,\
           trans=1,\
           zarea=None,\
           axtime=None,\
           redope=None,\
           seevar=False,\
           xlab=None,\
           ylab=None,\
           lbls=None,\
           lstyle=None,\
           cross=None,\
           streamflag=False):

    ####################################################################################################################
    ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png

    #################################
    ### Load librairies and functions
    from netCDF4 import Dataset
    from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\
                       fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\
                       zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\
                       getname,localtime,check_localtime,polarinterv,getsindex,define_axis,determineplot,readslices,bidimfind,getlschar,hole_bounds,\
                       windamplitude,slopeamplitude,deltat0t1
    from mymath import deg,max,min,mean,get_tsat,writeascii,fig2data,fig2img
    import matplotlib as mpl
    from matplotlib.pyplot import contour,contourf,hist, text,subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel, title, close, legend, xlabel, axis, ylabel, subplots_adjust, axes, clabel
    from matplotlib.cm import get_cmap
    #from mpl_toolkits.basemap import cm
    import numpy as np
    from numpy.core.defchararray import find
    from videosink import VideoSink
    from times import sol2ls
    import subprocess
    #from singlet import singlet
    from itertools import cycle
    import os

#########################
### PRELIMINARY STUFF ###
#########################
### we say hello
    print "********************************************"
    print "********** WELCOME TO PLANETOPLOT **********"
    print "********************************************"
### we ensure namefiles and var are arrays
    if not isinstance(namefiles, np.ndarray): namefiles = [namefiles]
    if not isinstance(var, np.ndarray):       var = [var]
### we initialize a few variables
    initime=-1 ; sslon = None ; sslat = None
    if slon is not None: sslon = np.zeros([1,2])
    if slat is not None: sslat = np.zeros([1,2])
    k = 0 ; firstfile = True ; count = 0
### we avoid specific cases not yet implemented
    if mrate is not None and len(var) > 1: errormess("multivar not allowed in movies. should be fixed soon!")
### we prepare number of plot fields [zelen] and plot instances [numplot] according to user choices
### --> we support multifile and multivar plots : files + vars separated by commas are on the same figure
    nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime)
    zelen = len(namefiles)*len(var)
    numplot = zelen*nslices
    print "********** FILES, SLICES, VARS, TOTAL PLOTS: ", len(namefiles), nslices, len(var), numplot
    print "********** MAPMODE: ", mapmode
### we correct number of plot fields for possible operation (substract, etc...)
    if ope is not None:
        if fileref is not None:       zelen = zelen + 2
        elif "var" in ope:            zelen = zelen + 1
### we define the arrays for plot fields -- which will be placed within multiplot loops
    all_var  = [[]]*zelen ; all_var2  = [[]]*zelen 
    all_title = [[]]*zelen ; all_varname = [[]]*zelen ; all_namefile = [[]]*zelen ; all_time = [[]]*zelen 
    all_windu = [[]]*zelen ; all_windv = [[]]*zelen
 
#############################
### LOOP OVER PLOT FIELDS ###
#############################
    for nnn in range(len(namefiles)):
     for vvv in range(len(var)): 

    ### we load each NETCDF objects in namefiles
      namefile = namefiles[nnn] 
      nc  = Dataset(namefile)
    ### we explore the variables in the file
      varinfile = nc.variables.keys()
      if seevar: print varinfile ; exit()
    ### we define the type of file we have (gcm, meso, etc...)
      typefile = whatkindfile(nc)
      if firstfile:                 typefile0 = typefile
      elif typefile != typefile0:   errormess("Not the same kind of files !", [typefile0, typefile])
    ### we care for input file being 1D simulations 
      if "longitude" in nc.dimensions and "latitude" in nc.dimensions: is1d = len(nc.variables["longitude"][:])*len(nc.variables["latitude"][:])
      elif "lon" in nc.dimensions and "lat" in nc.dimensions: is1d = len(nc.variables["lon"][:])*len(nc.variables["lat"][:])
      if typefile in ['gcm','earthgcm'] and is1d == 1:       mapmode=0 ; winds=False
    ### we create default vert and time prescriptions if not here in case mapping mode is on (lat/lon maps)
      if redope is None and mapmode == 1:
          if svert is None:  svert = readslices(str(level)) ; nvert=1
          if stime is None and mrate is None:
             stime = readslices(str(0)) ; ntime=1 ## this is a default choice
             print "WELL... nothing about time axis. I took default: first time reference stored in file."
    ### we get the names of variables to be read. in case only one available, we choose this one.
      varname=var[vvv] 
      if ((varname not in nc.variables) and not ((typefile in ['meso']) and (varname in ['UV','uv','uvmet','slopexy','SLOPEXY','deltat','DELTAT']))): 
          if len(varinfile) == 1:   varname = varinfile[0] 
          else:                     varname = False
    ### we get the names of wind variables to be read (if any)
      if winds:                                                    
         [uchar,vchar,metwind] = getwinddef(nc)             
         if uchar == 'not found': winds = False
    ### we tell the user that either no var or no wind is not acceptable
      if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables)
    ### we get the coordinates lat/lon to be used
      [lon2d,lat2d] = getcoorddef(nc)
    ### we get an adapted map projection if none is provided by the user
      if proj == None:   proj = getproj(nc)                 
    ### we define plot boundaries given projection or user choices
      if firstfile:
         if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d)
         elif proj in ["lcc","laea"]:      [wlon,wlat] = wrfinterv(lon2d,lat2d)
         else:                             [wlon,wlat] = simplinterv(lon2d,lat2d)
         if zoom:                          [wlon,wlat] = zoomset(wlon,wlat,zoom)
         elif zarea is not None:           [wlon,wlat] = latinterv(area=zarea)

##########################################################
############ LOAD 4D DIMENSIONS : x, y, z, t #############
##########################################################
      if typefile in ["gcm","earthgcm","ecmwf"]:
          if slon is not None: sslon = slon  
          if slat is not None: sslat = slat  
          ### LAT
          if "latitude" in nc.variables:  lat = nc.variables["latitude"][:]
          elif "lat" in nc.variables:     lat = nc.variables["lat"][:]
          ### LON
          if "longitude" in nc.variables: lon = nc.variables["longitude"][:]
          elif "lon" in nc.variables:     lon = nc.variables["lon"][:]
          ### ALT
          if "altitude" in nc.variables:  vert = nc.variables["altitude"][:]
          elif "Alt" in nc.variables:     vert = nc.variables["Alt"][:]
          elif "lev" in nc.variables:     vert = nc.variables["lev"][:]
          else:                           vert = [0.]
          ### AIRE (to weight means with the area)
          if "aire" in nc.variables:      area = nc.variables["aire"][:,:]  
          else:                           area = None
          ### TIME
          if "Time" in nc.variables:      	time = nc.variables["Time"][:]
          elif "time" in nc.variables:    	time = nc.variables["time"][:]
          elif "time_counter" in nc.variables:	time = nc.variables["time_counter"][:]/86400. #### time counter cinverstion from s-> days
          else:                           	time = [0.] #errormess("no time axis found.")
          if axtime in ["ls"]:
              print "converting to Ls ..."
              for iii in range(len(time)):
                time[iii] = sol2ls(time[iii])
                if iii > 0:
                  while abs(time[iii]-time[iii-1]) > 300:
                    time[iii] = time[iii]+360
          # for 1D plots (no need for longitude computation):
          if axtime in ["lt"]:
              if initime == -1: initime=input("Please type initial local time:")
              time = (initime+time*24)%24
              print "LOCAL TIMES.... ", time
      elif typefile in ['meso','geo']:
          area = None ## not active for the moment
          ###### STUFF TO GET THE CORRECT LAT/LON FROM MESOSCALE FILES WITH 2D LAT/LON ARRAYS
          ###### principle: calculate correct indices then repopulate slon and slat
          if slon is not None or slat is not None:
              if firstfile and save == 'png' and typefile == 'meso' and "HGT" in varinfile and display:   iwantawhereplot = nc     #show a topo map with a cross on the chosen point
              else:                                                                           iwantawhereplot = None   #do not show anything, just select indices
              numlon = 1 ; numlat = 1 
              if slon is not None:   numlon = slon.shape[1]    
              if slat is not None:   numlat = slat.shape[1]
              indices = np.ones([numlon,numlat,2]) ; vlon = None ; vlat = None
              for iii in range(numlon):  
               for jjj in range(numlat):
                 if slon is not None:  vlon = slon[0][iii]  ### note: slon[:][0] does not work
                 if slat is not None:  vlat = slat[0][jjj]  ### note: slon[:][0] does not work
                 indices[iii,jjj,:] = bidimfind(lon2d,lat2d,vlon,vlat,file=iwantawhereplot)  
                 lonp,latp = ( lon2d[indices[iii,jjj,0],indices[iii,jjj,1]] , lat2d[indices[iii,jjj,0],indices[iii,jjj,1]] )
              ### possible bug here if several --lat
              for iii in range(numlon):
               for jjj in range(numlat):
                 if slon is not None: sslon[0][iii] = indices[iii,0,1] #...this is idx
                 if slat is not None: sslat[0][jjj] = indices[0,jjj,0] #...this is idy
              lonp,latp = ( lon2d[indices[0,0,0],indices[0,0,1]] , lat2d[indices[0,0,0],indices[0,0,1]] )
          ######
          if typefile in ['meso'] and mapmode == 1: lon2d = dumpbdy(lon2d,6) ; lat2d = dumpbdy(lat2d,6)  ### important to do that now and not before
          ######
          if varname in ['PHTOT','W']:    vertdim='BOTTOM-TOP_PATCH_END_STAG'
          else:                           vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
          if (var2 is not None and var2 not in ['PHTOT','W']): dumped_vert_stag=True ; vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
          else:                                                dumped_vert_stag=False
          if varname in ['V']:  latdim='SOUTH-NORTH_PATCH_END_STAG'
          else:                 latdim='SOUTH-NORTH_PATCH_END_UNSTAG'
          if varname in ['U']:  londim='WEST-EAST_PATCH_END_STAG'
          else:                 londim='WEST-EAST_PATCH_END_UNSTAG'
          lon = np.arange(0,getattr(nc,londim),1) ; lat = np.arange(0,getattr(nc,latdim),1)
          ###
          if axtime in ["ls","sol"]:
              lstab, soltab, lttab = getlschar ( namefile, getaxis = True )
              if axtime == "ls":      time = lstab 
              elif axtime == "sol":   time = soltab
          else:
              if ope in ["cat"] and nnn > 0: 	count = time[-1] + 1  ## so that a cat is possible with simple subscripts
              else: 				count = 0
              if "Times" in nc.dimensions:   time = count + np.arange(0,len(nc.dimensions["Times"]),1)
              elif "Time" in nc.dimensions:  time = count + np.arange(0,len(nc.dimensions["Time"]),1)
              else:                          time = count + np.arange(0,1,1)
          if axtime in ["lt"]:
              ftime = np.zeros(len(time))
              for i in range(len(time)): 
                 ftime[i] = localtime ( interv[0]+time[i]*interv[1], 0.5*(wlon[0]+wlon[1]) )
              time=ftime
              time=check_localtime(time)
              print "LOCAL TIMES.... ", time

          ###
          if typefile in ['geo']:   vert = [0.] ; stime = readslices(str(0))
          else:
              if vertmode is None:  vertmode=0
              if vertmode == 0:     
                  if "vert" in nc.variables: vert = nc.variables["vert"][:]/1000. ; vertmode = 1
                  else:                      vert = np.arange(0,getattr(nc,vertdim),1)
              elif vertmode == -1:  vert = nc.variables["PHTOT"][0,:,0,0]/3.72 ; vert = np.array(vert[0:len(vert)-1]) #; print vert
              elif vertmode == 1 or vertmode == 2:  vert = nc.variables["vert"][:]        ## pressure in Pa
              else:                                 vert = nc.variables["vert"][:]/1000.  ## altitude in km
       #if firstfile:
       #   lat0 = lat
       #elif len(lat0) != len(lat):
       #   errormess("Not the same latitude lengths !", [len(lat0), len(lat)])
       #elif sum((lat == lat0) == False) != 0:
       #   errormess("Not the same latitudes !", [lat,lat0])
       ## Faire d'autre checks sur les compatibilites entre fichiers!!
##########################################################
##########################################################
##########################################################

      all_varname[k] = varname
      all_namefile[k] = namefile
      all_time[k] = time
      if var2: 
         all_var2[k] = getfield(nc,var2)
         if ((var2 in ['slopexy','SLOPEXY']) and (typefile in ['meso']) and (var2 not in nc.variables)): all_var2[k] = slopeamplitude(nc)
      if winds: all_windu[k] = getfield(nc,uchar) ; all_windv[k] = getfield(nc,vchar)
      #####################
      ##### GETFIELDS #####
      #####################
      ##### SPECIFIC CASES
      ##### 1. saturation temperature
      if varname in ["temp","t","T_nadir_nit","T_nadir_day","temp_day","temp_night"] and tsat:
          tt=getfield(nc,varname) ; print "computing Tsat-T, I ASSUME Z-AXIS IS PRESSURE"
          if type(tt).__name__=='MaskedArray':  tt.set_fill_value([np.NaN]) ; tinput=tt.filled()
          else:                                 tinput=tt
          all_var[k]=get_tsat(vert,tinput,zlon=lon,zlat=lat,zalt=vert,ztime=time)
      ##### 2. wind amplitude
      elif ((varname in ['UV','uv','uvmet']) and (typefile in ['meso']) and (varname not in nc.variables)):
          all_var[k]=windamplitude(nc)
      elif ((varname in ['slopexy','SLOPEXY']) and (typefile in ['meso']) and (varname not in nc.variables)):
          all_var[k]=slopeamplitude(nc)
      elif ((varname in ['DELTAT','deltat']) and (typefile in ['meso']) and (varname not in nc.variables)):
          all_var[k]=deltat0t1(nc)
      else:
      ##### GENERAL STUFF HERE
          all_var[k] = getfield(nc,varname)
      print "**** GOT SUBDATA:",k," NAMEFILE:",namefile," VAR:",varname, var2 ; k += 1 ; firstfile = False
      #### End of for namefile in namefiles

    ##################################
    ### Operation on files
    if ope is not None:
        print "********** OPERATION: ",ope
        if "var" not in ope:
             if len(var) > 1: errormess("for this operation... please set only one var !")
             if ope in ["-","+","-%"]:
                if fileref is not None:   
                   ncref = Dataset(fileref)
                   if ((all_varname[k-1] in ['UV','uv','uvmet']) and (typefile in ['meso']) and (all_varname[k-1] not in ncref.variables)):
                      all_var[k] = windamplitude(ncref)
                   elif ((all_varname[k-1] in ['slopexy','SLOPEXY']) and (typefile in ['meso']) and (all_varname[k-1] not in ncref.variables)):
                      all_var[k] = slopeamplitude(ncref)
                   elif ((all_varname[k-1] in ['DELTAT','deltat']) and (typefile in ['meso']) and (all_varname[k-1] not in ncref.variables)):
                      all_var[k]=deltat0t1(ncref)
                   else:
                      all_var[k] = getfield(ncref,all_varname[k-1])
                   all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1] ; all_var2[k] = all_var2[k-1]
                   if winds: all_windu[k] = getfield(ncref,uchar) ; all_windv[k] = getfield(ncref,vchar)
                else: errormess("fileref is missing!") 
                if ope == "-":     all_var[k+1]= all_var[k-1] - all_var[k]
                elif ope == "+":   all_var[k+1]= all_var[k-1] + all_var[k]
                elif ope == "-%":
                    masked = np.ma.masked_where(all_var[k] == 0,all_var[k])
                    masked.set_fill_value([np.NaN])
                    all_var[k+1]= 100.*(all_var[k-1] - masked)/masked
                all_varname[k+1] = all_varname[k] ; all_time[k+1] = all_time[k] ; all_namefile[k+1] = all_namefile[k] ; all_var2[k+1] = all_var2[k] ; numplot = numplot+2
                if winds: all_windu[k+1] = all_windu[k-1]-all_windu[k] ; all_windv[k+1] = all_windv[k-1] - all_windv[k]
             elif ope in ["cat"]:
                tabtime = all_time[0];tab = all_var[0];k = 1
                if var2: tab2 = all_var2[0]
                while k != len(namefiles) and len(all_time[k]) != 0:
                    if var2: tab2 = np.append(tab2,all_var2[k],axis=0) 
                    tabtime = np.append(tabtime,all_time[k]) ; tab = np.append(tab,all_var[k],axis=0) ; k += 1
                all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1
                if var2: all_var2[0] = np.array(tab2)
             else: errormess(ope+" : non-implemented operation. Check pp.py --help")
        else:
             if len(namefiles) > 1: errormess("for this operation... please set only one file !")  
             if len(var) > 2:       errormess("not sure this works for more than 2 vars... please check.")
             if   ope in ["div_var"]: all_var[k] = all_var[k-2] / all_var[k-1] ; insert = '_div_'
             elif ope in ["mul_var"]: all_var[k] = all_var[k-2] * all_var[k-1] ; insert = '_mul_'
             elif ope in ["add_var"]: all_var[k] = all_var[k-2] + all_var[k-1] ; insert = '_add_'
             elif ope in ["sub_var"]: all_var[k] = all_var[k-2] - all_var[k-1] ; insert = '_sub_'
             else:                    errormess(ope+" : non-implemented operation. Check pp.py --help")
             numplot = numplot + 1 ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1]
             all_varname[k] = all_varname[k-2] + insert + all_varname[k-1] 
    ##################################
    ### Open a figure and set subplots
    fig = figure()
    subv,subh = definesubplot( numplot, fig ) 
    if ope in ['-','-%']: subv,subh = 2,2
 
    #################################
    ### Time loop for plotting device
    nplot = 1 ; error = False 
    if lstyle is not None: linecycler = cycle(lstyle)
    else: linecycler = cycle(["-","--","-.",":"])
    print "********************************************"
    while error is False:
     
       print "********** NPLOT", nplot 
       if nplot > numplot: break

       ####################################################################
       ## get all indexes to be taken into account for this subplot and then reduce field
       ## We plot 1) all lon slices 2) all lat slices 3) all vert slices 4) all time slices and then go to the next slice
       indexlon  = getsindex(sslon,(nplot-1)%nlon,lon)
       indexlat  = getsindex(sslat,((nplot-1)//nlon)%nlat,lat)
       indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) 
       if ope is not None:
           if fileref is not None:      index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(namefiles)+2)  ## OK only 1 var,  see test in the beginning
           elif "var" in ope:           index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(var)+1)        ## OK only 1 file, see test in the beginning
           elif "cat" in ope:           index_f = 0
       else:                            yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah
       time = all_time[index_f]
       if mrate is not None:                 indextime = None 
       else:                                 indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time)
       ltst = None 
       if typefile in ['meso'] and indextime is not None:  ltst = localtime ( interv[0]+indextime*interv[1], 0.5*(wlon[0]+wlon[1]) )  
       print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime
       ##var = nc.variables["phisinit"][:,:]
       ##contourf(np.transpose(var),30,cmap = get_cmap(name="Greys_r") ) ; axis('off') ; plot(indexlat,indexlon,'mx',mew=4.0,ms=20.0)
       ##show()
       ##exit()
       #truc = True 
       #truc = False
       #if truc: indexvert = None
       ####################################################################
       ########## REDUCE FIELDS
       ####################################################################
       error = False
       varname = all_varname[index_f]
       if varname:   ### what is shaded.
           what_I_plot, error = reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area )
           if mult != 2718.:  what_I_plot = what_I_plot*mult 
           else:              what_I_plot = np.log10(what_I_plot) ; print "log plot"
                      
       if var2:      ### what is contoured.
           what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \
                                             yint=yintegral, alt=vert )
       if winds:     ### what is plot as vectors.
           vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
           vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
           if varname in [uchar,vchar]: what_I_plot = np.sqrt( np.square(vecx) + np.square(vecy) ) ; varname = "wind"

       #####################################################################
       #if truc:
       #   nx = what_I_plot.shape[2] ; ny = what_I_plot.shape[1] ; nz = what_I_plot.shape[0] 
       #   for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / smooth(what_I_plot[k,:,:],12)
       #   for iii in range(nx):
       #    for jjj in range(ny):
       #     deviation = what_I_plot[:,jjj,iii] ; mx = max(deviation) ; mn = min(deviation)
       #     if iii > 6 and iii < nx-6 and jjj > 6 and jjj < ny-6:   what_I_plot[0,jjj,iii],rel = singlet(deviation,vert/1000.)  ### z must be in km
       #     else:                                                   what_I_plot[0,jjj,iii]     = 0.
       #     if np.abs(what_I_plot[0,jjj,iii]) > 1.5: 
       #         print iii,jjj,what_I_plot[0,jjj,iii],int(abs(1.-mx)*100.),int(abs(1.-mn)*100.)
       #         plot(rel)
       #   show()
       #   anomaly = True ### pour avoir les bons reglages plots
       #   what_I_plot = what_I_plot[0,:,:]  
       #####################################################################

       ####################################################################
       ### General plot settings
       changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1)  ## default for 1D plots: superimposed. to be reworked for better flexibility.
       if changesubplot: subplot(subv,subh,nplot) #; subplots_adjust(wspace=0,hspace=0)
       ####################################################################
       if error:
               errormess("There is an error in reducing field !")
       else:
               ticks = ndiv + 1 
               fvar = varname 
               if anomaly: fvar = 'anomaly'
               ###
               if mapmode == 0:    ### could this be moved inside imov loop ?
                   itime=indextime
                   if len(what_I_plot.shape) == 3: itime=[0]
                   m = None ; x = None ; y = None
                   latyeah = lat ; lonyeah = lon
                   if typefile in ['meso']:
                       # now that the section is determined we can set the real lat
                       # ... or for now, a temptative one.
                       if slon is not None: latyeah = lat2d[:,0]
                       if slat is not None: lonyeah = lon2d[0,:]
                   what_I_plot, x, y = define_axis(lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
                         itime,what_I_plot, len(all_var[index_f].shape),vertmode)
               ###
               if (fileref is not None) and (index_f == numplot-1):    zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
               else:                                                   zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
               if (fileref is not None) and (index_f == numplot-1):    colorb = "RdBu_r"
               if colorb in ["def","nobar","onebar"]:                  palette = get_cmap(name=defcolorb(fvar.upper()))
               else:                                                   palette = get_cmap(name=colorb)
               #palette = cm.GMT_split
               ##### 1. ELIMINATE 0D or >3D CASES
               if len(what_I_plot.shape) == 0:   
                 print "VALUE VALUE VALUE VALUE ::: ",what_I_plot
                 save = 'donothing'
               elif len(what_I_plot.shape) >= 4:
                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape
                 errormess("Are you sure you did not forget to prescribe a dimension ?")
               ##### 2. HANDLE simple 1D/2D field and movies of 1D/2D fields
               else:
                 if mrate is not None: iend=len(time)-1
                 else:                 iend=0
                 imov = 0 
                 if len(what_I_plot.shape) == 3:
                    if var2:               which = "contour" ## have to start with contours rather than shading
                    else:                  which = "regular"
                    if mrate is None:      errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.")
                 elif len(what_I_plot.shape) == 2:
                    if var2:               which = "contour" ## have to start with contours rather than shading
                    else:                  which = "regular"
                    if mrate is not None:  which = "unidim"
                 elif len(what_I_plot.shape) == 1:
                    which = "unidim"
                    if what_I_plot.shape[-1] == 1:      print "VALUE VALUE VALUE VALUE ::: ", what_I_plot[0] ; save = 'donothing'
                 ##### IMOV LOOP #### IMOV LOOP
                 while imov <= iend:
                    print "-> frame ",imov+1, which
                    if which == "regular":   
                        if mrate is None:                                   what_I_plot_frame = what_I_plot
                        else:                                               what_I_plot_frame = what_I_plot[imov,:,:]
                        if winds:
                            if mrate is None:                                   vecx_frame = vecx ; vecy_frame = vecy
                            else:                                               vecx_frame = vecx[imov,:,:] ; vecy_frame = vecy[imov,:,:]
                    elif which == "contour":  
                        if mrate is None or what_I_plot_contour.ndim < 3:   what_I_plot_frame = what_I_plot_contour
                        else:                                               what_I_plot_frame = what_I_plot_contour[imov,:,:]
                    elif which == "unidim":
                        if mrate is None:                                   what_I_plot_frame = what_I_plot
                        else:                                               what_I_plot_frame = what_I_plot[:,imov]  ## because swapaxes 
                    #if mrate is not None:     
                    if mapmode == 1: 
                            m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)  ## this is dirty, defined above but out of imov loop
                            x, y = m(lon2d, lat2d)                                         ## this is dirty, defined above but out of imov loop
                    if typefile in ['meso'] and mapmode == 1:   what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True)
#                   if typefile in ['mesoideal']:    what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag)

                    if which == "unidim":
                        if lbls is not None: lbl=lbls[nplot-1] 
                        else:
                           lbl = ""
                           if indexlat is not None:  lbl = lbl + " ix" + str(indexlat[0])
                           if indexlon is not None:  lbl = lbl + " iy" + str(indexlon[0])
                           if indexvert is not None: lbl = lbl + " iz" + str(indexvert[0])
                           if indextime is not None: lbl = lbl + " it" + str(indextime[0])
                           if lbl == "": lbl = all_namefile[index_f]

                        if mrate is not None: x = y  ## because swapaxes...
                        #what_I_plot_frame = np.diff(what_I_plot_frame, n=1) ; x = x[1:]
                      
                        zeline = next(linecycler) ## "-" for simple lines
                        if tile:      zemarker = 'x'
                        else:         zemarker = None 
                        this_is_a_regular_plot = (indexvert is not None) or (indextime is None) or (indexlat is None) or (indexlon is None)
                        if this_is_a_regular_plot:   plot(x,what_I_plot_frame,zeline,label=lbl,marker=zemarker)  ## vertical profile
                        else:                        plot(what_I_plot_frame,x,zeline,label=lbl,marker=zemarker)  ## regular plot
                        if nplot > 1: legend(loc='best')
                        if indextime is None and axtime is not None and xlab is None:    xlabel(axtime.upper()) ## define the right label
                        if save == 'txt':  writeascii(np.transpose([x,np.transpose(what_I_plot)]),'profile'+str(nplot*1000+imov)+'.txt')

                    elif which == "regular":
                    
                        # plot stream lines if there is a stream file and a vert/lat slice. Might not work with movies ??
                        if streamflag and sslat is None and svert is None:
                             streamfile = all_namefile[index_f].replace('.nc','_stream.nc')
                             teststream = os.path.exists(streamfile)
                             if teststream:
                                print 'INFO: Using stream file',streamfile, 'for stream lines'
                                ncstream = Dataset(streamfile)
                                psi = getfield(ncstream,'psi')
                                psi = psi[0,:,:,0] # time and longitude are dummy dimensions
                                if psi.shape[1] != len(x) or psi.shape[0] != len(y):
                                    errormess('stream file does not fit! Dimensions: '+str(psi.shape)+' '+str(x.shape)+' '+str(y.shape))
                                zelevels = np.arange(-1.e10,1.e10,1.e9)
                                zemin = np.min(abs(zelevels))
                                zemax = np.max(abs(zelevels))
                                zewidth  =  (abs(zelevels)-zemin)*(5.- 0.5)/(zemax - zemin) + 0.5 # linewidth ranges from 5 to 0.5
                                cs = contour( x,y,psi, zelevels, colors='k', linewidths = zewidth)
                                clabel(cs, inline=True, fontsize = 4.*rcParams['font.size']/5., fmt="%1.1e")
                             else:
                                print 'WARNING: STREAM FILE',streamfile, 'DOES NOT EXIST !'
                             
                        if hole:         what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax)
                        else:            what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax)
                        if flagnolow:    what_I_plot_frame = nolow(what_I_plot_frame)
                        if not tile:
                            #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
                            zelevels = np.linspace(zevmin,zevmax,num=ticks)
                            #what_I_plot_frame = smooth(what_I_plot_frame,100)
                            if mapmode == 1:       m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
                            elif mapmode == 0:     contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
                            if cross is not None and mapmode == 1:
                               idx,idy=m(cross[0][0],cross[0][1])
                               mpl.pyplot.plot([idx],[idy],'+k',mew=0.5,ms=18)
                        else:
                            if mapmode == 1:       m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
                            elif mapmode == 0:     pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
                        

                        if colorb not in ['nobar','onebar']:        
                            if (fileref is not None) and (index_f == numplot-1):   daformat = "%.3f" 
                            elif mult != 1:                                        daformat = "%.1f"
                            else:                                                  daformat = fmtvar(fvar.upper())
                            #if proj in ['moll','cyl']:  zeorientation="horizontal" ; zepad = 0.05
                            if proj in ['moll']:        zeorientation="horizontal" ; zepad = 0.05
                            else:                       zeorientation="vertical" ; zepad = 0.03
                            zecb = colorbar( fraction=0.05,pad=zepad,format=daformat,orientation=zeorientation,\
                                      ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) 
                            if zeorientation == "horizontal" and zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]=""
                        if winds:
                            if typefile in ['meso']:
                                [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)]
                                key = True
                                if fvar in ['UV','uv','uvmet']: key = False
                            elif typefile in ['gcm']:
                                key = False
                            if metwind and mapmode == 1:   [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d)
                            if var:       colorvec = definecolorvec(colorb) 
                            else:         colorvec = definecolorvec(back) 
                            vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\
                                             #scale=15., factor=300., color=colorvec, key=key)
                                             scale=20., factor=250., color=colorvec, key=key)
                                                              #200.         ## or csmooth=stride
                        if ope == '-' and nplot == numplot: # this should work as long as ope is '-' guarantees 3 plots for 4 panels without contour
                            subplot(subv,subh,nplot+1)
                            rcParams["legend.fontsize"] = 'xx-large'
                            if indexlat is None:
                                latmin = -50.; latmax = 50. # latitude range for histogram of difference
                                zeindexlat = (lat<latmax)*(lat>latmin)
                                # this follows the define_axis logic in myplot.py:
                                if indextime is None or indexlon is None: what_I_plot_frame = what_I_plot_frame[zeindexlat,:]
                                else: what_I_plot_frame = what_I_plot_frame[:,zeindexlat]
                            toplot = np.ravel(what_I_plot_frame[np.isnan(what_I_plot_frame)==False])
                            zebins = np.linspace(zevmin,zevmax,num=30)
                            hist(toplot,bins=zebins,histtype='step',linewidth=2,color='k',normed=True)
                            zestd = np.std(toplot);zemean = np.mean(toplot)
                            zebins = np.linspace(zevmin,zevmax,num=300)
                            zegauss = (1./(zestd * np.sqrt(2 * np.pi)) * np.exp( - (zebins - zemean)**2 / (2 * zestd**2) ) )
                            plot(zebins, zegauss, linewidth=1, color='r',label="mean: "+str(zemean)[0:5]+"\nstd: "+str(zestd)[0:5])
                            legend(loc=0,frameon=False)
                            title("Histogram fig(1) "+ope+" fig(2)")
                            subplot(subv,subh,nplot) # go back to last plot for title of contour difference
                            
                    elif which == "contour":
                        zevminc, zevmaxc = calculate_bounds(what_I_plot_frame, vmin=min(what_I_plot_frame), vmax=max(what_I_plot_frame))
                        zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20)
                        if var2 == 'HGT':     zelevels = np.arange(-10000.,30000.,1000.)
                        elif var2 == 'tpot':  zelevels = np.arange(270,370,5)
                        elif var2 == 'tk':    zelevels = np.arange(150,250,5)
                        if mapmode == 0:   
                            what_I_plot_frame, x, y = define_axis( lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
                                                              itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode )
                            ## is this needed? only if len(all_var2[index_f].shape) != len(all_var[index_f].shape)
                            cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
                            clabel(cs, inline=1, fontsize = 4.*rcParams['font.size']/5., fmt=fmtvar(var2.upper()))
                        elif mapmode == 1:  cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
                    if which in ["regular","unidim"]:

                        if nplot > 1 and which == "unidim":
                           pass  ## because we superimpose nplot instances
                        else:
                           # Axis directives for movie frames [including the first one).
                           zxmin, zxmax = xaxis ; zymin, zymax = yaxis
                           if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin)
                           if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax)
                           if zymin is not None: mpl.pyplot.ylim(ymin=zymin)
                           if zymax is not None: mpl.pyplot.ylim(ymax=zymax)
                           if ylog:      mpl.pyplot.semilogy()
                           if invert_y:  ax = mpl.pyplot.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
                           if xlab is not None: xlabel(xlab)
                           if ylab is not None: ylabel(ylab)

                        if mrate is not None:
                           ### THIS IS A MENCODER MOVIE
                           if mrate > 0:
                             figframe=mpl.pyplot.gcf()
                             if mquality:   figframe.set_dpi(600.)
                             else:          figframe.set_dpi(200.)
                             mframe=fig2img(figframe)
                             if imov == 0:
                                moviename='movie' ;W,H = figframe.canvas.get_width_height()
                                video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba")
                             video.run(mframe) ; close()
                             if imov == iend: video.close()                            
                           ### THIS IS A WEBPAGE MOVIE 
                           else:
                             nameframe = "image"+str(1000+imov)
                             makeplotres(nameframe,res=100.,disp=False) ; close()
                             if imov == 0: myfile = open("zepics", 'w')
                             myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n')
                             if imov == iend:
                                 myfile.write("first_image = 0;"+ '\n')
                                 myfile.write("last_image = "+str(iend)+";"+ '\n')
                                 myfile.close()
                        if var2 and which == "regular":  which = "contour"
                        imov = imov+1
                    elif which == "contour":
                        which = "regular"

       ### Next subplot
       zevarname = varname
       if redope is not None: zevarname = zevarname + "_" + redope 
       basename = getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly)
       if len(what_I_plot.shape) > 3:
           basename = basename + getstralt(nc,level) 
       if mrate is not None: basename = "movie_" + basename 
       if typefile in ['meso']:
            if sslon is not None: basename = basename + "_lon_" + str(int(round(lonp)))
            if sslat is not None: basename = basename + "_lat_" + str(int(round(latp)))
            plottitle = basename
            ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus)
            if addchar and indextime is not None:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
            ### en fait redope is None doit etre remplace par : n'est ni maxt ni mint
            if redope is None and ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ):  plottitle = plottitle + "_LT" + str(ltst)
       else:
            if fileref is not None:
                if index_f is numplot-1:     plottitle = basename+' '+"fig(1) "+ope+" fig(2)"
                elif index_f is numplot-2:   plottitle = basename+' '+fileref
                else:                        plottitle = basename+' '+all_namefile[index_f]
            else:                            plottitle = basename+' '+all_namefile[index_f]
       if mult != 1:                         plottitle = '{:.0e}'.format(mult) + "*" + plottitle
       if zetitle[0] != "fill":                 
          if index_f < len(zetitle): plottitle = zetitle[index_f]
          else: plottitle = zetitle[0]
          if titleref is "fill":             titleref=zetitle[index_f]
          if fileref is not None:
             if index_f is numplot-2:        plottitle = titleref
             if index_f is numplot-1:        plottitle = "fig(1) "+ope+" fig(2)"
#       if indexlon is not None:      plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon]))
#       if indexlat is not None:      plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat]))
#       if indexvert is not None:     plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
#       if indextime is not None:     plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
       if colorb != "onebar": title( plottitle )
       if nplot >= numplot: error = True
       nplot += 1

    if colorb == "onebar":
        cax = axes([0.1, 0.2, 0.8, 0.03]) # a ameliorer
        zecb = colorbar(cax=cax, orientation="horizontal", format=fmtvar(fvar.upper()),\
                 ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional')
        if zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]=""


    ##########################################################################
    ### Save the figure in a file in the data folder or an user-defined folder
    if outputname is None:
       if typefile in ['meso']:   prefix = getprefix(nc)
       elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
       else:                                prefix = ''
    ###
       zeplot = prefix + basename 
       if addchar:         zeplot = zeplot + addchar
       if numplot <= 0:    zeplot = zeplot + "_LT"+str(abs(numplot))
    ###
       if not target:      zeplot = namefile[0:find(namefile,'wrfout')] + zeplot
       else:               zeplot = target + "/" + zeplot  
    ###
    else:
       zeplot=outputname

    if mrate is None:
        pad_inches_value = 0.35
        print "********** SAVE ", save
        if save == 'png': 
            if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
            makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
        elif save in ['eps','svg','pdf']:     makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save)
        elif save == 'gui':                   show()
        elif save == 'donothing':             pass
        elif save == 'txt':                   print "Saved results in txt file." 
        else: 
            print "INFO: save mode not supported. using gui instead."
            show()

    ###################################
    #### Getting more out of this video -- PROBLEMS WITH CREATED VIDEOS
    #
    #if mrate is not None:
    #    print "Re-encoding movie.. first pass"
    #    video.first_pass(filename=moviename,quality=mquality,rate=mrate)
    #    print "Re-encoding movie.. second pass"
    #    video.second_pass(filename=moviename,quality=mquality,rate=mrate)   

    ###############
    ### Now the end
    return zeplot
