Index: /TOOLS/MOSAIX/CalvingWeights.py
===================================================================
--- /TOOLS/MOSAIX/CalvingWeights.py	(revision 6665)
+++ /TOOLS/MOSAIX/CalvingWeights.py	(revision 6666)
@@ -25,58 +25,100 @@
 ##  software by incorrectly or partially configured
 ##
-##
-import numpy as np, xarray as xr
-import sys, os, platform, argparse, textwrap, time
+'''Python code to generates weights for calving. Launched by `CreateWeights.bash`.
+
+More information with python `CalvingWeights.py -h`.
+
+- The atmosphere model integrate the calving over on specific
+  regions. Presently the regions are three latitudinal bands with
+  limits 90Â°S/40Â°S/50Â°N/90Â°N.
+
+- The weights distribute the calving in the ocean in the
+  corresponding latitudinal bands. By default, the distribution is
+  uniform.
+
+- For the southernmost band, it is possible to use a geographical
+  distribution read in a file. These files are currently available
+  for eORCA1 and eORCA025.
+
+## SVN information
+Author   = "$Author$"
+Date     = "$Date$"
+Revision = "$Revision$"
+Id       = "$Id$"
+HeadURL  = "$HeadURL$"
+'''
+import sys
+import os
+import getpass
+import platform
+import argparse
+import time
+import numpy as np
+import xarray as xr
 from scipy import ndimage
 import nemo
 
 ## SVN information
-__Author__   = "$Author$"
-__Date__     = "$Date$"
-__Revision__ = "$Revision$"
-__Id__       = "$Id$"
-__HeadURL__  = "$HeadURL$"
-__SVN_Date__ = "$SVN_Date: $"
-
+__SVN__ =  ( {
+    'Author'   : "$Author$",
+    'Date'     : '$Date$',
+    'Revision' : '$Revision$',
+    'Id'       : '$Id$',
+    'HeadURL'  : '$HeadURL$',
+    'SVN_Date' : '$SVN_Date: $',
+    } )
 ###
 
-### ===== Handling command line parameters ==================================================
+### ===== Handling command line parameters ==========================
 # Creating a parser
 parser = argparse.ArgumentParser (
-    description = """Compute calving weights""",
+    description = '''Compute calving weights''',
     epilog='-------- End of the help message --------')
 
 # Adding arguments
 parser.add_argument ('--oce'     , help='oce model name', type=str, default='eORCA1.2',
-                         choices=['ORCA2.3', 'ORCA1.0', 'ORCA1.1', 'ORCA1_CNRM', 'eORCA1.2', 'eORCA1.4', 'eORCA1.4.2', 'eORCA025', 'eORCA025.1', 'eORCA025.4'] )
-parser.add_argument ('--atm'     , help='atm model name (ICO* or LMD*)', type=str, default='ICO40'    )
-parser.add_argument ('--type'    , help='Type of distribution', type=str, choices=['iceshelf', 'iceberg', 'nosouth', 'full'], default='full'  )
+                      choices=['ORCA2.3', 'ORCA1.0', 'ORCA1.1', 'ORCA1_CNRM', 'eORCA1.2',
+                               'eORCA1.4', 'eORCA1.4.2', 'eORCA025', 'eORCA025.1', 'eORCA025.4'] )
+parser.add_argument ('--atm'     , type=str, default='ICO40',
+                         help='atm model name (ICO* or LMD*)' )
+parser.add_argument ('--type'    , help='Type of distribution', type=str,
+                         choices=['iceshelf', 'iceberg', 'nosouth', 'full'], default='full'  )
 ## parser.add_argument ('--dir'     , help='Directory of input file', type=str, default='./' )
-parser.add_argument ('--repartition_file', help='Data files with iceberg melting' , type=str, default='./runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc' )
-parser.add_argument ('--repartition_var' , help='Variable name for iceshelf'      , type=str, default=None)
+parser.add_argument ('--repartition_file', help='Data files with iceberg melting' , type=str,
+                         default='./runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc' )
+parser.add_argument ('--repartition_var' , type=str, default=None,
+                         help='Variable name for iceshelf' )
 parser.add_argument ('--grids' , help='grids file name', default='grids.nc' )
 parser.add_argument ('--areas' , help='masks file name', default='areas.nc' )
 parser.add_argument ('--masks' , help='areas file name', default='masks.nc' )
 parser.add_argument ('--o2a'   , help='o2a file name'  , default='o2a.nc'   )
-parser.add_argument ('--output'  , help='output rmp file name', default='rmp_tlmd_to_torc_calving.nc' )
-parser.add_argument ('--fmt'     , help='NetCDF file format, using nco syntax', default='netcdf4',
-                         choices=['classic', 'netcdf3', '64bit', '64bit_data', '64bit_data', 'netcdf4', 'netcdf4_classsic'] )
-parser.add_argument ('--ocePerio', help='periodicity of ocean grid', type=float, default=0, choices=nemo.nperio_valid_range )
+parser.add_argument ('--output', help='output rmp file name',
+                         default='rmp_tlmd_to_torc_calving.nc' )
+parser.add_argument ('--fmt' , default='netcdf4'    ,
+                         help='NetCDF file format, using nco syntax',
+                         choices=['classic', 'netcdf3', '64bit', '64bit_data',
+                                  '64bit_data', 'netcdf4', 'netcdf4_classsic'] )
+parser.add_argument ('--ocePerio', type=float, default=0, choices=nemo.NPERIO_VALID_RANGE,
+                         help='periodicity of ocean grid' )
+parser.add_argument ('--modelName'   , help='Name of model', type=str, default=None)
 
 # Parse command line
-myargs = parser.parse_args()
+myargs = parser.parse_args ()
 
 # Model Names
-src_Name = myargs.atm ; dst_Name = myargs.oce
-    
+src_Name   = myargs.atm
+dst_Name   = myargs.oce
+model_name = myargs.modelName
+
 # Default vars
-if myargs.repartition_var == None :
+if myargs.repartition_var is None :
     # Runoff from Antarctica iceshelves (Depoorter, 2013)
-    if myargs.type == 'iceshelf' : repartitionVar = 'sornfisf'
-        
+    if myargs.type == 'iceshelf' :
+        repartitionVar = 'sornfisf'
     # Runoff from Antarctica iceberg (Depoorter, 2013)
-    if myargs.type == 'iceberg' :  repartitionVar = 'Icb_Flux'
-        
-else :                             repartitionVar = myargs.repartition_var
+    if myargs.type == 'iceberg' :
+        repartitionVar = 'Icb_Flux'
+else :
+    repartitionVar = myargs.repartition_var
 
 # Latitude limits of each calving zone
@@ -92,8 +134,9 @@
 if myargs.fmt == 'netcdf4'         : FmtNetcdf = 'NETCDF4'
 if myargs.fmt == 'netcdf4_classic' : FmtNetcdf = 'NETCDF4_CLASSIC'
-### ==========================================================================================
+### =====================================================================
 
 # Model short names
-src_name = None ; dst_name = None
+src_name = None
+dst_name = None
 if src_Name.count('ICO')  != 0 : src_name = 'ico'
 if src_Name.count('LMD')  != 0 : src_name = 'lmd'
@@ -138,5 +181,5 @@
     if dst_Name in ['eORCA1.2', 'eORCA1.3']          : nperio_dst = 6
     if dst_Name in ['ORCA025', 'eORCA025', 'eORCA025.1', 'eORCA025.4'] : nperio_dst = 6
-        
+
 print ('nperio_dst: ' + str(nperio_dst) )
 dst_mskutil = nemo.lbc_mask (dst_mskutil, nperio=nperio_dst, cd_type='T', sval=0 )
@@ -161,5 +204,5 @@
     # Set Hudson Strait to 0 to fill Hudson Bay
     dst_mskutil[997:1012,907] = 0
-    
+
 if dst_Name in [ 'eORCA1.2', 'eORCA1.3', 'eORCA1.4', 'eORCA1.4.2' ] :
     print ('Filling some seas for ' + dst_Name)
@@ -174,5 +217,5 @@
     # Set Hudson Strait to 0 to fill Hudson Bay
     dst_mskutil[284,222:225] = 0
-    
+
 if dst_Name in [ 'ORCA2.3', 'ORCA2.4' ] :
     print ('Filling some seas for ' + dst_Name)
@@ -193,5 +236,7 @@
 # Fill closed seas with image processing library
 # ----------------------------------------------
-dst_mskutil = nemo.lbc_mask ( 1-ndimage.binary_fill_holes (1-nemo.lbc(dst_mskutil, nperio=nperio_dst, cd_type='T')), nperio=nperio_dst, cd_type='T', sval=0)
+dst_mskutil = nemo.lbc_mask ( 1-ndimage.binary_fill_holes (
+    1-nemo.lbc(dst_mskutil, nperio=nperio_dst, cd_type='T')),
+                              nperio=nperio_dst, cd_type='T', sval=0)
 
 # Surfaces
@@ -208,10 +253,12 @@
 
 # Indices
-( src_jpj, src_jpi) = src_lat.shape ; src_grid_size = src_jpj*src_jpi
-( dst_jpj, dst_jpi) = dst_lat.shape ; dst_grid_size = dst_jpj*dst_jpi
+( src_jpj, src_jpi) = src_lat.shape
+src_grid_size = src_jpj*src_jpi
+( dst_jpj, dst_jpi) = dst_lat.shape
+dst_grid_size = dst_jpj*dst_jpi
 orc_index = np.arange (dst_jpj*dst_jpi, dtype=np.int32) + 1 # Fortran indices (starting at one)
 
-### ===== Reading needed data ==================================================
-if myargs.type in ['iceberg', 'iceshelf' ]: 
+### ===== Reading needed data ========================================
+if myargs.type in ['iceberg', 'iceshelf' ]:
     # Reading data file for calving or iceberg geometry around Antarctica
     print ( 'Opening ' + myargs.repartition_file)
@@ -226,5 +273,5 @@
 print (' ')
 
-### ===== Starting loop on basins==============================================
+### ===== Starting loop on basins=====================================
 
 # Initialise some fields
@@ -238,42 +285,62 @@
 ## Loop
 for n_bas in np.arange ( nb_zone ) :
-    south = False ; ok_run = False
-    lat_south = np.min(limit_lat[n_bas]) ; lat_north = np.max(limit_lat[n_bas])
+    south  = False
+    ok_run = False
+    lat_south = np.min(limit_lat[n_bas])
+    lat_north = np.max(limit_lat[n_bas])
     if lat_south <= -60.0 : south = True
-    
-    print ( 'basin: {:2d} -- Latitudes: {:+.1f} {:+.1f} --'.format(n_bas, lat_south, lat_north) )
+
+    print ( f'basin: {n_bas:2d} -- Latitudes: {lat_south:+.1f} {lat_north:+.1f} --' )
     ##
-    if myargs.type == 'iceberg'  and     south : ok_run = True  ; print ('Applying iceberg to south' )
-    if myargs.type == 'iceshelf' and     south : ok_run = True  ; print ('Applying iceshelf to south' )
-    if myargs.type == 'iceberg'  and not south : ok_run = False ; print ('Skipping iceberg: not south ')
-    if myargs.type == 'iceshelf' and not south : ok_run = False ; print ('Skipping iceshelf: not south ')
-    if myargs.type == 'nosouth'  and     south : ok_run = False ; print ('Skipping south: nosouth case' )
-    if myargs.type == 'nosouth'  and not south : ok_run = True  ; print ('Running: not in south, uniform repartition')
-    if myargs.type == 'full'                   : ok_run = True  ; print ('Running general trivial case, uniform repartition' )
+    if myargs.type == 'iceberg'  and     south :
+        ok_run = True
+        print ('Applying iceberg to south' )
+    if myargs.type == 'iceshelf' and     south :
+        ok_run = True
+        print ('Applying iceshelf to south' )
+    if myargs.type == 'iceberg'  and not south :
+        ok_run = False
+        print ('Skipping iceberg: not south ')
+    if myargs.type == 'iceshelf' and not south :
+        ok_run = False
+        print ('Skipping iceshelf: not south ')
+    if myargs.type == 'nosouth'  and     south :
+        ok_run = False
+        print ('Skipping south: nosouth case' )
+    if myargs.type == 'nosouth'  and not south :
+        ok_run = True
+        print ('Running: not in south, uniform repartition')
+    if myargs.type == 'full' :
+        ok_run = True
+        print ('Running general trivial case, uniform repartition' )
 
     if ok_run :
         # Calving integral send to one point per latitude bands
         index_src = ((src_grid_size - 1)*n_bas) // (nb_zone-1) + 1
-   
+
         # Basin mask
-        basin_msk[n_bas] = np.where ( (dst_lat > lat_south ) & (dst_lat <= lat_north ), dst_mskutil, 0 )
+        basin_msk[n_bas] = np.where ( (dst_lat > lat_south ) & (dst_lat <= lat_north ),
+                                          dst_mskutil, 0 )
 
         # Repartition pattern
-        if myargs.type in ['iceberg', 'iceshelf' ] : key_repartition[n_bas] = repartition * basin_msk[n_bas]
-        else :                                       key_repartition[n_bas] =               basin_msk[n_bas]
+        if myargs.type in ['iceberg', 'iceshelf' ] :
+            key_repartition[n_bas] = repartition * basin_msk[n_bas]
+        else :
+            key_repartition[n_bas] =               basin_msk[n_bas]
 
         # Integral and normalisation
         sum_repartition = np.sum ( key_repartition[n_bas] * dst_srfutil ).values
         key_repartition = key_repartition / sum_repartition
-    
+
         print ( 'Sum of repartition key                      : {:12.3e}'.format (np.sum (key_repartition[n_bas]               )) )
         print ( 'Integral (area weighted) of repartition key : {:12.3e}'.format (np.sum (key_repartition[n_bas] * dst_srfutil ).values) )
-    
+
         # Basin surface (modulated by repartition key)
         basin_srfutil = np.sum ( key_repartition[n_bas] * dst_srfutil )
-            
+
         # Weights and links
         poids = 1.0 / basin_srfutil
-        matrix_local   = np.where ( basin_msk[n_bas].ravel() > 0.5, key_repartition[n_bas].ravel()*poids.values, 0. )
+        matrix_local   = np.where ( basin_msk[n_bas].ravel() > 0.5,
+                                        key_repartition[n_bas].ravel()*poids.values, 0. )
         matrix_local   = matrix_local[matrix_local > 0.0] # Keep only non zero values
         num_links      = np.count_nonzero (matrix_local)
@@ -289,18 +356,16 @@
         #
         #print ( 'Sum of remap_matrix : {:12.3e}'.format(np.sum(matrix_local)) )
-        print ( 'Point in atmospheric grid : {:4d} -- num_links: {:6d}'.format(index_src, num_links) ) 
+        print ( 'Point in atmospheric grid : {index_src:4d} -- num_links: {num_links:6d}' )
         print ('  ')
-
-
 
 ## End of loop
 print (' ')
 
-# 
+#
 num_links = np.count_nonzero (remap_matrix)
-print ( 'Total num_links : {:10d}'.format(num_links) )
+print ( f'Total num_links : {num_links:10d}' )
 
 # Diag : interpolate uniform field
-src_field = np.zeros(shape=(src_grid_size))
+src_field = np.zeros(shape=(src_grid_size,))
 for n_bas in np.arange ( nb_zone ) :
     index_src = ((src_grid_size - 1)*n_bas) // (nb_zone-1) + 1
@@ -311,78 +376,105 @@
     dst_field [dst_address [link]-1] +=  remap_matrix[link] * src_field[src_address[link]-1]
 
-### ===== Writing the weights file, for OASIS MCT ==========================================
+### ===== Writing the weights file, for OASIS MCT =======================
 
 # Output file
 calving = myargs.output
-    
+
 print ('Output file: ' + calving )
 
-remap_matrix = xr.DataArray (np.reshape(remap_matrix, (num_links, 1)), dims = ['num_links', 'num_wgts'] )
-src_address  = xr.DataArray (src_address.astype(np.int32) , dims = ['num_links',] )
-src_address.attrs['convention'] = "Fortran style addressing, starting at 1"
-dst_address  = xr.DataArray (dst_address.astype(np.int32) , dims =  ['num_links',] )
-dst_address.attrs['convention'] = "Fortran style addressing, starting at 1"
-
-src_grid_dims       = xr.DataArray ( np.array (( src_jpi, src_jpi ), dtype=np.int32), dims =  ['src_grid_rank',] )
+remap_matrix = xr.DataArray (np.reshape(remap_matrix, (num_links, 1)),
+                                 dims = ['num_links', 'num_wgts'] )
+src_address  = xr.DataArray (src_address.astype(np.int32) ,
+                                 dims = ['num_links',] )
+src_address.attrs['convention'] = 'Fortran style addressing, starting at 1'
+dst_address  = xr.DataArray (dst_address.astype(np.int32) ,
+                                 dims =  ['num_links',] )
+dst_address.attrs['convention'] = 'Fortran style addressing, starting at 1'
+
+src_grid_dims       = xr.DataArray ( np.array (( src_jpi, src_jpi ), dtype=np.int32),
+                                         dims =  ['src_grid_rank',] )
 src_grid_center_lon = xr.DataArray ( src_lon.values.ravel(), dims = ['src_grid_size',] )
 src_grid_center_lat = xr.DataArray ( src_lat.values.ravel(), dims = ['src_grid_size',] )
-src_grid_center_lon.attrs['units']='degrees_east'  ; src_grid_center_lon.attrs['long_name']='Longitude'
-src_grid_center_lon.attrs['long_name']='longitude' ; src_grid_center_lon.attrs['bounds']="src_grid_corner_lon" 
-src_grid_center_lat.attrs['units']='degrees_north' ; src_grid_center_lat.attrs['long_name']='Latitude'
-src_grid_center_lat.attrs['long_name']='latitude ' ; src_grid_center_lat.attrs['bounds']="src_grid_corner_lat" 
-src_grid_corner_lon = xr.DataArray ( src_clo.values.reshape( (src_jpi*src_jpj, src_clo.shape[0]) ), dims = ['src_grid_size', 'src_grid_corners'] )
-src_grid_corner_lat = xr.DataArray ( src_cla.values.reshape( (src_jpi*src_jpj, src_clo.shape[0]) ), dims = ['src_grid_size', 'src_grid_corners' ] )
-src_grid_corner_lon.attrs['units']="degrees_east"
-src_grid_corner_lat.attrs['units']="degrees_north"
+src_grid_center_lon.attrs.update ( {'units':'degrees_east ', 'long_name':'Longitude',
+                                        'standard_name':'longitude',
+                                        'bounds':'src_grid_corner_lon'})
+src_grid_center_lat.attrs.update ( {'units':'degrees_north', 'long_name':'Latitude' ,
+                                        'standard_name':'latitude' ,
+                                        'bounds':'src_grid_corner_lat'})
+src_grid_corner_lon = xr.DataArray ( src_clo.values.reshape( (src_jpi*src_jpj, src_clo.shape[0]) ),
+                                         dims = ['src_grid_size', 'src_grid_corners'] )
+src_grid_corner_lat = xr.DataArray ( src_cla.values.reshape( (src_jpi*src_jpj, src_clo.shape[0]) ),
+                                         dims = ['src_grid_size', 'src_grid_corners' ] )
+src_grid_corner_lon.attrs['units']='degrees_east'
+src_grid_corner_lat.attrs['units']='degrees_north'
 src_grid_area       = xr.DataArray ( src_srf.values.ravel(), dims = ['src_grid_size',] )
-src_grid_area.attrs['long_name']="Grid area" ; src_grid_area.attrs['standard_name']="cell_area" ; src_grid_area.attrs['units']="m2"
-src_grid_imask      = xr.DataArray ( src_msk.values.ravel().astype(np.int32) , dims = ['src_grid_size',] )
-src_grid_imask.attrs['long_name']="Land-sea mask" ; src_grid_imask.attrs['units']="Land:1, Ocean:0"
+src_grid_area.attrs.update ({'long_name':'Grid area', 'standard_name':'cell_area', 'units':'m2'})
+src_grid_imask      = xr.DataArray ( src_msk.values.ravel().astype(np.int32) ,
+                                         dims = ['src_grid_size',] )
+src_grid_imask.attrs.update ( {'long_name':'-sea mask', 'units':'Land:1, Ocean:0' })
 
 # --
-dst_grid_dims       = xr.DataArray ( np.array(( dst_jpi, dst_jpi), dtype=np.int32) , dims = ['dst_grid_rank', ])
+dst_grid_dims       = xr.DataArray ( np.array(( dst_jpi, dst_jpi), dtype=np.int32) ,
+                                         dims = ['dst_grid_rank', ])
 dst_grid_center_lon = xr.DataArray ( dst_lon.values.ravel(), dims = ['dst_grid_size', ])
 dst_grid_center_lat = xr.DataArray ( dst_lat.values.ravel(), dims = ['dst_grid_size', ])
-dst_grid_center_lon.attrs['units']='degrees_east'  ; dst_grid_center_lon.attrs['long_name']='Longitude'
-dst_grid_center_lon.attrs['long_name']='longitude' ; dst_grid_center_lon.attrs['bounds']="dst_grid_corner_lon" 
-dst_grid_center_lat.attrs['units']='degrees_north' ; dst_grid_center_lat.attrs['long_name']='Latitude'
-dst_grid_center_lat.attrs['long_name']='latitude'  ; dst_grid_center_lat.attrs['bounds']="dst_grid_corner_lat" 
-dst_grid_corner_lon = xr.DataArray ( dst_clo.values.reshape(dst_jpi*dst_jpj, dst_clo.shape[0] ), dims = ['dst_grid_size', 'dst_grid_corners'] )
-dst_grid_corner_lat = xr.DataArray ( dst_cla.values.reshape(dst_jpi*dst_jpj, dst_clo.shape[0] ), dims = ['dst_grid_size', 'dst_grid_corners'] )
-dst_grid_corner_lon.attrs['units']="degrees_east"
-dst_grid_corner_lat.attrs['units']="degrees_north"
+dst_grid_center_lon.attrs.update ( {'units':'degrees_east ', 'long_name':'Longitude',
+                                        'standard_name':'longitude',
+                                        'bounds':'dst_grid_corner_lon'})
+dst_grid_center_lat.attrs.update ( {'units':'degrees_north', 'long_name':'Latitude' ,
+                                        'standard_name':'latitude' ,
+                                        'bounds':'dst_grid_corner_lat'})
+dst_grid_corner_lon = xr.DataArray ( dst_clo.values.reshape(dst_jpi*dst_jpj, dst_clo.shape[0] ),
+                                         dims = ['dst_grid_size', 'dst_grid_corners'] )
+dst_grid_corner_lat = xr.DataArray ( dst_cla.values.reshape(dst_jpi*dst_jpj, dst_clo.shape[0] ),
+                                         dims = ['dst_grid_size', 'dst_grid_corners'] )
+dst_grid_corner_lon.attrs['units']='degrees_east'
+dst_grid_corner_lat.attrs['units']='degrees_north'
 dst_grid_area       = xr.DataArray ( dst_srf.values.ravel(), dims = ['dst_grid_size', ] )
-dst_grid_area.attrs['long_name']="Grid area" ; dst_grid_area.attrs['standard_name']="cell_area" ; dst_grid_area.attrs['units']="m2"
+dst_grid_area.attrs.update ({'long_name':'Grid area', 'standard_name':'cell_area', 'units':'m2'})
 dst_grid_imask      = xr.DataArray ( dst_msk.values.ravel(), dims =  ['dst_grid_size',]  )
-dst_grid_imask.attrs['long_name']="Land-sea mask" ; dst_grid_imask.attrs['units']="Land:1, Ocean:0"
-
-dst_bassin      = xr.DataArray ( basin_msk.reshape ( (nb_zone,dst_grid_size) ) , dims = ['nb_zone', 'dst_grid_size',  ] )
-dst_repartition = xr.DataArray ( key_repartition.reshape( (nb_zone,dst_grid_size) ) , dims = ['nb_zone', 'dst_grid_size',  ] )
-
-dst_southLimit = xr.DataArray ( np.min(limit_lat, axis=(1,)).astype(np.float32) , dims = ['nb_zone', ] )
-dst_northLimit = xr.DataArray ( np.min(limit_lat, axis=(1,)).astype(np.float32) , dims = ['nb_zone', ] )
+dst_grid_imask.attrs.update ( {'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0' } )
+
+dst_bassin      = xr.DataArray ( basin_msk.reshape ( (nb_zone,dst_grid_size) ) ,
+                                     dims = ['nb_zone', 'dst_grid_size',  ] )
+dst_repartition = xr.DataArray ( key_repartition.reshape( (nb_zone,dst_grid_size) ) ,
+                                     dims = ['nb_zone', 'dst_grid_size',  ] )
+
+dst_southLimit = xr.DataArray ( np.min(limit_lat, axis=(1,)).astype(np.float32) ,
+                                    dims = ['nb_zone', ] )
+dst_northLimit = xr.DataArray ( np.min(limit_lat, axis=(1,)).astype(np.float32) ,
+                                    dims = ['nb_zone', ] )
 
 # Additionnal fields for debugging
 # ================================
-dst_grid_imaskutil  = xr.DataArray ( dst_mskutil.ravel().astype(np.float32), dims = ['dst_grid_size',] )
-dst_grid_imaskutil.attrs['long_name']="Land-sea mask" ; dst_grid_imaskutil.attrs['units']="Land:1, Ocean:0"
+dst_grid_imaskutil  = xr.DataArray ( dst_mskutil.ravel().astype(np.float32),
+                                         dims = ['dst_grid_size',] )
+dst_grid_imaskutil.attrs.update ( {'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0' })
 dst_grid_imaskclose = xr.DataArray ( dst_closed.values.ravel(), dims = ['dst_grid_size',] )
-dst_grid_imaskclose.attrs['long_name']="Land-sea mask" ; dst_grid_imaskclose.attrs['units']="Land:1, Ocean:0"
-
-dst_lon_addressed = xr.DataArray ( dst_lon.values.ravel()[dst_address-1].ravel(), dims = ['num_links',] )
-dst_lat_addressed = xr.DataArray ( dst_lat.values.ravel()[dst_address-1].ravel(), dims = ['num_links',] )
-dst_lon_addressed.attrs['long_name']="Longitude" ; dst_lon_addressed.attrs['standard_name']="longitude" ; dst_lon_addressed.attrs['units']="degrees_east"
-dst_lat_addressed.attrs['long_name']="Latitude"  ; dst_lat_addressed.attrs['standard_name']="latitude"  ; dst_lat_addressed.attrs['units']="degrees_north"
-dst_area_addressed  = xr.DataArray ( dst_srf.values.ravel()[dst_address-1].ravel(), dims = ['num_links',] )
-dst_area_addressed.attrs['long_name']="Grid area" ; dst_area_addressed.attrs['standard_name']="cell_area" ; dst_grid_area.attrs['units']="m2"
-dst_imask_addressed = xr.DataArray ( dst_msk.values.ravel()[dst_address-1].ravel(), dims = ['num_links', ] )
-dst_imask_addressed.attrs['long_name']="Land-sea mask" ; dst_imask_addressed.attrs['units']="Land:1, Ocean:0"
-dst_imaskutil_addressed = xr.DataArray ( dst_mskutil.ravel()[dst_address-1].astype(np.float32), dims = ['num_links'] )
-dst_imaskutil_addressed.attrs['long_name']="Land-sea mask" ; dst_imaskutil_addressed.attrs['units']="Land:1, Ocean:0"
+dst_grid_imaskclose.attrs.update ({'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0' })
+
+dst_lon_addressed = xr.DataArray ( dst_lon.values.ravel()[dst_address-1].ravel(),
+                                       dims = ['num_links',] )
+dst_lat_addressed = xr.DataArray ( dst_lat.values.ravel()[dst_address-1].ravel(),
+                                       dims = ['num_links',] )
+dst_lon_addressed.attrs.update ( {'units':'degrees_east ', 'long_name':'Longitude',
+                                      'standard_name':'longitude' })
+dst_lat_addressed.attrs.update ( {'units':'degrees_north', 'long_name':'Latitude' ,
+                                      'standard_name':'latitude'  })
+dst_area_addressed  = xr.DataArray ( dst_srf.values.ravel()[dst_address-1].ravel(),
+                                         dims = ['num_links',] )
+dst_area_addressed.attrs.update ( {'long_name':'Grid area0', 'standard_name':'cell_area',
+                                       'units':'m2' })
+dst_imask_addressed = xr.DataArray ( dst_msk.values.ravel()[dst_address-1].ravel(),
+                                         dims = ['num_links', ] )
+dst_imask_addressed.attrs.update ( {'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0' })
+dst_imaskutil_addressed = xr.DataArray ( dst_mskutil.ravel()[dst_address-1].astype(np.float32),
+                                             dims = ['num_links'] )
+dst_imaskutil_addressed.attrs.update ( {'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0' })
 
 src_field = xr.DataArray ( src_field, dims = ['src_grid_size',] )
 dst_field = xr.DataArray ( dst_field, dims = ['dst_grid_size',] )
 
-f_calving =  xr.Dataset ( { 
+f_calving =  xr.Dataset ( {
     'remap_matrix'            : remap_matrix,
 	'src_address'             : src_address,
@@ -417,49 +509,43 @@
     } )
 
-f_calving.attrs['Conventions']     = "CF-1.6"
-f_calving.attrs['source']          = "IPSL Earth system model"
-f_calving.attrs['group']           = "ICMC IPSL Climate Modelling Center"
-f_calving.attrs['Institution']     = "IPSL https.//www.ipsl.fr"
-f_calving.attrs['Ocean']           = dst_Name + " https://www.nemo-ocean.eu"
-f_calving.attrs['Atmosphere']      = src_Name + " http://lmdz.lmd.jussieu.fr"
-if myargs.type in ['iceberg', 'iceshelf' ]: f_calving.attrs['originalFiles'] = myargs.repartition_file
-f_calving.attrs['associatedFiles'] = grids + " " + areas + " " + masks
-
-f_calving.attrs['description']     = "Generated with XIOS http://forge.ipsl.jussieu.fr/ioserver and MOSAIX https://forge.ipsl.jussieu.fr/igcmg/browser/TOOLS/MOSAIX"
-f_calving.attrs['title']           = calving
-f_calving.attrs['Program']         = "Generated by " + sys.argv[0] + " with flags " + ' '.join (sys.argv[1:]) 
-
-f_calving.attrs['repartitionType'] = myargs.type
+f_calving.attrs.update ( {
+    'Conventions'     : 'CF-1.6',
+    'source'          : 'IPSL Earth system model',
+    'group'           : 'ICMC IPSL Climate Modelling Center',
+    'Institution'     : 'IPSL https.//www.ipsl.fr',
+    'Ocean'           : f'{dst_Name} https://www.nemo-ocean.eu',
+    'Atmosphere'      : f'{src_Name} http://lmdz.lmd.jussieu.fr',
+    'associatedFiles' : f'{grids} {areas} {masks}',
+    'description'     : 'Generated with XIOS http://forge.ipsl.jussieu.fr/ioserver and MOSAIX https://forge.ipsl.jussieu.fr/igcmg/browser/TOOLS/MOSAIX',
+    'title'           : calving,
+    'Program'         : f'Generated by {sys.argv[0]} with flags ' + ' '.join (sys.argv[1:]),
+    'repartitionType' : myargs.type,
+    'gridsFile'       : grids,
+    'areasFile'       : areas,
+    'masksFile'       : masks,
+    'timeStamp'       : time.asctime(),
+    'directory'       : os.getcwd (),
+    'HOSTNAME'        : platform.node (),
+    'LOGNAME'         : getpass.getuser(),
+    'Python'          : 'Python version ' +  platform.python_version (),
+    'OS'              : platform.system (),
+    'release'         : platform.release (),
+    'hardware'        : platform.machine (),
+    'conventions'     : 'SCRIP',
+    'dest_grid'       : 'curvilinear',
+    'Model'           : model_name,
+    'SVN_Author'      : '$Author$',
+    'SVN_Date'        : '$Date$',
+    'SVN_Revision'    : '$Revision$',
+    'SVN_Id'          : '$Id$',
+    'SVN_HeadURL'     : '$HeadURL$',
+    })
+
 if myargs.type in [ 'iceberg', 'iceshelf' ] :
-    f_calving.attrs['repartitionFile'] = myargs.repartition_file
-    f_calving.attrs['repartitionVar']  = repartitionVar
-f_calving.attrs['gridsFile']       = grids
-f_calving.attrs['areasFile']       = areas
-f_calving.attrs['masksFile']       = masks
-f_calving.attrs['timeStamp']       = time.asctime()
-try    : f_calving.attrs['directory'] = os.getcwd ()
-except : pass
-try    : f_runoff.attrs['HOSTNAME'] = platform.node ()
-except : pass
-try    : f_runoff.attrs['LOGNAME']  = os.getlogin ()
-except : pass
-try    : f_runoff.attrs['Python']   = "Python version " +  platform.python_version ()
-except : pass
-try    : f_runoff.attrs['OS']       = platform.system ()
-except : pass
-try    : f_runoff.attrs['release']  = platform.release ()
-except : pass
-try    : f_runoff.attrs['hardware'] = platform.machine ()
-except : pass
-f_calving.attrs['conventions']     = "SCRIP"
-if src_name == 'lmd' : f_calving.attrs['source_grid'] = "curvilinear"
-if src_name == 'ico' : f_calving.attrs['source_grid'] = "unstructured"
-f_calving.attrs['dest_grid']       = "curvilinear"
-f_calving.attrs['Model']           = "IPSL CM6"
-f_calving.attrs['SVN_Author']      = "$Author$"
-f_calving.attrs['SVN_Date']        = "$Date$"
-f_calving.attrs['SVN_Revision']    = "$Revision$"
-f_calving.attrs['SVN_Id']          = "$Id$"
-f_calving.attrs['SVN_HeadURL']     = "$HeadURL$"
+    f_calving.attrs.update ( {
+    'originalFiles'   : myargs.repartition_file,
+    'repartitionFile' : myargs.repartition_file,
+    'repartitionVar'  : repartitionVar,
+    } )
 
 ##
@@ -467,4 +553,4 @@
 f_calving.close()
 
-print ('That''s all folks !')
+print ("That''s all folks !")
 ## ======================================================================================
Index: /TOOLS/MOSAIX/CreateWeightsMask.bash
===================================================================
--- /TOOLS/MOSAIX/CreateWeightsMask.bash	(revision 6665)
+++ /TOOLS/MOSAIX/CreateWeightsMask.bash	(revision 6666)
@@ -3,7 +3,7 @@
 #MSUB -o Out_WeightsMask    # Standard output
 #MSUB -e Out_WeightsMask    # Error output
-#MSUB -n 1                  # Number of processors
-#MSUB -T 7200              # Time limit (seconds)
-#MSUB -Q normal
+#MSUB -n 4                  # Number of processors
+#MSUB -T 1800              # Time limit (seconds)
+#MSUB -Q test
 #MSUB -q rome
 #MSUB -p devcmip6
@@ -21,24 +21,12 @@
 ### ===========================================================================
 ##
-##  MOSAIX is under CeCILL_V2 licence. See "Licence_CeCILL_V2-en.txt"
-##  file for an english version of the licence and
-##  "Licence_CeCILL_V2-fr.txt" for a french version.
-##
-##  Permission is hereby granted, free of charge, to any person or
-##  organization obtaining a copy of the software and accompanying
-##  documentation covered by this license (the "Software") to use,
-##  reproduce, display, distribute, execute, and transmit the
-##  Software, and to prepare derivative works of the Software, and to
-##  permit third-parties to whom the Software is furnished to do so,
-##  all subject to the following:
-##
-##  Warning, to install, configure, run, use any of MOSAIX software or
-##  to read the associated documentation you'll need at least one (1)
-##  brain in a reasonably working order. Lack of this implement will
-##  void any warranties (either express or implied).  Authors assumes
-##  no responsability for errors, omissions, data loss, or any other
-##  consequences caused directly or indirectly by the usage of his
-##  software by incorrectly or partially configured
-##
+##  Warning, to install, configure, run, use any of Olivier Marti's
+##  software or to read the associated documentation you'll need at least
+##  one (1) brain in a reasonably working order. Lack of this implement
+##  will void any warranties (either express or implied).
+##  O. Marti assumes no responsability for errors, omissions,
+##  data loss, or any other consequences caused directly or indirectly by
+##  the usage of his software by incorrectly or partially configured
+##  personal.
 ##
 ## SVN information
@@ -50,5 +38,5 @@
 #
 ## Tested with : 
-# CplModel=eORCA1.2xLMD144142 ; qsub -r ${CplModel} -o Out_${CplModel} -e Out_${CplModel} CreateWeightsMask.bash
+# CplModel=eORCA1.4.2xICO60 ; ccc_msub -r ${CplModel} -o Out_${CplModel} -e Out_${CplModel} CreateWeightsMask.bash
 # CplModel=ORCA2.3xLMD9695
 # CplModel=ORCA2.3xICO30
@@ -59,5 +47,10 @@
 # CplModel=eORCA025.1xLMD144142
 # CplModel=eORCA025.1xLMD256256
-#
+# CplModel=eORCA1.4.2xICO40
+# CplModel=eORCA1.4.2xICO60
+# ccc_msub -r ${CplModel} -o Out_${CplModel} -e Out_${CplModel} CreateWeightsMask.bash
+
+echo 'Test'
+ls -alt /ccc/work/cont003/gencmip6/p86mart/TMP/MOSAIX
 
 set +vx
@@ -82,5 +75,5 @@
 echo ${Titre}"Defines model"${Norm}
 # =================================
-#CplModel=ORCA2.3xLMD9695
+CplModel=ORCA2.3xLMD9695
 #CplModel=ORCA2.3xICO30
 #CplModel=ORCA2.3xICO40
@@ -90,8 +83,8 @@
 #CplModel=eORCA1.2xLMD256256
 #CplModel=eORCA1.2xICO40
+#CplModel=eORCA1.2xICO60
 #CplModel=eORCA1.4.2xICO40
 #CplModel=eORCA1.2xICO450
 #CplModel=eORCA025.1xLMD256256
-CplModel=eORCA1.4.2xICO80
 
 #Version="v0" ; Comment="Fully tested in IPSLCM6 eORCA1.2 x LMD 144x142"
@@ -144,5 +137,5 @@
 # \!/ No spaces in any analysis \!/
 #
-# Specific commands : 'Runoff', 'Calving'
+# Specific commands : 'Runoff', 'Calving', 'Grids'
 #
 # Keywords : 
@@ -194,4 +187,8 @@
 #CommandList=( Grids )
 
+if [[ ${Version} = test_runoff_* ]] ; then
+    CommandList=( Runoff )
+fi
+
 ## ===========================================================================
 ##
@@ -286,5 +283,5 @@
     set +e
     R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
-    TMPDIR=${CCCWORKDIR}/TMP
+    TMPDIR=${CCCWORKDIR}/TMP/MOSAIX
     SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
     MpiRun="time ccc_mprun"
@@ -292,10 +289,8 @@
     module purge
     source ${SUBMIT_DIR}/arch.env
-    module load nco #/4.9.1
-    module load cdo #/1.9.5
+    module load nco
     module load python3 
     module load datadir/igcmg
     module list
-    cp ${SUBMIT_DIR}/arch.env . ${TMPDIR}
     set -e
     ;;
@@ -311,5 +306,5 @@
 
 set -x ; set -e
-
+ls -alt ${TMPDIR}
 mkdir -p ${TMPDIR}/${CplModel} || exit 1
 cd       ${TMPDIR}/${CplModel} || exit 2
@@ -346,4 +341,5 @@
 cp ${SUBMIT_DIR}/iodef_atm_to_oce.xml   .
 cp ${SUBMIT_DIR}/iodef_oce_to_atm.xml   .
+cp ${SUBMIT_DIR}/arch.env               .
 
 [[ -f ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc       ]] && cp ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc        .
@@ -604,5 +600,4 @@
 	    --attribute Ocean,global,o,c,"${OCE} https://www.nemo-ocean.eu"       \
 	    --attribute Atmosphere,global,o,c,"${ATM} http://lmdz.lmd.jussieu.fr" \
-	    --attribute production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4}')" \
 	    --attribute originalFiles,global,o,c,"${OCE}_coordinates_mask.nc ${ATM}_grid_mask.nc"      \
 	    --attribute associatedFiles,global,o,c,"grids_${CplModel}.nc areas_${CplModel}.nc masks_${CplModel}.nc" \
@@ -822,5 +817,5 @@
 	      --o2a=${ATM}_grid_maskFrom_${OCE}.nc --output=rmp_t${atm}_to_t${oce}_runoff_${runOff_atmQuantity}_to_${runOff_oceQuantity}.nc \
               --fmt=${FMT_XIOS} \
-	      --atmQuantity=${runOff_atmQuantity} --oceQuantity=${runOff_oceQuantity} --ocePerio=${OcePerio}
+	      --atmQuantity=${runOff_atmQuantity} --oceQuantity=${runOff_oceQuantity} --ocePerio=${OcePerio} --modelName="${ModelName}"
 fi
 
@@ -835,13 +830,13 @@
 		 --oce=${OCE} --atm=${ATM} --type=nosouth   \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceberg.nc  --fmt=${FMT_XIOS} \
 		 --oce=${OCE} --atm=${ATM} --type=iceberg  --repartition_file=eORCA_R025_runoff_v1.2.nc --repartition_var=Icb_flux \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceshelf.nc --fmt=${FMT_XIOS} \
 		 --oce=${OCE} --atm=${ATM} --type=iceshelf --repartition_file=eORCA_R025_runoff_v1.2.nc --repartition_var=sornfisf \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	;;
 	
@@ -858,13 +853,13 @@
 		 --oce=${OCE} --atm=${ATM} --type=nosouth   \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceberg.nc  --fmt=${FMT_XIOS} \
 		 --oce=${OCE} --atm=${ATM} --type=iceberg --repartition_file=runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc --repartition_var=Icb_flux \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceshelf.nc --fmt=${FMT_XIOS} \
 		 --oce=${OCE} --atm=${ATM} --type=iceshelf --repartition_file=runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc --repartition_var=sornfisf \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	;;
 	
@@ -873,5 +868,5 @@
 		 --oce=${OCE} --atm=${ATM} --type=full --ocePerio=${OcePerio} \
 		 --grids=grids_${CplModel}.nc --areas=areas_${CplModel}.nc --masks=masks_${CplModel}.nc \
-	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc
+	         --o2a=${ATM}_grid_maskFrom_${OCE}.nc --modelName="${ModelName}"
 	;;
     esac
@@ -957,12 +952,14 @@
 Python version   : ${PYTHON_VER}
 
-EOF
-
-echo 'SVN Information : '                                              >> README.txt
-echo '$Author$ '                                              >> README.txt
-echo '$Date$ '          >> README.txt
-echo '$Revision$ '                                              >> README.txt
-echo '$Id$ ' >> README.txt
-echo '$HeadURL$ ' >> README.txt
+SVN Information :
+$Author$
+$Date$
+$Revision$
+$Id$
+$HeadURL$
+
+EOF
+
+
 
 echo ${Titre}"Compute checksums and add them to README"${Norm}
@@ -996,3 +993,2 @@
 ##
 ## ===========================================================================
-
Index: /TOOLS/MOSAIX/RunoffWeights.py
===================================================================
--- /TOOLS/MOSAIX/RunoffWeights.py	(revision 6665)
+++ /TOOLS/MOSAIX/RunoffWeights.py	(revision 6666)
@@ -29,18 +29,50 @@
 ##
 ##
+'''Python code to generates weights for run-off. Launched by `CreateWeights.bash`.
+
+More information with python `RunOffWeights.py -h`.
+
+- Defines a coastal band on land in the atmosphere model. For LMDZ
+  rectilinear grids, the width of this band is parametrized, in grid
+  points. For ico grids, the band contains only point with a
+  fraction of ocean in ]0,1[.
+
+- Defines a coastal band on ocean in the ocean model. The width of
+  this band is parametrized.
+
+- An atmosphere point of the coastal band is linked to an ocean
+  point in the coastal band if the distance between the two is less
+  than searchRadius.
+
+## SVN information
+Author   = "$Author$"
+Date     = "$Date$"
+Revision = "$Revision$"
+Id       = "$Id$"
+HeadURL  = "$HeadURL$"
+'''
+
+## Modules
+import sys
+import os
+import platform
+import getpass
+import argparse
+import time
+import numpy as np
+import xarray as xr
+from scipy import ndimage
+import nemo
+
 # SVN information
-__Author__   = "$Author$"
-__Date__     = "$Date$"
-__Revision__ = "$Revision$"
-__Id__       = "$Id$"
-__HeadURL__  = "$HeadURL$"
-__SVN_Date__ = "$SVN_Date: $"
-##
-
-## Modules
-import numpy as np, xarray as xr
-import nemo
-from scipy import ndimage
-import sys, os, platform, argparse, textwrap, time
+__SVN__ = ({
+    'Author'   : '$Author$',
+    'Date'     : '$Date$',
+    'Revision' : '$Revision$',
+    'Id'       : '$Id$',
+    'HeadURL'  : '$HeadURL$',
+    'SVN_Date' : '$SVN_Date: $',
+    })
+##
 
 ## Useful constants
@@ -54,35 +86,48 @@
 ## Functions
 def geodist (plon1, plat1, plon2, plat2) :
-      """Distance between two points (on sphere)"""
-      zs = np.sin (rad*plat1) * np.sin (rad*plat2) +  np.cos (rad*plat1) * np.cos (rad*plat2) * np.cos(rad*(plon2-plon1))
-      zs = np.maximum (-zone, np.minimum (zone, zs))
-      geodist =  np.arccos (zs)
-      return geodist
+    '''Distance between two points (on sphere)'''
+    zs = ( np.sin (rad*plat1) * np.sin (rad*plat2) +
+           np.cos (rad*plat1) * np.cos (rad*plat2) * np.cos(rad*(plon2-plon1)) )
+    zs = np.maximum (-zone, np.minimum (zone, zs))
+    zgeodist =  np.arccos (zs)
+    return zgeodist
 
 ### ===== Reading command line parameters ==================================================
 # Creating a parser
 parser = argparse.ArgumentParser (
-    description = """Compute calving weights""",
+    description = '''Compute calving weights''',
     epilog='-------- End of the help message --------')
 
 # Adding arguments
 parser.add_argument ('--oce'          , help='oce model name', type=str, default='eORCA1.2',
-                         choices=['ORCA2.3',  'ORCA1.0', 'ORCA1.1', 'ORCA1_CNRM', 'eORCA1.2', 'eORCA1.4', 'eORCA1.4.2', 'eORCA025', 'eORCA025.1', 'eORCA025.4'] )
+                     choices=['ORCA2.3',  'ORCA1.0', 'ORCA1.1', 'ORCA1_CNRM', 'eORCA1.2',
+                              'eORCA1.4', 'eORCA1.4.2', 'eORCA025', 'eORCA025.1', 'eORCA025.4'] )
 parser.add_argument ('--atm'          , help='atm model name', type=str, default='LMD9695'    )
-parser.add_argument ('--atmCoastWidth', help='width of the coastal band in atmosphere (in grid points)', type=int, default=1 )
-parser.add_argument ('--oceCoastWidth', help='width of the coastal band in ocean (in grid points)'     , type=int, default=2 )
-parser.add_argument ('--atmQuantity'  , help='Quantity if atm provides quantities (m/s), Surfacic if atm provided flux (m/s/m2)' , type=str,
-                         default='Quantity', choices=['Quantity', 'Surfacic'] )
-parser.add_argument ('--oceQuantity'  , help='Quantity if oce requires quantities (ks/s), Surfacic if oce requires flux (m/s/m2)', type=str,
-                         default='Surfacic', choices=['Quantity', 'Surfacic'] )
-parser.add_argument ('--searchRadius' , help='max distance to connect a land point to an ocean point (in km)', type=float, default=600.0 )
+parser.add_argument ('--atmCoastWidth', type=int, default=1,
+                         help='width of the coastal band in atmosphere (in grid points)' )
+parser.add_argument ('--oceCoastWidth',
+                         help='width of the coastal band in ocean (in grid points)'     ,
+                         type=int, default=2 )
+parser.add_argument ('--atmQuantity'  , type=str, default='Quantity',
+                         choices=['Quantity', 'Surfacic'],
+                         help='Quantity if atm provides quantities (m/s), Surfacic if atm provided flux (m/s/m2)' )
+parser.add_argument ('--oceQuantity'  , type=str, default='Surfacic',
+                         choices=['Quantity', 'Surfacic'],
+                         help='Quantity if oce requires quantities (ks/s), Surfacic if oce requires flux (m/s/m2)' )
+parser.add_argument ('--searchRadius' , type=float, default=600.0,
+                         help='max distance to connect a land point to an ocean point (in km)' )
 parser.add_argument ('--grids' , help='grids file name', default='grids.nc' )
 parser.add_argument ('--areas' , help='masks file name', default='areas.nc' )
 parser.add_argument ('--masks' , help='areas file name', default='masks.nc' )
 parser.add_argument ('--o2a'   , help='o2a file name'  , default='o2a.nc'   )
-parser.add_argument ('--output', help='output rmp file name', default='rmp_tlmd_to_torc_runoff.nc' )
-parser.add_argument ('--fmt'   , help='NetCDF file format, using nco syntax', default='netcdf4',
-                         choices=['classic', 'netcdf3', '64bit', '64bit_data', '64bit_data', 'netcdf4', 'netcdf4_classsic'] )
-parser.add_argument ('--ocePerio'   , help='periodicity of ocean grid', type=float, default=0, choices=nemo.nperio_valid_range)
+parser.add_argument ('--output', help='output rmp file name',
+                         default='rmp_tlmd_to_torc_runoff.nc' )
+parser.add_argument ('--fmt'   , default='netcdf4',
+                         help='NetCDF file format, using nco syntax',
+                         choices=['classic', 'netcdf3', '64bit', '64bit_data',
+                                  '64bit_data', 'netcdf4', 'netcdf4_classsic'] )
+parser.add_argument ('--ocePerio' , help='periodicity of ocean grid', type=float,
+                         default=0, choices=nemo.NPERIO_VALID_RANGE)
+parser.add_argument ('--modelName' , help='Name of model', type=str, default=None)
 
 # Parse command line
@@ -96,9 +141,10 @@
 
 # Model Names
-atm_Name = myargs.atm
-oce_Name = myargs.oce
+atm_Name   = myargs.atm
+oce_Name   = myargs.oce
+model_name = myargs.modelName
 # Width of the coastal band (land points) in the atmopshere
 atmCoastWidth = myargs.atmCoastWidth
-# Width of the coastal band (ocean points) in the ocean 
+# Width of the coastal band (ocean points) in the ocean
 oceCoastWidth = myargs.oceCoastWidth
 searchRadius  = myargs.searchRadius * 1000.0 # From km to meters
@@ -152,5 +198,5 @@
     atm_grid_area       = atm_grid_area.rename  ({'ycell':'cell'})
     atm_grid_imask      = atm_grid_imask.rename ({'ycell':'cell'})
-    
+
 if atmDomainType == 'rectilinear' :
     atm_grid_center_lat = atm_grid_center_lat.stack (cell=['y', 'x'])
@@ -164,5 +210,4 @@
 atm_grid_pmask = atm_grid_imask
 
-
 atm_address = np.arange(atm_jpj*atm_jpi)
 
@@ -186,12 +231,14 @@
 #    if oce_jpi ==  362 : oce_perio = 6 # ORCA 1
 #    if oce_jpi == 1442 : oce_perio = 6 # ORCA 025
-oce_preio = nemo.__guessNperio__ (oce_jpj, oce_jpi, nperio=oce_perio)
-
-print ("Oce NPERIO parameter : {:}".format(oce_perio))
-oce_grid_imask = nemo.lbc      (np.reshape(oce_grid_imask.values, (oce_jpj,oce_jpi)), nperio=oce_perio, cd_type='T'        ).ravel()
-oce_grid_pmask = nemo.lbc_mask (np.reshape(oce_grid_imask       , (oce_jpj,oce_jpi)), nperio=oce_perio, cd_type='T', sval=0).ravel()
+oce_preio = nemo.__guess_nperio__ (oce_jpj, oce_jpi, nperio=oce_perio)
+
+print ( f'Oce NPERIO parameter : {oce_perio}' )
+oce_grid_imask = nemo.lbc      (np.reshape(oce_grid_imask.values, (oce_jpj,oce_jpi)),
+                                nperio=oce_perio, cd_type='T'        ).ravel()
+oce_grid_pmask = nemo.lbc_mask (np.reshape(oce_grid_imask       , (oce_jpj,oce_jpi)),
+                                nperio=oce_perio, cd_type='T', sval=0).ravel()
 oce_address = np.arange(oce_jpj*oce_jpi)
 
-print ("Fill closed seas with image processing library")
+print ('Fill closed seas with image processing library')
 oce_grid_imask2D = np.reshape (oce_grid_imask, (oce_jpj,oce_jpi))
 oce_grid_imask2D = 1-nemo.fill_closed_seas (1-oce_grid_imask2D, nperio=oce_perio, cd_type='T')
@@ -200,6 +247,6 @@
 oce_grid_imask = oce_grid_imask2D.ravel ()
 
-## 
-print ("Computes an ocean coastal band with image processing library")
+##
+print ('Computes an ocean coastal band with image processing library')
 oceLand2D  = np.reshape ( np.where (oce_grid_imask < 0.5, True, False), (oce_jpj, oce_jpi) )
 oceOcean2D = np.reshape ( np.where (oce_grid_imask > 0.5, True, False), (oce_jpj, oce_jpi) )
@@ -208,5 +255,6 @@
 oceOceanFiltered2D = ndimage.uniform_filter (oceOcean2D.astype(float), size=NNocean)
 oceCoast2D = np.where (oceOceanFiltered2D<(1.0-0.5/(NNocean**2)),True,False) & oceOcean2D
-oceCoast2D = nemo.lbc_mask (np.reshape(oceCoast2D, (oce_jpj,oce_jpi)), nperio=oce_perio, cd_type='T', sval=0.).ravel()
+oceCoast2D = nemo.lbc_mask (np.reshape(oceCoast2D, (oce_jpj,oce_jpi)),
+                            nperio=oce_perio, cd_type='T', sval=0.).ravel()
 
 oceOceanFiltered = oceOceanFiltered2D.ravel()
@@ -215,7 +263,7 @@
 oceCoast = oceCoast2D.ravel()
 
-print ('Number of points in oceLand  : {:8d}'.format (oceLand.sum())  )
-print ('Number of points in oceOcean : {:8d}'.format (oceOcean.sum()) )
-print ('Number of points in oceCoast : {:8d}'.format (oceCoast.sum()) )
+print ( f'Number of points in oceLand  : {oceLand.sum():8d}' )
+print ( f'Number of points in oceOcean : {oceOcean.sum():8d}' )
+print ( f'Number of points in oceCoast : {oceCoast.sum():8d}' )
 
 # Arrays with coastal points only
@@ -227,8 +275,9 @@
 oceCoast_address         = oce_address        [oceCoast]
 
-print ("Computes an atmosphere coastal band" )
+print ('Computes an atmosphere coastal band' )
 atmLand      = np.where (o2aFrac[:] < epsfrac       , True, False)
 atmLandFrac  = np.where (o2aFrac[:] < zone-epsfrac  , True, False)
-atmFrac      = np.where (o2aFrac[:] > epsfrac       , True, False) & np.where (o2aFrac[:] < (zone-epsfrac), True, False)
+atmFrac      = np.where (o2aFrac[:] > epsfrac       , True, False) & \
+                         np.where (o2aFrac[:] < (zone-epsfrac), True, False)
 atmOcean     = np.where (o2aFrac[:] < (zone-epsfrac), True, False)
 atmOceanFrac = np.where (o2aFrac[:] > epsfrac       , True, False)
@@ -236,5 +285,5 @@
 ## For LMDZ only !!
 if atmDomainType == 'rectilinear' :
-    print ("Extend coastal band " )
+    print ('Extend coastal band ' )
     NNatm = 1+2*atmCoastWidth
     atmLand2D = np.reshape ( atmLand, ( atm_jpj, atm_jpi) )
@@ -242,16 +291,16 @@
     atmLandFiltered2D = ndimage.uniform_filter(atmLand2D.astype(float), size=NNatm)
     atmCoast2D = np.where (atmLandFiltered2D<(1.0-0.5/(NNatm**2)),True,False) & atmLandFrac
-    
+
     atmLandFiltered = atmLandFiltered2D.ravel()
     atmCoast = atmCoast2D.ravel()
 
-    print ('Number of points in atmLand  : {:8d}'.format (atmLand.sum())  )
-    print ('Number of points in atmOcean : {:8d}'.format (atmOcean.sum()) )
-    print ('Number of points in atmCoast : {:8d}'.format (atmCoast.sum()) )
+    print ( f'Number of points in atmLand  : {atmLand.sum():8d}'  )
+    print ( f'Number of points in atmOcean : {atmOcean.sum():8d}' )
+    print ( f'Number of points in atmCoast : {atmCoast.sum():8d}' )
 
 else :
     atmCoast = atmFrac
-    
-    
+
+
 # Arrays with coastal points only
 atmCoast_grid_center_lon = atm_grid_center_lon[atmCoast]
@@ -269,7 +318,8 @@
 ## Loop on atmosphere coastal points
 if searchRadius > 0. :
-    print ("Loop on atmosphere coastal points")
+    print ('Loop on atmosphere coastal points')
     for ja in np.arange (len(atmCoast_grid_pmask)) :
-        z_dist = geodist ( atmCoast_grid_center_lon[ja], atmCoast_grid_center_lat[ja], oceCoast_grid_center_lon, oceCoast_grid_center_lat)
+        z_dist = geodist ( atmCoast_grid_center_lon[ja], atmCoast_grid_center_lat[ja],
+                               oceCoast_grid_center_lon, oceCoast_grid_center_lat)
         z_mask = np.where (z_dist*ra < searchRadius, True, False)
         num_links = int (z_mask.sum())
@@ -280,6 +330,6 @@
         if myargs.oceQuantity == 'Quantity' : poids = poids * oceCoast_grid_area[z_mask]
         if  ja % (len(atmCoast_grid_pmask)//50) == 0 : # Control print
-            print ( 'ja:{:8d}, num_links:{:8d},  z_area:{:8.4e},  atm area:{:8.4e},  weights sum:{:8.4e}  '
-                        .format(ja, num_links, z_area, atm_grid_area[ja].values, poids.sum() ) )
+            print ( f'ja:{ja:8d} num_links:{num_links:8d} z_area:{z_area:8.4e} '+
+                    f'atm area:{atm_grid_area[ja].values:8.4e} weights sum:{poids.sum():8.4e}' )
         #
         matrix_local = poids
@@ -296,81 +346,107 @@
 num_links = remap_matrix.shape[0]
 
-print ("Write output file")
+print ('Write output file')
 runoff = myargs.output
 print ('Output file: ' + runoff )
 
-
-remap_matrix = xr.DataArray ( np.reshape(remap_matrix, (num_links, 1)), dims = ['num_links', 'num_wgts'] )
+remap_matrix = xr.DataArray ( np.reshape(remap_matrix, (num_links, 1)),
+                                  dims = ['num_links', 'num_wgts'] )
 
 # OASIS uses Fortran style indexing, starting at one
 src_address  = xr.DataArray ( atm_address.astype(np.int32)+1, dims = ['num_links'],
-                                 attrs={"convention": "Fortran style addressing, starting at 1"}) 
+                                 attrs={'convention': 'Fortran style addressing, starting at 1'})
 dst_address  = xr.DataArray ( oce_address.astype(np.int32)+1, dims = ['num_links'],
-                                 attrs={"convention": "Fortran style addressing, starting at 1"})
-
-src_grid_dims       = xr.DataArray (np.array(atm_grid_dims, dtype=np.int32), dims = ['src_grid_rank',] )
+                                 attrs={'convention': 'Fortran style addressing, starting at 1'})
+
+src_grid_dims       = xr.DataArray (np.array(atm_grid_dims, dtype=np.int32),
+                                        dims = ['src_grid_rank',] )
 src_grid_center_lon = xr.DataArray (atm_grid_center_lon.values , dims = ['src_grid_size',] )
 src_grid_center_lat = xr.DataArray (atm_grid_center_lat.values , dims = ['src_grid_size',] )
 
-src_grid_center_lon.attrs['units']='degrees_east'  ; src_grid_center_lon.attrs['long_name']='Longitude'
-src_grid_center_lon.attrs['long_name']='longitude' ; src_grid_center_lon.attrs['bounds']="src_grid_corner_lon"
-src_grid_center_lat.attrs['units']='degrees_north' ; src_grid_center_lat.attrs['long_name']='Latitude'
-src_grid_center_lat.attrs['long_name']='latitude ' ; src_grid_center_lat.attrs['bounds']="src_grid_corner_lat"
- 
-src_grid_corner_lon = xr.DataArray (atm_grid_corner_lon.values.transpose(), dims = [ 'src_grid_size', 'src_grid_corners'] )
-src_grid_corner_lat = xr.DataArray (atm_grid_corner_lat.values.transpose(), dims = [ 'src_grid_size', 'src_grid_corners'] )
-src_grid_corner_lon.attrs['units']="degrees_east"
-src_grid_corner_lat.attrs['units']="degrees_north"
-
-src_grid_area       =  xr.DataArray (atm_grid_area.values, dims = ['src_grid_size',] ) 
-src_grid_area.attrs['long_name']="Grid area" ; src_grid_area.attrs['standard_name']="cell_area" ; src_grid_area.attrs['units']="m2"
-
-src_grid_imask      =  xr.DataArray (atm_grid_imask.values, dims = ['src_grid_size',] ) 
-src_grid_imask.attrs['long_name']="Land-sea mask" ; src_grid_imask.attrs['units']="Land:1, Ocean:0"
-
-src_grid_pmask      =  xr.DataArray (atm_grid_pmask.values, dims = ['src_grid_size',] ) 
-src_grid_pmask.attrs['long_name']="Land-sea mask (periodicity removed)" ; src_grid_pmask.attrs['units']="Land:1, Ocean:0"
+src_grid_center_lon.attrs.update ( {'units':'degrees_east' , 'long_name':'Longitude',
+                                        'standard_name':'longitude',
+                                        'bounds':'src_grid_corner_lon'} )
+src_grid_center_lat.attrs.update ( {'units':'degrees_north', 'long_name':'Latitude' ,
+                                        'standard_name':'latitude' ,
+                                        'bounds':'src_grid_corner_lat'} )
+
+src_grid_corner_lon = xr.DataArray (atm_grid_corner_lon.values.transpose(),
+                                        dims = [ 'src_grid_size', 'src_grid_corners'] )
+src_grid_corner_lat = xr.DataArray (atm_grid_corner_lat.values.transpose(),
+                                        dims = [ 'src_grid_size', 'src_grid_corners'] )
+src_grid_corner_lon.attrs['units']='degrees_east'
+src_grid_corner_lat.attrs['units']='degrees_north'
+
+src_grid_area       =  xr.DataArray (atm_grid_area.values, dims = ['src_grid_size',] )
+src_grid_area.attrs.update ( {'long_name':'Grid area', 'standard_name':'cell_area',
+                                  'units':'m2' } )
+src_grid_imask      =  xr.DataArray (atm_grid_imask.values, dims = ['src_grid_size',] )
+src_grid_imask.attrs.update ( {'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0'} )
+
+src_grid_pmask      =  xr.DataArray (atm_grid_pmask.values, dims = ['src_grid_size',] )
+src_grid_pmask.attrs.update ( {'long_name':'Land-sea mask (periodicity removed)',
+                                   'units':'Land:1, Ocean:0' } )
 
 # --
-dst_grid_dims       = xr.DataArray (np.array(oce_grid_dims, dtype=np.int32), dims = ['dst_grid_rank',] )
+dst_grid_dims       = xr.DataArray (np.array(oce_grid_dims, dtype=np.int32),
+                                        dims = ['dst_grid_rank',] )
 dst_grid_center_lon = xr.DataArray (oce_grid_center_lon.values, dims = ['dst_grid_size',] )
 dst_grid_center_lat = xr.DataArray (oce_grid_center_lat.values, dims = ['dst_grid_size',] )
 
-dst_grid_center_lon.attrs['units']='degrees_east'  ; dst_grid_center_lon.attrs['long_name']='Longitude'
-dst_grid_center_lon.attrs['long_name']='longitude' ; dst_grid_center_lon.attrs['bounds']="dst_grid_corner_lon"
-dst_grid_center_lat.attrs['units']='degrees_north' ; dst_grid_center_lat.attrs['long_name']='Latitude'
-dst_grid_center_lat.attrs['long_name']='latitude ' ; dst_grid_center_lat.attrs['bounds']="dst_grid_corner_lat"
-
-dst_grid_corner_lon = xr.DataArray (np.transpose(oce_grid_corner_lon.values), dims = [ 'dst_grid_size', 'dst_grid_corners'] )
-dst_grid_corner_lat = xr.DataArray (np.transpose(oce_grid_corner_lat.values), dims = [ 'dst_grid_size', 'dst_grid_corners'] )
-dst_grid_corner_lon.attrs['units']="degrees_east"
-dst_grid_corner_lat.attrs['units']="degrees_north"
-
-dst_grid_area       =  xr.DataArray (oce_grid_area.values, dims = ['dst_grid_size',] ) 
-dst_grid_area.attrs['long_name']="Grid area" ; dst_grid_area.attrs['standard_name']="cell_area" ; dst_grid_area.attrs['units']="m2"
-
-dst_grid_imask      =  xr.DataArray (oce_grid_imask.astype(np.int32), dims = ['dst_grid_size',] ) 
-dst_grid_imask.attrs['long_name']="Land-sea mask" ; dst_grid_imask.attrs['units']="Land:1, Ocean:0"
-
-dst_grid_pmask      =  xr.DataArray (oce_grid_pmask, dims = ['dst_grid_size',] ) 
-dst_grid_pmask.attrs['long_name']="Land-sea mask (periodicity removed)" ; dst_grid_pmask.attrs['units']="Land:1, Ocean:0"
-
-src_lon_addressed   =  xr.DataArray (atm_grid_center_lon.values[atm_address]                  , dims = ['num_links'] )
-src_lat_addressed   =  xr.DataArray (atm_grid_center_lat.values[atm_address]                  , dims = ['num_links'] )
-src_area_addressed  =  xr.DataArray (atm_grid_area      .values[atm_address]                  , dims = ['num_links'] )
-src_imask_addressed =  xr.DataArray (1-atm_grid_imask   .values[atm_address].astype(np.int32) , dims = ['num_links'] )
-src_pmask_addressed =  xr.DataArray (1-atm_grid_pmask   .values[atm_address].astype(np.int32) , dims = ['num_links'] )
-
-dst_lon_addressed   =  xr.DataArray (oce_grid_center_lon.values[atm_address], dims = ['num_links'] )
-dst_lat_addressed   =  xr.DataArray (oce_grid_center_lat.values[oce_address], dims = ['num_links'] )
-dst_area_addressed  =  xr.DataArray (oce_grid_area.values[oce_address].astype(np.int32)      , dims = ['num_links'] )
-dst_imask_addressed =  xr.DataArray (1-oce_grid_imask[oce_address].astype(np.int32)   , dims = ['num_links'] )
-dst_pmask_addressed =  xr.DataArray (1-oce_grid_pmask[oce_address].astype(np.int32)   , dims = ['num_links'] )
-
-src_lon_addressed.attrs['long_name']="Longitude" ; src_lon_addressed.attrs['standard_name']="longitude" ; src_lon_addressed.attrs['units']="degrees_east"
-src_lat_addressed.attrs['long_name']="Latitude"  ; src_lat_addressed.attrs['standard_name']="latitude"  ; src_lat_addressed.attrs['units']="degrees_north"
-
-dst_lon_addressed.attrs['long_name']="Longitude" ; dst_lon_addressed.attrs['standard_name']="longitude" ; dst_lon_addressed.attrs['units']="degrees_east"
-dst_lat_addressed.attrs['long_name']="Latitude"  ; dst_lat_addressed.attrs['standard_name']="latitude"  ; dst_lat_addressed.attrs['units']="degrees_north"
+dst_grid_center_lon.attrs.update ( {'units':'degrees_east' , 'long_name':'Longitude',
+                                        'standard_name':'longitude',
+                                        'bounds':'dst_grid_corner_lon' } )
+dst_grid_center_lat.attrs.update ( {'units':'degrees_north', 'long_name':'Latitude' ,
+                                        'standard_name':'latitude' ,
+                                        'bounds':'dst_grid_corner_lat' } )
+
+dst_grid_corner_lon = xr.DataArray (np.transpose(oce_grid_corner_lon.values),
+                                        dims = [ 'dst_grid_size', 'dst_grid_corners'] )
+dst_grid_corner_lat = xr.DataArray (np.transpose(oce_grid_corner_lat.values),
+                                        dims = [ 'dst_grid_size', 'dst_grid_corners'] )
+dst_grid_corner_lon.attrs['units']='degrees_east'
+dst_grid_corner_lat.attrs['units']='degrees_north'
+
+dst_grid_area       =  xr.DataArray (oce_grid_area.values, dims = ['dst_grid_size',] )
+dst_grid_area.attrs.update ( {'long_name':'Grid area', 'standard_name':'cell_area', 'units':'m2' })
+
+dst_grid_imask      =  xr.DataArray (oce_grid_imask.astype(np.int32), dims = ['dst_grid_size',] )
+dst_grid_imask.attrs.update ( {'long_name':'Land-sea mask', 'units':'Land:1, Ocean:0'} )
+
+dst_grid_pmask      =  xr.DataArray (oce_grid_pmask, dims = ['dst_grid_size',] )
+dst_grid_pmask.attrs.update ( {'long_name':'Land-sea mask (periodicity removed)',
+                                   'units':'Land:1, Ocean:0'} )
+
+src_lon_addressed   =  xr.DataArray (atm_grid_center_lon.values[atm_address] ,
+                                         dims = ['num_links'] )
+src_lat_addressed   =  xr.DataArray (atm_grid_center_lat.values[atm_address] ,
+                                         dims = ['num_links'] )
+src_area_addressed  =  xr.DataArray (atm_grid_area      .values[atm_address] ,
+                                         dims = ['num_links'] )
+src_imask_addressed =  xr.DataArray (1-atm_grid_imask   .values[atm_address].astype(np.int32) ,
+                                         dims = ['num_links'] )
+src_pmask_addressed =  xr.DataArray (1-atm_grid_pmask   .values[atm_address].astype(np.int32) ,
+                                         dims = ['num_links'] )
+
+dst_lon_addressed   =  xr.DataArray (oce_grid_center_lon.values[atm_address],
+                                         dims = ['num_links'] )
+dst_lat_addressed   =  xr.DataArray (oce_grid_center_lat.values[oce_address],
+                                         dims = ['num_links'] )
+dst_area_addressed  =  xr.DataArray (oce_grid_area.values[oce_address].astype(np.int32) ,
+                                         dims = ['num_links'] )
+dst_imask_addressed =  xr.DataArray (1-oce_grid_imask[oce_address].astype(np.int32)   ,
+                                         dims = ['num_links'] )
+dst_pmask_addressed =  xr.DataArray (1-oce_grid_pmask[oce_address].astype(np.int32)   ,
+                                         dims = ['num_links'] )
+
+src_lon_addressed.attrs.update ({'units':'degrees_east' , 'long_name':'Longitude',
+                                     'standard_name':'longitude' })
+src_lat_addressed.attrs.update ({'units':'degrees_north', 'long_name':'Latitude' ,
+                                     'standard_name':'latitude'  })
+
+dst_lon_addressed.attrs.update ({'units':'degrees_east' , 'long_name':'Longitude',
+                                     'standard_name':'longitude' })
+dst_lat_addressed.attrs.update ({'units':'degrees_north', 'long_name':'Latitude' ,
+                                     'standard_name':'latitude'  })
 
 if atmDomainType == 'rectilinear' :
@@ -390,5 +466,5 @@
 
 f_runoff = xr.Dataset ( {
-    'remap_matrix'            : remap_matrix,
+    'remap_matrix'        : remap_matrix,
 	'src_address'         : src_address,
 	'dst_address'         : dst_address,
@@ -398,5 +474,4 @@
     'src_grid_corner_lon' : src_grid_corner_lon,
     'src_grid_corner_lat' : src_grid_corner_lat,
-	'src_grid_area'       : src_grid_area,
 	'src_grid_area'       : src_grid_area,
 	'src_grid_imask'      : src_grid_imask,
@@ -425,47 +500,42 @@
     } )
 
-f_runoff.attrs['Conventions']     = "CF-1.6"
-f_runoff.attrs['source']          = "IPSL Earth system model"
-f_runoff.attrs['group']           = "ICMC IPSL Climate Modelling Center"
-f_runoff.attrs['Institution']     = "IPSL https.//www.ipsl.fr"
-f_runoff.attrs['Ocean']           = oce_Name + " https://www.nemo-ocean.eu"
-f_runoff.attrs['Atmosphere']      = atm_Name + " http://lmdz.lmd.jussieu.fr"
-f_runoff.attrs['associatedFiles'] = grids + " " + areas + " " + masks
-f_runoff.attrs['description']     = "Generated with RunoffWeights.py"
-f_runoff.attrs['title']           = runoff
-f_runoff.attrs['Program']         = "Generated by " + sys.argv[0] + " with flags " + ' '.join (sys.argv[1:]) 
-f_runoff.attrs['atmCoastWidth']   = "{:d} grid points".format(atmCoastWidth)
-f_runoff.attrs['oceCoastWidth']   = "{:d} grid points".format(oceCoastWidth)
-f_runoff.attrs['searchRadius']    = "{:.0f} km".format(searchRadius/1000.)
-f_runoff.attrs['atmQuantity']     = myargs.atmQuantity
-f_runoff.attrs['oceQuantity']     = myargs.oceQuantity
-f_runoff.attrs['gridsFile']       = grids
-f_runoff.attrs['areasFile']       = areas
-f_runoff.attrs['masksFile']       = masks
-f_runoff.attrs['o2aFile']         = o2a
-f_runoff.attrs['timeStamp']       = time.asctime ()
-try    : f_calving.attrs['directory'] = os.getcwd ()
-except : pass
-try    : f_runoff.attrs['HOSTNAME'] = platform.node ()
-except : pass
-try    : f_runoff.attrs['LOGNAME']  = os.getlogin ()
-except : pass
-try    : f_runoff.attrs['Python']   = "Python version " +  platform.python_version ()
-except : pass
-try    : f_runoff.attrs['OS']       = platform.system ()
-except : pass
-try    : f_runoff.attrs['release']  = platform.release ()
-except : pass
-try    : f_runoff.attrs['hardware'] = platform.machine ()
-except : pass
-f_runoff.attrs['conventions']     = "SCRIP"
-f_runoff.attrs['source_grid']     = "curvilinear"
-f_runoff.attrs['dest_grid']       = "curvilinear"
-f_runoff.attrs['Model']           = "IPSL CM6"
-f_runoff.attrs['SVN_Author']      = "$Author$"
-f_runoff.attrs['SVN_Date']        = "$Date$"
-f_runoff.attrs['SVN_Revision']    = "$Revision$"
-f_runoff.attrs['SVN_Id']          = "$Id$"
-f_runoff.attrs['SVN_HeadURL']     = "$HeadURL$"
+f_runoff.attrs.update ( {
+    'Conventions'     : 'CF-1.6',
+    'source'          : 'IPSL Earth system model',
+    'group'           : 'ICMC IPSL Climate Modelling Center',
+    'Institution'     : 'IPSL https.//www.ipsl.fr',
+    'Ocean'           : f'{oce_Name} https://www.nemo-ocean.eu',
+    'Atmosphere'      : f'{atm_Name} http://lmdz.lmd.jussieu.fr',
+    'associatedFiles' : f'{grids} {areas} {masks}',
+    'description'     : 'Generated with RunoffWeights.py',
+    'title'           : runoff,
+    'Program'         : f'Generated by {sys.argv[0]} with flags ' + ' '.join (sys.argv[1:]),
+    'atmCoastWidth'   : f'{atmCoastWidth:d} grid points',
+    'oceCoastWidth'   : f'{oceCoastWidth:d} grid points',
+    'searchRadius'    : f'{searchRadius/1000.:.0f} km',
+    'atmQuantity'     : myargs.atmQuantity,
+    'oceQuantity'     : myargs.oceQuantity,
+    'gridsFile'       : grids,
+    'areasFile'       : areas,
+    'masksFile'       : masks,
+    'o2aFile'         : o2a,
+    'timeStamp'       : time.asctime (),
+    'directory'       : os.getcwd (),
+    'HOSTNAME'        : platform.node (),
+    'LOGNAME'         : getpass.getuser(),
+    'Python'          : f'Python version {platform.python_version ()}',
+    'OS'              : platform.system (),
+    'release'         : platform.release (),
+    'hardware'        : platform.machine (),
+    'conventions'     : 'SCRIP',
+    'source_grid'     : 'curvilinear',
+    'dest_grid'       : 'curvilinear',
+    'Model'           : model_name,
+    'SVN_Author'      : '$Author$',
+    'SVN_Date'        : '$Date$',
+    'SVN_Revision'    : '$Revision$',
+    'SVN_Id'          : '$Id$',
+    'SVN_HeadURL'     : '$HeadURL$',
+    } )
 
 f_runoff.to_netcdf ( runoff, mode='w', format=FmtNetcdf )
@@ -474,4 +544,4 @@
 ##
 
-print ('That''s all folks !')
+print ("That''s all folks !")
 ## ======================================================================================
Index: /TOOLS/MOSAIX/nemo.py
===================================================================
--- /TOOLS/MOSAIX/nemo.py	(revision 6665)
+++ /TOOLS/MOSAIX/nemo.py	(revision 6666)
@@ -18,72 +18,129 @@
 ##
 ## ===========================================================================
+'''Utilities to plot NEMO ORCA fields,
+
+Handles periodicity and other stuff
+
+- Lots of tests for xarray object
+- Not much tested for numpy objects
+
+Author: olivier.marti@lsce.ipsl.fr
+
+## SVN information
+Author   = "$Author$"
+Date     = "$Date$"
+Revision = "$Revision$"
+Id       = "$Id$"
+HeadURL  = "$HeadURL$"
 '''
-Utilities to plot NEMO ORCA fields
-Periodicity and other stuff
-
-olivier.marti@lsce.ipsl.fr
-'''
-
-## SVN information
-__Author__   = "$Author$"
-__Date__     = "$Date$"
-__Revision__ = "$Revision$"
-__Id__       = "$Id$"
-__HeadURL    = "$HeadURL$"
 
 import numpy as np
-try    : import xarray as xr
-except ImportError : pass
-
-try    : import f90nml
-except : pass
-
-try : from sklearn.impute import SimpleImputer
-except : pass
-
-try    : import numba
-except : pass
-
-rpi = np.pi ; rad = np.deg2rad (1.0) ; dar = np.rad2deg (1.0)
-
-nperio_valid_range = [0, 1, 4, 4.2, 5, 6, 6.2]
-
-rday   = 24.*60.*60.     # Day length [s]
-rsiyea = 365.25 * rday * 2. * rpi / 6.283076 # Sideral year length [s]
-rsiday = rday / (1. + rday / rsiyea)
-raamo  =  12.        # Number of months in one year
-rjjhh  =  24.        # Number of hours in one day
-rhhmm  =  60.        # Number of minutes in one hour
-rmmss  =  60.        # Number of seconds in one minute
-omega  = 2. * rpi / rsiday # Earth rotation parameter [s-1]
-ra     = 6371229.    # Earth radius [m]
-grav   = 9.80665     # Gravity [m/s2]
-repsi  = np.finfo (1.0).eps
-
-xList = [ 'x', 'X', 'lon'   , 'longitude' ]
-yList = [ 'y', 'Y', 'lat'   , 'latitude'  ]
-zList = [ 'z', 'Z', 'depth' , ]
-tList = [ 't', 'T', 'time'  , ]
+import xarray as xr
+
+# Tries to import some moldules that are available in all Python installations
+#  and used in only a few specific functions
+try :
+    from sklearn.impute import SimpleImputer
+except ImportError as err :
+    print ( f'===> Warning : Module nemo : Import error of sklearn.impute.SimpleImputer : {err}' )
+    SimpleImputer = None
+
+try :
+    import f90nml
+except ImportError as err :
+    print ( f'===> Warning : Module nemo : Import error of f90nml : {err}' )
+    f90nml = None
+
+# SVN information
+__SVN__ = ({
+    'Author'   : '$Author$',
+    'Date'     : '$Date$',
+    'Revision' : '$Revision$',
+    'Id'       : '$Id$',
+    'HeadURL'  : '$HeadURL$',
+    'SVN_Date' : '$SVN_Date: $',
+    })
+##
+    
+RPI   = np.pi
+RAD   = np.deg2rad (1.0)
+DAR   = np.rad2deg (1.0)
+REPSI = np.finfo (1.0).eps
+
+NPERIO_VALID_RANGE = [0, 1, 4, 4.2, 5, 6, 6.2]
+
+RAAMO    =      12          # Number of months in one year
+RJJHH    =      24          # Number of hours in one day
+RHHMM    =      60          # Number of minutes in one hour
+RMMSS    =      60          # Number of seconds in one minute
+RA       = 6371229.0        # Earth radius                                  [m]
+GRAV     =       9.80665    # Gravity                                       [m/s2]
+RT0      =     273.15       # Freezing point of fresh water                 [Kelvin]
+RAU0     =    1026.0        # Volumic mass of sea water                     [kg/m3]
+SICE     =       6.0        # Salinity of ice (for pisces)                  [psu]
+SOCE     =      34.7        # Salinity of sea (for pisces and isf)          [psu]
+RLEVAP   =       2.5e+6     # Latent heat of evaporation (water)            [J/K]
+VKARMN   =       0.4        # Von Karman constant
+STEFAN   =       5.67e-8    # Stefan-Boltzmann constant                     [W/m2/K4]
+RHOS     =     330.         # Volumic mass of snow                          [kg/m3]
+RHOI     =     917.         # Volumic mass of sea ice                       [kg/m3]
+RHOW     =    1000.         # Volumic mass of freshwater in melt ponds      [kg/m3]
+RCND_I   =       2.034396   # Thermal conductivity of fresh ice             [W/m/K]
+RCPI     =    2067.0        # Specific heat of fresh ice                    [J/kg/K]
+RLSUB    =       2.834e+6   # Pure ice latent heat of sublimation           [J/kg]
+RLFUS    =       0.334e+6   # Latent heat of fusion of fresh ice            [J/kg]
+RTMLT    =       0.054      # Decrease of seawater meltpoint with salinity
+
+RDAY     = RJJHH * RHHMM * RMMSS                # Day length               [s]
+RSIYEA   = 365.25 * RDAY * 2. * RPI / 6.283076  # Sideral year length      [s]
+RSIDAY   = RDAY / (1. + RDAY / RSIYEA)          # Sideral day length       [s]
+OMEGA    = 2. * RPI / RSIDAY                    # Earth rotation parameter [s-1]
+
+## Default names of dimensions
+UDIMS = {'x':'x', 'y':'y', 'z':'olevel', 't':'time_counter'}
+
+## All possibles name of dimensions in Nemo files
+XNAME = [ 'x', 'X', 'X1', 'xx', 'XX',
+              'x_grid_T', 'x_grid_U', 'x_grid_V', 'x_grid_F', 'x_grid_W',
+              'lon', 'nav_lon', 'longitude', 'X1', 'x_c', 'x_f', ]
+YNAME = [ 'y', 'Y', 'Y1', 'yy', 'YY',
+              'y_grid_T', 'y_grid_U', 'y_grid_V', 'y_grid_F', 'y_grid_W',
+              'lat', 'nav_lat', 'latitude' , 'Y1', 'y_c', 'y_f', ]
+ZNAME = [ 'z', 'Z', 'Z1', 'zz', 'ZZ', 'depth', 'tdepth', 'udepth',
+              'vdepth', 'wdepth', 'fdepth', 'deptht', 'depthu',
+              'depthv', 'depthw', 'depthf', 'olevel', 'z_c', 'z_f', ]
+TNAME = [ 't', 'T', 'tt', 'TT', 'time', 'time_counter', 'time_centered', ]
+
+## All possibles name of units of dimensions in Nemo files
+XUNIT = [ 'degrees_east', ]
+YUNIT = [ 'degrees_north', ]
+ZUNIT = [ 'm', 'meter', ]
+TUNIT = [ 'second', 'minute', 'hour', 'day', 'month', 'year', ]
+
+## All possibles size of dimensions in Orca files
+XLENGTH = [ 180, 182, 360, 362, 1440 ]
+YLENGTH = [ 148, 149, 331, 332 ]
+ZLENGTH = [ 31, 75]
 
 ## ===========================================================================
-def __mmath__ (tab, default=None) :
+def __mmath__ (ptab, default=None) :
+    '''Determines the type of tab : xarray, numpy or numpy.ma object ?
+
+    Returns type
+    '''
     mmath = default
-    try    :
-        if type (tab) == xr.core.dataarray.DataArray : mmath = xr
-    except :
-        pass
-
-    try    :
-        if type (tab) == np.ndarray : mmath = np
-    except :
-        pass
-            
+    if isinstance (ptab, xr.core.dataarray.DataArray) :
+        mmath = xr
+    if isinstance (ptab, np.ndarray) :
+        mmath = np
+    if isinstance (ptab, np.ma.MaskType) :
+        mmath = np.ma
+
     return mmath
 
-
-def __guessNperio__ (jpj, jpi, nperio=None, out='nperio') :
-    '''
-    Tries to guess the value of nperio (periodicity parameter. See NEMO documentation for details)
-    
+def __guess_nperio__ (jpj, jpi, nperio=None, out='nperio') :
+    '''Tries to guess the value of nperio (periodicity parameter.
+
+    See NEMO documentation for details)
     Inputs
     jpj    : number of latitudes
@@ -91,13 +148,12 @@
     nperio : periodicity parameter
     '''
-    if nperio == None :
-        nperio = __guessConfig__ (jpj, jpi, nperio=None, out='nperio')
-    
+    if nperio is None :
+        nperio = __guess_config__ (jpj, jpi, nperio=None, out=out)
     return nperio
 
-def __guessConfig__ (jpj, jpi, nperio=None, config=None, out='nperio') :
-    '''
-    Tries to guess the value of nperio (periodicity parameter. See NEMO documentation for details)
-    
+def __guess_config__ (jpj, jpi, nperio=None, config=None, out='nperio') :
+    '''Tries to guess the value of nperio (periodicity parameter).
+
+    See NEMO documentation for details)
     Inputs
     jpj    : number of latitudes
@@ -105,54 +161,51 @@
     nperio : periodicity parameter
     '''
-    if nperio == None :
+    print ( jpi, jpj)
+    if nperio is None :
         ## Values for NEMO version < 4.2
-        if jpj ==  149 and jpi ==  182 :
-            config = 'ORCA2.3'
-            nperio = 4   # ORCA2. We choose legacy orca2.
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'T'
-        if jpj ==  332 and jpi ==  362 : # eORCA1.
-            config = 'eORCA1.2'
-            nperio = 6  
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'F'
+        if ( (jpj == 149 and jpi == 182) or (jpj is None and jpi == 182) or
+             (jpj == 149 or jpi is None) ) :
+            # ORCA2. We choose legacy orca2.
+            config, nperio, iperio, jperio, nfold, nftype = 'ORCA2.3' , 4, 1, 0, 1, 'T'
+        if ((jpj == 332 and jpi == 362) or (jpj is None and jpi == 362) or
+            (jpj ==  332 and jpi is None) ) : # eORCA1.
+            config, nperio, iperio, jperio, nfold, nftype = 'eORCA1.2', 6, 1, 0, 1, 'F'
         if jpi == 1442 :  # ORCA025.
-            config = 'ORCA025'
-            nperio = 6 
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'F'
+            config, nperio, iperio, jperio, nfold, nftype = 'ORCA025' , 6, 1, 0, 1, 'F'
         if jpj ==  294 : # ORCA1
-            config = 'ORCA1'
-            nperio = 6
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'F'
-            
+            config, nperio, iperio, jperio, nfold, nftype = 'ORCA1'   , 6, 1, 0, 1, 'F'
+
         ## Values for NEMO version >= 4.2. No more halo points
-        if jpj == 148 and jpi ==  180 :
-            config = 'ORCA2.4'
-            nperio = 4.2 # ORCA2. We choose legacy orca2.
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'F'
-        if jpj == 331  and jpi ==  360 : # eORCA1.
-            config = 'eORCA1.4'
-            nperio = 6.2
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'F'
+        if  (jpj == 148 and jpi == 180) or (jpj is None and jpi == 180) or \
+            (jpj == 148 and jpi is None) :  # ORCA2. We choose legacy orca2.
+            config, nperio, iperio, jperio, nfold, nftype = 'ORCA2.4' , 4.2, 1, 0, 1, 'F'
+        if  (jpj == 331 and jpi == 360) or (jpj is None and jpi == 360) or \
+            (jpj == 331 and jpi is None) : # eORCA1.
+            config, nperio, iperio, jperio, nfold, nftype = 'eORCA1.4', 6.2, 1, 0, 1, 'F'
         if jpi == 1440 : # ORCA025.
-            config = 'ORCA025'
-            nperio = 6.2
-            Iperio = 1 ; Jperio = 0 ; NFold = 1 ; NFtype = 'F'
-            
-        if nperio == None :
-            raise Exception  ('in nemo module : nperio not found, and cannot by guessed')
+            config, nperio, iperio, jperio, nfold, nftype = 'ORCA025' , 6.2, 1, 0, 1, 'F'
+
+        if nperio is None :
+            raise ValueError ('in nemo module : nperio not found, and cannot by guessed')
+
+        if nperio in NPERIO_VALID_RANGE :
+            print ( f'nperio set as {nperio} (deduced from {jpj=} and {jpi=})' )
         else :
-            if nperio in nperio_valid_range :
-                print ('nperio set as {:} (deduced from jpj={:d} jpi={:d})'.format (nperio, jpj, jpi))
-            else : 
-                raise ValueError ('nperio set as {:} (deduced from jpi={:d}) : nemo.py is not ready for this value'.format (nperio, jpi))
-
-    if out == 'nperio' : return nperio
-    if out == 'config' : return config
-    if out == 'perio'  : return Iperio, Jperio, NFold, NFtype
-    if out in ['full', 'all'] : return {'nperio':nperio, 'Iperio':Iperio, 'Jperio':Jperio, 'NFold':NFold, 'NFtype':NFtype}
-        
-def __guessPoint__ (ptab) :
-    '''
-    Tries to guess the grid point (periodicity parameter. See NEMO documentation for details)
-    
+            raise ValueError ( f'nperio set as {nperio} (deduced from {jpi=} and {jpj=}) : \n'+
+                                'nemo.py is not ready for this value' )
+
+    if out == 'nperio' :
+        return nperio
+    if out == 'config' :
+        return config
+    if out == 'perio'  :
+        return iperio, jperio, nfold, nftype
+    if out in ['full', 'all'] :
+        return {'nperio':nperio, 'iperio':iperio, 'jperio':jperio, 'nfold':nfold, 'nftype':nftype}
+
+def __guess_point__ (ptab) :
+    '''Tries to guess the grid point (periodicity parameter.
+
+    See NEMO documentation for details)
     For array conforments with xgcm requirements
 
@@ -162,370 +215,555 @@
     Credits : who is the original author ?
     '''
-    gP = None
+
+    gp = None
     mmath = __mmath__ (ptab)
     if mmath == xr :
-        if 'x_c' in ptab.dims and 'y_c' in ptab.dims                        : gP = 'T'
-        if 'x_f' in ptab.dims and 'y_c' in ptab.dims                        : gP = 'U'
-        if 'x_c' in ptab.dims and 'y_f' in ptab.dims                        : gP = 'V'
-        if 'x_f' in ptab.dims and 'y_f' in ptab.dims                        : gP = 'F'
-        if 'x_c' in ptab.dims and 'y_c' in ptab.dims and 'z_c' in ptab.dims : gP = 'T'
-        if 'x_c' in ptab.dims and 'y_c' in ptab.dims and 'z_f' in ptab.dims : gP = 'W'
-        if 'x_f' in ptab.dims and 'y_c' in ptab.dims and 'z_f' in ptab.dims : gP = 'U'
-        if 'x_c' in ptab.dims and 'y_f' in ptab.dims and 'z_f' in ptab.dims : gP = 'V'
-        if 'x_f' in ptab.dims and 'y_f' in ptab.dims and 'z_f' in ptab.dims : gP = 'F'
-             
-        if gP == None :
-            raise Exception ('in nemo module : cd_type not found, and cannot by guessed')
-        else :
-            print ('Grid set as', gP, 'deduced from dims ', ptab.dims)
-            return gP
-    else :
-         raise Exception  ('in nemo module : cd_type not found, input is not an xarray data')
+        if ('x_c' in ptab.dims and 'y_c' in ptab.dims ) :
+            gp = 'T'
+        if ('x_f' in ptab.dims and 'y_c' in ptab.dims ) :
+            gp = 'U'
+        if ('x_c' in ptab.dims and 'y_f' in ptab.dims ) :
+            gp = 'V'
+        if ('x_f' in ptab.dims and 'y_f' in ptab.dims ) :
+            gp = 'F'
+        if ('x_c' in ptab.dims and 'y_c' in ptab.dims
+              and 'z_c' in ptab.dims )                :
+            gp = 'T'
+        if ('x_c' in ptab.dims and 'y_c' in ptab.dims
+                and 'z_f' in ptab.dims )                :
+            gp = 'W'
+        if ('x_f' in ptab.dims and 'y_c' in ptab.dims
+                and 'z_f' in ptab.dims )                :
+            gp = 'U'
+        if ('x_c' in ptab.dims and 'y_f' in ptab.dims
+                and 'z_f' in ptab.dims ) :
+            gp = 'V'
+        if ('x_f' in ptab.dims and 'y_f' in ptab.dims
+                and 'z_f' in ptab.dims ) :
+            gp = 'F'
+
+        if gp is None :
+            raise AttributeError ('in nemo module : cd_type not found, and cannot by guessed')
+        print ( f'Grid set as {gp} deduced from dims {ptab.dims}' )
+        return gp
+    else :
+        raise AttributeError  ('in nemo module : cd_type not found, input is not an xarray data')
+
+def get_shape ( ptab ) :
+    '''Get shape of ptab return a string with axes names
+
+    shape may contain X, Y, Z or T
+    Y is missing for a latitudinal slice
+    X is missing for on longitudinal slice
+    etc ...
+    '''
+
+    g_shape = ''
+    if __find_axis__ (ptab, 'x')[0] :
+        g_shape = 'X'
+    if __find_axis__ (ptab, 'y')[0] :
+        g_shape = 'Y' + g_shape
+    if __find_axis__ (ptab, 'z')[0] :
+        g_shape = 'Z' + g_shape
+    if __find_axis__ (ptab, 't')[0] :
+        g_shape = 'T' + g_shape
+    return g_shape
 
 def lbc_diag (nperio) :
-    lperio = nperio ; aperio = False
+    '''Useful to switch between field with and without halo'''
+    lperio, aperio = nperio, False
     if nperio == 4.2 :
-        lperio = 4 ; aperio = True
+        lperio, aperio = 4, True
     if nperio == 6.2 :
-        lperio = 6 ; aperio = True
-        
-    return lperio, aperio 
-
-def __findAxis__ (tab, axis='z') :
-    '''
-    Find number and name of the requested axis
-    '''
-    mmath = __mmath__ (tab)
-    ix = None ; ax = None
-
-    if axis in xList :
-        axList = [ 'x', 'X',
-                   'lon', 'nav_lon', 'nav_lon_T', 'nav_lon_U', 'nav_lon_V', 'nav_lon_F', 'nav_lon_W',
-                   'x_grid_T', 'x_grid_U', 'x_grid_V', 'x_grid_F', 'x_grid_W',
-                   'glam', 'glamt', 'glamu', 'glamv', 'glamf', 'glamw' ]
-        unList = [ 'degrees_east' ]
-    if axis in yList :
-        axList = [ 'y', 'Y', 'lat',
-                   'nav_lat', 'nav_lat_T', 'nav_lat_U', 'nav_lat_V', 'nav_lat_F', 'nav_lat_W',
-                   'y_grid_T', 'y_grid_U', 'y_grid_V', 'y_grid_F', 'y_grid_W',
-                   'gphi', 'gphi', 'gphiu', 'gphiv', 'gphif', 'gphiw']
-        unList = [ 'degrees_north' ]
-    if axis in zList :
-        axList = [ 'z', 'Z',
-                   'depth', 'deptht', 'depthu', 'depthv', 'depthf', 'depthw',
-                   'olevel' ]
-        unList = [ 'm', 'meter' ]
-    if axis in tList :
-        axList = [ 't', 'T', 'time', 'time_counter' ]
-        unList = [ 'second', 'minute', 'hour', 'day', 'month' ]
-    
+        lperio, aperio = 6, True
+    return lperio, aperio
+
+def __find_axis__ (ptab, axis='z', back=True) :
+    '''Returns name and name of the requested axis'''
+    mmath = __mmath__ (ptab)
+    ax, ix = None, None
+
+    if axis in XNAME :
+        ax_name, unit_list, length = XNAME, XUNIT, XLENGTH
+    if axis in YNAME :
+        ax_name, unit_list, length = YNAME, YUNIT, YLENGTH
+    if axis in ZNAME :
+        ax_name, unit_list, length = ZNAME, ZUNIT, ZLENGTH
+    if axis in TNAME :
+        ax_name, unit_list, length = TNAME, TUNIT, None
+
     if mmath == xr :
-        for Name in axList :
-            try    :
-                ix = tab.dims.index (Name)
-                ax = Name
-            except : pass
-
-        for i, dim in enumerate (tab.dims) :
-            if 'units' in tab.coords[dim].attrs.keys() :
-                for name in unList :
-                    if name in tab.coords[dim].attrs['units'] :
-                        ix = i
-                        ax = dim
-    else :
-        if axis in xList : ix=-1
-        if axis in yList :
-            if len(tab.shape) >= 2 : ix=-2
-        if axis in zList :
-            if len(tab.shape) >= 3 : ix=-3
-        if axis in tList :
-            if len(tab.shape) >=3  : ix=-3
-            if len(tab.shape) >=4  : ix=-4
-       
-    return ix, ax
-
-#@numba.jit(forceobj=True)
-def fixed_lon (lon, center_lon=0.0) :
-    '''
-    Returns corrected longitudes for nicer plots
+        # Try by name
+        for dim in ax_name :
+            if dim in ptab.dims :
+                ix, ax = ptab.dims.index (dim), dim
+
+        # If not found, try by axis attributes
+        if not ix :
+            for i, dim in enumerate (ptab.dims) :
+                if 'axis' in ptab.coords[dim].attrs.keys() :
+                    l_axis = ptab.coords[dim].attrs['axis']
+                    if axis in ax_name and l_axis == 'X' :
+                        ix, ax = (i, dim)
+                    if axis in ax_name and l_axis == 'Y' :
+                        ix, ax = (i, dim)
+                    if axis in ax_name and l_axis == 'Z' :
+                        ix, ax = (i, dim)
+                    if axis in ax_name and l_axis == 'T' :
+                        ix, ax = (i, dim)
+
+        # If not found, try by units
+        if not ix :
+            for i, dim in enumerate (ptab.dims) :
+                if 'units' in ptab.coords[dim].attrs.keys() :
+                    for name in unit_list :
+                        if name in ptab.coords[dim].attrs['units'] :
+                            ix, ax = i, dim
+
+    # If numpy array or dimension not found, try by length
+    if mmath != xr or not ix :
+        if length :
+            l_shape = ptab.shape
+            for nn in np.arange ( len(l_shape) ) :
+                if l_shape[nn] in length :
+                    ix = nn
+
+    if ix and back :
+        ix -= len(ptab.shape)
+
+    return ax, ix
+
+def find_axis ( ptab, axis='z', back=True ) :
+    '''Version of find_axis with no __'''
+    ix, xx = __find_axis__ (ptab, axis, back)
+    return xx, ix
+
+def fixed_lon (plon, center_lon=0.0) :
+    '''Returns corrected longitudes for nicer plots
 
     lon        : longitudes of the grid. At least 2D.
     center_lon : center longitude. Default=0.
 
-    Designed by Phil Pelson. See https://gist.github.com/pelson/79cf31ef324774c97ae7
-    '''
-    mmath = __mmath__ (lon)
+    Designed by Phil Pelson.
+    See https://gist.github.com/pelson/79cf31ef324774c97ae7
+    '''
+    mmath = __mmath__ (plon)
+
+    f_lon = plon.copy ()
+
+    f_lon = mmath.where (f_lon > center_lon+180., f_lon-360.0, f_lon)
+    f_lon = mmath.where (f_lon < center_lon-180., f_lon+360.0, f_lon)
+
+    for i, start in enumerate (np.argmax (np.abs (np.diff (f_lon, axis=-1)) > 180., axis=-1)) :
+        f_lon [..., i, start+1:] += 360.
+
+    # Special case for eORCA025
+    if f_lon.shape [-1] == 1442 :
+        f_lon [..., -2, :] = f_lon [..., -3, :]
+    if f_lon.shape [-1] == 1440 :
+        f_lon [..., -1, :] = f_lon [..., -2, :]
+
+    if f_lon.min () > center_lon :
+        f_lon += -360.0
+    if f_lon.max () < center_lon :
+        f_lon +=  360.0
+
+    if f_lon.min () < center_lon-360.0 :
+        f_lon +=  360.0
+    if f_lon.max () > center_lon+360.0 :
+        f_lon += -360.0
+
+    return f_lon
+
+def bounds_clolon ( pbounds_lon, plon, rad=False, deg=True) :
+    '''Choose closest to lon0 longitude, adding/substacting 360Â° if needed
+    '''
+
+    if rad :
+        lon_range = 2.0*np.pi
+    if deg :
+        lon_range = 360.0
+    b_clolon = pbounds_lon.copy ()
+
+    b_clolon = xr.where ( b_clolon < plon-lon_range/2.,
+                          b_clolon+lon_range,
+                          b_clolon )
+    b_clolon = xr.where ( b_clolon > plon+lon_range/2.,
+                          b_clolon-lon_range,
+                          b_clolon )
+    return b_clolon
+
+def unify_dims ( dd, x='x', y='y', z='olevel', t='time_counter', verbose=False ) :
+    '''Rename dimensions to unify them between NEMO versions
+    '''
+    for xx in XNAME :
+        if xx in dd.dims and xx != x :
+            if verbose :
+                print ( f"{xx} renamed to {x}" )
+            dd = dd.rename ( {xx:x})
+
+    for yy in YNAME :
+        if yy in dd.dims and yy != y  :
+            if verbose :
+                print ( f"{yy} renamed to {y}" )
+            dd = dd.rename ( {yy:y} )
+
+    for zz in ZNAME :
+        if zz in dd.dims and zz != z :
+            if verbose :
+                print ( f"{zz} renamed to {z}" )
+            dd = dd.rename ( {zz:z} )
+
+    for tt in TNAME  :
+        if tt in dd.dims and tt != t :
+            if verbose :
+                print ( f"{tt} renamed to {t}" )
+            dd = dd.rename ( {tt:t} )
+
+    return dd
+
+
+if SimpleImputer : 
+  def fill_empty (ptab, sval=np.nan, transpose=False) :
+        '''Fill empty values
+
+        Useful when NEMO has run with no wet points options :
+        some parts of the domain, with no ocean points, have no
+        values
+        '''
+        mmath = __mmath__ (ptab)
+
+        imp = SimpleImputer (missing_values=sval, strategy='mean')
+        if transpose :
+            imp.fit (ptab.T)
+            ztab = imp.transform (ptab.T).T
+        else :
+            imp.fit (ptab)
+            ztab = imp.transform (ptab)
+
+        if mmath == xr :
+            ztab = xr.DataArray (ztab, dims=ztab.dims, coords=ztab.coords)
+            ztab.attrs.update (ptab.attrs)
+
+        return ztab
+
     
-    fixed_lon = lon.copy ()
-        
-    fixed_lon = mmath.where (fixed_lon > center_lon+180., fixed_lon-360.0, fixed_lon)
-    fixed_lon = mmath.where (fixed_lon < center_lon-180., fixed_lon+360.0, fixed_lon)
-    
-    for i, start in enumerate (np.argmax (np.abs (np.diff (fixed_lon, axis=-1)) > 180., axis=-1)) :
-        fixed_lon [..., i, start+1:] += 360.
-
-    # Special case for eORCA025
-    if fixed_lon.shape [-1] == 1442 : fixed_lon [..., -2, :] = fixed_lon [..., -3, :]
-    if fixed_lon.shape [-1] == 1440 : fixed_lon [..., -1, :] = fixed_lon [..., -2, :]
-
-    if fixed_lon.min () > center_lon : fixed_lon += -360.0
-    if fixed_lon.max () < center_lon : fixed_lon +=  360.0
-        
-    if fixed_lon.min () < center_lon-360.0 : fixed_lon +=  360.0
-    if fixed_lon.max () > center_lon+360.0 : fixed_lon += -360.0
-                
-    return fixed_lon
-
-#@numba.jit(forceobj=True)
-def fill_empty (ztab, sval=np.nan, transpose=False) :
-    '''
-    Fill values
-
-    Useful when NEMO has run with no wet points options : 
-    some parts of the domain, with no ocean points, has no
+else : 
+    print ("Import error of sklearn.impute.SimpleImputer")
+    def fill_empty (ptab, sval=np.nan, transpose=False) :
+        '''Void version of fill_empy, because module sklearn.impute.SimpleImputer is not available
+
+        fill_empty : 
+          Fill values
+
+          Useful when NEMO has run with no wet points options :
+          some parts of the domain, with no ocean points, have no
+          values
+        '''
+        print ( 'Error : module sklearn.impute.SimpleImputer not found' )
+        print ( 'Can not call fill_empty' )
+        print ( 'Call arguments where : ' )
+        print ( f'{ptab.shape=} {sval=} {transpose=}' )
+  
+def fill_lonlat (plon, plat, sval=-1) :
+    '''Fill longitude/latitude values
+
+    Useful when NEMO has run with no wet points options :
+    some parts of the domain, with no ocean points, have no
     lon/lat values
     '''
-    mmath = __mmath__ (ztab)
+    from sklearn.impute import SimpleImputer
+    mmath = __mmath__ (plon)
 
     imp = SimpleImputer (missing_values=sval, strategy='mean')
-    if transpose :
-        imp.fit (ztab.T)
-        ptab = imp.transform (ztab.T).T
-    else : 
-        imp.fit (ztab)
-        ptab = imp.transform (ztab)
-   
+    imp.fit (plon)
+    zlon = imp.transform (plon)
+    imp.fit (plat.T)
+    zlat = imp.transform (plat.T).T
+
     if mmath == xr :
-        ptab = xr.DataArray (ptab, dims=ztab.dims, coords=ztab.coords)
-        ptab.attrs = ztab.attrs
-        
-    return ptab
-
-#@numba.jit(forceobj=True)
-def fill_lonlat (lon, lat, sval=-1) :
-    '''
-    Fill longitude/latitude values
-
-    Useful when NEMO has run with no wet points options : 
+        zlon = xr.DataArray (zlon, dims=plon.dims, coords=plon.coords)
+        zlat = xr.DataArray (zlat, dims=plat.dims, coords=plat.coords)
+        zlon.attrs.update (plon.attrs)
+        zlat.attrs.update (plat.attrs)
+
+    zlon = fixed_lon (zlon)
+
+    return zlon, zlat
+
+def fill_bounds_lonlat (pbounds_lon, pbounds_lat, sval=-1) :
+    '''Fill longitude/latitude bounds values
+
+    Useful when NEMO has run with no wet points options :
     some parts of the domain, with no ocean points, as no
     lon/lat values
     '''
-    mmath = __mmath__ (lon)
+    mmath = __mmath__ (pbounds_lon)
+
+    z_bounds_lon = np.empty ( pbounds_lon.shape )
+    z_bounds_lat = np.empty ( pbounds_lat.shape )
 
     imp = SimpleImputer (missing_values=sval, strategy='mean')
-    imp.fit (lon)
-    plon = imp.transform (lon)
-    imp.fit (lat.T)
-    plat = imp.transform (lat.T).T
+
+    for n in np.arange (4) :
+        imp.fit (pbounds_lon[:,:,n])
+        z_bounds_lon[:,:,n] = imp.transform (pbounds_lon[:,:,n])
+        imp.fit (pbounds_lat[:,:,n].T)
+        z_bounds_lat[:,:,n] = imp.transform (pbounds_lat[:,:,n].T).T
 
     if mmath == xr :
-        plon = xr.DataArray (plon, dims=lon.dims, coords=lon.coords)
-        plat = xr.DataArray (plat, dims=lat.dims, coords=lat.coords)
-        plon.attrs = lon.attrs ; plat.attrs = lat.attrs
-        
-    plon = fixed_lon (plon)
-    
-    return plon, plat
-
-#@numba.jit(forceobj=True)
-def jeq (lat) :
-    '''
-    Returns j index of equator in the grid
-    
+        z_bounds_lon = xr.DataArray (pbounds_lon, dims=pbounds_lon.dims,
+                                         coords=pbounds_lon.coords)
+        z_bounds_lat = xr.DataArray (pbounds_lat, dims=pbounds_lat.dims,
+                                         coords=pbounds_lat.coords)
+        z_bounds_lon.attrs.update (pbounds_lat.attrs)
+        z_bounds_lat.attrs.update (pbounds_lat.attrs)
+
+    return z_bounds_lon, z_bounds_lat
+
+def jeq (plat) :
+    '''Returns j index of equator in the grid
+
     lat : latitudes of the grid. At least 2D.
     '''
-    mmath = __mmath__ (lat)
-    ix, ax = __findAxis__ (lat, 'x')
-    iy, ay = __findAxis__ (lat, 'y')
+    mmath = __mmath__ (plat)
+    jy = __find_axis__ (plat, 'y')[-1]
 
     if mmath == xr :
-        jeq = int ( np.mean ( np.argmin (np.abs (np.float64 (lat)), axis=iy) ) )
-    else : 
-        jeq = np.argmin (np.abs (np.float64 (lat[...,:, 0])))
-    return jeq
-
-#@numba.jit(forceobj=True)
-def lon1D (lon, lat=None) :
-    '''
-    Returns 1D longitude for simple plots.
-    
-    lon : longitudes of the grid
-    lat (optionnal) : latitudes of the grid
-    '''
-    mmath = __mmath__ (lon)
-    if np.max (lat) != None :
-        je    = jeq (lat)
-        lon1D = lon.copy() [..., je, :]
-    else :
-        jpj, jpi = lon.shape [-2:]
-        lon1D    = lon.copy() [..., jpj//3, :]
-
-    start = np.argmax (np.abs (np.diff (lon1D, axis=-1)) > 180.0, axis=-1)
-    lon1D [..., start+1:] += 360
+        jj = int ( np.mean ( np.argmin (np.abs (np.float64 (plat)),
+                                                axis=jy) ) )
+    else :
+        jj = np.argmin (np.abs (np.float64 (plat[...,:, 0])))
+
+    return jj
+
+def lon1d (plon, plat=None) :
+    '''Returns 1D longitude for simple plots.
+
+    plon : longitudes of the grid
+    plat (optionnal) : latitudes of the grid
+    '''
+    mmath = __mmath__ (plon)
+    jpj, jpi  = plon.shape [-2:]
+    if np.max (plat) :
+        je    = jeq (plat)
+        lon0 = plon [..., je, 0].copy()
+        dlon = plon [..., je, 1].copy() - plon [..., je, 0].copy()
+        lon_1d = np.linspace ( start=lon0, stop=lon0+360.+2*dlon, num=jpi )
+    else :
+        lon0 = plon [..., jpj//3, 0].copy()
+        dlon = plon [..., jpj//3, 1].copy() - plon [..., jpj//3, 0].copy()
+        lon_1d = np.linspace ( start=lon0, stop=lon0+360.+2*dlon, num=jpi )
+
+    #start = np.argmax (np.abs (np.diff (lon1D, axis=-1)) > 180.0, axis=-1)
+    #lon1D [..., start+1:] += 360
 
     if mmath == xr :
-        lon1D.attrs = lon.attrs
-        lon1D = lon1D.assign_coords ( {'x':lon1D} )
-        
-    return lon1D
-
-#@numba.jit(forceobj=True)
-def latreg (lat, diff=0.1) :
-    '''
-    Returns maximum j index where gridlines are along latitudes in the northern hemisphere
-    
+        lon_1d = xr.DataArray( lon_1d, dims=('lon',), coords=(lon_1d,))
+        lon_1d.attrs.update (plon.attrs)
+        lon_1d.attrs['units']         = 'degrees_east'
+        lon_1d.attrs['standard_name'] = 'longitude'
+        lon_1d.attrs['long_name :']   = 'Longitude'
+
+    return lon_1d
+
+def latreg (plat, diff=0.1) :
+    '''Returns maximum j index where gridlines are along latitudes
+    in the northern hemisphere
+
     lat : latitudes of the grid (2D)
     diff [optional] : tolerance
     '''
-    mmath = __mmath__ (lat)
-    if diff == None :
-        dy   = np.float64 (np.mean (np.abs (lat - np.roll (lat,shift=1,axis=-2, roll_coords=False))))
+    #mmath = __mmath__ (plat)
+    if diff is None :
+        dy = np.float64 (np.mean (np.abs (plat -
+                        np.roll (plat,shift=1,axis=-2, roll_coords=False))))
+        print ( f'{dy=}' )
         diff = dy/100.
-    
-    je     = jeq (lat)
-    jreg   = np.where (lat[...,je:,:].max(axis=-1) - lat[...,je:,:].min(axis=-1)< diff)[-1][-1] + je
-    latreg = np.float64 (lat[...,jreg,:].mean(axis=-1))
-    JREG   = jreg
-
-    return jreg, latreg
-
-#@numba.jit(forceobj=True)
-def lat1D (lat) :
-    '''
-    Returns 1D latitudes for zonal means and simple plots.
-
-    lat : latitudes of the grid (2D)
-    '''
-    mmath = __mmath__ (lat)
-    jpj, jpi = lat.shape[-2:]
-
-    dy     = np.float64 (np.mean (np.abs (lat - np.roll (lat, shift=1,axis=-2))))
-    je     = jeq (lat)
-    lat_eq = np.float64 (lat[...,je,:].mean(axis=-1))
-      
-    jreg, lat_reg = latreg (lat)
-    lat_ave = np.mean (lat, axis=-1)
-
-    if (np.abs (lat_eq) < dy/100.) : # T, U or W grid
-        dys    = (90.-lat_reg) / (jpj-jreg-1)*0.5
+
+    je     = jeq (plat)
+    jreg   = np.where (plat[...,je:,:].max(axis=-1) -
+                       plat[...,je:,:].min(axis=-1)< diff)[-1][-1] + je
+    lareg  = np.float64 (plat[...,jreg,:].mean(axis=-1))
+
+    return jreg, lareg
+
+def lat1d (plat) :
+    '''Returns 1D latitudes for zonal means and simple plots.
+
+    plat : latitudes of the grid (2D)
+    '''
+    mmath = __mmath__ (plat)
+    iy = __find_axis__ (plat, 'y')[-1]
+    jpj = plat.shape[iy]
+
+    dy     = np.float64 (np.mean (np.abs (plat - np.roll (plat, shift=1,axis=-2))))
+    je     = jeq (plat)
+    lat_eq = np.float64 (plat[...,je,:].mean(axis=-1))
+
+    jreg, lat_reg = latreg (plat)
+    lat_ave = np.mean (plat, axis=-1)
+
+    if np.abs (lat_eq) < dy/100. : # T, U or W grid
+        if jpj-1 > jreg :
+            dys = (90.-lat_reg) / (jpj-jreg-1)*0.5
+        else            :
+            dys = (90.-lat_reg) / 2.0
         yrange = 90.-dys-lat_reg
     else                           :  # V or F grid
-        yrange = 90.    -lat_reg
-        
-    lat1D = mmath.where (lat_ave<lat_reg, lat_ave, lat_reg + yrange * (np.arange(jpj)-jreg)/(jpj-jreg-1))   
-        
+        yrange = 90.-lat_reg
+
+    if jpj-1 > jreg :
+        lat_1d = mmath.where (lat_ave<lat_reg,
+                 lat_ave,
+                 lat_reg + yrange * (np.arange(jpj)-jreg)/(jpj-jreg-1) )
+    else :
+        lat_1d = lat_ave
+    lat_1d[-1] = 90.0
+
     if mmath == xr :
-        lat1D.attrs = lat.attrs
-        lat1D = lat1D.assign_coords ( {'y':lat1D} )
-
-    return lat1D
-
-#@numba.jit(forceobj=True)
-def latlon1D (lat, lon) :
-    '''
-    Returns simple latitude and longitude (1D) for simple plots.
-
-    lat, lon : latitudes and longitudes of the grid (2D)
-    '''
-    return lat1D (lat),  lon1D (lon, lat)
-
-##@numba.jit(forceobj=True)
+        lat_1d = xr.DataArray( lat_1d.values, dims=('lat',), coords=(lat_1d,))
+        lat_1d.attrs.update (plat.attrs)
+        lat_1d.attrs ['units']         = 'degrees_north'
+        lat_1d.attrs ['standard_name'] = 'latitude'
+        lat_1d.attrs ['long_name :']   = 'Latitude'
+
+    return lat_1d
+
+def latlon1d (plat, plon) :
+    '''Returns simple latitude and longitude (1D) for simple plots.
+
+    plat, plon : latitudes and longitudes of the grid (2D)
+    '''
+    return lat1d (plat),  lon1d (plon, plat)
+
+def ff (plat) :
+    '''Returns Coriolis factor
+    '''
+    zff   = np.sin (RAD * plat) * OMEGA
+    return zff
+
+def beta (plat) :
+    '''Return Beta factor (derivative of Coriolis factor)
+    '''
+    zbeta = np.cos (RAD * plat) * OMEGA / RA
+    return zbeta
+
 def mask_lonlat (ptab, x0, x1, y0, y1, lon, lat, sval=np.nan) :
+    '''Returns masked values outside a lat/lon box
+    '''
     mmath = __mmath__ (ptab)
-    try :
+    if mmath == xr :
         lon = lon.copy().to_masked_array()
         lat = lat.copy().to_masked_array()
-    except : pass
-            
-    mask = np.logical_and (np.logical_and(lat>y0, lat<y1), 
-            np.logical_or (np.logical_or (np.logical_and(lon>x0, lon<x1), np.logical_and(lon+360>x0, lon+360<x1)),
-                                      np.logical_and(lon-360>x0, lon-360<x1)))
-    tab = mmath.where (mask, ptab, np.nan)
-    
+
+    mask = np.logical_and (np.logical_and(lat>y0, lat<y1),
+            np.logical_or (np.logical_or (
+                np.logical_and(lon>x0, lon<x1),
+                np.logical_and(lon+360>x0, lon+360<x1)),
+                np.logical_and(lon-360>x0, lon-360<x1)))
+    tab = mmath.where (mask, ptab, sval)
+
     return tab
 
-#@numba.jit(forceobj=True)      
-def extend (tab, Lon=False, jplus=25, jpi=None, nperio=4) :
-    '''
-    Returns extended field eastward to have better plots, and box average crossing the boundary
+def extend (ptab, blon=False, jplus=25, jpi=None, nperio=4) :
+    '''Returns extended field eastward to have better plots,
+    and box average crossing the boundary
+
     Works only for xarray and numpy data (?)
-
-    tab : field to extend.
-    Lon : (optional, default=False) : if True, add 360 in the extended parts of the field
-    jpi : normal longitude dimension of the field. exrtend does nothing it the actual
-        size of the field != jpi (avoid to extend several times)
-    jplus (optional, default=25) : number of points added on the east side of the field
-    
-    '''
-    mmath = __mmath__ (tab)
-    
-    if tab.shape[-1] == 1 : extend = tab
-
-    else :
-        if jpi == None : jpi = tab.shape[-1]
-
-        if Lon : xplus = -360.0
-        else   : xplus =    0.0
-
-        if tab.shape[-1] > jpi :
-            extend = tab
+    Useful for plotting vertical sections in OCE and ATM.
+
+    ptab : field to extend.
+    blon  : (optional, default=False) : if True, add 360 in the extended
+          parts of the field
+    jpi   : normal longitude dimension of the field. extend does nothing
+          if the actual size of the field != jpi
+          (avoid to extend several times in notebooks)
+    jplus (optional, default=25) : number of points added on
+          the east side of the field
+
+    '''
+    mmath = __mmath__ (ptab)
+
+    if ptab.shape[-1] == 1 :
+        tabex = ptab
+
+    else :
+        if jpi is None :
+            jpi = ptab.shape[-1]
+
+        if blon :
+            xplus = -360.0
+        else   :
+            xplus =    0.0
+
+        if ptab.shape[-1] > jpi :
+            tabex = ptab
         else :
-            if nperio == 0 or nperio == 4.2 :
-                istart = 0 ; le=jpi+1 ; la=0
+            if nperio in [ 0, 4.2 ] :
+                istart, le, la = 0, jpi+1, 0
             if nperio == 1 :
-                istart = 0 ; le=jpi+1 ; la=0
-            if nperio == 4 or nperio == 6 : # OPA case with two halo points for periodicity
-                istart = 1 ; le=jpi-2 ; la=1  # Perfect, except at the pole that should be masked by lbc_plot
-           
+                istart, le, la = 0, jpi+1, 0
+            if nperio in [4, 6] : # OPA case with two halo points for periodicity
+                # Perfect, except at the pole that should be masked by lbc_plot
+                istart, le, la = 1, jpi-2, 1
             if mmath == xr :
-                extend = np.concatenate ((tab.values[..., istart   :istart+le+1    ] + xplus,
-                                          tab.values[..., istart+la:istart+la+jplus]         ), axis=-1)
-                lon    = tab.dims[-1]
+                tabex = np.concatenate (
+                     (ptab.values[..., istart   :istart+le+1    ] + xplus,
+                      ptab.values[..., istart+la:istart+la+jplus]         ),
+                      axis=-1)
+                lon    = ptab.dims[-1]
                 new_coords = []
-                for coord in tab.dims :
-                    if coord == lon : new_coords.append ( np.arange( extend.shape[-1]))
-                    else            : new_coords.append ( tab.coords[coord].values)
-                extend = xr.DataArray ( extend, dims=tab.dims, coords=new_coords )
-            else : 
-                extend = np.concatenate ((tab [..., istart   :istart+le+1    ] + xplus,
-                                          tab [..., istart+la:istart+la+jplus]          ), axis=-1)
-    return extend
-
-def orca2reg (ff, lat_name='nav_lat', lon_name='nav_lon', y_name='y', x_name='x') :
-    '''
-    Assign an ORCA dataset on a regular grid.
+                for coord in ptab.dims :
+                    if coord == lon :
+                        new_coords.append ( np.arange( tabex.shape[-1]))
+                    else            :
+                        new_coords.append ( ptab.coords[coord].values)
+                tabex = xr.DataArray ( tabex, dims=ptab.dims,
+                                           coords=new_coords )
+            else :
+                tabex = np.concatenate (
+                    (ptab [..., istart   :istart+le+1    ] + xplus,
+                     ptab [..., istart+la:istart+la+jplus]          ),
+                     axis=-1)
+    return tabex
+
+def orca2reg (dd, lat_name='nav_lat', lon_name='nav_lon',
+                  y_name='y', x_name='x') :
+    '''Assign an ORCA dataset on a regular grid.
+
     For use in the tropical region.
-    
-    Inputs : 
+    Inputs :
       ff : xarray dataset
       lat_name, lon_name : name of latitude and longitude 2D field in ff
       y_name, x_name     : namex of dimensions in ff
-      
+
       Returns : xarray dataset with rectangular grid. Incorrect above 20Â°N
     '''
     # Compute 1D longitude and latitude
-    (lat, lon) = latlon1D (ff[lat_name], ff[lon_name])
-
+    (zlat, zlon) = latlon1d ( dd[lat_name], dd[lon_name])
+
+    zdd = dd
     # Assign lon and lat as dimensions of the dataset
-    if y_name in ff.dims : 
-        lat = xr.DataArray (lat, coords=[lat,], dims=['lat',])     
-        ff  = ff.rename_dims ({y_name: "lat",}).assign_coords (lat=lat)
-    if x_name in ff.dims :
-        lon = xr.DataArray (lon, coords=[lon,], dims=['lon',])
-        ff  = ff.rename_dims ({x_name: "lon",}).assign_coords (lon=lon)
+    if y_name in zdd.dims :
+        zlat = xr.DataArray (zlat, coords=[zlat,], dims=['lat',])
+        zdd  = zdd.rename_dims ({y_name: "lat",}).assign_coords (lat=zlat)
+    if x_name in zdd.dims :
+        zlon = xr.DataArray (zlon, coords=[zlon,], dims=['lon',])
+        zdd  = zdd.rename_dims ({x_name: "lon",}).assign_coords (lon=zlon)
     # Force dimensions to be in the right order
     coord_order = ['lat', 'lon']
     for dim in [ 'depthw', 'depthv', 'depthu', 'deptht', 'depth', 'z',
-                 'time_counter', 'time', 'tbnds', 
+                 'time_counter', 'time', 'tbnds',
                  'bnds', 'axis_nbounds', 'two2', 'two1', 'two', 'four',] :
-        if dim in ff.dims : coord_order.insert (0, dim)
-        
-    ff = ff.transpose (*coord_order)
-    return ff
+        if dim in zdd.dims :
+            coord_order.insert (0, dim)
+
+    zdd = zdd.transpose (*coord_order)
+    return zdd
 
 def lbc_init (ptab, nperio=None) :
-    '''
-    Prepare for all lbc calls
-    
+    '''Prepare for all lbc calls
+
     Set periodicity on input field
     nperio    : Type of periodicity
@@ -539,351 +777,415 @@
     See NEMO documentation for further details
     '''
-    jpj, jpi = ptab.shape[-2:]
-    if nperio == None : nperio = __guessNperio__ (jpj, jpi, nperio)
-    
-    if nperio not in nperio_valid_range :
-        raise Exception ('nperio=', nperio, ' is not in the valid range', nperio_valid_range)
+    jpi, jpj = None, None
+    ax, ix = __find_axis__ (ptab, 'x')
+    ay, jy = __find_axis__ (ptab, 'y')
+    if ax :
+        jpi = ptab.shape[ix]
+    if ay :
+        jpj = ptab.shape[jy]
+
+    if nperio is None :
+        nperio = __guess_nperio__ (jpj, jpi, nperio)
+
+    if nperio not in NPERIO_VALID_RANGE :
+        raise AttributeError ( f'{nperio=} is not in the valid range {NPERIO_VALID_RANGE}' )
 
     return jpj, jpi, nperio
-        
-#@numba.jit(forceobj=True)
-def lbc (ptab, nperio=None, cd_type='T', psgn=1.0, nemo_4U_bug=False) :
-    '''
-    Set periodicity on input field
+
+def lbc (ptab, nperio=None, cd_type='T', psgn=1.0, nemo_4u_bug=False) :
+    '''Set periodicity on input field
+
     ptab      : Input array (works for rank 2 at least : ptab[...., lat, lon])
     nperio    : Type of periodicity
     cd_type   : Grid specification : T, U, V or F
     psgn      : For change of sign for vector components (1 for scalars, -1 for vector components)
-    
+
     See NEMO documentation for further details
     '''
-    jpj, jpi, nperio = lbc_init (ptab, nperio)
+    jpi, nperio = lbc_init (ptab, nperio)[1:]
+    ax = __find_axis__ (ptab, 'x')[0]
+    ay = __find_axis__ (ptab, 'y')[0]
     psgn   = ptab.dtype.type (psgn)
-    mmath = __mmath__ (ptab)
-    
-    if mmath == xr : ztab = ptab.values.copy ()
-    else           : ztab = ptab.copy ()
-        
-    #
-    #> East-West boundary conditions
-    # ------------------------------
-    if nperio in [1, 4, 6] :
+    mmath  = __mmath__ (ptab)
+
+    if mmath == xr :
+        ztab = ptab.values.copy ()
+    else           :
+        ztab = ptab.copy ()
+
+    if ax :
+        #
+        #> East-West boundary conditions
+        # ------------------------------
+        if nperio in [1, 4, 6] :
         # ... cyclic
-        ztab [..., :,  0] = ztab [..., :, -2]
-        ztab [..., :, -1] = ztab [..., :,  1]
-    #
-    #> North-South boundary conditions
-    # --------------------------------
-    if nperio in [3, 4] :  # North fold T-point pivot
-        if cd_type in [ 'T', 'W' ] : # T-, W-point
-            ztab [..., -1, 1:       ] = psgn * ztab [..., -3, -1:0:-1      ]
-            ztab [..., -1, 0        ] = psgn * ztab [..., -3, 2            ]
-            ztab [..., -2, jpi//2:  ] = psgn * ztab [..., -2, jpi//2:0:-1  ]
-                
-        if cd_type == 'U' :
-            ztab [..., -1, 0:-1     ] = psgn * ztab [..., -3, -1:0:-1      ]       
-            ztab [..., -1,  0       ] = psgn * ztab [..., -3,  1           ]
-            ztab [..., -1, -1       ] = psgn * ztab [..., -3, -2           ]
-                
-            if nemo_4U_bug :
-                ztab [..., -2, jpi//2+1:-1] = psgn * ztab [..., -2, jpi//2-2:0:-1]
-                ztab [..., -2, jpi//2-1   ] = psgn * ztab [..., -2, jpi//2       ]
-            else :
-                ztab [..., -2, jpi//2-1:-1] = psgn * ztab [..., -2, jpi//2:0:-1]
-                
-        if cd_type == 'V' : 
-            ztab [..., -2, 1:       ] = psgn * ztab [..., -3, jpi-1:0:-1   ]
-            ztab [..., -1, 1:       ] = psgn * ztab [..., -4, -1:0:-1      ]   
-            ztab [..., -1, 0        ] = psgn * ztab [..., -4, 2            ]
-                
-        if cd_type == 'F' :
-            ztab [..., -2, 0:-1     ] = psgn * ztab [..., -3, -1:0:-1      ]
-            ztab [..., -1, 0:-1     ] = psgn * ztab [..., -4, -1:0:-1      ]
-            ztab [..., -1,  0       ] = psgn * ztab [..., -4,  1           ]
-            ztab [..., -1, -1       ] = psgn * ztab [..., -4, -2           ]
-
-    if nperio in [4.2] :  # North fold T-point pivot
-        if cd_type in [ 'T', 'W' ] : # T-, W-point
-            ztab [..., -1, jpi//2:  ] = psgn * ztab [..., -1, jpi//2:0:-1  ]
-                
-        if cd_type == 'U' :
-            ztab [..., -1, jpi//2-1:-1] = psgn * ztab [..., -1, jpi//2:0:-1]
-                
-        if cd_type == 'V' : 
-            ztab [..., -1, 1:       ] = psgn * ztab [..., -2, jpi-1:0:-1   ]
-                
-        if cd_type == 'F' :
-            ztab [..., -1, 0:-1     ] = psgn * ztab [..., -2, -1:0:-1      ]
-
-    if nperio in [5, 6] :            #  North fold F-point pivot  
-        if cd_type in ['T', 'W']  :
-            ztab [..., -1, 0:       ] = psgn * ztab [..., -2, -1::-1       ]
-                
-        if cd_type == 'U' :
-            ztab [..., -1, 0:-1     ] = psgn * ztab [..., -2, -2::-1       ]       
-            ztab [..., -1, -1       ] = psgn * ztab [..., -2, 0            ] # Bug ?
-                
-        if cd_type == 'V' :
-            ztab [..., -1, 0:       ] = psgn * ztab [..., -3, -1::-1       ]
-            ztab [..., -2, jpi//2:  ] = psgn * ztab [..., -2, jpi//2-1::-1 ]
-                
-        if cd_type == 'F' :
-            ztab [..., -1, 0:-1     ] = psgn * ztab [..., -3, -2::-1       ]
-            ztab [..., -1, -1       ] = psgn * ztab [..., -3, 0            ]
-            ztab [..., -2, jpi//2:-1] = psgn * ztab [..., -2, jpi//2-2::-1 ]
-
-    #
-    #> East-West boundary conditions
-    # ------------------------------
-    if nperio in [1, 4, 6] :
-        # ... cyclic
-        ztab [..., :,  0] = ztab [..., :, -2]
-        ztab [..., :, -1] = ztab [..., :,  1]
+            ztab [...,  0] = ztab [..., -2]
+            ztab [..., -1] = ztab [...,  1]
+
+        if ay :
+            #
+            #> North-South boundary conditions
+            # --------------------------------
+            if nperio in [3, 4] :  # North fold T-point pivot
+                if cd_type in [ 'T', 'W' ] : # T-, W-point
+                    ztab [..., -1, 1:       ] = psgn * ztab [..., -3, -1:0:-1      ]
+                    ztab [..., -1, 0        ] = psgn * ztab [..., -3, 2            ]
+                    ztab [..., -2, jpi//2:  ] = psgn * ztab [..., -2, jpi//2:0:-1  ]
+
+                if cd_type == 'U' :
+                    ztab [..., -1, 0:-1     ] = psgn * ztab [..., -3, -1:0:-1      ]
+                    ztab [..., -1,  0       ] = psgn * ztab [..., -3,  1           ]
+                    ztab [..., -1, -1       ] = psgn * ztab [..., -3, -2           ]
+
+                    if nemo_4u_bug :
+                        ztab [..., -2, jpi//2+1:-1] = psgn * ztab [..., -2, jpi//2-2:0:-1]
+                        ztab [..., -2, jpi//2-1   ] = psgn * ztab [..., -2, jpi//2       ]
+                    else :
+                        ztab [..., -2, jpi//2-1:-1] = psgn * ztab [..., -2, jpi//2:0:-1]
+
+                if cd_type == 'V' :
+                    ztab [..., -2, 1:       ] = psgn * ztab [..., -3, jpi-1:0:-1   ]
+                    ztab [..., -1, 1:       ] = psgn * ztab [..., -4, -1:0:-1      ]
+                    ztab [..., -1, 0        ] = psgn * ztab [..., -4, 2            ]
+
+                if cd_type == 'F' :
+                    ztab [..., -2, 0:-1     ] = psgn * ztab [..., -3, -1:0:-1      ]
+                    ztab [..., -1, 0:-1     ] = psgn * ztab [..., -4, -1:0:-1      ]
+                    ztab [..., -1,  0       ] = psgn * ztab [..., -4,  1           ]
+                    ztab [..., -1, -1       ] = psgn * ztab [..., -4, -2           ]
+
+            if nperio in [4.2] :  # North fold T-point pivot
+                if cd_type in [ 'T', 'W' ] : # T-, W-point
+                    ztab [..., -1, jpi//2:  ] = psgn * ztab [..., -1, jpi//2:0:-1  ]
+
+                if cd_type == 'U' :
+                    ztab [..., -1, jpi//2-1:-1] = psgn * ztab [..., -1, jpi//2:0:-1]
+
+                if cd_type == 'V' :
+                    ztab [..., -1, 1:       ] = psgn * ztab [..., -2, jpi-1:0:-1   ]
+
+                if cd_type == 'F' :
+                    ztab [..., -1, 0:-1     ] = psgn * ztab [..., -2, -1:0:-1      ]
+
+            if nperio in [5, 6] :            #  North fold F-point pivot
+                if cd_type in ['T', 'W']  :
+                    ztab [..., -1, 0:       ] = psgn * ztab [..., -2, -1::-1       ]
+
+                if cd_type == 'U' :
+                    ztab [..., -1, 0:-1     ] = psgn * ztab [..., -2, -2::-1       ]
+                    ztab [..., -1, -1       ] = psgn * ztab [..., -2, 0            ] # Bug ?
+
+                if cd_type == 'V' :
+                    ztab [..., -1, 0:       ] = psgn * ztab [..., -3, -1::-1       ]
+                    ztab [..., -2, jpi//2:  ] = psgn * ztab [..., -2, jpi//2-1::-1 ]
+
+                if cd_type == 'F' :
+                    ztab [..., -1, 0:-1     ] = psgn * ztab [..., -3, -2::-1       ]
+                    ztab [..., -1, -1       ] = psgn * ztab [..., -3, 0            ]
+                    ztab [..., -2, jpi//2:-1] = psgn * ztab [..., -2, jpi//2-2::-1 ]
+
+            #
+            #> East-West boundary conditions
+            # ------------------------------
+            if nperio in [1, 4, 6] :
+                # ... cyclic
+                ztab [...,  0] = ztab [..., -2]
+                ztab [..., -1] = ztab [...,  1]
 
     if mmath == xr :
-        ztab = xr.DataArray ( ztab, dims=ptab.dims, coords=ptab.coords)
+        ztab = xr.DataArray ( ztab, dims=ptab.dims, coords=ptab.coords )
         ztab.attrs = ptab.attrs
-        
+
     return ztab
 
-#@numba.jit(forceobj=True)
 def lbc_mask (ptab, nperio=None, cd_type='T', sval=np.nan) :
-    #
-    '''
-    Mask fields on duplicated points
+    '''Mask fields on duplicated points
+
     ptab      : Input array. Rank 2 at least : ptab [...., lat, lon]
     nperio    : Type of periodicity
     cd_type   : Grid specification : T, U, V or F
-    
+
     See NEMO documentation for further details
     '''
-    jpj, jpi, nperio = lbc_init (ptab, nperio)
+    jpi, nperio = lbc_init (ptab, nperio)[1:]
+    ax = __find_axis__ (ptab, 'x')[0]
+    ay = __find_axis__ (ptab, 'y')[0]
     ztab = ptab.copy ()
 
-    #
-    #> East-West boundary conditions
-    # ------------------------------
-    if nperio in [1, 4, 6] :
+    if ax :
+        #
+        #> East-West boundary conditions
+        # ------------------------------
+        if nperio in [1, 4, 6] :
         # ... cyclic
-        ztab [..., :,  0] = sval
-        ztab [..., :, -1] = sval
-
-    #
-    #> South (in which nperio cases ?)
-    # --------------------------------
-    if nperio in [1, 3, 4, 5, 6] :
-        ztab [..., 0, :] = sval
-        
-    #
-    #> North-South boundary conditions
-    # --------------------------------
-    if nperio in [3, 4] :  # North fold T-point pivot
-        if cd_type in [ 'T', 'W' ] : # T-, W-point
-            ztab [..., -1,  :         ] = sval
-            ztab [..., -2, :jpi//2  ] = sval
-                
-        if cd_type == 'U' :
-            ztab [..., -1,  :         ] = sval  
-            ztab [..., -2, jpi//2+1:  ] = sval
-                
-        if cd_type == 'V' :
-            ztab [..., -2, :       ] = sval
-            ztab [..., -1, :       ] = sval   
-                
-        if cd_type == 'F' :
-            ztab [..., -2, :       ] = sval
-            ztab [..., -1, :       ] = sval
-
-    if nperio in [4.2] :  # North fold T-point pivot
-        if cd_type in [ 'T', 'W' ] : # T-, W-point
-            ztab [..., -1, jpi//2  :  ] = sval
-                
-        if cd_type == 'U' :
-            ztab [..., -1, jpi//2-1:-1] = sval
-                
-        if cd_type == 'V' : 
-            ztab [..., -1, 1:       ] = sval
-                
-        if cd_type == 'F' :
-            ztab [..., -1, 0:-1     ] = sval
-    
-    if nperio in [5, 6] :            #  North fold F-point pivot
-        if cd_type in ['T', 'W']  :
-            ztab [..., -1, 0:       ] = sval
-                
-        if cd_type == 'U' :
-            ztab [..., -1, 0:-1     ] = sval       
-            ztab [..., -1, -1       ] = sval
-             
-        if cd_type == 'V' :
-            ztab [..., -1, 0:       ] = sval
-            ztab [..., -2, jpi//2:  ] = sval
-                             
-        if cd_type == 'F' :
-            ztab [..., -1, 0:-1       ] = sval
-            ztab [..., -1, -1         ] = sval
-            ztab [..., -2, jpi//2+1:-1] = sval
+            ztab [...,  0] = sval
+            ztab [..., -1] = sval
+
+        if ay :
+            #
+            #> South (in which nperio cases ?)
+            # --------------------------------
+            if nperio in [1, 3, 4, 5, 6] :
+                ztab [..., 0, :] = sval
+
+            #
+            #> North-South boundary conditions
+            # --------------------------------
+            if nperio in [3, 4] :  # North fold T-point pivot
+                if cd_type in [ 'T', 'W' ] : # T-, W-point
+                    ztab [..., -1,  :         ] = sval
+                    ztab [..., -2, :jpi//2  ] = sval
+
+                if cd_type == 'U' :
+                    ztab [..., -1,  :         ] = sval
+                    ztab [..., -2, jpi//2+1:  ] = sval
+
+                if cd_type == 'V' :
+                    ztab [..., -2, :       ] = sval
+                    ztab [..., -1, :       ] = sval
+
+                if cd_type == 'F' :
+                    ztab [..., -2, :       ] = sval
+                    ztab [..., -1, :       ] = sval
+
+            if nperio in [4.2] :  # North fold T-point pivot
+                if cd_type in [ 'T', 'W' ] : # T-, W-point
+                    ztab [..., -1, jpi//2  :  ] = sval
+
+                if cd_type == 'U' :
+                    ztab [..., -1, jpi//2-1:-1] = sval
+
+                if cd_type == 'V' :
+                    ztab [..., -1, 1:       ] = sval
+
+                if cd_type == 'F' :
+                    ztab [..., -1, 0:-1     ] = sval
+
+            if nperio in [5, 6] :            #  North fold F-point pivot
+                if cd_type in ['T', 'W']  :
+                    ztab [..., -1, 0:       ] = sval
+
+                if cd_type == 'U' :
+                    ztab [..., -1, 0:-1     ] = sval
+                    ztab [..., -1, -1       ] = sval
+
+                if cd_type == 'V' :
+                    ztab [..., -1, 0:       ] = sval
+                    ztab [..., -2, jpi//2:  ] = sval
+
+                if cd_type == 'F' :
+                    ztab [..., -1, 0:-1       ] = sval
+                    ztab [..., -1, -1         ] = sval
+                    ztab [..., -2, jpi//2+1:-1] = sval
 
     return ztab
 
-#@numba.jit(forceobj=True)
 def lbc_plot (ptab, nperio=None, cd_type='T', psgn=1.0, sval=np.nan) :
-    '''
-    Set periodicity on input field, adapted for plotting for any cartopy projection
+    '''Set periodicity on input field, for plotting for any cartopy projection
+
+      Points at the north fold are masked
+      Points for zonal periodicity are kept
     ptab      : Input array. Rank 2 at least : ptab[...., lat, lon]
     nperio    : Type of periodicity
     cd_type   : Grid specification : T, U, V or F
-    psgn      : For change of sign for vector components (1 for scalars, -1 for vector components)
-    
+    psgn      : For change of sign for vector components
+           (1 for scalars, -1 for vector components)
+
     See NEMO documentation for further details
     '''
-
-    jpj, jpi, nperio = lbc_init (ptab, nperio)
+    jpi, nperio = lbc_init (ptab, nperio)[1:]
+    ax = __find_axis__ (ptab, 'x')[0]
+    ay = __find_axis__ (ptab, 'y')[0]
     psgn   = ptab.dtype.type (psgn)
     ztab   = ptab.copy ()
-    #
-    #> East-West boundary conditions
-    # ------------------------------
-    if nperio in [1, 4, 6] :
-        # ... cyclic
-        ztab [..., :,  0] = ztab [..., :, -2]
-        ztab [..., :, -1] = ztab [..., :,  1]
-
-    #> Masks south
-    # ------------
-    if nperio in [4, 6] : ztab [..., 0, : ] = sval
-        
-    #
-    #> North-South boundary conditions
-    # --------------------------------
-    if nperio in [3, 4] :  # North fold T-point pivot
-        if cd_type in [ 'T', 'W' ] : # T-, W-point
-            ztab [..., -1,  :      ] = sval
-            #ztab [..., -2, jpi//2: ] = sval
-            ztab [..., -2, :jpi//2 ] = sval # Give better plots than above
-        if cd_type == 'U' :
-            ztab [..., -1, : ] = sval
-
-        if cd_type == 'V' : 
-            ztab [..., -2, : ] = sval
-            ztab [..., -1, : ] = sval
-            
-        if cd_type == 'F' :
-            ztab [..., -2, : ] = sval
-            ztab [..., -1, : ] = sval
-
-    if nperio in [4.2] :  # North fold T-point pivot
-        if cd_type in [ 'T', 'W' ] : # T-, W-point
-            ztab [..., -1, jpi//2:  ] = sval
-                
-        if cd_type == 'U' :
-            ztab [..., -1, jpi//2-1:-1] = sval
-                
-        if cd_type == 'V' : 
-            ztab [..., -1, 1:       ] = sval
-                
-        if cd_type == 'F' :
-            ztab [..., -1, 0:-1     ] = sval
-      
-    if nperio in [5, 6] :            #  North fold F-point pivot  
-        if cd_type in ['T', 'W']  :
-            ztab [..., -1, : ] = sval
-                
-        if cd_type == 'U' :
-            ztab [..., -1, : ] = sval      
-             
-        if cd_type == 'V' :
-            ztab [..., -1, :        ] = sval
-            ztab [..., -2, jpi//2:  ] = sval
-                             
-        if cd_type == 'F' :
-            ztab [..., -1, :          ] = sval
-            ztab [..., -2, jpi//2+1:-1] = sval
+
+    if ax :
+        #
+        #> East-West boundary conditions
+        # ------------------------------
+        if nperio in [1, 4, 6] :
+            # ... cyclic
+            ztab [..., :,  0] = ztab [..., :, -2]
+            ztab [..., :, -1] = ztab [..., :,  1]
+
+        if ay :
+            #> Masks south
+            # ------------
+            if nperio in [4, 6] :
+                ztab [..., 0, : ] = sval
+
+            #
+            #> North-South boundary conditions
+            # --------------------------------
+            if nperio in [3, 4] :  # North fold T-point pivot
+                if cd_type in [ 'T', 'W' ] : # T-, W-point
+                    ztab [..., -1,  :      ] = sval
+                    #ztab [..., -2, jpi//2: ] = sval
+                    ztab [..., -2, :jpi//2 ] = sval # Give better plots than above
+                if cd_type == 'U' :
+                    ztab [..., -1, : ] = sval
+
+                if cd_type == 'V' :
+                    ztab [..., -2, : ] = sval
+                    ztab [..., -1, : ] = sval
+
+                if cd_type == 'F' :
+                    ztab [..., -2, : ] = sval
+                    ztab [..., -1, : ] = sval
+
+            if nperio in [4.2] :  # North fold T-point pivot
+                if cd_type in [ 'T', 'W' ] : # T-, W-point
+                    ztab [..., -1, jpi//2:  ] = sval
+
+                if cd_type == 'U' :
+                    ztab [..., -1, jpi//2-1:-1] = sval
+
+                if cd_type == 'V' :
+                    ztab [..., -1, 1:       ] = sval
+
+                if cd_type == 'F' :
+                    ztab [..., -1, 0:-1     ] = sval
+
+            if nperio in [5, 6] :            #  North fold F-point pivot
+                if cd_type in ['T', 'W']  :
+                    ztab [..., -1, : ] = sval
+
+                if cd_type == 'U' :
+                    ztab [..., -1, : ] = sval
+
+                if cd_type == 'V' :
+                    ztab [..., -1, :        ] = sval
+                    ztab [..., -2, jpi//2:  ] = sval
+
+                if cd_type == 'F' :
+                    ztab [..., -1, :          ] = sval
+                    ztab [..., -2, jpi//2+1:-1] = sval
 
     return ztab
 
-#@numba.jit(forceobj=True)
-def lbc_add (ptab, nperio=None, cd_type=None, psgn=1, sval=None) :
-    '''
-    Handle NEMO domain changes between NEMO 4.0 to NEMO 4.2
-      Peridodicity halo has been removed
+def lbc_add (ptab, nperio=None, cd_type=None, psgn=1) :
+    '''Handles NEMO domain changes between NEMO 4.0 to NEMO 4.2
+
+    Periodicity and north fold halos has been removed in NEMO 4.2
     This routine adds the halos if needed
 
-    ptab      : Input array (works 
+    ptab      : Input array (works
       rank 2 at least : ptab[...., lat, lon]
     nperio    : Type of periodicity
- 
+
     See NEMO documentation for further details
     '''
-    mmath = __mmath__ (ptab) 
-    jpj, jpi, nperio = lbc_init (ptab, nperio)
+    mmath = __mmath__ (ptab)
+    nperio = lbc_init (ptab, nperio)[-1]
+    lshape = get_shape (ptab)
+    ix = __find_axis__ (ptab, 'x')[-1]
+    jy = __find_axis__ (ptab, 'y')[-1]
 
     t_shape = np.array (ptab.shape)
 
-    if nperio == 4.2 or nperio == 6.2 :
-      
-        ext_shape = t_shape
-        ext_shape[-1] = ext_shape[-1] + 2
-        ext_shape[-2] = ext_shape[-2] + 1
+    if nperio in [4.2, 6.2] :
+
+        ext_shape = t_shape.copy()
+        if 'X' in lshape :
+            ext_shape[ix] = ext_shape[ix] + 2
+        if 'Y' in lshape :
+            ext_shape[jy] = ext_shape[jy] + 1
 
         if mmath == xr :
-            ptab_ext = xr.DataArray (np.zeros (ext_shape), dims=ptab.dims) 
-            ptab_ext.values[..., :-1, 1:-1] = ptab.values.copy ()
+            ptab_ext = xr.DataArray (np.zeros (ext_shape), dims=ptab.dims)
+            if 'X' in lshape and 'Y' in lshape :
+                ptab_ext.values[..., :-1, 1:-1] = ptab.values.copy ()
+            else :
+                if 'X' in lshape     :
+                    ptab_ext.values[...,      1:-1] = ptab.values.copy ()
+                if 'Y' in lshape     :
+                    ptab_ext.values[..., :-1      ] = ptab.values.copy ()
         else           :
             ptab_ext =               np.zeros (ext_shape)
-            ptab_ext[..., :-1, 1:-1] = ptab.copy ()
-            
-        #if sval != None :  ptab_ext[..., 0, :] = sval
-        
-        if nperio == 4.2 : ptab_ext = lbc (ptab_ext, nperio=4, cd_type=cd_type, psgn=psgn)
-        if nperio == 6.2 : ptab_ext = lbc (ptab_ext, nperio=6, cd_type=cd_type, psgn=psgn)
-             
+            if 'X' in lshape and 'Y' in lshape :
+                ptab_ext       [..., :-1, 1:-1] = ptab.copy ()
+            else :
+                if 'X' in lshape     :
+                    ptab_ext       [...,      1:-1] = ptab.copy ()
+                if 'Y' in lshape     :
+                    ptab_ext       [..., :-1      ] = ptab.copy ()
+
+        if nperio == 4.2 :
+            ptab_ext = lbc (ptab_ext, nperio=4, cd_type=cd_type, psgn=psgn)
+        if nperio == 6.2 :
+            ptab_ext = lbc (ptab_ext, nperio=6, cd_type=cd_type, psgn=psgn)
+
         if mmath == xr :
             ptab_ext.attrs = ptab.attrs
+            az = __find_axis__ (ptab, 'z')[0]
+            at = __find_axis__ (ptab, 't')[0]
+            if az :
+                ptab_ext = ptab_ext.assign_coords ( {az:ptab.coords[az]} )
+            if at :
+                ptab_ext = ptab_ext.assign_coords ( {at:ptab.coords[at]} )
 
     else : ptab_ext = lbc (ptab, nperio=nperio, cd_type=cd_type, psgn=psgn)
-        
+
     return ptab_ext
 
 def lbc_del (ptab, nperio=None, cd_type='T', psgn=1) :
-    '''
-    Handle NEMO domain changes between NEMO 4.0 to NEMO 4.2
-      Periodicity halo has been removed
+    '''Handles NEMO domain changes between NEMO 4.0 to NEMO 4.2
+
+    Periodicity and north fold halos has been removed in NEMO 4.2
     This routine removes the halos if needed
 
-    ptab      : Input array (works 
+    ptab      : Input array (works
       rank 2 at least : ptab[...., lat, lon]
     nperio    : Type of periodicity
- 
+
     See NEMO documentation for further details
     '''
-
-    jpj, jpi, nperio = lbc_init (ptab, nperio)
-
-    if nperio == 4.2 or nperio == 6.2 :
-        return lbc (ptab[..., :-1, 1:-1], nperio=nperio, cd_type=cd_type, psgn=psgn)
-    else :
-        return ptab
-
-#@numba.jit(forceobj=True)
+    nperio = lbc_init (ptab, nperio)[-1]
+    #lshape = get_shape (ptab)
+    ax = __find_axis__ (ptab, 'x')[0]
+    ay = __find_axis__ (ptab, 'y')[0]
+
+    if nperio in [4.2, 6.2] :
+        if ax or ay :
+            if ax and ay :
+                ztab = lbc (ptab[..., :-1, 1:-1],
+                            nperio=nperio, cd_type=cd_type, psgn=psgn)
+            else :
+                if ax :
+                    ztab = lbc (ptab[...,      1:-1],
+                                nperio=nperio, cd_type=cd_type, psgn=psgn)
+                if ay :
+                    ztab = lbc (ptab[..., -1],
+                                nperio=nperio, cd_type=cd_type, psgn=psgn)
+        else :
+            ztab = ptab
+    else :
+        ztab = ptab
+
+    return ztab
+
 def lbc_index (jj, ii, jpj, jpi, nperio=None, cd_type='T') :
-    '''
-    For indexes of a NEMO point, give the corresponding point inside the util domain
+    '''For indexes of a NEMO point, give the corresponding point
+        inside the domain (i.e. not in the halo)
+
     jj, ii    : indexes
     jpi, jpi  : size of domain
     nperio    : type of periodicity
     cd_type   : grid specification : T, U, V or F
-    
+
     See NEMO documentation for further details
     '''
 
-    if nperio == None : nperio = __guessNperio__ (jpj, jpi, nperio)
-    
-    ## For the sake of simplicity, switch to the convention of original lbc Fortran routine from NEMO
-    ## : starts indexes at 1
-    jy = jj + 1 ; ix = ii + 1
+    if nperio is None :
+        nperio = __guess_nperio__ (jpj, jpi, nperio)
+
+    ## For the sake of simplicity, switch to the convention of original
+    ## lbc Fortran routine from NEMO : starts indexes at 1
+    jy = jj + 1
+    ix = ii + 1
 
     mmath = __mmath__ (jj)
-    if mmath == None : mmath=np
+    if mmath is None :
+        mmath=np
 
     #
@@ -896,5 +1198,5 @@
 
     #
-    def modIJ (cond, jy_new, ix_new) :
+    def mod_ij (cond, jy_new, ix_new) :
         jy_r = mmath.where (cond, jy_new, jy)
         ix_r = mmath.where (cond, ix_new, ix)
@@ -905,53 +1207,191 @@
     if nperio in [ 3 , 4 ]  :
         if cd_type in  [ 'T' , 'W' ] :
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix>=2       ), jpj-2, jpi-ix+2)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==1       ), jpj-1, 3       )   
-            (jy, ix) = modIJ (np.logical_and (jy==jpj-1, ix>=jpi//2+1), jy   , jpi-ix+2) 
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix>=2       ), jpj-2, jpi-ix+2)
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==1       ), jpj-1, 3       )
+            jy, ix = mod_ij (np.logical_and (jy==jpj-1, ix>=jpi//2+1),
+                                  jy , jpi-ix+2)
 
         if cd_type in [ 'U' ] :
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , np.logical_and (ix>=1, ix <= jpi-1)   ), jy   , jpi-ix+1)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==1  )                               , jpj-2, 2       )
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==jpi)                               , jpj-2, jpi-1   )
-            (jy, ix) = modIJ (np.logical_and (jy==jpj-1, np.logical_and (ix>=jpi//2, ix<=jpi-1)), jy   , jpi-ix+1)
-          
+            jy, ix = mod_ij (np.logical_and (
+                      jy==jpj  ,
+                      np.logical_and (ix>=1, ix <= jpi-1)   ),
+                                         jy   , jpi-ix+1)
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==1  ) , jpj-2, 2       )
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==jpi) , jpj-2, jpi-1   )
+            jy, ix = mod_ij (np.logical_and (jy==jpj-1,
+                            np.logical_and (ix>=jpi//2, ix<=jpi-1)), jy   , jpi-ix+1)
+
         if cd_type in [ 'V' ] :
-            (jy, ix) = modIJ (np.logical_and (jy==jpj-1, ix>=2  ), jpj-2, jpi-ix+2)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix>=2  ), jpj-3, jpi-ix+2)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==1  ), jpj-3,  3      )
-            
+            jy, ix = mod_ij (np.logical_and (jy==jpj-1, ix>=2  ), jpj-2, jpi-ix+2)
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix>=2  ), jpj-3, jpi-ix+2)
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==1  ), jpj-3,  3      )
+
         if cd_type in [ 'F' ] :
-            (jy, ix) = modIJ (np.logical_and (jy==jpj-1, ix<=jpi-1), jpj-2, jpi-ix+1)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix<=jpi-1), jpj-3, jpi-ix+1)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==1    ), jpj-3, 2       )
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==jpi  ), jpj-3, jpi-1   )
+            jy, ix = mod_ij (np.logical_and (jy==jpj-1, ix<=jpi-1), jpj-2, jpi-ix+1)
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix<=jpi-1), jpj-3, jpi-ix+1)
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==1    ), jpj-3, 2       )
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==jpi  ), jpj-3, jpi-1   )
 
     if nperio in [ 5 , 6 ] :
         if cd_type in [ 'T' , 'W' ] :                        # T-, W-point
-             (jy, ix) = modIJ (jy==jpj, jpj-1, jpi-ix+1)
- 
+            jy, ix = mod_ij (jy==jpj, jpj-1, jpi-ix+1)
+
         if cd_type in [ 'U' ] :                              # U-point
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix<=jpi-1   ), jpj-1, jpi-ix  )
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix==jpi     ), jpi-1, 1       )
-            
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix<=jpi-1   ), jpj-1, jpi-ix  )
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix==jpi     ), jpi-1, 1       )
+
         if cd_type in [ 'V' ] :    # V-point
-            (jy, ix) = modIJ (jy==jpj                                 , jy   , jpi-ix+1)
-            (jy, ix) = modIJ (np.logical_and (jy==jpj-1, ix>=jpi//2+1), jy   , jpi-ix+1)
-            
+            jy, ix = mod_ij (jy==jpj                                 , jy   , jpi-ix+1)
+            jy, ix = mod_ij (np.logical_and (jy==jpj-1, ix>=jpi//2+1), jy   , jpi-ix+1)
+
         if cd_type in [ 'F' ] :                              # F-point
-            (jy, ix) = modIJ (np.logical_and (jy==jpj  , ix<=jpi-1   ), jpj-2, jpi-ix  )
-            (jy, ix) = modIJ (np.logical_and (ix==jpj  , ix==jpi     ), jpj-2, 1       )
-            (jy, ix) = modIJ (np.logical_and (jy==jpj-1, ix>=jpi//2+1), jy   , jpi-ix  )
+            jy, ix = mod_ij (np.logical_and (jy==jpj  , ix<=jpi-1   ), jpj-2, jpi-ix  )
+            jy, ix = mod_ij (np.logical_and (ix==jpj  , ix==jpi     ), jpj-2, 1       )
+            jy, ix = mod_ij (np.logical_and (jy==jpj-1, ix>=jpi//2+1), jy   , jpi-ix  )
 
     ## Restore convention to Python/C : indexes start at 0
-    jy += -1 ; ix += -1
-
-    if isinstance (jj, int) : jy = jy.item ()
-    if isinstance (ii, int) : ix = ix.item ()
+    jy += -1
+    ix += -1
+
+    if isinstance (jj, int) :
+        jy = jy.item ()
+    if isinstance (ii, int) :
+        ix = ix.item ()
 
     return jy, ix
-    
-def geo2en (pxx, pyy, pzz, glam, gphi) : 
-    '''
-    Change vector from geocentric to east/north
+
+def find_ji (lat_data, lon_data, lat_grid, lon_grid, mask=1.0, verbose=False, out=None) :
+    '''
+    Description: seeks J,I indices of the grid point which is the closest
+       of a given point
+
+    Usage: go FindJI  <data latitude> <data longitude> <grid latitudes> <grid longitudes> [mask]
+    <grid latitudes><grid longitudes> are 2D fields on J/I (Y/X) dimensions
+    mask : if given, seek only non masked grid points (i.e with mask=1)
+
+    Example : findIJ (40, -20, nav_lat, nav_lon, mask=1.0)
+
+    Note : all longitudes and latitudes in degrees
+
+    Note : may work with 1D lon/lat (?)
+    '''
+    # Get grid dimensions
+    if len (lon_grid.shape) == 2 :
+        jpi = lon_grid.shape[-1]
+    else                         :
+        jpi = len(lon_grid)
+
+    #mmath = __mmath__ (lat_grid)
+
+    # Compute distance from the point to all grid points (in RADian)
+    arg      = ( np.sin (RAD*lat_data) * np.sin (RAD*lat_grid)
+               + np.cos (RAD*lat_data) * np.cos (RAD*lat_grid) *
+                 np.cos(RAD*(lon_data-lon_grid)) )
+    # Send masked points to 'infinite'
+    distance = np.arccos (arg) + 4.0*RPI*(1.0-mask)
+
+    # Truncates to alleviate some precision problem with some grids
+    prec = int (1E7)
+    distance = (distance*prec).astype(int) / prec
+
+    # Compute minimum of distance, and index of minimum
+    #
+    #distance_min = distance.min    ()
+    jimin        = int (distance.argmin ())
+
+    # Compute 2D indices (Python/C flavor : starting at 0)
+    jmin = jimin // jpi
+    imin = jimin - jmin*jpi
+
+    # Result
+    if verbose :
+        # Compute distance achieved
+        #mindist = distance [jmin, imin]
+
+        # Compute azimuth
+        dlon = lon_data-lon_grid[jmin,imin]
+        arg  = np.sin (RAD*dlon) / (
+                  np.cos(RAD*lat_data)*np.tan(RAD*lat_grid[jmin,imin])
+                - np.sin(RAD*lat_data)*np.cos(RAD*dlon))
+        azimuth = DAR*np.arctan (arg)
+        print ( f'I={imin:d} J={jmin:d} - Data:{lat_data:5.1f}Â°N {lon_data:5.1f}Â°E' \
+            +   f'- Grid:{lat_grid[jmin,imin]:4.1f}Â°N '   \
+            +   f'{lon_grid[jmin,imin]:4.1f}Â°E - Dist: {RA*distance[jmin,imin]:6.1f}km' \
+            +   f' {DAR*distance[jmin,imin]:5.2f}Â° ' \
+            +   f'- Azimuth: {RAD*azimuth:3.2f}RAD - {azimuth:5.1f}Â°' )
+
+    if   out=='dict'                     :
+        return {'x':imin, 'y':jmin}
+    elif out in ['array', 'numpy', 'np'] :
+        return np.array ( [jmin, imin] )
+    elif out in ['xarray', 'xr']         :
+        return xr.DataArray ( [jmin, imin] )
+    elif out=='list'                     :
+        return [jmin, imin]
+    elif out=='tuple'                    :
+        return jmin, imin
+    else                                 :
+        return jmin, imin
+
+def curl (tx, ty, e1f, e2f, nperio=None) :
+    '''Returns curl of a vector field
+    '''
+    ax = __find_axis__ (tx, 'x')[0]
+    ay = __find_axis__ (ty, 'y')[0]
+
+    tx_0  = lbc_add (tx , nperio=nperio, cd_type='U', psgn=-1)
+    ty_0  = lbc_add (ty , nperio=nperio, cd_type='V', psgn=-1)
+    e1f_0 = lbc_add (e1f, nperio=nperio, cd_type='U', psgn=-1)
+    e2f_0 = lbc_add (e2f, nperio=nperio, cd_type='V', psgn=-1)
+
+    tx_1  = tx_0.roll ( {ay:-1} )
+    ty_1  = ty_0.roll ( {ax:-1} )
+    tx_1  = lbc (tx_1, nperio=nperio, cd_type='U', psgn=-1)
+    ty_1  = lbc (ty_1, nperio=nperio, cd_type='V', psgn=-1)
+
+    zcurl = (ty_1 - ty_0)/e1f_0 - (tx_1 - tx_0)/e2f_0
+
+    mask = np.logical_or (
+             np.logical_or ( np.isnan(tx_0), np.isnan(tx_1)),
+             np.logical_or ( np.isnan(ty_0), np.isnan(ty_1)) )
+
+    zcurl = zcurl.where (np.logical_not (mask), np.nan)
+
+    zcurl = lbc_del (zcurl, nperio=nperio, cd_type='F', psgn=1)
+    zcurl = lbc (zcurl, nperio=nperio, cd_type='F', psgn=1)
+
+    return zcurl
+
+def div (ux, uy, e1t, e2t, nperio=None) :
+    '''Returns divergence of a vector field
+    '''
+    ax = __find_axis__ (ux, 'x')[0]
+    ay = __find_axis__ (ux, 'y')[0]
+
+    ux_0  = lbc_add (ux , nperio=nperio, cd_type='U', psgn=-1)
+    uy_0  = lbc_add (uy , nperio=nperio, cd_type='V', psgn=-1)
+    e1t_0 = lbc_add (e1t, nperio=nperio, cd_type='U', psgn=-1)
+    e2t_0 = lbc_add (e2t, nperio=nperio, cd_type='V', psgn=-1)
+
+    ux_1 = ux_0.roll ( {ay:1} )
+    uy_1 = uy_0.roll ( {ax:1} )
+    ux_1 = lbc (ux_1, nperio=nperio, cd_type='U', psgn=-1)
+    uy_1 = lbc (uy_1, nperio=nperio, cd_type='V', psgn=-1)
+
+    zdiv = (ux_0 - ux_1)/e2t_0 + (uy_0 - uy_1)/e1t_0
+
+    mask = np.logical_or (
+             np.logical_or ( np.isnan(ux_0), np.isnan(ux_1)),
+             np.logical_or ( np.isnan(uy_0), np.isnan(uy_1)) )
+
+    zdiv = zdiv.where (np.logical_not (mask), np.nan)
+
+    zdiv = lbc_del (zdiv, nperio=nperio, cd_type='T', psgn=1)
+    zdiv = lbc (zdiv, nperio=nperio, cd_type='T', psgn=1)
+
+    return zdiv
+
+def geo2en (pxx, pyy, pzz, glam, gphi) :
+    '''Change vector from geocentric to east/north
 
     Inputs :
@@ -960,9 +1400,9 @@
     '''
 
-    gsinlon = np.sin (rad * glam)
-    gcoslon = np.cos (rad * glam)
-    gsinlat = np.sin (rad * gphi)
-    gcoslat = np.cos (rad * gphi)
-          
+    gsinlon = np.sin (RAD * glam)
+    gcoslon = np.cos (RAD * glam)
+    gsinlat = np.sin (RAD * gphi)
+    gcoslat = np.cos (RAD * gphi)
+
     pte = - pxx * gsinlon            + pyy * gcoslon
     ptn = - pxx * gcoslon * gsinlat  - pyy * gsinlon * gsinlat + pzz * gcoslat
@@ -971,88 +1411,243 @@
 
 def en2geo (pte, ptn, glam, gphi) :
-    '''
-    Change vector from east/north to geocentric
-
-    Inputs : 
+    '''Change vector from east/north to geocentric
+
+    Inputs :
         pte, ptn   : eastward/northward components
         glam, gphi : longitude and latitude of the points
     '''
-    
-    gsinlon = np.sin (rad * glam)
-    gcoslon = np.cos (rad * glam)
-    gsinlat = np.sin (rad * gphi)
-    gcoslat = np.cos (rad * gphi)
+
+    gsinlon = np.sin (RAD * glam)
+    gcoslon = np.cos (RAD * glam)
+    gsinlat = np.sin (RAD * gphi)
+    gcoslat = np.cos (RAD * gphi)
 
     pxx = - pte * gsinlon - ptn * gcoslon * gsinlat
     pyy =   pte * gcoslon - ptn * gsinlon * gsinlat
     pzz =   ptn * gcoslat
-    
+
     return pxx, pyy, pzz
 
-def findJI (lat_data, lon_data, lat_grid, lon_grid, mask=1.0, verbose=False) :
-    '''
-    Description: seeks J,I indices of the grid point which is the closest of a given point 
-    Usage: go FindJI  <data latitude> <data longitude> <grid latitudes> <grid longitudes> [mask]
-    <longitude fields> <latitude field> are 2D fields on J/I (Y/X) dimensions
-    mask : if given, seek only non masked grid points (i.e with mask=1)
-    
-    Example : findIJ (40, -20, nav_lat, nav_lon, mask=1.0)
-
-    Note : all longitudes and latitudes in degrees
-        
-    Note : may work with 1D lon/lat (?)
-    '''
-    # Get grid dimensions
-    if len (lon_grid.shape) == 2 : (jpj, jpi) = lon_grid.shape
-    else                         : jpj = len(lat_grid) ; jpi=len(lon_grid)
-
-    mmath = __mmath__ (lat_grid)
-        
-    # Compute distance from the point to all grid points (in radian)
-    arg      = np.sin (rad*lat_data) * np.sin (rad*lat_grid) \
-             + np.cos (rad*lat_data) * np.cos (rad*lat_grid) * np.cos(rad*(lon_data-lon_grid))
-    distance = np.arccos (arg) + 4.0*rpi*(1.0-mask) # Send masked points to 'infinite' 
-
-    # Truncates to alleviate some precision problem with some grids
-    prec = int (1E7)
-    distance = (distance*prec).astype(int) / prec
-
-    # Compute minimum of distance, and index of minimum
-    #
-    distance_min = distance.min    ()
-    jimin        = int (distance.argmin ())
-    
-    # Compute 2D indices 
-    jmin = jimin // jpi ; imin = jimin - jmin*jpi
-
-    # Compute distance achieved
-    mindist = distance[jmin, imin]
-    
-    # Compute azimuth
-    dlon = lon_data-lon_grid[jmin,imin]
-    arg  = np.sin (rad*dlon) /  (np.cos(rad*lat_data)*np.tan(rad*lat_grid[jmin,imin]) - np.sin(rad*lat_data)*np.cos(rad*dlon))
-    azimuth = dar*np.arctan (arg)
-    
-    # Result
-    if verbose : 
-        print ('I={:d} J={:d} - Data:{:5.1f}Â°N {:5.1f}Â°E - Grid:{:4.1f}Â°N {:4.1f}Â°E - Dist: {:6.1f}km {:5.2f}Â° - Azimuth: {:3.2f}rad - {:5.1f}Â°'
-            .format (imin, jmin, lat_data, lon_data, lat_grid[jmin,imin], lon_grid[jmin,imin], ra*distance[jmin,imin], dar*distance[jmin,imin], rad*azimuth, azimuth))
-
-    return jmin, imin
-
-def clo_lon (lon, lon0) :
-    '''Choose closest to lon0 longitude, adding or substacting 360Â° if needed'''
+
+def clo_lon (lon, lon0=0., rad=False, deg=True) :
+    '''Choose closest to lon0 longitude, adding/substacting 360Â°
+    if needed
+    '''
     mmath = __mmath__ (lon, np)
-        
-    clo_lon = lon
-    clo_lon = mmath.where (clo_lon > lon0 + 180., clo_lon-360., clo_lon)
-    clo_lon = mmath.where (clo_lon < lon0 - 180., clo_lon+360., clo_lon)
-    clo_lon = mmath.where (clo_lon > lon0 + 180., clo_lon-360., clo_lon)
-    clo_lon = mmath.where (clo_lon < lon0 - 180., clo_lon+360., clo_lon)
-    if clo_lon.shape == () : clo_lon = clo_lon.item ()
-    return clo_lon
-
-def angle_full (glamt, gphit, glamu, gphiu, glamv, gphiv, glamf, gphif, nperio=None) :
-    '''Compute sinus and cosinus of model line direction with respect to east'''
+    if rad :
+        lon_range = 2.*np.pi
+    if deg :
+        lon_range = 360.
+    c_lon = lon
+    c_lon = mmath.where (c_lon > lon0 + lon_range*0.5,
+                             c_lon-lon_range, clo_lon)
+    c_lon = mmath.where (c_lon < lon0 - lon_range*0.5,
+                             c_lon+lon_range, clo_lon)
+    c_lon = mmath.where (c_lon > lon0 + lon_range*0.5,
+                             c_lon-lon_range, clo_lon)
+    c_lon = mmath.where (c_lon < lon0 - lon_range*0.5,
+                             c_lon+lon_range, clo_lon)
+    if c_lon.shape == () :
+        c_lon = c_lon.item ()
+    if mmath == xr :
+        if lon.attrs :
+            c_lon.attrs.update ( lon.attrs )
+    return c_lon
+
+def index2depth (pk, gdept_0) :
+    '''From index (real, continuous), get depth
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpk = gdept_0.shape[0]
+    kk = xr.DataArray(pk)
+    k  = np.maximum (0, np.minimum (jpk-1, kk    ))
+    k0 = np.floor (k).astype (int)
+    k1 = np.maximum (0, np.minimum (jpk-1,  k0+1))
+    zz = k - k0
+    gz = (1.0-zz)*gdept_0[k0]+ zz*gdept_0[k1]
+    return gz.values
+
+def depth2index (pz, gdept_0) :
+    '''From depth, get index (real, continuous)
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpk  = gdept_0.shape[0]
+    if   isinstance (pz, xr.core.dataarray.DataArray ) :
+        zz   = xr.DataArray (pz.values, dims=('zz',))
+    elif isinstance (pz,  np.ndarray) :
+        zz   = xr.DataArray (pz.ravel(), dims=('zz',))
+    else :
+        zz   = xr.DataArray (np.array([pz]).ravel(), dims=('zz',))
+    zz   = np.minimum (gdept_0[-1], np.maximum (0, zz))
+
+    idk1 = np.minimum ( (gdept_0-zz), 0.).argmax (axis=0).astype(int)
+    idk1 = np.maximum (0, np.minimum (jpk-1,  idk1  ))
+    idk2 = np.maximum (0, np.minimum (jpk-1,  idk1-1))
+
+    zff = (zz - gdept_0[idk2])/(gdept_0[idk1]-gdept_0[idk2])
+    idk = zff*idk1 + (1.0-zff)*idk2
+    idk = xr.where ( np.isnan(idk), idk1, idk)
+    return idk.values
+
+def index2depth_panels (pk, gdept_0, depth0, fact) :
+    '''From  index (real, continuous), get depth, with bottom part compressed
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpk = gdept_0.shape[0]
+    kk = xr.DataArray (pk)
+    k  = np.maximum (0, np.minimum (jpk-1, kk    ))
+    k0 = np.floor (k).astype (int)
+    k1 = np.maximum (0, np.minimum (jpk-1,  k0+1))
+    zz = k - k0
+    gz = (1.0-zz)*gdept_0[k0]+ zz*gdept_0[k1]
+    gz = xr.where ( gz<depth0, gz, depth0 + (gz-depth0)*fact)
+    return gz.values
+
+def depth2index_panels (pz, gdept_0, depth0, fact) :
+    '''From  index (real, continuous), get depth, with bottom part compressed
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpk = gdept_0.shape[0]
+    if isinstance (pz, xr.core.dataarray.DataArray) :
+        zz   = xr.DataArray (pz.values , dims=('zz',))
+    elif isinstance (pz, np.ndarray) :
+        zz   = xr.DataArray (pz.ravel(), dims=('zz',))
+    else :
+        zz   = xr.DataArray (np.array([pz]).ravel(), dims=('zz',))
+    zz         = np.minimum (gdept_0[-1], np.maximum (0, zz))
+    gdept_comp = xr.where ( gdept_0>depth0,
+                                (gdept_0-depth0)*fact+depth0, gdept_0)
+    zz_comp    = xr.where ( zz     >depth0, (zz     -depth0)*fact+depth0,
+                                zz     )
+    zz_comp    = np.minimum (gdept_comp[-1], np.maximum (0, zz_comp))
+
+    idk1 = np.minimum ( (gdept_0-zz_comp), 0.).argmax (axis=0).astype(int)
+    idk1 = np.maximum (0, np.minimum (jpk-1,  idk1  ))
+    idk2 = np.maximum (0, np.minimum (jpk-1,  idk1-1))
+
+    zff = (zz_comp - gdept_0[idk2])/(gdept_0[idk1]-gdept_0[idk2])
+    idk = zff*idk1 + (1.0-zff)*idk2
+    idk = xr.where ( np.isnan(idk), idk1, idk)
+    return idk.values
+
+def depth2comp (pz, depth0, fact ) :
+    '''Form depth, get compressed depth, with bottom part compressed
+
+    Needed to use transforms in Matplotlib
+    '''
+    #print ('start depth2comp')
+    if isinstance (pz, xr.core.dataarray.DataArray) :
+        zz   = pz.values
+    elif isinstance(pz, list) :
+        zz = np.array (pz)
+    else :
+        zz   = pz
+    gz = np.where ( zz>depth0, (zz-depth0)*fact+depth0, zz)
+    #print ( f'depth2comp : {gz=}' )
+    if type (pz) in [int, float] :
+        return gz.item()
+    else :
+        return gz
+
+def comp2depth (pz, depth0, fact ) :
+    '''Form compressed depth, get depth, with bottom part compressed
+
+    Needed to use transforms in Matplotlib
+    '''
+    if isinstance (pz, xr.core.dataarray.DataArray) :
+        zz   = pz.values
+    elif isinstance (pz, list) :
+        zz = np.array (pz)
+    else :
+        zz   = pz
+    gz = np.where ( zz>depth0, (zz-depth0)/fact+depth0, zz)
+    if type (pz) in [int, float] :
+        gz = gz.item()
+
+    return gz
+
+def index2lon (pi, plon_1d) :
+    '''From index (real, continuous), get longitude
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpi = plon_1d.shape[0]
+    ii = xr.DataArray (pi)
+    i =  np.maximum (0, np.minimum (jpi-1, ii    ))
+    i0 = np.floor (i).astype (int)
+    i1 = np.maximum (0, np.minimum (jpi-1,  i0+1))
+    xx = i - i0
+    gx = (1.0-xx)*plon_1d[i0]+ xx*plon_1d[i1]
+    return gx.values
+
+def lon2index (px, plon_1d) :
+    '''From longitude, get index (real, continuous)
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpi  = plon_1d.shape[0]
+    if isinstance (px, xr.core.dataarray.DataArray) :
+        xx   = xr.DataArray (px.values , dims=('xx',))
+    elif isinstance (px, np.ndarray) :
+        xx   = xr.DataArray (px.ravel(), dims=('xx',))
+    else :
+        xx   = xr.DataArray (np.array([px]).ravel(), dims=('xx',))
+    xx   = xr.where ( xx>plon_1d.max(), xx-360.0, xx)
+    xx   = xr.where ( xx<plon_1d.min(), xx+360.0, xx)
+    xx   = np.minimum (plon_1d.max(), np.maximum(xx, plon_1d.min() ))
+    idi1 = np.minimum ( (plon_1d-xx), 0.).argmax (axis=0).astype(int)
+    idi1 = np.maximum (0, np.minimum (jpi-1,  idi1  ))
+    idi2 = np.maximum (0, np.minimum (jpi-1,  idi1-1))
+
+    zff = (xx - plon_1d[idi2])/(plon_1d[idi1]-plon_1d[idi2])
+    idi = zff*idi1 + (1.0-zff)*idi2
+    idi = xr.where ( np.isnan(idi), idi1, idi)
+    return idi.values
+
+def index2lat (pj, plat_1d) :
+    '''From index (real, continuous), get latitude
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpj = plat_1d.shape[0]
+    jj  = xr.DataArray (pj)
+    j   = np.maximum (0, np.minimum (jpj-1, jj    ))
+    j0  = np.floor (j).astype (int)
+    j1  = np.maximum (0, np.minimum (jpj-1,  j0+1))
+    yy  = j - j0
+    gy  = (1.0-yy)*plat_1d[j0]+ yy*plat_1d[j1]
+    return gy.values
+
+def lat2index (py, plat_1d) :
+    '''From latitude, get index (real, continuous)
+
+    Needed to use transforms in Matplotlib
+    '''
+    jpj = plat_1d.shape[0]
+    if isinstance (py, xr.core.dataarray.DataArray) :
+        yy   = xr.DataArray (py.values , dims=('yy',))
+    elif isinstance (py, np.ndarray) :
+        yy   = xr.DataArray (py.ravel(), dims=('yy',))
+    else :
+        yy   = xr.DataArray (np.array([py]).ravel(), dims=('yy',))
+    yy   = np.minimum (plat_1d.max(), np.minimum(yy, plat_1d.max() ))
+    idj1 = np.minimum ( (plat_1d-yy), 0.).argmax (axis=0).astype(int)
+    idj1 = np.maximum (0, np.minimum (jpj-1,  idj1  ))
+    idj2 = np.maximum (0, np.minimum (jpj-1,  idj1-1))
+
+    zff = (yy - plat_1d[idj2])/(plat_1d[idj1]-plat_1d[idj2])
+    idj = zff*idj1 + (1.0-zff)*idj2
+    idj = xr.where ( np.isnan(idj), idj1, idj)
+    return idj.values
+
+def angle_full (glamt, gphit, glamu, gphiu, glamv, gphiv,
+                glamf, gphif, nperio=None) :
+    '''Computes sinus and cosinus of model line direction with
+    respect to east
+    '''
     mmath = __mmath__ (glamt)
 
@@ -1065,34 +1660,34 @@
     zlamf = lbc_add (glamf, nperio, 'F', 1.)
     zphif = lbc_add (gphif, nperio, 'F', 1.)
-    
+
     # north pole direction & modulous (at T-point)
-    zxnpt = 0. - 2.0 * np.cos (rad*zlamt) * np.tan (rpi/4.0 - rad*zphit/2.0)
-    zynpt = 0. - 2.0 * np.sin (rad*zlamt) * np.tan (rpi/4.0 - rad*zphit/2.0)
+    zxnpt = 0. - 2.0 * np.cos (RAD*zlamt) * np.tan (RPI/4.0 - RAD*zphit/2.0)
+    zynpt = 0. - 2.0 * np.sin (RAD*zlamt) * np.tan (RPI/4.0 - RAD*zphit/2.0)
     znnpt = zxnpt*zxnpt + zynpt*zynpt
-    
+
     # north pole direction & modulous (at U-point)
-    zxnpu = 0. - 2.0 * np.cos (rad*zlamu) * np.tan (rpi/4.0 - rad*zphiu/2.0)
-    zynpu = 0. - 2.0 * np.sin (rad*zlamu) * np.tan (rpi/4.0 - rad*zphiu/2.0)
+    zxnpu = 0. - 2.0 * np.cos (RAD*zlamu) * np.tan (RPI/4.0 - RAD*zphiu/2.0)
+    zynpu = 0. - 2.0 * np.sin (RAD*zlamu) * np.tan (RPI/4.0 - RAD*zphiu/2.0)
     znnpu = zxnpu*zxnpu + zynpu*zynpu
-    
+
     # north pole direction & modulous (at V-point)
-    zxnpv = 0. - 2.0 * np.cos (rad*zlamv) * np.tan (rpi/4.0 - rad*zphiv/2.0)
-    zynpv = 0. - 2.0 * np.sin (rad*zlamv) * np.tan (rpi/4.0 - rad*zphiv/2.0)
+    zxnpv = 0. - 2.0 * np.cos (RAD*zlamv) * np.tan (RPI/4.0 - RAD*zphiv/2.0)
+    zynpv = 0. - 2.0 * np.sin (RAD*zlamv) * np.tan (RPI/4.0 - RAD*zphiv/2.0)
     znnpv = zxnpv*zxnpv + zynpv*zynpv
 
     # north pole direction & modulous (at F-point)
-    zxnpf = 0. - 2.0 * np.cos( rad*zlamf ) * np.tan ( rpi/4. - rad*zphif/2. )
-    zynpf = 0. - 2.0 * np.sin( rad*zlamf ) * np.tan ( rpi/4. - rad*zphif/2. )
+    zxnpf = 0. - 2.0 * np.cos( RAD*zlamf ) * np.tan ( RPI/4. - RAD*zphif/2. )
+    zynpf = 0. - 2.0 * np.sin( RAD*zlamf ) * np.tan ( RPI/4. - RAD*zphif/2. )
     znnpf = zxnpf*zxnpf + zynpf*zynpf
 
     # j-direction: v-point segment direction (around T-point)
-    zlam = zlamv  
+    zlam = zlamv
     zphi = zphiv
     zlan = np.roll ( zlamv, axis=-2, shift=1)  # glamv (ji,jj-1)
     zphh = np.roll ( zphiv, axis=-2, shift=1)  # gphiv (ji,jj-1)
-    zxvvt =  2.0 * np.cos ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2.0 * np.cos ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
-    zyvvt =  2.0 * np.sin ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2.0 * np.sin ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
+    zxvvt =  2.0 * np.cos ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2.0 * np.cos ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
+    zyvvt =  2.0 * np.sin ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2.0 * np.sin ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
     znvvt = np.sqrt ( znnpt * ( zxvvt*zxvvt + zyvvt*zyvvt )  )
 
@@ -1102,54 +1697,46 @@
     zlan = np.roll (zlamf, axis=-2, shift=1) # glamf (ji,jj-1)
     zphh = np.roll (zphif, axis=-2, shift=1) # gphif (ji,jj-1)
-    zxffu =  2.0 * np.cos ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2.0 * np.cos ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
-    zyffu =  2.0 * np.sin ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2.0 * np.sin ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
+    zxffu =  2.0 * np.cos ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2.0 * np.cos ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
+    zyffu =  2.0 * np.sin ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2.0 * np.sin ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
     znffu = np.sqrt ( znnpu * ( zxffu*zxffu + zyffu*zyffu )  )
 
     # i-direction: f-point segment direction (around v-point)
-    zlam = zlamf  
+    zlam = zlamf
     zphi = zphif
     zlan = np.roll (zlamf, axis=-1, shift=1) # glamf (ji-1,jj)
     zphh = np.roll (zphif, axis=-1, shift=1) # gphif (ji-1,jj)
-    zxffv =  2.0 * np.cos ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2.0 * np.cos ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
-    zyffv =  2.0 * np.sin ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2.0 * np.sin ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
+    zxffv =  2.0 * np.cos ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2.0 * np.cos ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
+    zyffv =  2.0 * np.sin ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2.0 * np.sin ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
     znffv = np.sqrt ( znnpv * ( zxffv*zxffv + zyffv*zyffv )  )
 
     # j-direction: u-point segment direction (around f-point)
-    zlam = np.roll (zlamu, axis=-2, shift=-1) # glamu (ji,jj+1) 
+    zlam = np.roll (zlamu, axis=-2, shift=-1) # glamu (ji,jj+1)
     zphi = np.roll (zphiu, axis=-2, shift=-1) # gphiu (ji,jj+1)
     zlan = zlamu
     zphh = zphiu
-    zxuuf =  2. * np.cos ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2. * np.cos ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
-    zyuuf =  2. * np.sin ( rad*zlam ) * np.tan ( rpi/4. - rad*zphi/2. )   \
-          -  2. * np.sin ( rad*zlan ) * np.tan ( rpi/4. - rad*zphh/2. )
+    zxuuf =  2. * np.cos ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2. * np.cos ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
+    zyuuf =  2. * np.sin ( RAD*zlam ) * np.tan ( RPI/4. - RAD*zphi/2. ) \
+          -  2. * np.sin ( RAD*zlan ) * np.tan ( RPI/4. - RAD*zphh/2. )
     znuuf = np.sqrt ( znnpf * ( zxuuf*zxuuf + zyuuf*zyuuf )  )
 
-    
+
     # cosinus and sinus using scalar and vectorial products
     gsint = ( zxnpt*zyvvt - zynpt*zxvvt ) / znvvt
     gcost = ( zxnpt*zxvvt + zynpt*zyvvt ) / znvvt
-    
+
     gsinu = ( zxnpu*zyffu - zynpu*zxffu ) / znffu
     gcosu = ( zxnpu*zxffu + zynpu*zyffu ) / znffu
-    
+
     gsinf = ( zxnpf*zyuuf - zynpf*zxuuf ) / znuuf
     gcosf = ( zxnpf*zxuuf + zynpf*zyuuf ) / znuuf
-    
+
     gsinv = ( zxnpv*zxffv + zynpv*zyffv ) / znffv
-    gcosv =-( zxnpv*zyffv - zynpv*zxffv ) / znffv  # (caution, rotation of 90 degres)
-    
-    #gsint = lbc (gsint, cd_type='T', nperio=nperio, psgn=-1.)
-    #gcost = lbc (gcost, cd_type='T', nperio=nperio, psgn=-1.)
-    #gsinu = lbc (gsinu, cd_type='U', nperio=nperio, psgn=-1.)
-    #gcosu = lbc (gcosu, cd_type='U', nperio=nperio, psgn=-1.)
-    #gsinv = lbc (gsinv, cd_type='V', nperio=nperio, psgn=-1.)
-    #gcosv = lbc (gcosv, cd_type='V', nperio=nperio, psgn=-1.)
-    #gsinf = lbc (gsinf, cd_type='F', nperio=nperio, psgn=-1.)
-    #gcosf = lbc (gcosf, cd_type='F', nperio=nperio, psgn=-1.)
+    # (caution, rotation of 90 degres)
+    gcosv =-( zxnpv*zyffv - zynpv*zxffv ) / znffv
 
     gsint = lbc_del (gsint, cd_type='T', nperio=nperio, psgn=-1.)
@@ -1175,13 +1762,15 @@
 
 def angle (glam, gphi, nperio, cd_type='T') :
-    '''Compute sinus and cosinus of model line direction with respect to east'''
+    '''Computes sinus and cosinus of model line direction with
+    respect to east
+    '''
     mmath = __mmath__ (glam)
 
     zlam = lbc_add (glam, nperio, cd_type, 1.)
     zphi = lbc_add (gphi, nperio, cd_type, 1.)
-    
+
     # north pole direction & modulous
-    zxnp = 0. - 2.0 * np.cos (rad*zlam) * np.tan (rpi/4.0 - rad*zphi/2.0)
-    zynp = 0. - 2.0 * np.sin (rad*zlam) * np.tan (rpi/4.0 - rad*zphi/2.0)
+    zxnp = 0. - 2.0 * np.cos (RAD*zlam) * np.tan (RPI/4.0 - RAD*zphi/2.0)
+    zynp = 0. - 2.0 * np.sin (RAD*zlam) * np.tan (RPI/4.0 - RAD*zphi/2.0)
     znnp = zxnp*zxnp + zynp*zynp
 
@@ -1191,11 +1780,11 @@
     zlan_s = np.roll (zlam, axis=-2, shift= 1) # glam [jj-1, ji]
     zphh_s = np.roll (zphi, axis=-2, shift= 1) # gphi [jj-1, ji]
-    
-    zxff = 2.0 * np.cos (rad*zlan_n) * np.tan (rpi/4.0 - rad*zphh_n/2.0) \
-        -  2.0 * np.cos (rad*zlan_s) * np.tan (rpi/4.0 - rad*zphh_s/2.0)
-    zyff = 2.0 * np.sin (rad*zlan_n) * np.tan (rpi/4.0 - rad*zphh_n/2.0) \
-        -  2.0 * np.sin (rad*zlan_s) * np.tan (rpi/4.0 - rad*zphh_s/2.0)
+
+    zxff = 2.0 * np.cos (RAD*zlan_n) * np.tan (RPI/4.0 - RAD*zphh_n/2.0) \
+        -  2.0 * np.cos (RAD*zlan_s) * np.tan (RPI/4.0 - RAD*zphh_s/2.0)
+    zyff = 2.0 * np.sin (RAD*zlan_n) * np.tan (RPI/4.0 - RAD*zphh_n/2.0) \
+        -  2.0 * np.sin (RAD*zlan_s) * np.tan (RPI/4.0 - RAD*zphh_s/2.0)
     znff = np.sqrt (znnp * (zxff*zxff + zyff*zyff) )
- 
+
     gsin = (zxnp*zyff - zynp*zxff) / znff
     gcos = (zxnp*zxff + zynp*zyff) / znff
@@ -1207,48 +1796,48 @@
         gsin = gsin.assign_coords ( glam.coords )
         gcos = gcos.assign_coords ( glam.coords )
-        
+
     return gsin, gcos
 
 def rot_en2ij ( u_e, v_n, gsin, gcos, nperio, cd_type ) :
-    '''
-    ** Purpose :   Rotate the Repere: Change vector componantes between
+    '''Rotates the Repere: Change vector componantes between
     geographic grid --> stretched coordinates grid.
-    All components are on the same grid (T, U, V or F) 
+
+    All components are on the same grid (T, U, V or F)
     '''
 
     u_i = + u_e * gcos + v_n * gsin
     v_j = - u_e * gsin + v_n * gcos
-    
+
     u_i = lbc (u_i, nperio=nperio, cd_type=cd_type, psgn=-1.0)
     v_j = lbc (v_j, nperio=nperio, cd_type=cd_type, psgn=-1.0)
-    
+
     return u_i, v_j
 
 def rot_ij2en ( u_i, v_j, gsin, gcos, nperio, cd_type='T' ) :
-    '''
-    ** Purpose :   Rotate the Repere: Change vector componantes from
+    '''Rotates the Repere: Change vector componantes from
     stretched coordinates grid --> geographic grid
-    All components are on the same grid (T, U, V or F) 
+
+    All components are on the same grid (T, U, V or F)
     '''
     u_e = + u_i * gcos - v_j * gsin
     v_n = + u_i * gsin + v_j * gcos
+
+    u_e = lbc (u_e, nperio=nperio, cd_type=cd_type, psgn=1.0)
+    v_n = lbc (v_n, nperio=nperio, cd_type=cd_type, psgn=1.0)
+
+    return u_e, v_n
+
+def rot_uv2en ( uo, vo, gsint, gcost, nperio, zdim=None ) :
+    '''Rotate the Repere: Change vector componantes from
+    stretched coordinates grid --> geographic grid
+
+    uo : velocity along i at the U grid point
+    vo : valocity along j at the V grid point
     
-    u_e = lbc (u_e, nperio=nperio, cd_type=cd_type, psgn= 1.0)
-    v_n = lbc (v_n, nperio=nperio, cd_type=cd_type, psgn= 1.0)
-    
-    return u_e, v_n
-
-def rot_uv2en ( uo, vo, gsint, gcost, nperio, zdim='deptht' ) :
-    '''
-    ** Purpose :   Rotate the Repere: Change vector componantes from
-    stretched coordinates grid --> geographic grid
-    uo is on the U grid point, vo is on the V grid point
-    east-north components on the T grid point   
-    '''
-    mmath = __mmath__ (uo)
-
-    ut = U2T (uo, nperio=nperio, psgn=-1.0, zdim=zdim)
-    vt = V2T (vo, nperio=nperio, psgn=-1.0, zdim=zdim)
-    
+    Returns east-north components on the T grid point
+    '''
+    ut = u2t (uo, nperio=nperio, psgn=-1.0, zdim=zdim)
+    vt = v2t (vo, nperio=nperio, psgn=-1.0, zdim=zdim)
+
     u_e = + ut * gcost - vt * gsint
     v_n = + ut * gsint + vt * gcost
@@ -1256,19 +1845,19 @@
     u_e = lbc (u_e, nperio=nperio, cd_type='T', psgn=1.0)
     v_n = lbc (v_n, nperio=nperio, cd_type='T', psgn=1.0)
+
+    return u_e, v_n
+
+def rot_uv2enf ( uo, vo, gsinf, gcosf, nperio, zdim=None ) :
+    '''Rotates the Repere: Change vector componantes from
+    stretched coordinates grid --> geographic grid
+
+    uo : velocity along i at the U grid point
+    vo : valocity along j at the V grid point
     
-    return u_e, v_n
-
-def rot_uv2enF ( uo, vo, gsinf, gcosf, nperio, zdim='deptht' ) :
-    '''
-    ** Purpose : Rotate the Repere: Change vector componantes from
-    stretched coordinates grid --> geographic grid
-    uo is on the U grid point, vo is on the V grid point
-    east-north components on the T grid point   
-    '''
-    mmath = __mmath__ (uo)
-
-    uf = U2F (uo, nperio=nperio, psgn=-1.0, zdim=zdim)
-    vf = V2F (vo, nperio=nperio, psgn=-1.0, zdim=zdim)
-    
+    Returns east-north components on the F grid point
+    '''
+    uf = u2f (uo, nperio=nperio, psgn=-1.0, zdim=zdim)
+    vf = v2f (vo, nperio=nperio, psgn=-1.0, zdim=zdim)
+
     u_e = + uf * gcosf - vf * gsinf
     v_n = + uf * gsinf + vf * gcosf
@@ -1276,207 +1865,263 @@
     u_e = lbc (u_e, nperio=nperio, cd_type='F', psgn= 1.0)
     v_n = lbc (v_n, nperio=nperio, cd_type='F', psgn= 1.0)
-    
+
     return u_e, v_n
 
-#@numba.jit(forceobj=True)
-def U2T (utab, nperio=None, psgn=-1.0, zdim='deptht', action='ave') :
-    '''Interpolate an array from U grid to T grid i-mean)'''
+def u2t (utab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
+    '''Interpolates an array from U grid to T grid (i-mean)
+    '''
     mmath = __mmath__ (utab)
     utab_0 = mmath.where ( np.isnan(utab), 0., utab)
-    lperio, aperio = lbc_diag (nperio)
+    #lperio, aperio = lbc_diag (nperio)
     utab_0 = lbc_add (utab_0, nperio=nperio, cd_type='U', psgn=psgn)
-    ix, ax = __findAxis__ (utab_0, 'x')
-    iz, az = __findAxis__ (utab_0, 'z')
-    if action == 'ave'  : ttab = 0.5 *      (utab_0 + np.roll (utab_0, axis=ix, shift=1))
-    if action == 'min'  : ttab = np.minimum (utab_0 , np.roll (utab_0, axis=ix, shift=1))
-    if action == 'max'  : ttab = np.maximum (utab_0 , np.roll (utab_0, axis=ix, shift=1))
-    if action == 'mult' : ttab =             utab_0 * np.roll (utab_0, axis=ix, shift=1)
-    ttab = lbc_del (ttab, nperio=nperio, cd_type='T', psgn=psgn)
-    
+    ax, ix = __find_axis__ (utab_0, 'x')
+    az     = __find_axis__ (utab_0, 'z')[0]
+
+    if ax :
+        if action == 'ave' :
+            ttab = 0.5 *      (utab_0 + np.roll (utab_0, axis=ix, shift=1))
+        if action == 'min' :
+            ttab = np.minimum (utab_0 , np.roll (utab_0, axis=ix, shift=1))
+        if action == 'max' :
+            ttab = np.maximum (utab_0 , np.roll (utab_0, axis=ix, shift=1))
+        if action == 'mult':
+            ttab =             utab_0 * np.roll (utab_0, axis=ix, shift=1)
+        ttab = lbc_del (ttab  , nperio=nperio, cd_type='T', psgn=psgn)
+    else :
+        ttab = lbc_del (utab_0, nperio=nperio, cd_type='T', psgn=psgn)
+
     if mmath == xr :
-        if ax != None :
+        if ax :
             ttab = ttab.assign_coords({ax:np.arange (ttab.shape[ix])+1.})
-        if zdim != None and iz != None  and az != 'olevel' : 
-            ttab = ttab.rename( {az:zdim}) 
+        if zdim and az :
+            if az != zdim :
+                ttab = ttab.rename( {az:zdim})
     return ttab
 
-#@numba.jit(forceobj=True)
-def V2T (vtab, nperio=None, psgn=-1.0, zdim='deptht', action='ave') :
-    '''Interpolate an array from V grid to T grid (j-mean)'''
+def v2t (vtab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
+    '''Interpolates an array from V grid to T grid (j-mean)
+    '''
     mmath = __mmath__ (vtab)
-    lperio, aperio = lbc_diag (nperio)
+    #lperio, aperio = lbc_diag (nperio)
     vtab_0 = mmath.where ( np.isnan(vtab), 0., vtab)
     vtab_0 = lbc_add (vtab_0, nperio=nperio, cd_type='V', psgn=psgn)
-    iy, ay = __findAxis__ (vtab_0, 'y')
-    iz, az = __findAxis__ (vtab_0, 'z')
-    if action == 'ave'  : ttab = 0.5 *      (vtab_0 + np.roll (vtab_0, axis=iy, shift=1))
-    if action == 'min'  : ttab = np.minimum (vtab_0 , np.roll (vtab_0, axis=iy, shift=1))
-    if action == 'max'  : ttab = np.maximum (vtab_0 , np.roll (vtab_0, axis=iy, shift=1))
-    if action == 'mult' : ttab =             vtab_0 * np.roll (vtab_0, axis=iy, shift=1)
-    ttab = lbc_del (ttab, nperio=nperio, cd_type='T', psgn=psgn)
+    ay, jy = __find_axis__ (vtab_0, 'y')
+    az     = __find_axis__ (vtab_0, 'z')[0]
+    if ay :
+        if action == 'ave'  :
+            ttab = 0.5 *      (vtab_0 + np.roll (vtab_0, axis=jy, shift=1))
+        if action == 'min'  :
+            ttab = np.minimum (vtab_0 , np.roll (vtab_0, axis=jy, shift=1))
+        if action == 'max'  :
+            ttab = np.maximum (vtab_0 , np.roll (vtab_0, axis=jy, shift=1))
+        if action == 'mult' :
+            ttab =             vtab_0 * np.roll (vtab_0, axis=jy, shift=1)
+        ttab = lbc_del (ttab  , nperio=nperio, cd_type='T', psgn=psgn)
+    else :
+        ttab = lbc_del (vtab_0, nperio=nperio, cd_type='T', psgn=psgn)
+
     if mmath == xr :
-        if ay !=None : 
-            ttab = ttab.assign_coords({ay:np.arange(ttab.shape[iy])+1.})
-        if zdim != None and iz != None  and az != 'olevel' :
-            ttab = ttab.rename( {az:zdim}) 
+        if ay :
+            ttab = ttab.assign_coords({ay:np.arange(ttab.shape[jy])+1.})
+        if zdim and az :
+            if az != zdim :
+                ttab = ttab.rename( {az:zdim})
     return ttab
 
-#@numba.jit(forceobj=True)
-def F2T (ftab, nperio=None, psgn=1.0, zdim='depthf', action='ave') :
-    '''Interpolate an array from F grid to T grid (i- and j- means)'''
+def f2t (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
+    '''Interpolates an array from F grid to T grid (i- and j- means)
+    '''
     mmath = __mmath__ (ftab)
     ftab_0 = mmath.where ( np.isnan(ftab), 0., ftab)
     ftab_0 = lbc_add (ftab_0 , nperio=nperio, cd_type='F', psgn=psgn)
-    ttab = V2T(F2V(ftab_0, nperio=nperio, psgn=psgn, zdim=zdim, action=action), nperio=nperio, psgn=psgn, zdim=zdim, action=action)
+    ttab = v2t (f2v (ftab_0, nperio=nperio, psgn=psgn, zdim=zdim, action=action),
+                     nperio=nperio, psgn=psgn, zdim=zdim, action=action)
     return lbc_del (ttab, nperio=nperio, cd_type='T', psgn=psgn)
 
-#@numba.jit(forceobj=True)
-def T2U (ttab, nperio=None, psgn=1.0, zdim='depthu', action='ave') :
-    '''Interpolate an array from T grid to U grid (i-mean)'''
+def t2u (ttab, nperio=None, psgn=1.0, zdim=None, action='ave') :
+    '''Interpolates an array from T grid to U grid (i-mean)
+    '''
     mmath = __mmath__ (ttab)
     ttab_0 = mmath.where ( np.isnan(ttab), 0., ttab)
     ttab_0 = lbc_add (ttab_0 , nperio=nperio, cd_type='T', psgn=psgn)
-    ix, ax = __findAxis__ (ttab_0, 'x')
-    iz, az = __findAxis__ (ttab_0, 'z')
-    if action == 'ave'  : utab = 0.5 *      (ttab_0 + np.roll (ttab_0, axis=ix, shift=-1))
-    if action == 'min'  : utab = np.minimum (ttab_0 , np.roll (ttab_0, axis=ix, shift=-1))
-    if action == 'max'  : utab = np.maximum (ttab_0 , np.roll (ttab_0, axis=ix, shift=-1))
-    if action == 'mult' : utab =             ttab_0 * np.roll (ttab_0, axis=ix, shift=-1)
-    utab = lbc_del (utab, nperio=nperio, cd_type='U', psgn=psgn)
-
-    if mmath == xr :    
-        if ax != None : 
+    ax, ix = __find_axis__ (ttab_0, 'x')[0]
+    az     = __find_axis__ (ttab_0, 'z')
+    if ix :
+        if action == 'ave'  :
+            utab = 0.5 *      (ttab_0 + np.roll (ttab_0, axis=ix, shift=-1))
+        if action == 'min'  :
+            utab = np.minimum (ttab_0 , np.roll (ttab_0, axis=ix, shift=-1))
+        if action == 'max'  :
+            utab = np.maximum (ttab_0 , np.roll (ttab_0, axis=ix, shift=-1))
+        if action == 'mult' :
+            utab =             ttab_0 * np.roll (ttab_0, axis=ix, shift=-1)
+        utab = lbc_del (utab  , nperio=nperio, cd_type='U', psgn=psgn)
+    else :
+        utab = lbc_del (ttab_0, nperio=nperio, cd_type='U', psgn=psgn)
+
+    if mmath == xr :
+        if ax :
             utab = ttab.assign_coords({ax:np.arange(utab.shape[ix])+1.})
-        if zdim != None  and iz != None  and az != 'olevel' :
-            utab = utab.rename( {az:zdim}) 
+        if zdim and az :
+            if az != zdim :
+                utab = utab.rename( {az:zdim})
     return utab
 
-#@numba.jit(forceobj=True)
-def T2V (ttab, nperio=None, psgn=1.0, zdim='depthv', action='ave') :
-    '''Interpolate an array from T grid to V grid (j-mean)'''
+def t2v (ttab, nperio=None, psgn=1.0, zdim=None, action='ave') :
+    '''Interpolates an array from T grid to V grid (j-mean)
+    '''
     mmath = __mmath__ (ttab)
     ttab_0 = mmath.where ( np.isnan(ttab), 0., ttab)
     ttab_0 = lbc_add (ttab_0 , nperio=nperio, cd_type='T', psgn=psgn)
-    iy, ay = __findAxis__ (ttab_0, 'y')
-    iz, az = __findAxis__ (ttab_0, 'z')
-    if action == 'ave'  : vtab = 0.5 *      (ttab_0 + np.roll (ttab_0, axis=iy, shift=-1))
-    if action == 'min'  : vtab = np.minimum (ttab_0 , np.roll (ttab_0, axis=iy, shift=-1))
-    if action == 'max'  : vtab = np.maximum (ttab_0 , np.roll (ttab_0, axis=iy, shift=-1))
-    if action == 'mult' : vtab =             ttab_0 * np.roll (ttab_0, axis=iy, shift=-1)
-
-    vtab = lbc_del (vtab, nperio=nperio, cd_type='V', psgn=psgn)
+    ay, jy = __find_axis__ (ttab_0, 'y')
+    az     = __find_axis__ (ttab_0, 'z')[0]
+    if jy :
+        if action == 'ave'  :
+            vtab = 0.5 *      (ttab_0 + np.roll (ttab_0, axis=jy, shift=-1))
+        if action == 'min'  :
+            vtab = np.minimum (ttab_0 , np.roll (ttab_0, axis=jy, shift=-1))
+        if action == 'max'  :
+            vtab = np.maximum (ttab_0 , np.roll (ttab_0, axis=jy, shift=-1))
+        if action == 'mult' :
+            vtab =             ttab_0 * np.roll (ttab_0, axis=jy, shift=-1)
+        vtab = lbc_del (vtab  , nperio=nperio, cd_type='V', psgn=psgn)
+    else :
+        vtab = lbc_del (ttab_0, nperio=nperio, cd_type='V', psgn=psgn)
+
     if mmath == xr :
-        if ay != None : 
-            vtab = vtab.assign_coords({ay:np.arange(vtab.shape[iy])+1.})
-        if zdim != None  and iz != None and az != 'olevel' :
-            vtab = vtab.rename( {az:zdim}) 
+        if ay :
+            vtab = vtab.assign_coords({ay:np.arange(vtab.shape[jy])+1.})
+        if zdim and az :
+            if az != zdim :
+                vtab = vtab.rename( {az:zdim})
     return vtab
 
-#@numba.jit(forceobj=True)
-def V2F (vtab, nperio=None, psgn=-1.0, zdim='depthf', action='ave') :
-    '''Interpolate an array from V grid to F grid (i-mean)'''
+def v2f (vtab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
+    '''Interpolates an array from V grid to F grid (i-mean)
+    '''
     mmath = __mmath__ (vtab)
     vtab_0 = mmath.where ( np.isnan(vtab), 0., vtab)
     vtab_0 = lbc_add (vtab_0 , nperio=nperio, cd_type='V', psgn=psgn)
-    ix, ax = __findAxis__ (vtab_0, 'x')
-    iz, az = __findAxis__ (vtab_0, 'z')
-    if action == 'ave'  : 0.5 *      (vtab_0 + np.roll (vtab_0, axis=ix, shift=-1))
-    if action == 'min'  : np.minimum (vtab_0 , np.roll (vtab_0, axis=ix, shift=-1))
-    if action == 'max'  : np.maximum (vtab_0 , np.roll (vtab_0, axis=ix, shift=-1))
-    if action == 'mult' :             vtab_0 * np.roll (vtab_0, axis=ix, shift=-1)
-    ftab = lbc_del (ftab, nperio=nperio, cd_type='F', psgn=psgn)
-    
+    ax, ix = __find_axis__ (vtab_0, 'x')
+    az     = __find_axis__ (vtab_0, 'z')[0]
+    if ix :
+        if action == 'ave'  :
+            ftab = 0.5 *      (vtab_0 + np.roll (vtab_0, axis=ix, shift=-1))
+        if action == 'min'  :
+            ftab = np.minimum (vtab_0 , np.roll (vtab_0, axis=ix, shift=-1))
+        if action == 'max'  :
+            ftab = np.maximum (vtab_0 , np.roll (vtab_0, axis=ix, shift=-1))
+        if action == 'mult' :
+            ftab =             vtab_0 * np.roll (vtab_0, axis=ix, shift=-1)
+        ftab = lbc_del (ftab  , nperio=nperio, cd_type='F', psgn=psgn)
+    else :
+        ftab = lbc_del (vtab_0, nperio=nperio, cd_type='F', psgn=psgn)
+
     if mmath == xr :
-        if ax != None : 
+        if ax :
             ftab = ftab.assign_coords({ax:np.arange(ftab.shape[ix])+1.})
-        if zdim != None and iz != None and az != 'olevel' :
-            ftab = ftab.rename( {az:zdim}) 
+        if zdim and az :
+            if az != zdim :
+                ftab = ftab.rename( {az:zdim})
     return lbc_del (ftab, nperio=nperio, cd_type='F', psgn=psgn)
 
-#@numba.jit(forceobj=True)
-def U2F (utab, nperio=None, psgn=-1.0, zdim='depthf', action='ave') :
-    '''Interpolate an array from U grid to F grid i-mean)'''
+def u2f (utab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
+    '''Interpolates an array from U grid to F grid i-mean)
+    '''
     mmath = __mmath__ (utab)
     utab_0 = mmath.where ( np.isnan(utab), 0., utab)
     utab_0 = lbc_add (utab_0 , nperio=nperio, cd_type='U', psgn=psgn)
-    iy, ay = __findAxis__ (utab_0, 'y')
-    iz, az = __findAxis__ (utab_0, 'z')
-    if action == 'ave'  :    ftab = 0.5 *      (utab_0 + np.roll (utab_0, axis=iy, shift=-1))
-    if action == 'min'  :    ftab = np.minimum (utab_0 , np.roll (utab_0, axis=iy, shift=-1))
-    if action == 'max'  :    ftab = np.maximum (utab_0 , np.roll (utab_0, axis=iy, shift=-1))
-    if action == 'mult' :    ftab =             utab_0 * np.roll (utab_0, axis=iy, shift=-1)
-    ftab = lbc_del (ftab, nperio=nperio, cd_type='F', psgn=psgn)
+    ay, jy = __find_axis__ (utab_0, 'y')
+    az     = __find_axis__ (utab_0, 'z')[0]
+    if jy :
+        if action == 'ave'  :
+            ftab = 0.5 *      (utab_0 + np.roll (utab_0, axis=jy, shift=-1))
+        if action == 'min'  :
+            ftab = np.minimum (utab_0 , np.roll (utab_0, axis=jy, shift=-1))
+        if action == 'max'  :
+            ftab = np.maximum (utab_0 , np.roll (utab_0, axis=jy, shift=-1))
+        if action == 'mult' :
+            ftab =             utab_0 * np.roll (utab_0, axis=jy, shift=-1)
+        ftab = lbc_del (ftab, nperio=nperio, cd_type='F', psgn=psgn)
+    else :
+        ftab = lbc_del (utab_0, nperio=nperio, cd_type='F', psgn=psgn)
 
     if mmath == xr :
-        if ay != None : 
-            ftab = ftab.assign_coords({'y':np.arange(ftab.shape[iy])+1.})
-        if zdim != None and iz != None and az != 'olevel' :
-            ftab = ftab.rename( {az:zdim}) 
+        if ay :
+            ftab = ftab.assign_coords({'y':np.arange(ftab.shape[jy])+1.})
+        if zdim and az :
+            if az != zdim :
+                ftab = ftab.rename( {az:zdim})
     return ftab
 
-#@numba.jit(forceobj=True)
-def F2T (ftab, nperio=None, psgn=1.0, zdim='deptht', action='ave') :
-    '''Interpolate an array on F grid to T grid (i- and j- means)'''
-    mmath = __mmath__ (ftab)
-    ftab_0 = mmath.where ( np.isnan(ttab), 0., ttab)
-    ftab_0 = lbc_add (ftab_0 , nperio=nperio, cd_type='F', psgn=psgn)
-    ttab = U2T(F2U(ftab_0, nperio=nperio, psgn=psgn, zdim=zdim, action=action), nperio=nperio, psgn=psgn, zdim=zdim, action=action)
-    return lbc_del (ttab, nperio=nperio, cd_type='T', psgn=psgn)
-
-#@numba.jit(forceobj=True)
-def T2F (ttab, nperio=None, psgn=1.0, zdim='deptht', action='mean') :
-    '''Interpolate an array on T grid to F grid (i- and j- means)'''
+def t2f (ttab, nperio=None, psgn=1.0, zdim=None, action='mean') :
+    '''Interpolates an array on T grid to F grid (i- and j- means)
+    '''
     mmath = __mmath__ (ttab)
     ttab_0 = mmath.where ( np.isnan(ttab), 0., ttab)
     ttab_0 = lbc_add (ttab_0 , nperio=nperio, cd_type='T', psgn=psgn)
-    ftab = T2U(U2F(ttab, nperio=nperio, psgn=psgn, zdim=zdim, action=action), nperio=nperio, psgn=psgn, zdim=zdim, action=action)
-    
+    ftab = t2u (u2f (ttab, nperio=nperio, psgn=psgn, zdim=zdim, action=action),
+                     nperio=nperio, psgn=psgn, zdim=zdim, action=action)
+
     return lbc_del (ftab, nperio=nperio, cd_type='F', psgn=psgn)
 
-#@numba.jit(forceobj=True)
-def F2U (ftab, nperio=None, psgn=1.0, zdim='depthu', action='ave') :
-    '''Interpolate an array on F grid to FUgrid (i-mean)'''
+def f2u (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
+    '''Interpolates an array on F grid to U grid (j-mean)
+    '''
     mmath = __mmath__ (ftab)
     ftab_0 = mmath.where ( np.isnan(ftab), 0., ftab)
     ftab_0 = lbc_add (ftab_0 , nperio=nperio, cd_type='F', psgn=psgn)
-    iy, ay = __findAxis__ (ftab_0, 'y')
-    iz, az = __findAxis__ (ftab_0, 'z')
-    if action == 'ave'  : utab = 0.5 *      (ftab_0 + np.roll (ftab_0, axis=iy, shift=-1))
-    if action == 'min'  : utab = np.minimum (ftab_0 , np.roll (ftab_0, axis=iy, shift=-1))
-    if action == 'max'  : utab = np.maximum (ftab_0 , np.roll (ftab_0, axis=iy, shift=-1))
-    if action == 'mult' : utab =             ftab_0 * np.roll (ftab_0, axis=iy, shift=-1)
-
-    utab = lbc_del (utab, nperio=nperio, cd_type='U', psgn=psgn)
-    
+    ay, jy = __find_axis__ (ftab_0, 'y')
+    az     = __find_axis__ (ftab_0, 'z')[0]
+    if jy :
+        if action == 'ave'  :
+            utab = 0.5 *      (ftab_0 + np.roll (ftab_0, axis=jy, shift=-1))
+        if action == 'min'  :
+            utab = np.minimum (ftab_0 , np.roll (ftab_0, axis=jy, shift=-1))
+        if action == 'max'  :
+            utab = np.maximum (ftab_0 , np.roll (ftab_0, axis=jy, shift=-1))
+        if action == 'mult' :
+            utab =             ftab_0 * np.roll (ftab_0, axis=jy, shift=-1)
+        utab = lbc_del (utab  , nperio=nperio, cd_type='U', psgn=psgn)
+    else :
+        utab = lbc_del (ftab_0, nperio=nperio, cd_type='U', psgn=psgn)
+
     if mmath == xr :
-        utab = utab.assign_coords({ay:np.arange(ftab.shape[iy])+1.})
-        if zdim != None and iz != None and az != 'olevel' :
-            utab = utab.rename( {az:zdim}) 
+        utab = utab.assign_coords({ay:np.arange(ftab.shape[jy])+1.})
+        if zdim and az and az != zdim :
+            utab = utab.rename( {az:zdim})
     return utab
 
-#@numba.jit(forceobj=True)
-def F2V (ftab, nperio=None, psgn=1.0, zdim='depthv', action='ave') :
-    '''Interpolate an array from F grid to V grid (i-mean)'''
+def f2v (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
+    '''Interpolates an array from F grid to V grid (i-mean)
+    '''
     mmath = __mmath__ (ftab)
     ftab_0 = mmath.where ( np.isnan(ftab), 0., ftab)
     ftab_0 = lbc_add (ftab_0 , nperio=nperio, cd_type='F', psgn=psgn)
-    ix, ax = __findAxis__ (ftab_0, 'x')
-    iz, az = __findAxis__ (ftab_0, 'z')
-    if action == 'ave'  : vtab = 0.5 *      (ftab_0 + np.roll (ftab_0, axis=ix, shift=-1))
-    if action == 'min'  : vtab = np.minimum (ftab_0 , np.roll (ftab_0, axis=ix, shift=-1))
-    if action == 'max'  : vtab = np.maximum (ftab_0 , np.roll (ftab_0, axis=ix, shift=-1))
-    if action == 'mult' : vtab =             ftab_0 * np.roll (ftab_0, axis=ix, shift=-1)
-
-    vtab = lbc_del (vtab, nperio=nperio, cd_type='V', psgn=psgn)
+    ax, ix = __find_axis__ (ftab_0, 'x')
+    az     = __find_axis__ (ftab_0, 'z')[0]
+    if ix :
+        if action == 'ave'  :
+            vtab = 0.5 *      (ftab_0 + np.roll (ftab_0, axis=ix, shift=-1))
+        if action == 'min'  :
+            vtab = np.minimum (ftab_0 , np.roll (ftab_0, axis=ix, shift=-1))
+        if action == 'max'  :
+            vtab = np.maximum (ftab_0 , np.roll (ftab_0, axis=ix, shift=-1))
+        if action == 'mult' :
+            vtab =             ftab_0 * np.roll (ftab_0, axis=ix, shift=-1)
+        vtab = lbc_del (vtab  , nperio=nperio, cd_type='V', psgn=psgn)
+    else :
+        vtab = lbc_del (ftab_0, nperio=nperio, cd_type='V', psgn=psgn)
+
     if mmath == xr :
         vtab = vtab.assign_coords({ax:np.arange(ftab.shape[ix])+1.})
-        if zdim != None and iz != None and az != 'olevel' :
-            vtab = vtab.rename( {az:zdim}) 
+        if zdim and az :
+            if az != zdim :
+                vtab = vtab.rename( {az:zdim})
     return vtab
 
-#@numba.jit(forceobj=True)
-def W2T (wtab, zcoord=None, zdim='deptht', sval=np.nan) :
-    '''
-    Interpolate an array on W grid to T grid (k-mean)
+def w2t (wtab, zcoord=None, zdim=None, sval=np.nan) :
+    '''Interpolates an array on W grid to T grid (k-mean)
+
     sval is the bottom value
     '''
@@ -1484,14 +2129,18 @@
     wtab_0 = mmath.where ( np.isnan(wtab), 0., wtab)
 
-    iz, az = __findAxis__ (wtab_0, 'z')
-       
-    ttab = 0.5 * ( wtab_0 + np.roll (wtab_0, axis=iz, shift=-1) )
-    
+    az, kz = __find_axis__ (wtab_0, 'z')
+
+    if kz :
+        ttab = 0.5 * ( wtab_0 + np.roll (wtab_0, axis=kz, shift=-1) )
+    else :
+        ttab = wtab_0
+
     if mmath == xr :
-        ttab[{az:iz}] = sval
-        if zdim != None and iz != None and az != 'olevel' :
-            ttab = ttab.rename ( {az:zdim} )
-        try    : ttab = ttab.assign_coords ( {zdim:zcoord} )
-        except : pass
+        ttab[{az:kz}] = sval
+        if zdim and az :
+            if az != zdim :
+                ttab = ttab.rename ( {az:zdim} )
+        if zcoord is not None :
+            ttab = ttab.assign_coords ( {zdim:zcoord} )
     else :
         ttab[..., -1, :, :] = sval
@@ -1499,7 +2148,7 @@
     return ttab
 
-#@numba.jit(forceobj=True)
-def T2W (ttab, zcoord=None, zdim='depthw', sval=np.nan, extrap_surf=False) :
-    '''Interpolate an array from T grid to W grid (k-mean)
+def t2w (ttab, zcoord=None, zdim=None, sval=np.nan, extrap_surf=False) :
+    '''Interpolates an array from T grid to W grid (k-mean)
+
     sval is the surface value
     if extrap_surf==True, surface value is taken from 1st level value.
@@ -1507,50 +2156,55 @@
     mmath = __mmath__ (ttab)
     ttab_0 = mmath.where ( np.isnan(ttab), 0., ttab)
-    iz, az = __findAxis__ (ttab_0, 'z')
-    wtab = 0.5 * ( ttab_0 + np.roll (ttab_0, axis=iz, shift=1) )
+    az, kz = __find_axis__ (ttab_0, 'z')
+    wtab = 0.5 * ( ttab_0 + np.roll (ttab_0, axis=kz, shift=1) )
 
     if mmath == xr :
-        if extrap_surf : wtab[{az:0}] = ttabb[{az:0}]
-        else           : wtab[{az:0}] = sval
-    else : 
-        if extrap_surf : wtab[..., 0, :, :] = ttab[..., 0, :, :]
-        else           : wtab[..., 0, :, :] = sval
+        if extrap_surf :
+            wtab[{az:0}] = ttab[{az:0}]
+        else           :
+            wtab[{az:0}] = sval
+    else :
+        if extrap_surf :
+            wtab[..., 0, :, :] = ttab[..., 0, :, :]
+        else           :
+            wtab[..., 0, :, :] = sval
 
     if mmath == xr :
-        if zdim != None and iz != None and az != 'olevel' :
-                wtab = wtab.rename ( {az:zdim})
-        if zcoord != None : wtab = wtab.assign_coords ( {zdim:zcoord})
-        else              : ztab = wtab.assign_coords ( {zdim:np.arange(ttab.shape[iz])+1.} )
+        if zdim and az and az != zdim :
+            wtab = wtab.rename ( {az:zdim})
+        if zcoord is not None :
+            wtab = wtab.assign_coords ( {zdim:zcoord})
+        else :
+            wtab = wtab.assign_coords ( {zdim:np.arange(ttab.shape[kz])+1.} )
     return wtab
 
-#@numba.jit(forceobj=True)
-def fill (ptab, nperio, cd_type='T', npass=1, sval=0.) :
-    '''
-    Fill sval values with mean of neighbours
-   
+def fill (ptab, nperio, cd_type='T', npass=1, sval=np.nan) :
+    '''Fills np.nan values with mean of neighbours
+
     Inputs :
        ptab : input field to fill
        nperio, cd_type : periodicity characteristics
-    '''       
+    '''
 
     mmath = __mmath__ (ptab)
 
-    DoPerio = False ; lperio = nperio
+    do_perio  = False
+    lperio    = nperio
     if nperio == 4.2 :
-        DoPerio = True ; lperio = 4
+        do_perio, lperio = True, 4
     if nperio == 6.2 :
-        DoPerio = True ; lperio = 6
-        
-    if DoPerio :
-        ztab = lbc_add (ptab, nperio=nperio, sval=sval)
-    else : 
+        do_perio, lperio = True, 6
+
+    if do_perio :
+        ztab = lbc_add (ptab, nperio=nperio)
+    else :
         ztab = ptab
-        
-    if np.isnan (sval) : 
+
+    if np.isnan (sval) :
         ztab   = mmath.where (np.isnan(ztab), np.nan, ztab)
     else :
         ztab   = mmath.where (ztab==sval    , np.nan, ztab)
-   
-    for nn in np.arange (npass) : 
+
+    for _ in np.arange (npass) :
         zmask = mmath.where ( np.isnan(ztab), 0., 1.   )
         ztab0 = mmath.where ( np.isnan(ztab), 0., ztab )
@@ -1576,16 +2230,16 @@
         zcount = lbc (zcount, nperio=lperio, cd_type=cd_type)
         znew   = lbc (znew  , nperio=lperio, cd_type=cd_type)
-        
+
         ztab = mmath.where (np.logical_and (zmask==0., zcount>0), znew/zcount, ztab)
 
     ztab = mmath.where (zcount==0, sval, ztab)
-    if DoPerio : ztab = lbc_del (ztab, nperio=lperio)
+    if do_perio :
+        ztab = lbc_del (ztab, nperio=lperio)
 
     return ztab
 
-#@numba.jit(forceobj=True)
 def correct_uv (u, v, lat) :
     '''
-    Correct a Cartopy bug in Orthographic projection
+    Corrects a Cartopy bug in orthographic projection
 
     See https://github.com/SciTools/cartopy/issues/1179
@@ -1593,133 +2247,183 @@
     The correction is needed with cartopy <= 0.20
     It seems that version 0.21 will correct the bug (https://github.com/SciTools/cartopy/pull/1926)
+    Later note : the bug is still present in Cartopy 0.22
 
     Inputs :
-       u, v : eastward/nothward components
+       u, v : eastward/northward components
        lat  : latitude of the point (degrees north)
 
-    Outputs : 
+    Outputs :
        modified eastward/nothward components to have correct polar projections in cartopy
     '''
     uv = np.sqrt (u*u + v*v)           # Original modulus
     zu = u
-    zv = v * np.cos (rad*lat)
+    zv = v * np.cos (RAD*lat)
     zz = np.sqrt ( zu*zu + zv*zv )     # Corrected modulus
-    uc = zu*uv/zz ; vc = zv*uv/zz      # Final corrected values
+    uc = zu*uv/zz
+    vc = zv*uv/zz      # Final corrected values
     return uc, vc
 
-def msf (v_e1v_e3v, lat1d, depthw) :
-    '''
-    Computes the meridonal stream function
-    First input is meridional_velocity*e1v*e3v
-    '''
-    @numba.jit(forceobj=True)
-    def iin (tab, dim) :
-        '''
-        Integrate from the bottom
-        '''
-        result = tab * 0.0
-        nlen = len(tab.coords[dim])
-        for jn in np.arange (nlen-2, 0, -1) :
-            result [{dim:jn}] = result [{dim:jn+1}] - tab [{dim:jn}]
-        result = result.where (result !=0, np.nan)
-        return result
-    
-    zomsf = iin ((v_e1v_e3v).sum (dim='x', keep_attrs=True)*1E-6, dim='depthv')
-    zomsf = zomsf.assign_coords ( {'depthv':depthw.values, 'y':lat1d})
-    zomsf = zomsf.rename ( {'depthv':'depthw', 'y':'lat'})
+def norm_uv (u, v) :
+    '''Returns norm of a 2 components vector
+    '''
+    return np.sqrt (u*u + v*v)
+
+def normalize_uv (u, v) :
+    '''Normalizes 2 components vector
+    '''
+    uv = norm_uv (u, v)
+    return u/uv, v/uv
+
+def msf (vv, e1v_e3v, plat1d, depthw) :
+    '''Computes the meridonal stream function
+
+    vv : meridional_velocity
+    e1v_e3v : prodcut of scale factors e1v*e3v
+    '''
+
+    v_e1v_e3v = vv * e1v_e3v
+    v_e1v_e3v.attrs = vv.attrs
+
+    ax = __find_axis__ (v_e1v_e3v, 'x')[0]
+    az = __find_axis__ (v_e1v_e3v, 'z')[0]
+    if az == 'olevel' :
+        new_az = 'olevel'
+    else :
+        new_az = 'depthw'
+
+    zomsf = -v_e1v_e3v.cumsum ( dim=az, keep_attrs=True).sum (dim=ax, keep_attrs=True)*1.E-6
+    zomsf = zomsf - zomsf.isel ( { az:-1} )
+
+    ay = __find_axis__ (zomsf, 'y' )[0]
+    zomsf = zomsf.assign_coords ( {az:depthw.values, ay:plat1d.values})
+
+    zomsf = zomsf.rename ( {ay:'lat'})
+    if az != new_az :
+        zomsf = zomsf.rename ( {az:new_az} )
+    zomsf.attrs['standard_name'] = 'Meridional stream function'
     zomsf.attrs['long_name'] = 'Meridional stream function'
-
     zomsf.attrs['units'] = 'Sv'
-    zomsf.depthw.attrs=depthw.attrs
-    zomsf.lat.attrs=lat1d.attrs
-        
+    zomsf[new_az].attrs  = depthw.attrs
+    zomsf.lat.attrs=plat1d.attrs
+
     return zomsf
 
-def bsf (u_e2u_e3u, mask, nperio=None, bsf0=None ) :
-    '''
-    Computes the barotropic stream function
-    First input is zonal_velocity*e2u*e3u
-    bsf0 is the point with bsf=0 (ex: bsf0={'x':5, 'y':120} )
-    '''
-    @numba.jit(forceobj=True)
-    def iin (tab, dim) :
-        '''
-        Integrate from the south
-        '''
-        result = tab * 0.0
-        nlen = len(tab.coords[dim])
-        for jn in np.arange (3, nlen) :
-            result [{dim:jn}] = result [{dim:jn-1}] + tab [{dim:jn}]
-        return result
-    
-    bsf = iin ((u_e2u_e3u).sum(dim='depthu', keep_attrs=True)*1E-6, dim='y')
-    bsf.attrs = u_e2u_e3u.attrs
-    if bsf0 != None :
-        bsf = bsf - bsf.isel (bsf0)
-       
-    bsf = bsf.where (mask !=0, np.nan)
-    bsf.attrs['long_name'] = 'Barotropic stream function'
-    bsf.attrs['units'] = 'Sv'
-    bsf = lbc (bsf, nperio=nperio, cd_type='F')
-       
-    return bsf
-
-def namelist_read (ref=None, cfg=None, out='dict', flat=False, verbose=False) :
-    '''
-    Read NEMO namelist(s) and return either a dictionnary or an xarray dataset
-
-    ref : file with reference namelist, or a f90nml.namelist.Namelist object
-    cfg : file with config namelist, or a f90nml.namelist.Namelist object
-    At least one namelist neaded
-
-    out: 
+def bsf (uu, e2u_e3u, mask, nperio=None, bsf0=None ) :
+    '''Computes the barotropic stream function
+
+    uu      : zonal_velocity
+    e2u_e3u : product of scales factor e2u*e3u
+    bsf0    : the point with bsf=0
+    (ex: bsf0={'x':3, 'y':120} for orca2,
+         bsf0={'x':5, 'y':300} for eORCA1
+    '''
+    u_e2u_e3u       = uu * e2u_e3u
+    u_e2u_e3u.attrs = uu.attrs
+
+    ay = __find_axis__ (u_e2u_e3u, 'y')[0]
+    az = __find_axis__ (u_e2u_e3u, 'z')[0]
+
+    zbsf = -u_e2u_e3u.cumsum ( dim=ay, keep_attrs=True )
+    zbsf = zbsf.sum (dim=az, keep_attrs=True)*1.E-6
+
+    if bsf0 :
+        zbsf = zbsf - zbsf.isel (bsf0)
+
+    zbsf = zbsf.where (mask !=0, np.nan)
+    zbsf.attrs.update (uu.attrs)
+    zbsf.attrs['standard_name'] = 'barotropic_stream_function'
+    zbsf.attrs['long_name']     = 'Barotropic stream function'
+    zbsf.attrs['units']         = 'Sv'
+    zbsf = lbc (zbsf, nperio=nperio, cd_type='F')
+
+    return zbsf
+
+if f90nml :
+    def namelist_read (ref=None, cfg=None, out='dict', flat=False, verbose=False) :
+        '''Read NEMO namelist(s) and return either a dictionnary or an xarray dataset
+
+        ref : file with reference namelist, or a f90nml.namelist.Namelist object
+        cfg : file with config namelist, or a f90nml.namelist.Namelist object
+        At least one namelist neaded
+
+        out:
         'dict' to return a dictonnary
         'xr'   to return an xarray dataset
-    flat : only for dict output. Output a flat dictionnary with all values.
-    
-    '''
-
-    if ref != None :
-        if isinstance (ref, str) : nml_ref = f90nml.read (ref)
-        if isinstance (ref, f90nml.namelist.Namelist) : nml_ref = ref
-        
-    if cfg != None :
-        if isinstance (cfg, str) : nml_cfg = f90nml.read (cfg)
-        if isinstance (cfg, f90nml.namelist.Namelist) : nml_cfg = cfg
-    
-    if out == 'dict' : dict_namelist = {}
-    if out == 'xr'   : xr_namelist = xr.Dataset ()
-
-    list_nml = [] ; list_comment = []
-
-    if ref != None :
-        list_nml.append (nml_ref) ; list_comment.append ('ref')
-    if cfg != None :
-        list_nml.append (nml_cfg) ; list_comment.append ('cfg')
-
-    for nml, comment in zip (list_nml, list_comment) :
-        if verbose : print (comment)
-        if flat and out =='dict' :
-            for nam in nml.keys () :
-                if verbose : print (nam)
-                for value in nml[nam] :
-                     if out == 'dict' : dict_namelist[value] = nml[nam][value]
-                     if verbose : print (nam, ':', value, ':', nml[nam][value])
-        else :
-            for nam in nml.keys () :
-                if verbose : print (nam)
-                if out == 'dict' :
-                    if nam not in dict_namelist.keys () : dict_namelist[nam] = {}
-                for value in nml[nam] :
-                    if out == 'dict' : dict_namelist[nam][value] = nml[nam][value]
-                    if out == 'xr'   : xr_namelist[value] = nml[nam][value]
-                    if verbose : print (nam, ':', value, ':', nml[nam][value])
-
-    if out == 'dict' : return dict_namelist
-    if out == 'xr'   : return xr_namelist
-
+        flat : only for dict output. Output a flat dictionary with all values.
+
+        '''
+        if ref :
+            if isinstance (ref, str) :
+                nml_ref = f90nml.read (ref)
+            if isinstance (ref, f90nml.namelist.Namelist) :
+                nml_ref = ref
+
+        if cfg :
+            if isinstance (cfg, str) :
+                nml_cfg = f90nml.read (cfg)
+            if isinstance (cfg, f90nml.namelist.Namelist) :
+                nml_cfg = cfg
+
+        if out == 'dict' :
+            dict_namelist = {}
+        if out == 'xr'   :
+            xr_namelist = xr.Dataset ()
+
+        list_nml     = []
+        list_comment = []
+
+        if ref :
+            list_nml.append (nml_ref)
+            list_comment.append ('ref')
+        if cfg :
+            list_nml.append (nml_cfg)
+            list_comment.append ('cfg')
+
+        for nml, comment in zip (list_nml, list_comment) :
+            if verbose :
+                print (comment)
+            if flat and out =='dict' :
+                for nam in nml.keys () :
+                    if verbose :
+                        print (nam)
+                    for value in nml[nam] :
+                        if out == 'dict' :
+                            dict_namelist[value] = nml[nam][value]
+                        if verbose :
+                            print (nam, ':', value, ':', nml[nam][value])
+            else :
+                for nam in nml.keys () :
+                    if verbose :
+                        print (nam)
+                    if out == 'dict' :
+                        if nam not in dict_namelist.keys () :
+                            dict_namelist[nam] = {}
+                    for value in nml[nam] :
+                        if out == 'dict' :
+                            dict_namelist[nam][value] = nml[nam][value]
+                        if out == 'xr'   :
+                            xr_namelist[value] = nml[nam][value]
+                        if verbose :
+                            print (nam, ':', value, ':', nml[nam][value])
+
+        if out == 'dict' :
+            return dict_namelist
+        if out == 'xr'   :
+            return xr_namelist
+else :
+     def namelist_read (ref=None, cfg=None, out='dict', flat=False, verbose=False) :
+        '''Shadow version of namelist read, when f90nm module was not found
+
+        namelist_read : 
+        Read NEMO namelist(s) and return either a dictionnary or an xarray dataset
+        '''
+        print ( 'Error : module f90nml not found' )
+        print ( 'Cannot call namelist_read' )
+        print ( 'Call parameters where : ')
+        print ( f'{err=} {ref=} {cfg=} {out=} {flat=} {verbose=}' )
 
 def fill_closed_seas (imask, nperio=None,  cd_type='T') :
     '''Fill closed seas with image processing library
+
     imask : mask, 1 on ocean, 0 on land
     '''
@@ -1730,4 +2434,118 @@
 
     return imask_filled
+
+# ======================================================
+# Sea water state function parameters from NEMO code
+
+RDELTAS = 32.
+R1_S0   = 0.875/35.16504
+R1_T0   = 1./40.
+R1_Z0   = 1.e-4
+
+EOS000 =  8.0189615746e+02
+EOS100 =  8.6672408165e+02
+EOS200 = -1.7864682637e+03
+EOS300 =  2.0375295546e+03
+EOS400 = -1.2849161071e+03
+EOS500 =  4.3227585684e+02
+EOS600 = -6.0579916612e+01
+EOS010 =  2.6010145068e+01
+EOS110 = -6.5281885265e+01
+EOS210 =  8.1770425108e+01
+EOS310 = -5.6888046321e+01
+EOS410 =  1.7681814114e+01
+EOS510 = -1.9193502195
+EOS020 = -3.7074170417e+01
+EOS120 =  6.1548258127e+01
+EOS220 = -6.0362551501e+01
+EOS320 =  2.9130021253e+01
+EOS420 = -5.4723692739
+EOS030 =  2.1661789529e+01
+EOS130 = -3.3449108469e+01
+EOS230 =  1.9717078466e+01
+EOS330 = -3.1742946532
+EOS040 = -8.3627885467
+EOS140 =  1.1311538584e+01
+EOS240 = -5.3563304045
+EOS050 =  5.4048723791e-01
+EOS150 =  4.8169980163e-01
+EOS060 = -1.9083568888e-01
+EOS001 =  1.9681925209e+01
+EOS101 = -4.2549998214e+01
+EOS201 =  5.0774768218e+01
+EOS301 = -3.0938076334e+01
+EOS401 =  6.6051753097
+EOS011 = -1.3336301113e+01
+EOS111 = -4.4870114575
+EOS211 =  5.0042598061
+EOS311 = -6.5399043664e-01
+EOS021 =  6.7080479603
+EOS121 =  3.5063081279
+EOS221 = -1.8795372996
+EOS031 = -2.4649669534
+EOS131 = -5.5077101279e-01
+EOS041 =  5.5927935970e-01
+EOS002 =  2.0660924175
+EOS102 = -4.9527603989
+EOS202 =  2.5019633244
+EOS012 =  2.0564311499
+EOS112 = -2.1311365518e-01
+EOS022 = -1.2419983026
+EOS003 = -2.3342758797e-02
+EOS103 = -1.8507636718e-02
+EOS013 =  3.7969820455e-01
+
+def rhop ( ptemp, psal ) :
+    '''Returns potential density referenced to surface
+
+    Computation from NEMO code
+    '''
+    zt      = ptemp * R1_T0                                  # Temperature (Â°C)
+    zs      = np.sqrt ( np.abs( psal + RDELTAS ) * R1_S0 )   # Square root of salinity (PSS)
+    #
+    prhop = (
+      (((((EOS060*zt
+         + EOS150*zs     + EOS050)*zt
+         + (EOS240*zs    + EOS140)*zs + EOS040)*zt
+         + ((EOS330*zs   + EOS230)*zs + EOS130)*zs + EOS030)*zt
+         + (((EOS420*zs  + EOS320)*zs + EOS220)*zs + EOS120)*zs + EOS020)*zt
+         + ((((EOS510*zs + EOS410)*zs + EOS310)*zs + EOS210)*zs + EOS110)*zs + EOS010)*zt
+         + (((((EOS600*zs+ EOS500)*zs + EOS400)*zs + EOS300)*zs + EOS200)*zs + EOS100)*zs + EOS000 )
+    #
+    return prhop
+
+def rho ( pdep, ptemp, psal ) :
+    '''Returns in situ density
+
+    Computation from NEMO code
+    '''
+    zh      = pdep  * R1_Z0                                  # Depth (m)
+    zt      = ptemp * R1_T0                                  # Temperature (Â°C)
+    zs      = np.sqrt ( np.abs( psal + RDELTAS ) * R1_S0 )   # Square root salinity (PSS)
+    #
+    zn3 = EOS013*zt + EOS103*zs+EOS003
+    #
+    zn2 = (EOS022*zt + EOS112*zs+EOS012)*zt + (EOS202*zs+EOS102)*zs+EOS002
+    #
+    zn1 = (
+      (((EOS041*zt
+       + EOS131*zs   + EOS031)*zt
+       + (EOS221*zs  + EOS121)*zs + EOS021)*zt
+       + ((EOS311*zs  + EOS211)*zs + EOS111)*zs + EOS011)*zt
+       + (((EOS401*zs + EOS301)*zs + EOS201)*zs + EOS101)*zs + EOS001 )
+    #
+    zn0 = (
+      (((((EOS060*zt
+         + EOS150*zs      + EOS050)*zt
+         + (EOS240*zs     + EOS140)*zs + EOS040)*zt
+         + ((EOS330*zs    + EOS230)*zs + EOS130)*zs + EOS030)*zt
+         + (((EOS420*zs   + EOS320)*zs + EOS220)*zs + EOS120)*zs + EOS020)*zt
+         + ((((EOS510*zs  + EOS410)*zs + EOS310)*zs + EOS210)*zs + EOS110)*zs + EOS010)*zt
+         + (((((EOS600*zs + EOS500)*zs + EOS400)*zs + EOS300)*zs +
+                                       EOS200)*zs + EOS100)*zs + EOS000 )
+    #
+    prho  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+    #
+    return prho
 
 ## ===========================================================================
@@ -1737,44 +2555,44 @@
 ## ===========================================================================
 
-def __is_orca_north_fold__ ( Xtest, cname_long='T' ) :
-    '''
-    Ported (pirated !!?) from Sosie
-
-    Tell if there is a 2/point band overlaping folding at the north pole typical of the ORCA grid
-
-    0 => not an orca grid (or unknown one)
-    4 => North fold T-point pivot (ex: ORCA2)
-    6 => North fold F-point pivot (ex: ORCA1)
-
-    We need all this 'cname_long' stuff because with our method, there is a
-    confusion between "Grid_U with T-fold" and "Grid_V with F-fold"
-    => so knowing the name of the longitude array (as in namelist, and hence as
-    in netcdf file) might help taking the righ decision !!! UGLY!!!
-    => not implemented yet
-    '''
-    
-    ifld_nord =  0 ; cgrd_type = 'X'
-    ny, nx = Xtest.shape[-2:]
-
-    if ny > 3 : # (case if called with a 1D array, ignoring...)
-        if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-1:nx-nx//2+1:-1] ).sum() == 0. :
-          ifld_nord = 4 ; cgrd_type = 'T' # T-pivot, grid_T      
-
-        if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-2:nx-nx//2  :-1] ).sum() == 0. :
-            if cnlon == 'U' : ifld_nord = 4 ;  cgrd_type = 'U' # T-pivot, grid_T
-                ## LOLO: PROBLEM == 6, V !!!
-
-        if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-1:nx-nx//2+1:-1] ).sum() == 0. :
-            ifld_nord = 4 ; cgrd_type = 'V' # T-pivot, grid_V
-
-        if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-2, nx-1-1:nx-nx//2:-1] ).sum() == 0. :
-            ifld_nord = 6 ; cgrd_type = 'T'# F-pivot, grid_T
-
-        if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-1, nx-1:nx-nx//2-1:-1] ).sum() == 0. :
-            ifld_nord = 6 ;  cgrd_type = 'U' # F-pivot, grid_U
-
-        if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-2:nx-nx//2  :-1] ).sum() == 0. :
-            if cnlon == 'V' : ifld_nord = 6 ; cgrd_type = 'V' # F-pivot, grid_V
-                ## LOLO: PROBLEM == 4, U !!!
-
-    return ifld_nord, cgrd_type
+# def __is_orca_north_fold__ ( Xtest, cname_long='T' ) :
+#     '''
+#     Ported (pirated !!?) from Sosie
+
+#     Tell if there is a 2/point band overlaping folding at the north pole typical of the ORCA grid
+
+#     0 => not an orca grid (or unknown one)
+#     4 => North fold T-point pivot (ex: ORCA2)
+#     6 => North fold F-point pivot (ex: ORCA1)
+
+#     We need all this 'cname_long' stuff because with our method, there is a
+#     confusion between "Grid_U with T-fold" and "Grid_V with F-fold"
+#     => so knowing the name of the longitude array (as in namelist, and hence as
+#     in netcdf file) might help taking the righ decision !!! UGLY!!!
+#     => not implemented yet
+#     '''
+
+#     ifld_nord =  0 ; cgrd_type = 'X'
+#     ny, nx = Xtest.shape[-2:]
+
+#     if ny > 3 : # (case if called with a 1D array, ignoring...)
+#         if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-1:nx-nx//2+1:-1] ).sum() == 0. :
+#           ifld_nord = 4 ; cgrd_type = 'T' # T-pivot, grid_T
+
+#         if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-2:nx-nx//2  :-1] ).sum() == 0. :
+#             if cnlon == 'U' : ifld_nord = 4 ;  cgrd_type = 'U' # T-pivot, grid_T
+#                 ## LOLO: PROBLEM == 6, V !!!
+
+#         if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-1:nx-nx//2+1:-1] ).sum() == 0. :
+#             ifld_nord = 4 ; cgrd_type = 'V' # T-pivot, grid_V
+
+#         if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-2, nx-1-1:nx-nx//2:-1] ).sum() == 0. :
+#             ifld_nord = 6 ; cgrd_type = 'T'# F-pivot, grid_T
+
+#         if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-1, nx-1:nx-nx//2-1:-1] ).sum() == 0. :
+#             ifld_nord = 6 ;  cgrd_type = 'U' # F-pivot, grid_U
+
+#         if ( Xtest [ny-1, 1:nx//2-1] - Xtest [ny-3, nx-2:nx-nx//2  :-1] ).sum() == 0. :
+#             if cnlon == 'V' : ifld_nord = 6 ; cgrd_type = 'V' # F-pivot, grid_V
+#                 ## LOLO: PROBLEM == 4, U !!!
+
+#     return ifld_nord, cgrd_type
Index: /TOOLS/MOSAIX/update_xml.py
===================================================================
--- /TOOLS/MOSAIX/update_xml.py	(revision 6665)
+++ /TOOLS/MOSAIX/update_xml.py	(revision 6666)
@@ -26,11 +26,25 @@
 ##  software by incorrectly or partially configured
 ##
-##
+'''
+Python script used to perform on the fly
+editing of xml files. Used by `CreateWeights.bash`. More
+information with `python update_xml.py -h`.
+
 ## SVN information
-__Author__   = "$Author$"
-__Date__     = "$Date$"
-__Revision__ = "$Revision$"
-__Id__       = "$Id$"
-__HeadURL    = "$HeadURL$"
+Author   = "$Author$"
+Date     = "$Date$"
+Revision = "$Revision$"
+Id       = "$Id$"
+HeadURL  = "$HeadURL$"
+'''
+
+## SVN information
+__SVN__ = ({
+    'Author'   : "$Author$",
+    'Date'     : "$Date$",
+    'Revision' : "$Revision$",
+    'Id'       : "$Id$",
+    'HeadURL'  : "$HeadURL$",
+    })
 
 # python update_xml.py -i ~/Unix/TOOLS/MOSAIX/iodef_atm_to_oce.xml -o essai.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]/field[@id="mask_src"]' -k name=Bidon
@@ -41,12 +55,8 @@
 #
 import xml.etree.ElementTree
-import argparse, sys, textwrap, shlex
-    
+import argparse, sys, shlex
+
 # Check version of Python
 Version = sys.version_info
-if Version < (2,7,0) :
-  sys.stderr.write ( "You need python 2.7 or later to run this script\n" )
-  sys.stderr.write ( "Present version is: " + str(Version[0]) + "." + str(Version[1]) + "." + str(Version[2]) + "\n" )
-  sys.exit (1)
 
 ## ============================================================================
@@ -56,6 +66,6 @@
     '''Concatenate some elements of the list of strings when needed'''
     zlist = list_str.copy () ; list_new = []
-    while ( len (zlist) > 0 ) :
-        arg = zlist.pop (0)    
+    while len (zlist) > 0 :
+        arg = zlist.pop (0)
         if arg[0] == '"' :
             for arg2 in zlist.copy () :
@@ -66,22 +76,22 @@
         list_new.append (arg)
     return list_new
-  
-def UpdateNode (iodef, Node, Text=None, Key=None) :
+
+def UpdateNode (piodef, pNode, pText=None, pKey=None) :
     '''Update an xml node'''
     # Remove whitespaces at both ends
-    Node = Node.rstrip().lstrip()
+    zNode = pNode.rstrip().lstrip()
 
     ## Find node
-    nodeList = iodef.findall (Node)
+    nodeList = piodef.findall (zNode)
 
     ## Check that one and only one node is found
     if len (nodeList) == 0 :
         print ( "Error : node not found" )
-        print ( "Node  : ", Node )
+        print ( "Node  : ", zNode )
         sys.exit (1)
-    
+
     if len (nodeList) > 1 :
         print ( "Error : " + len (nodeList)+" occurences of node found in file" )
-        print ( "Node  : ", Node )
+        print ( "Node  : ", zNode )
         sys.exit (2)
 
@@ -89,20 +99,20 @@
     elem = nodeList[0]
 
-    if Text != None :
-        if Verbose : print ( 'Node:', Node, ' -- Text:', Text  )
+    if pText is not None :
+        if Verbose : print ( 'Node:', zNode, ' -- Text:', pText  )
         if Debug :
             print ( 'Attributes of node: ' + str (elem.attrib) )
             print ( 'Text              : ' + str (elem.text)   )
-        elem.text = Text
-
-    if Key != None :
-      
+        elem.text = pText
+
+    if pKey is not None :
+
         # Check the syntax
-        if not '=' in Key :
+        if not '=' in pKey :
             print ( 'Key syntax error. Correct syntax is -k Key=Value' )
             sys.exit (-1)
         else :
-            KeyName, Value = Key.split ('=')
-            if Verbose : print ( 'Node:', Node, ' -- Key:', Key )
+            KeyName, Value = pKey.split ('=')
+            if Verbose : print ( 'Node:', zNode, ' -- Key:', pKey )
             # To do : check that KeyName exist (it is added if not : do we want that ?)
             if Debug :
@@ -110,5 +120,5 @@
             elem.attrib.update ( { KeyName:Value } )
 
-    return iodef
+    return piodef
 
 ## ============================================================================
@@ -118,15 +128,15 @@
 # The first step in using the argparse is creating an ArgumentParser object:
 parser = argparse.ArgumentParser (description = """
-Examples with the modification on the command line : 
+Examples with the modification on the command line :
      python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name -v maskutil_T
      python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t dstDomainType
 
-Usage with a command file : 
+Usage with a command file :
      python %(prog)s -i iodef.xml -c commands.txt
-   
-Syntax in the command file : removes the quote around the node description : 
+
+Syntax in the command file : removes the quote around the node description :
 -n context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]   -t dstDomainType
 
-   """ + "SVN : " + __Revision__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='-------- This is the end of the help message --------')
+   """ + "SVN : " + __SVN__['Revision'], formatter_class=argparse.RawDescriptionHelpFormatter, epilog='-------- This is the end of the help message --------')
 
 # Adding arguments
@@ -155,16 +165,16 @@
 Key         = myargs.key
 Text        = myargs.text
-    
-if FileCommand != None : 
-    if ( Node != None or Key != None or Text != None ) :
+
+if FileCommand is not None :
+    if ( Node is not None or Key is not None or Text is not None ) :
         print ('Error : when a command file is specified, options -k|--key, -n|--node are unused' )
         exit (-2)
-    
-if FileOut == None : FileOut = FileIn
-    
+
+if FileOut is None : FileOut = FileIn
+
 ## Get XML tree from input file
 iodef = xml.etree.ElementTree.parse ( FileIn )
 
-if FileCommand == None :
+if FileCommand is None :
     ## Only one node to modify
     iodef = UpdateNode (iodef, Node, Key, Text)
@@ -172,15 +182,15 @@
 else :
     ## Read a list of modification commands in a command file
-    fic = open (FileCommand, 'r')
-    lignes = fic.readlines()
+    fic = open (FileCommand, 'r', encoding='utf-8')
+    lignes = fic.readlines ()
 
     for nn, ligne in enumerate (lignes) :
         ligne = ligne.strip ().split ('#')[0] # Remove leading and trailing blanks, and trailing comments
         if Debug : print (nn+1, ':', type (ligne) , ':', len (ligne) , ':', ligne, ':')
-        if ligne == '' or ligne == None or len(ligne) == 0 or ligne[0] == '#' :
+        if ligne == '' or ligne is None or len(ligne) == 0 or ligne[0] == '#' :
             if Debug : print ('Skips blank or comment line')
-        else : 
+        else :
             list_args = shlex.split (ligne)
-        
+
             if Debug :
                 print ( '{:3d} : '.format(nn+1), end='')
@@ -193,6 +203,6 @@
             Text     = myargs_ligne.text
 
-            UpdateNode (iodef, Node, Text, Key)
-    
+            iodef = UpdateNode (iodef, Node, Text, Key)
+
 ## Writes XML tree to file
 iodef.write ( FileOut )
@@ -201,5 +211,5 @@
 if Debug : print ('This is the end')
 #sys.exit (0)
-    
+
 ### ===========================================================================
 ###
@@ -207,3 +217,2 @@
 ###
 ### ===========================================================================
-
