Index: TOOLS/WATER_BUDGET/ATM_waterbudget.py
===================================================================
--- TOOLS/WATER_BUDGET/ATM_waterbudget.py	(revision 6620)
+++ TOOLS/WATER_BUDGET/ATM_waterbudget.py	(revision 6647)
@@ -34,8 +34,10 @@
     raise Exception ( "Minimum Python version is 3.8" )
 
-## Import local module
+## Import local modules
 import WaterUtils as wu
 import libIGCM_sys
 import nemo, lmdz
+
+from WaterUtils import VarInt, Rho, Ra, Grav, ICE_rho_ice, ICE_rho_sno, OCE_rho_liq, ATM_rho, SRF_rho, RUN_rho, ICE_rho_pnd, YearLength
 
 ## Creates parser for reading .ini input file
@@ -47,6 +49,7 @@
 ## ---------------------
 ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False
-OCE_icb=False ; Coupled=False ; Routing=None
+OCE_icb=False ; Coupled=False ; Routing=None ; TestInterp=None
 TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None
+YearBegin=None ; YearEnd=None ; DateBegin=None ; DateEnd=None
 
 ##
@@ -66,4 +69,11 @@
 tar_restart_end_RUN=None ; tar_restart_end_OCE=None ; tar_restart_end_ICE=None
 ContinueOnError=False ; ErrorCount=0 ; SortIco = False
+
+##
+## Precision of history file reading
+## ---------------------------------
+# Default is float (full precision). Degrade the precision by using np.float32
+# Restart file are always read at the full precision
+readPrec=float
 
 ## Read command line arguments
@@ -138,4 +148,13 @@
 print ( f'\nConfig file readed : {IniFile} ' )
 
+##
+## Reading prec
+if wu.unDefined ( 'readPrec' )  :
+    readPrec = np.float64
+else :
+    if readPrec in ["float", "float64", "r8", "double", "<class 'float'>"         ] : readPrec = float
+    if readPrec in [         "float32", "r4", "single", "<class 'numpy.float32'>" ] : readPrec = np.float32
+    if readPrec in [         "float16", "r2", "half"  , "<class 'numpy.float16'>" ] : readPrec = np.float16
+    
 ## Some physical constants
 ## =======================
@@ -155,8 +174,8 @@
 if not 'Files' in config.keys () : config['Files'] = {}
 
-config['Physics'] = { 'Ra':Ra, 'Grav':Grav, 'ICE_rho_ice':ICE_rho_ice, 'ICE_rho_sno':ICE_rho_sno,
-                      'OCE_rho_liq':OCE_rho_liq, 'ATM_rho':ATM_rho, 'SRF_rho':SRF_rho, 'RUN_rho':RUN_rho}
-
-config['Config'] = { 'ContinueOnError':ContinueOnError, 'SortIco':SortIco }
+config['Physics'] = { 'Ra':str(Ra), 'Grav':str(Grav), 'ICE_rho_ice':str(ICE_rho_ice), 'ICE_rho_sno':str(ICE_rho_sno),
+                      'OCE_rho_liq':str(OCE_rho_liq), 'ATM_rho':str(ATM_rho), 'SRF_rho':str(SRF_rho), 'RUN_rho':str(RUN_rho)}
+
+config['Config'] = { 'ContinueOnError':str(ContinueOnError), 'SortIco':str(SortIco), 'TestInterp':str(TestInterp), 'readPrec':str(readPrec) }
 
 ## --------------------------
@@ -176,16 +195,17 @@
 if wu.unDefined ( 'DateBegin' ) :
     DateBegin = f'{YearBegin}0101'
-    config['Experiment']['DateBegin'] = DateBegin
+    config['Experiment']['DateBegin'] = str(DateBegin)
 else :
-    YearBegin, MonthBegin, DayBegin = wu.DateSplit ( DateBegin )
-    DateBegin = wu.FormatToGregorian ( DateBegin)
-    config['Experiment']['YearBegin'] = YearBegin
+    YearBegin, MonthBegin, DayBegin = wu.SplitDate ( DateBegin )
+    DateBegin = wu.FormatToGregorian (DateBegin)
+    config['Experiment']['YearBegin'] = str(YearBegin)
 
 if wu.unDefined ( 'DateEnd' )   :
     DateEnd   = f'{YearEnd}1231'
-    config['Experiment']['DateEnd']   = DateEnd
+    config['Experiment']['DateEnd'] = str(DateEnd)
 else :
-    YearEnd, MonthEnd, DayEnd = wu.DateSplit ( DateEnd )
-    DateEnd   = wu.FormatToGregorian ( DateEnd)
+    YearEnd, MonthEnd, DayEnd = wu.SplitDate ( DateEnd )
+    DateEnd   = wu.FormatToGregorian (DateEnd)
+    config['Experiment']['DateEnd'] = str(DateEnd)
 
 if wu.unDefined ( 'PackFrequency' ) :
@@ -200,5 +220,12 @@
 ## Output file with water budget diagnostics
 ## -----------------------------------------
-if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{DateBegin}_{DateEnd}.out'
+if wu.unDefined ( 'FileOut' ) :
+    FileOut = f'ATM_waterbudget_{JobName}_{YearBegin}_{YearEnd}'
+    if ICO : 
+        if ATM_HIS == 'latlon' : FileOut = f'{FileOut}_LATLON'
+        if ATM_HIS == 'ico'    : FileOut = f'{FileOut}_ICO'
+    if readPrec == np.float32  : FileOut = f'{FileOut}_float32'
+    FileOut = f'{FileOut}.out'
+
 config['Files']['FileOut'] = FileOut
 
@@ -207,4 +234,9 @@
 ## Useful functions
 ## ----------------
+if readPrec == float :
+    def rprec (tab) : return tab
+else : 
+    def rprec (tab) : return tab.astype(readPrec).astype(float)
+    
 def kg2Sv    (val, rho=ATM_rho) :
     '''From kg to Sverdrup'''
@@ -216,5 +248,5 @@
 
 def var2prt (var, small=False, rho=ATM_rho) :
-    if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*100#
+    if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000
     else     :  return var , kg2Sv(var, rho=rho)      , kg2myear(var, rho=rho)
 
@@ -236,5 +268,29 @@
     f_out.flush ()
     return None
-    
+
+echo ( f'{ContinueOnError = }' )
+echo ( f'{SortIco         = }' )
+echo ( f'{readPrec        = }' )
+
+echo ( f'{JobName         = }' )
+echo ( f'{ConfigCard      = }' )
+echo ( f'{libIGCM         = }' )     
+echo ( f'{User            = }' )       
+echo ( f'{Group           = }' )       
+echo ( f'{Freq            = }' )       
+echo ( f'{YearBegin       = }' )     
+echo ( f'{YearEnd         = }' )     
+echo ( f'{DateBegin       = }' )
+echo ( f'{DateEnd         = }' )
+echo ( f'{PackFrequency   = }' ) 
+echo ( f'{ATM             = }' )       
+echo ( f'{Routing         = }' )       
+echo ( f'{ORCA            = }' )      
+echo ( f'{NEMO            = }' )      
+echo ( f'{Coupled         = }' )      
+echo ( f'{ATM_HIS         = }' )      
+echo ( f'{SRF_HIS         = }' )      
+echo ( f'{RUN_HIS         = }' )      
+
 ## Set libIGCM directories
 ## -----------------------
@@ -266,7 +322,7 @@
 
 echo (' ')
-echo ( f'JobName    : {JobName}'   )
-echo ( f'Comment    : {Comment}'   )
-echo ( f'TmpDir     : {TmpDir}'    )
+echo ( f'JobName     : {JobName}'    )
+echo ( f'Comment     : {Comment}'    )
+echo ( f'TmpDir      : {TmpDir}'     )
 echo ( f'FileDir     : {FileDir}'    )
 echo ( f'FileDirOCE  : {FileDirOCE}' )
@@ -598,76 +654,67 @@
 # ATM grid with cell surfaces
 if LMDZ :
-    ATM_lat  = lmdz.geo2point (   d_ATM_his ['lat']+0*d_ATM_his ['lon'], dim1D='cell_latlon' )
-    ATM_lon  = lmdz.geo2point ( 0*d_ATM_his ['lat']+  d_ATM_his ['lon'], dim1D='cell_latlon' )
-    ATM_aire = lmdz.geo2point ( d_ATM_his ['aire']     [0], cumulPoles=True, dim1D='cell_latlon' )
-    ATM_fter = lmdz.geo2point ( d_ATM_his ['fract_ter'][0], dim1D='cell_latlon' )
-    ATM_foce = lmdz.geo2point ( d_ATM_his ['fract_oce'][0], dim1D='cell_latlon' )
-    ATM_fsic = lmdz.geo2point ( d_ATM_his ['fract_sic'][0], dim1D='cell_latlon' )
-    ATM_flic = lmdz.geo2point ( d_ATM_his ['fract_lic'][0], dim1D='cell_latlon' )
-    SRF_lat  = lmdz.geo2point (   d_SRF_his ['lat']+0*d_SRF_his ['lon'], dim1D='cell_latlon' )
-    SRF_lon  = lmdz.geo2point ( 0*d_SRF_his ['lat']+  d_SRF_his ['lon'], dim1D='cell_latlon' )
-    SRF_aire      = lmdz.geo2point ( d_SRF_his ['Areas'] * d_SRF_his ['Contfrac'], dim1D='cell_latlonl', cumulPoles=True )
-    SRF_areas     = lmdz.geo2point ( d_SRF_his ['Areas'],  dim1D='cell_latlonl', cumulPoles=True )
-    SRF_contfrac  = lmdz.geo2point ( d_SRF_his ['Contfrac'], dim1D='cell_latlonl' )
-
-    #SRF_res_aire = SRF_aire
-    
+    echo ('ATM grid with cell surfaces : LMDZ')
+    ATM_lat       = lmdz.geo2point (   rprec (d_ATM_his ['lat'])+0*rprec (d_ATM_his ['lon']), dim1D='cell' )
+    ATM_lon       = lmdz.geo2point ( 0*rprec (d_ATM_his ['lat'])+  rprec (d_ATM_his ['lon']), dim1D='cell' )
+    ATM_aire      = lmdz.geo2point ( rprec (d_ATM_his ['aire'] )    [0], cumulPoles=True, dim1D='cell' )
+    ATM_fter      = lmdz.geo2point ( rprec (d_ATM_his ['fract_ter'][0]), dim1D='cell' )
+    ATM_foce      = lmdz.geo2point ( rprec (d_ATM_his ['fract_oce'][0]), dim1D='cell' )
+    ATM_fsic      = lmdz.geo2point ( rprec (d_ATM_his ['fract_sic'][0]), dim1D='cell' )
+    ATM_flic      = lmdz.geo2point ( rprec (d_ATM_his ['fract_lic'][0]), dim1D='cell' )
+    SRF_lat       = lmdz.geo2point (   rprec (d_SRF_his ['lat'])+0*rprec (d_SRF_his ['lon']), dim1D='cell' )
+    SRF_lon       = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat'])+  rprec (d_SRF_his ['lon']), dim1D='cell' )
+    SRF_aire      = lmdz.geo2point ( rprec (d_SRF_his ['Areas']) * rprec (d_SRF_his ['Contfrac']), dim1D='cell', cumulPoles=True )
+    SRF_areas     = lmdz.geo2point ( rprec (d_SRF_his ['Areas'])  ,  dim1D='cell', cumulPoles=True )
+    SRF_contfrac  = lmdz.geo2point ( rprec (d_SRF_his ['Contfrac']), dim1D='cell' )
+
 if ICO :
     if ATM_HIS == 'latlon' :
-        jpja, jpia = d_ATM_his['aire'][0].shape
-        if wu.unDefined ( 'file_ATM_aire' ) : 
-            file_ATM_aire = os.path.join ( R_IN, 'ATM', 'GRID', f'aire_{ATM}_to_{jpia}x{jpja}.nc' )
-            config['Files']['file_ATM_aire'] = file_ATM_aire
-        echo ( f'Aire sur grille reguliere : {file_ATM_aire = }' )
-        d_ATM_aire = xr.open_dataset ( file_ATM_aire, decode_times=False ).squeeze()
-        try :
-            ATM_lat  = lmdz.geo2point (   d_ATM_his ['lat']+0*d_ATM_his ['lon'], dim1D='cell_latlon' )
-            ATM_lon  = lmdz.geo2point ( 0*d_ATM_his ['lat']+  d_ATM_his ['lon'], dim1D='cell_latlon' )
-        except :
-            ATM_lat  = lmdz.geo2point (   d_ATM_his ['lat_dom_out']+0*d_ATM_his ['lon_dom_out'], dim1D='cell_latlon' )
-            ATM_lon  = lmdz.geo2point ( 0*d_ATM_his ['lat_dom_out']+  d_ATM_his ['lon_dom_out'], dim1D='cell_latlon' )
-        ATM_aire = lmdz.geo2point ( d_ATM_aire ['aire'].squeeze(), cumulPoles=True, dim1D='cell_latlon' )
-        ATM_fter = lmdz.geo2point ( d_ATM_his ['fract_ter'][0], dim1D='cell_latlon' )
-        ATM_foce = lmdz.geo2point ( d_ATM_his ['fract_oce'][0], dim1D='cell_latlon' )
-        ATM_fsic = lmdz.geo2point ( d_ATM_his ['fract_sic'][0], dim1D='cell_latlon' )
-        ATM_flic = lmdz.geo2point ( d_ATM_his ['fract_lic'][0], dim1D='cell_latlon' )
+        echo ( 'ATM areas and fractions on latlon grid' )
+        if 'lat_dom_out' in d_ATM_his.variables :
+            ATM_lat  = lmdz.geo2point (   rprec (d_ATM_his ['lat_dom_out'])+0*rprec (d_ATM_his ['lon_dom_out']), dim1D='cell' )
+            ATM_lon  = lmdz.geo2point ( 0*rprec (d_ATM_his ['lat_dom_out'])+  rprec (d_ATM_his ['lon_dom_out']), dim1D='cell' )
+        else :
+            ATM_lat  = lmdz.geo2point (   rprec (d_ATM_his ['lat'])+0*rprec (d_ATM_his ['lon']), dim1D='cell' )
+            ATM_lon  = lmdz.geo2point ( 0*rprec (d_ATM_his ['lat'])+  rprec (d_ATM_his ['lon']), dim1D='cell' )
+        ATM_aire = lmdz.geo2point ( rprec (d_ATM_his ['aire'][0]).squeeze(), cumulPoles=True, dim1D='cell' )
+        ATM_fter = lmdz.geo2point ( rprec (d_ATM_his ['fract_ter'][0]), dim1D='cell' )
+        ATM_foce = lmdz.geo2point ( rprec (d_ATM_his ['fract_oce'][0]), dim1D='cell' )
+        ATM_fsic = lmdz.geo2point ( rprec (d_ATM_his ['fract_sic'][0]), dim1D='cell' )
+        ATM_flic = lmdz.geo2point ( rprec (d_ATM_his ['fract_lic'][0]), dim1D='cell' )
+
+    if ATM_HIS == 'ico' :
+        echo ( 'ATM areas and fractions on ICO grid' )
+        ATM_aire =  rprec (d_ATM_his ['aire']     [0])[ATM_his_keysort].squeeze()
+        ATM_lat  =  rprec (d_ATM_his ['lat']         )[ATM_his_keysort]
+        ATM_lon  =  rprec (d_ATM_his ['lon']         )[ATM_his_keysort]
+        ATM_fter =  rprec (d_ATM_his ['fract_ter'][0])[ATM_his_keysort]
+        ATM_foce =  rprec (d_ATM_his ['fract_oce'][0])[ATM_his_keysort]
+        ATM_fsic =  rprec (d_ATM_his ['fract_sic'][0])[ATM_his_keysort]
+        ATM_flic =  rprec (d_ATM_his ['fract_lic'][0])[ATM_his_keysort]
 
     if SRF_HIS == 'latlon' :
-        try :
-            SRF_lat  = lmdz.geo2point (   d_SRF_his ['lat']+0*d_SRF_his ['lon'], dim1D='cell_latlon' )
-            SRF_lon  = lmdz.geo2point ( 0*d_SRF_his ['lat']+  d_SRF_his ['lon'], dim1D='cell_latlon' )
-        except :
-            try : 
-                SRF_lat  = lmdz.geo2point (   d_SRF_his ['lat_dom_out']+0*d_SRF_his ['lon_dom_out'], dim1D='cell_latlon' )
-                SRF_lon  = lmdz.geo2point ( 0*d_SRF_his ['lat_dom_out']+  d_SRF_his ['lon_dom_out'], dim1D='cell_latlon' )
-            except : 
-                SRF_lat  = lmdz.geo2point (   d_SRF_his ['lat_domain_landpoints_out']+0*d_SRF_his ['lon_domain_landpoints_out'], dim1D='cell_latlon' )
-                SRF_lon  = lmdz.geo2point ( 0*d_SRF_his ['lat_domain_landpoints_out']+  d_SRF_his ['lon_domain_landpoints_out'], dim1D='cell_latlon' )
-        SRF_areas    = d_SRF_his ['Areas'].values
-        SRF_areafrac = d_SRF_his ['AreaFrac'].values
-        SRF_areas    = xr.DataArray ( SRF_areas   , coords=d_SRF_his ['Contfrac'].coords, dims=d_SRF_his ['Contfrac'].dims)
-        SRF_areafrac = xr.DataArray ( SRF_areafrac, coords=d_SRF_his ['Contfrac'].coords, dims=d_SRF_his ['Contfrac'].dims)
-
-        SRF_areas     = lmdz.geo2point ( SRF_areas   , dim1D='cell_latlon', cumulPoles=True )
-        SRF_areafrac  = lmdz.geo2point ( SRF_areafrac, dim1D='cell_latlon', cumulPoles=True )
-        SRF_contfrac  = SRF_areafrac / SRF_areas
-        SRF_aire      = SRF_areafrac
-
-    if ATM_HIS == 'ico' :
-        echo ( f'Grille icosaedre' )
-        ATM_aire =  d_ATM_his ['aire']     [0][ATM_his_keysort].squeeze()
-        ATM_lat  =  d_ATM_his ['lat']         [ATM_his_keysort]
-        ATM_lon  =  d_ATM_his ['lon']         [ATM_his_keysort]
-        ATM_fter =  d_ATM_his ['fract_ter'][0][ATM_his_keysort]
-        ATM_foce =  d_ATM_his ['fract_oce'][0][ATM_his_keysort]
-        ATM_fsic =  d_ATM_his ['fract_sic'][0][ATM_his_keysort]
-        ATM_flic =  d_ATM_his ['fract_lic'][0][ATM_his_keysort]
-        
-    if SRF_HIS == 'ico' : 
-        SRF_lat       =  d_SRF_his ['lat']      [SRF_his_keysort]
-        SRF_lon       =  d_SRF_his ['lon']      [SRF_his_keysort]
-        SRF_areas     =  d_SRF_his ['Areas']    [SRF_his_keysort] 
-        #SRF_areafrac =  d_SRF_his ['AreaFrac'] [SRF_his_keysort] 
-        SRF_contfrac  =  d_SRF_his ['Contfrac'][SRF_his_keysort]
+        echo ( 'SRF areas and fractions on latlon grid' )
+        if 'lat_domain_landpoints_out' in d_SRF_his  : 
+            SRF_lat  = lmdz.geo2point (   rprec (d_SRF_his ['lat_domain_landpoints_out'])+0*rprec (d_SRF_his ['lon_domain_landpoints_out']), dim1D='cell' )
+            SRF_lon  = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat_domain_landpoints_out'])+  rprec (d_SRF_his ['lon_domain_landpoints_out']), dim1D='cell' )
+        else : 
+            if 'lat_domain_landpoints_out' in d_SRF_his :
+                SRF_lat  = lmdz.geo2point (   rprec (d_SRF_his ['lat_dom_out'])+0*rprec (d_SRF_his ['lon_dom_out']), dim1D='cell' )
+                SRF_lon  = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat_dom_out'])+  rprec (d_SRF_his ['lon_dom_out']), dim1D='cell' )
+            else :
+                SRF_lat  = lmdz.geo2point (   rprec (d_SRF_his ['lat'])+0*rprec (d_SRF_his ['lon']), dim1D='cell' )
+                SRF_lon  = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat'])+  rprec (d_SRF_his ['lon']), dim1D='cell' )
+                
+        SRF_areas     = lmdz.geo2point ( rprec (d_SRF_his ['Areas']   )   , dim1D='cell', cumulPoles=True )
+        SRF_areafrac  = lmdz.geo2point ( rprec (d_SRF_his ['AreaFrac'])   , dim1D='cell', cumulPoles=True )
+        SRF_contfrac  = lmdz.geo2point ( rprec (d_SRF_his ['Contfrac'])   , dim1D='cell', cumulPoles=True )
+        SRF_aire = SRF_areafrac
+ 
+    if SRF_HIS == 'ico' :
+        echo ( 'SRF areas and fractions on latlon grid' )
+        SRF_lat       =  rprec (d_SRF_his ['lat']     ) [SRF_his_keysort]
+        SRF_lon       =  rprec (d_SRF_his ['lon']     ) [SRF_his_keysort]
+        SRF_areas     =  rprec (d_SRF_his ['Areas']   ) [SRF_his_keysort] 
+        SRF_contfrac  =  rprec (d_SRF_his ['Contfrac']) [SRF_his_keysort]
         SRF_aire      =  SRF_areas * SRF_contfrac
 
@@ -681,5 +728,5 @@
 ATM_aire_fsea = ATM_aire * ATM_fsea
 
-SRF_aire = SRF_aire.where ( np.abs (SRF_aire) < 1E15, 0. )
+#SRF_aire = SRF_aire.where ( np.abs (SRF_aire) < 1E15, 0. )
 
 ## Write the full configuration
@@ -713,6 +760,6 @@
     DYN_fsea = ATM_fsea
     DYN_flnd = ATM_flnd
-    DYN_fter = d_ATM_beg['FTER']
-    DYN_flic = d_ATM_beg['FLIC']
+    DYN_fter = rprec (d_ATM_beg['FTER'])
+    DYN_flic = rprec (d_ATM_beg['FLIC'])
     DYN_aire_fter = DYN_aire * DYN_fter
 
@@ -728,4 +775,9 @@
     return ATM_flux_int
 
+def LIC_flux_int (flux) :
+    '''Integrate (* time * surface) flux on land ice grid'''
+    LIC_flux_int  = wu.Psum ( (flux * dtime_per_sec * ATM_aire_flic).to_masked_array().ravel() )
+    return LIC_flux_int
+
 def SRF_stock_int (stock) :
     '''Integrate (* surface) stock on land grid'''
@@ -749,19 +801,29 @@
     return ONE_flux_int
 
+def Sprec ( tlist ) :
+    '''Accurate sum of list of scalar elements'''
+    return wu.Psum ( np.array ( tlist) )
+
 ATM_aire_sea     = ATM_aire * ATM_fsea
+
 ATM_aire_tot     = ONE_stock_int (ATM_aire)
-ATM_aire_sea_tot = ONE_stock_int (ATM_aire*ATM_fsea)
-
-DYN_aire_tot     =  ONE_stock_int ( DYN_aire )
-SRF_aire_tot     =  ONE_stock_int ( SRF_aire )
+ATM_aire_sea_tot = ONE_stock_int (ATM_aire_fsea)
+ATM_aire_ter_tot = ONE_stock_int (ATM_aire_fter)
+ATM_aire_lic_tot = ONE_stock_int (ATM_aire_flic)
+
+DYN_aire_tot     = ONE_stock_int ( DYN_aire )
+SRF_aire_tot     = ONE_stock_int ( SRF_aire )
 
 echo ('')
-echo ( f'ATM DYN : Area of atmosphere : {DYN_aire_tot:18.9e}' )
-echo ( f'ATM HIS : Area of atmosphere : {ATM_aire_tot:18.9e}' )
-echo ( f'ATM SRF : Area of atmosphere : {SRF_aire_tot:18.9e}' )
+echo ( f'ATM DYN : Area of atmosphere        : {DYN_aire_tot:18.9e}' )
+echo ( f'ATM HIS : Area of atmosphere        : {ATM_aire_tot:18.9e}' )
+echo ( f'ATM HIS : Area of ter in atmosphere : {ATM_aire_ter_tot:18.9e}' )
+echo ( f'ATM HIS : Area of lic in atmosphere : {ATM_aire_lic_tot:18.9e}' )
+echo ( f'ATM SRF : Area of atmosphere        : {SRF_aire_tot:18.9e}' )
 echo ('')
-echo ( 'ATM DYN : Area of atmosphere/(4pi R^2) : {:18.9f}'.format(DYN_aire_tot/(Ra*Ra*4*np.pi) ) )
-echo ( 'ATM HIS : Area of atmosphere/(4pi R^2) : {:18.9f}'.format(ATM_aire_tot/(Ra*Ra*4*np.pi) ) )
-echo ( 'ATM SRF : Area of atmosphere/(4pi R^2) : {:18.9f}'.format(SRF_aire_tot/(Ra*Ra*4*np.pi) ) )
+echo ( 'ATM DYN : Area of atmosphere/(4pi R^2)        : {:18.9f}'.format(DYN_aire_tot/(Ra*Ra*4*np.pi) ) )
+echo ( 'ATM HIS : Area of atmosphere/(4pi R^2)        : {:18.9f}'.format(ATM_aire_tot/(Ra*Ra*4*np.pi) ) )
+echo ( 'ATM HIS : Area of ter in atmosphere/(4pi R^2) : {:18.9f}'.format(ATM_aire_ter_tot/(Ra*Ra*4*np.pi) ) )
+echo ( 'ATM SRF : Area of atmosphere/(4pi R^2)        : {:18.9f}'.format(SRF_aire_tot/(Ra*Ra*4*np.pi) ) )
 echo ('')
 echo ( f'ATM SRF : Area of atmosphere (no contfrac): {ONE_stock_int (SRF_areas):18.9e}' )
@@ -786,6 +848,6 @@
     DYN_psol_end = d_DYN_end['ps'][DYN_end_keysort]
 if LMDZ : 
-    DYN_psol_beg = lmdz.geo2point ( d_DYN_beg['ps'].isel(rlonv=slice(0,-1)), dim1D='cell_latlon' )
-    DYN_psol_end = lmdz.geo2point ( d_DYN_end['ps'].isel(rlonv=slice(0,-1)), dim1D='cell_latlon' )
+    DYN_psol_beg = lmdz.geo2point ( d_DYN_beg['ps'].isel(rlonv=slice(0,-1)), dim1D='cell' )
+    DYN_psol_end = lmdz.geo2point ( d_DYN_end['ps'].isel(rlonv=slice(0,-1)), dim1D='cell' )
     
 echo ( '3D Pressure at the interface layers (not scalar points)' )
@@ -793,4 +855,29 @@
 DYN_pres_end = ATM_Ahyb + ATM_Bhyb * DYN_psol_end
 
+echo ( 'Check computation of pressure levels' )
+
+ind = np.empty (8)
+
+ind[0] = (DYN_pres_beg[ 0]-DYN_psol_beg).min().item()
+ind[1] = (DYN_pres_beg[ 0]-DYN_psol_beg).max().item()
+ind[2] = (DYN_pres_beg[-1]).min().item()
+ind[3] = (DYN_pres_beg[-1]).max().item()
+ind[4] = (DYN_pres_end[ 0]-DYN_psol_end).min().item()
+ind[5] = (DYN_pres_end[ 0]-DYN_psol_end).max().item()
+ind[6] = (DYN_pres_end[-1]).min().item()
+ind[7] = (DYN_pres_end[-1]).max().item()
+
+if any ( ind != 0) :
+    echo ( 'All values should be zero' )
+    echo ( f'(DYN_pres_beg[ 0]-DYN_psol_beg).min().item() = {ind[0]}' )
+    echo ( f'(DYN_pres_beg[ 0]-DYN_psol_beg).max().item() = {ind[1]}' )
+    echo ( f'(DYN_pres_beg[-1]).min().item()              = {ind[2]}' )
+    echo ( f'(DYN_pres_beg[-1]).max().item()              = {ind[3]}' )
+    echo ( f'(DYN_pres_end[ 0]-DYN_psol_end).min().item() = {ind[4]}' )
+    echo ( f'(DYN_pres_end[ 0]-DYN_psol_end).max().item() = {ind[5]}' )
+    echo ( f'(DYN_pres_end[-1]).min().item()              = {ind[6]}' )
+    echo ( f'(DYN_pres_end[-1]).max().item()              = {ind[7]}' )
+    raise Exception
+    
 klevp1 = ATM_Bhyb.shape[-1]
 cell   = DYN_psol_beg.shape[-1]
@@ -798,44 +885,60 @@
 
 echo ( 'Layer thickness (pressure)' )
-DYN_dpres_beg = xr.DataArray ( np.empty( (klev, cell )), dims = ('sigs', 'cell'), coords=(np.arange(klev), np.arange(cell) ) )
-DYN_dpres_end = xr.DataArray ( np.empty( (klev, cell )), dims = ('sigs', 'cell'), coords=(np.arange(klev), np.arange(cell) ) )
-    
-for k in np.arange (klevp1-1) :
-    DYN_dpres_beg[k,:] = DYN_pres_beg[k,:] - DYN_pres_beg[k+1,:]
-    DYN_dpres_end[k,:] = DYN_pres_end[k,:] - DYN_pres_end[k+1,:]
+DYN_mass_beg = xr.DataArray ( np.empty( (klev, cell)), dims = ('sigs', 'cell'), coords=(np.arange(klev), np.arange(cell) ) )
+DYN_mass_end = xr.DataArray ( np.empty( (klev, cell)), dims = ('sigs', 'cell'), coords=(np.arange(klev), np.arange(cell) ) )
+    
+for k in np.arange (klev) :
+    DYN_mass_beg[k,:] = ( DYN_pres_beg[k,:] - DYN_pres_beg[k+1,:] ) / Grav
+    DYN_mass_end[k,:] = ( DYN_pres_end[k,:] - DYN_pres_end[k+1,:] ) / Grav
+
+DYN_mass_beg_2D = DYN_mass_beg.sum (dim='sigs')
+DYN_mass_end_2D = DYN_mass_end.sum (dim='sigs')
+
+DYN_mas_air_beg = DYN_stock_int ( DYN_mass_beg_2D )
+DYN_mas_air_end = DYN_stock_int ( DYN_mass_end_2D )
 
 echo ( 'Vertical and horizontal integral, and sum of liquid, solid and vapor water phases' )
 if LMDZ :
-    try : 
-        DYN_wat_beg = lmdz.geo3point ( (d_DYN_beg['H2Ov']  + d_DYN_beg['H2Ol']  + d_DYN_beg['H2Oi'] ).isel(rlonv=slice(0,-1) ), dim1D='cell' )
-        DYN_wat_end = lmdz.geo3point ( (d_DYN_end['H2Ov']  + d_DYN_end['H2Ol']  + d_DYN_end['H2Oi'] ).isel(rlonv=slice(0,-1) ), dim1D='cell' )
-    except :
+    if 'H2Ov' in d_DYN_beg.variables :
+        echo ('reading LATLON : H2Ov, H2Ol, H2Oi' )
+        DYN_wat_beg = lmdz.geo3point ( d_DYN_beg['H2Ov'] + d_DYN_beg['H2Ol'] + d_DYN_beg['H2Oi'].isel(rlonv=slice(0,-1) ), dim1D='cell' )
+        DYN_wat_end = lmdz.geo3point ( d_DYN_end['H2Ov'] + d_DYN_end['H2Ol'] + d_DYN_end['H2Oi'].isel(rlonv=slice(0,-1) ), dim1D='cell' )
+    if 'H2Ov_g' in d_DYN_beg.variables :
+        echo ('reading LATLON : H2O_g, H2O_l, H2O_s' )
         DYN_wat_beg = lmdz.geo3point ( (d_DYN_beg['H2O_g'] + d_DYN_beg['H2O_l'] + d_DYN_beg['H2O_s']).isel(rlonv=slice(0,-1) ), dim1D='cell' )
         DYN_wat_end = lmdz.geo3point ( (d_DYN_end['H2O_g'] + d_DYN_end['H2O_l'] + d_DYN_end['H2O_s']).isel(rlonv=slice(0,-1) ), dim1D='cell' )
 if ICO :
-    try :
+    if 'H2Ov_g' in d_DYN_beg.variables :
+        echo ('reading ICO : H2O_g, H2O_l, H2O_s' )
         DYN_wat_beg = (d_DYN_beg['H2O_g'] + d_DYN_beg['H2O_l'] + d_DYN_beg['H2O_s'])[..., DYN_beg_keysort]
         DYN_wat_end = (d_DYN_end['H2O_g'] + d_DYN_end['H2O_l'] + d_DYN_end['H2O_s'])[..., DYN_beg_keysort]
-        
-    except : 
+    elif 'H2O_g' in d_DYN_beg.variables :
+        echo ('reading ICO : H2O_g, H2O_l, H2O_s' )
+        DYN_wat_beg = (d_DYN_beg['H2O_g'] + d_DYN_beg['H2O_l'] + d_DYN_beg['H2O_s'])[..., DYN_beg_keysort]
+        DYN_wat_end = (d_DYN_end['H2O_g'] + d_DYN_end['H2O_l'] + d_DYN_end['H2O_s'])[..., DYN_beg_keysort]
+    elif 'q' in d_DYN_beg.variables :
+        echo ('reading ICO : q' )
         DYN_wat_beg = (d_DYN_beg['q'].isel(nq=0) + d_DYN_beg['q'].isel(nq=1) + d_DYN_beg['q'].isel(nq=2) )[..., DYN_beg_keysort]
         DYN_wat_end = (d_DYN_end['q'].isel(nq=0) + d_DYN_end['q'].isel(nq=1) + d_DYN_end['q'].isel(nq=2) )[..., DYN_beg_keysort]
-        
+
+if 'lev' in DYN_wat_beg.dims : 
     DYN_wat_beg = DYN_wat_beg.rename ( {'lev':'sigs'} )
-    DYN_wat_beg = DYN_wat_end.rename ( {'lev':'sigs'} )
+    DYN_wat_end = DYN_wat_end.rename ( {'lev':'sigs'} )
     
 echo ( 'Compute water content : vertical and horizontal integral' )
-DYN_mas_wat_beg = DYN_stock_int ( (DYN_dpres_beg * DYN_wat_beg).sum (dim='sigs') ) / Grav
-DYN_mas_wat_end = DYN_stock_int ( (DYN_dpres_end * DYN_wat_end).sum (dim='sigs') ) / Grav
+
+DYN_wat_beg_2D =  (DYN_mass_beg * DYN_wat_beg).sum (dim='sigs')
+DYN_wat_end_2D =  (DYN_mass_end * DYN_wat_end).sum (dim='sigs')
+
+DYN_mas_wat_beg = DYN_stock_int ( DYN_wat_beg_2D )
+DYN_mas_wat_end = DYN_stock_int ( DYN_wat_end_2D )
 
 echo ( 'Variation of water content' )
 dDYN_mas_wat = DYN_mas_wat_end - DYN_mas_wat_beg
 
-# \([a-z,A-Z,_]*\)/dtime_sec\*1e-9  kg2Sv(\1)
-# \([a-z,A-Z,_]*\)\/ATM_aire_sea_tot\/ATM_rho\/NbYear  kg2myear(\1)
-
 echo ( f'\nChange of atmosphere water content (dynamics)  -- {Title} ' )
 echo ( '------------------------------------------------------------------------------------' )
-echo ( 'DYN_mas_beg = {:12.6e} kg | DYN_mas_end = {:12.6e} kg'.format (DYN_mas_wat_beg, DYN_mas_wat_end) )
+echo ( 'DYN_mas_air_beg = {:12.6e} kg | DYN_mas_air_end = {:12.6e} kg'.format (DYN_mas_air_beg, DYN_mas_air_end) )
+echo ( 'DYN_mas_wat_beg = {:12.6e} kg | DYN_mas_wat_end = {:12.6e} kg'.format (DYN_mas_wat_beg, DYN_mas_wat_end) )
 prtFlux ( 'dMass (atm)  ', dDYN_mas_wat, 'e', True )
 
@@ -850,6 +953,6 @@
               d_ATM_end['QS03']  *d_ATM_end['FOCE'] + d_ATM_end['QS04']  *d_ATM_end['FSIC']
 
-ATM_qsol_beg = d_ATM_beg['QSOL']
-ATM_qsol_end = d_ATM_end['QSOL']
+ATM_qsol_beg     = d_ATM_beg['QSOL']
+ATM_qsol_end     = d_ATM_end['QSOL']
 
 LIC_sno_beg      = d_ATM_beg['SNOW02']*d_ATM_beg['FLIC']
@@ -859,32 +962,33 @@
 LIC_runlic0_end  = d_ATM_end['RUNOFFLIC0']
 
-ATM_qs01_beg  = d_ATM_beg['QS01'] * d_ATM_beg['FTER']
-ATM_qs01_end  = d_ATM_end['QS01'] * d_ATM_end['FTER']
-ATM_qs02_beg  = d_ATM_beg['QS02'] * d_ATM_beg['FLIC']
-ATM_qs02_end  = d_ATM_end['QS02'] * d_ATM_end['FLIC']
-ATM_qs03_beg  = d_ATM_beg['QS03'] * d_ATM_beg['FOCE']
-ATM_qs03_end  = d_ATM_end['QS03'] * d_ATM_end['FOCE']
-ATM_qs04_beg  = d_ATM_beg['QS04'] * d_ATM_beg['FSIC']
-ATM_qs04_end  = d_ATM_end['QS04'] * d_ATM_end['FSIC']  
+ATM_qs01_beg     = d_ATM_beg['QS01'] * d_ATM_beg['FTER']
+ATM_qs02_beg     = d_ATM_beg['QS02'] * d_ATM_beg['FLIC']
+ATM_qs03_beg     = d_ATM_beg['QS03'] * d_ATM_beg['FOCE']
+ATM_qs04_beg     = d_ATM_beg['QS04'] * d_ATM_beg['FSIC']
+
+ATM_qs01_end     = d_ATM_end['QS01'] * d_ATM_end['FTER']
+ATM_qs02_end     = d_ATM_end['QS02'] * d_ATM_end['FLIC']
+ATM_qs03_end     = d_ATM_end['QS03'] * d_ATM_end['FOCE']
+ATM_qs04_end     = d_ATM_end['QS04'] * d_ATM_end['FSIC']  
 
 if ICO :
-     ATM_sno_beg       = ATM_sno_beg    [ATM_beg_keysort]
-     ATM_sno_end       = ATM_sno_end    [ATM_end_keysort]
-     ATM_qs_beg        = ATM_qs_beg     [ATM_beg_keysort]
-     ATM_qs_end        = ATM_qs_end     [ATM_end_keysort]
-     ATM_qsol_beg      = ATM_qsol_beg   [ATM_beg_keysort]
-     ATM_qsol_end      = ATM_qsol_end   [ATM_end_keysort]
-     ATM_qs01_beg      = ATM_qs01_beg   [ATM_beg_keysort]
-     ATM_qs01_end      = ATM_qs01_end   [ATM_end_keysort]
-     ATM_qs02_beg      = ATM_qs02_beg   [ATM_beg_keysort]
-     ATM_qs02_end      = ATM_qs02_end   [ATM_end_keysort]
-     ATM_qs03_beg      = ATM_qs03_beg   [ATM_beg_keysort]
-     ATM_qs03_end      = ATM_qs03_end   [ATM_end_keysort]
-     ATM_qs04_beg      = ATM_qs04_beg   [ATM_beg_keysort]
-     ATM_qs04_end      = ATM_qs04_end   [ATM_end_keysort]
-     LIC_sno_beg       = LIC_sno_beg    [ATM_beg_keysort]
-     LIC_sno_end       = LIC_sno_end    [ATM_end_keysort]
-     LIC_runlic0_beg   = LIC_runlic0_beg[ATM_beg_keysort]
-     LIC_runlic0_end   = LIC_runlic0_end[ATM_end_keysort]
+     ATM_sno_beg     = ATM_sno_beg    [ATM_beg_keysort]
+     ATM_sno_end     = ATM_sno_end    [ATM_end_keysort]
+     ATM_qs_beg      = ATM_qs_beg     [ATM_beg_keysort]
+     ATM_qs_end      = ATM_qs_end     [ATM_end_keysort]
+     ATM_qsol_beg    = ATM_qsol_beg   [ATM_beg_keysort]
+     ATM_qs01_beg    = ATM_qs01_beg   [ATM_beg_keysort]
+     ATM_qs02_beg    = ATM_qs02_beg   [ATM_beg_keysort]
+     ATM_qs03_beg    = ATM_qs03_beg   [ATM_beg_keysort]
+     ATM_qs04_beg    = ATM_qs04_beg   [ATM_beg_keysort]
+     ATM_qsol_end    = ATM_qsol_end   [ATM_end_keysort]
+     ATM_qs01_end    = ATM_qs01_end   [ATM_end_keysort]
+     ATM_qs02_end    = ATM_qs02_end   [ATM_end_keysort]
+     ATM_qs03_end    = ATM_qs03_end   [ATM_end_keysort]
+     ATM_qs04_end    = ATM_qs04_end   [ATM_end_keysort]
+     LIC_sno_beg     = LIC_sno_beg    [ATM_beg_keysort]
+     LIC_sno_end     = LIC_sno_end    [ATM_end_keysort]
+     LIC_runlic0_beg = LIC_runlic0_beg[ATM_beg_keysort]
+     LIC_runlic0_end = LIC_runlic0_end[ATM_end_keysort]
    
 LIC_qs_beg = ATM_qs02_beg
@@ -897,12 +1001,12 @@
 ATM_mas_qs_end      = DYN_stock_int ( ATM_qs_end   )
 ATM_mas_qsol_beg    = DYN_stock_int ( ATM_qsol_beg )
+ATM_mas_qs01_beg    = DYN_stock_int ( ATM_qs01_beg )
+ATM_mas_qs02_beg    = DYN_stock_int ( ATM_qs02_beg )
+ATM_mas_qs03_beg    = DYN_stock_int ( ATM_qs03_beg )
+ATM_mas_qs04_beg    = DYN_stock_int ( ATM_qs04_beg )
 ATM_mas_qsol_end    = DYN_stock_int ( ATM_qsol_end )
-ATM_mas_qs01_beg    = DYN_stock_int ( ATM_qs01_beg )
 ATM_mas_qs01_end    = DYN_stock_int ( ATM_qs01_end )
-ATM_mas_qs02_beg    = DYN_stock_int ( ATM_qs02_beg )
 ATM_mas_qs02_end    = DYN_stock_int ( ATM_qs02_end )
-ATM_mas_qs03_beg    = DYN_stock_int ( ATM_qs03_beg )
 ATM_mas_qs03_end    = DYN_stock_int ( ATM_qs03_end )
-ATM_mas_qs04_beg    = DYN_stock_int ( ATM_qs04_beg )
 ATM_mas_qs04_end    = DYN_stock_int ( ATM_qs04_end )
 
@@ -929,5 +1033,6 @@
 dLIC_mas_sno     = LIC_mas_sno_end     - LIC_mas_sno_beg
 dLIC_mas_runlic0 = LIC_mas_runlic0_end - LIC_mas_runlic0_beg
-dLIC_mas_wat     = dLIC_mas_qs + dLIC_mas_sno
+
+dLIC_mas_wat     = dLIC_mas_qs + dLIC_mas_sno # + dLIC_mas_runlic0
 
 echo ( f'\nChange of atmosphere snow content (Land ice) -- {Title} ' )
@@ -980,8 +1085,9 @@
     RUN_mas_wat_pond_end   = ONE_stock_int ( d_SRF_end ['pondres']   )
 
-RUN_mas_wat_beg = RUN_mas_wat_fast_beg  + RUN_mas_wat_slow_beg + RUN_mas_wat_stream_beg + \
-                  RUN_mas_wat_flood_beg + RUN_mas_wat_lake_beg + RUN_mas_wat_pond_beg
-RUN_mas_wat_end = RUN_mas_wat_fast_end  + RUN_mas_wat_slow_end + RUN_mas_wat_stream_end + \
-                  RUN_mas_wat_flood_end + RUN_mas_wat_lake_end + RUN_mas_wat_pond_end
+RUN_mas_wat_beg = Sprec ( [RUN_mas_wat_fast_beg , RUN_mas_wat_slow_beg, RUN_mas_wat_stream_beg,
+                           RUN_mas_wat_flood_beg, RUN_mas_wat_lake_beg, RUN_mas_wat_pond_beg] )
+                  
+RUN_mas_wat_end = Sprec ( [RUN_mas_wat_fast_end  , RUN_mas_wat_slow_end , RUN_mas_wat_stream_end,
+                           RUN_mas_wat_flood_end , RUN_mas_wat_lake_end , RUN_mas_wat_pond_end] )
 
 dRUN_mas_wat_fast   = RUN_mas_wat_fast_end   - RUN_mas_wat_fast_beg
@@ -1032,12 +1138,12 @@
 
 if LMDZ :
-    SRF_tot_watveg_beg  = lmdz.geo2point (SRF_tot_watveg_beg , dim1D='cell_latlon')
-    SRF_tot_watsoil_beg = lmdz.geo2point (SRF_tot_watsoil_beg, dim1D='cell_latlon')
-    SRF_snow_beg        = lmdz.geo2point (SRF_snow_beg       , dim1D='cell_latlon')
-    SRF_lakeres_beg     = lmdz.geo2point (SRF_lakeres_beg    , dim1D='cell_latlon')
-    SRF_tot_watveg_end  = lmdz.geo2point (SRF_tot_watveg_end , dim1D='cell_latlon')
-    SRF_tot_watsoil_end = lmdz.geo2point (SRF_tot_watsoil_end, dim1D='cell_latlon')
-    SRF_snow_end        = lmdz.geo2point (SRF_snow_end       , dim1D='cell_latlon')
-    SRF_lakeres_end     = lmdz.geo2point (SRF_lakeres_end    , dim1D='cell_latlon')
+    SRF_tot_watveg_beg  = lmdz.geo2point (SRF_tot_watveg_beg , dim1D='cell')
+    SRF_tot_watsoil_beg = lmdz.geo2point (SRF_tot_watsoil_beg, dim1D='cell')
+    SRF_snow_beg        = lmdz.geo2point (SRF_snow_beg       , dim1D='cell')
+    SRF_lakeres_beg     = lmdz.geo2point (SRF_lakeres_beg    , dim1D='cell')
+    SRF_tot_watveg_end  = lmdz.geo2point (SRF_tot_watveg_end , dim1D='cell')
+    SRF_tot_watsoil_end = lmdz.geo2point (SRF_tot_watsoil_end, dim1D='cell')
+    SRF_snow_end        = lmdz.geo2point (SRF_snow_end       , dim1D='cell')
+    SRF_lakeres_end     = lmdz.geo2point (SRF_lakeres_end    , dim1D='cell')
   
 if ICO :
@@ -1053,5 +1159,5 @@
 # Stock dSoilHum dInterce dSWE dStream dFastR dSlowR dLake dPond dFlood
 
-SRF_wat_beg = SRF_tot_watveg_beg + SRF_tot_watsoil_beg + SRF_snow_beg 
+SRF_wat_beg = SRF_tot_watveg_beg + SRF_tot_watsoil_beg + SRF_snow_beg
 SRF_wat_end = SRF_tot_watveg_end + SRF_tot_watsoil_end + SRF_snow_end
 
@@ -1079,8 +1185,8 @@
 print (' -- ') ; sys.stdout.flush ()
 
-dSRF_mas_watveg   = SRF_mas_watveg_end  - SRF_mas_watveg_beg
-dSRF_mas_watsoil  = SRF_mas_watsoil_end - SRF_mas_watsoil_beg
-dSRF_mas_snow     = SRF_mas_snow_end    - SRF_mas_snow_beg
-dSRF_mas_lake     = SRF_mas_lake_end    - SRF_mas_lake_beg
+dSRF_mas_watveg   = Sprec ( [SRF_mas_watveg_end , -SRF_mas_watveg_beg] )
+dSRF_mas_watsoil  = Sprec ( [SRF_mas_watsoil_end, -SRF_mas_watsoil_beg] )
+dSRF_mas_snow     = Sprec ( [SRF_mas_snow_end   , -SRF_mas_snow_beg] )
+dSRF_mas_lake     = Sprec ( [SRF_mas_lake_end   , -SRF_mas_lake_beg] )
 
 echo ( '------------------------------------------------------------------------------------' )
@@ -1096,7 +1202,9 @@
 prtFlux ( 'dMass (lake)   ', dSRF_mas_lake   , 'e' , True )
 
-SRF_mas_wat_beg = SRF_mas_watveg_beg + SRF_mas_watsoil_beg + SRF_mas_snow_beg 
-SRF_mas_wat_end = SRF_mas_watveg_end + SRF_mas_watsoil_end + SRF_mas_snow_end 
-dSRF_mas_wat    = SRF_mas_wat_end - SRF_mas_wat_beg
+SRF_mas_wat_beg = Sprec ( [SRF_mas_watveg_beg , SRF_mas_watsoil_beg, SRF_mas_snow_beg] )
+SRF_mas_wat_end = Sprec ( [SRF_mas_watveg_end , SRF_mas_watsoil_end, SRF_mas_snow_end] )
+
+dSRF_mas_wat    = Sprec ( [+SRF_mas_watveg_end , +SRF_mas_watsoil_end, +SRF_mas_snow_end, 
+                           -SRF_mas_watveg_beg , -SRF_mas_watsoil_beg, -SRF_mas_snow_beg]  )
 
 echo ( '------------------------------------------------------------------------------------' )
@@ -1115,74 +1223,63 @@
 echo ( f'-- ATM Fluxes  -- {Title} ' )
 
-Step=1
-print ( 'Step {Step}', end='' ) ; Step += 1
 if ATM_HIS == 'latlon' :
-    ATM_wbilo_oce   = lmdz.geo2point ( d_ATM_his ['wbilo_oce'], dim1D='cell_latlon' )
-    ATM_wbilo_sic   = lmdz.geo2point ( d_ATM_his ['wbilo_sic'], dim1D='cell_latlon' )
-    ATM_wbilo_ter   = lmdz.geo2point ( d_ATM_his ['wbilo_ter'], dim1D='cell_latlon' )
-    ATM_wbilo_lic   = lmdz.geo2point ( d_ATM_his ['wbilo_lic'], dim1D='cell_latlon' )
-    ATM_runofflic   = lmdz.geo2point ( d_ATM_his ['runofflic'], dim1D='cell_latlon' )
-    ATM_fqcalving   = lmdz.geo2point ( d_ATM_his ['fqcalving'], dim1D='cell_latlon' )
-    ATM_fqfonte     = lmdz.geo2point ( d_ATM_his ['fqfonte']  , dim1D='cell_latlon' )
-    ATM_precip      = lmdz.geo2point ( d_ATM_his ['precip']   , dim1D='cell_latlon' )
-    ATM_snowf       = lmdz.geo2point ( d_ATM_his ['snow']     , dim1D='cell_latlon' )
-    ATM_evap        = lmdz.geo2point ( d_ATM_his ['evap']     , dim1D='cell_latlon' )
-    ATM_wevap_ter   = lmdz.geo2point ( d_ATM_his ['wevap_ter'], dim1D='cell_latlon' )
-    ATM_wevap_oce   = lmdz.geo2point ( d_ATM_his ['wevap_oce'], dim1D='cell_latlon' )
-    ATM_wevap_lic   = lmdz.geo2point ( d_ATM_his ['wevap_lic'], dim1D='cell_latlon' )
-    ATM_wevap_sic   = lmdz.geo2point ( d_ATM_his ['wevap_sic'], dim1D='cell_latlon' )
-
-    ATM_wrain_ter   = lmdz.geo2point ( d_ATM_his ['wrain_ter'], dim1D='cell_latlon' )
-    ATM_wrain_oce   = lmdz.geo2point ( d_ATM_his ['wrain_oce'], dim1D='cell_latlon' )
-    ATM_wrain_lic   = lmdz.geo2point ( d_ATM_his ['wrain_lic'], dim1D='cell_latlon' )
-    ATM_wrain_sic   = lmdz.geo2point ( d_ATM_his ['wrain_sic'], dim1D='cell_latlon' )
-
-    ATM_wsnow_ter   = lmdz.geo2point ( d_ATM_his ['wsnow_ter'], dim1D='cell_latlon' )
-    ATM_wsnow_oce   = lmdz.geo2point ( d_ATM_his ['wsnow_oce'], dim1D='cell_latlon' )
-    ATM_wsnow_lic   = lmdz.geo2point ( d_ATM_his ['wsnow_lic'], dim1D='cell_latlon' )
-    ATM_wsnow_sic   = lmdz.geo2point ( d_ATM_his ['wsnow_sic'], dim1D='cell_latlon' )
-
-    ATM_wevap_ter   = lmdz.geo2point ( d_ATM_his ['wevap_ter'], dim1D='cell_latlon' )
-    ATM_wevap_oce   = lmdz.geo2point ( d_ATM_his ['wevap_oce'], dim1D='cell_latlon' )
-    ATM_wevap_lic   = lmdz.geo2point ( d_ATM_his ['wevap_lic'], dim1D='cell_latlon' )
-    ATM_wevap_sic   = lmdz.geo2point ( d_ATM_his ['wevap_sic'], dim1D='cell_latlon' )
-    
-    ATM_runofflic   = lmdz.geo2point ( d_ATM_his ['runofflic'], dim1D='cell_latlon' )
-    
-print ( 'Step {Step}', end='' ) ; Step += 1
+    echo ( ' latlon case' )
+    ATM_wbilo_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_oce']), dim1D='cell' )
+    ATM_wbilo_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_sic']), dim1D='cell' )
+    ATM_wbilo_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_ter']), dim1D='cell' )
+    ATM_wbilo_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_lic']), dim1D='cell' )
+    ATM_runofflic   = lmdz.geo2point ( rprec (d_ATM_his ['runofflic']), dim1D='cell' )
+    ATM_fqcalving   = lmdz.geo2point ( rprec (d_ATM_his ['fqcalving']), dim1D='cell' )
+    ATM_fqfonte     = lmdz.geo2point ( rprec (d_ATM_his ['fqfonte']  ), dim1D='cell' )
+    ATM_precip      = lmdz.geo2point ( rprec (d_ATM_his ['precip']   ), dim1D='cell' )
+    ATM_snowf       = lmdz.geo2point ( rprec (d_ATM_his ['snow']     ), dim1D='cell' )
+    ATM_evap        = lmdz.geo2point ( rprec (d_ATM_his ['evap']     ), dim1D='cell' )
+    ATM_wevap_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_ter']), dim1D='cell' )
+    ATM_wevap_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_oce']), dim1D='cell' )
+    ATM_wevap_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_lic']), dim1D='cell' )
+    ATM_wevap_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_sic']), dim1D='cell' )
+    ATM_wrain_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_ter']), dim1D='cell' )
+    ATM_wrain_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_oce']), dim1D='cell' )
+    ATM_wrain_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_lic']), dim1D='cell' )
+    ATM_wrain_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_sic']), dim1D='cell' )
+    ATM_wsnow_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_ter']), dim1D='cell' )
+    ATM_wsnow_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_oce']), dim1D='cell' )
+    ATM_wsnow_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_lic']), dim1D='cell' )
+    ATM_wsnow_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_sic']), dim1D='cell' )
+    ATM_runofflic   = lmdz.geo2point ( rprec (d_ATM_his ['runofflic']), dim1D='cell' )
+    echo ( f'End of LATLON case')
+    
 if ATM_HIS == 'ico' :
-    ATM_wbilo_oce   = d_ATM_his ['wbilo_oce'][..., ATM_his_keysort]
-    ATM_wbilo_sic   = d_ATM_his ['wbilo_sic'][..., ATM_his_keysort]
-    ATM_wbilo_ter   = d_ATM_his ['wbilo_ter'][..., ATM_his_keysort]
-    ATM_wbilo_lic   = d_ATM_his ['wbilo_lic'][..., ATM_his_keysort]
-    ATM_runofflic   = d_ATM_his ['runofflic'][..., ATM_his_keysort]
-    ATM_fqcalving   = d_ATM_his ['fqcalving'][..., ATM_his_keysort]
-    ATM_fqfonte     = d_ATM_his ['fqfonte']  [..., ATM_his_keysort]
-    ATM_precip      = d_ATM_his ['precip']   [..., ATM_his_keysort]
-    ATM_snowf       = d_ATM_his ['snow']     [..., ATM_his_keysort]
-    ATM_evap        = d_ATM_his ['evap']     [..., ATM_his_keysort]
-    ATM_wevap_ter   = d_ATM_his ['wevap_ter'][..., ATM_his_keysort]
-    ATM_wevap_oce   = d_ATM_his ['wevap_oce'][..., ATM_his_keysort]
-    ATM_wevap_lic   = d_ATM_his ['wevap_lic'][..., ATM_his_keysort]
-    ATM_wevap_sic   = d_ATM_his ['wevap_sic'][..., ATM_his_keysort]
-    ATM_runofflic   = d_ATM_his ['runofflic'][..., ATM_his_keysort]
-
-    ATM_wevap_ter   = d_ATM_his ['wevap_ter'][..., ATM_his_keysort]
-    ATM_wevap_oce   = d_ATM_his ['wevap_oce'][..., ATM_his_keysort]
-    ATM_wevap_lic   = d_ATM_his ['wevap_lic'][..., ATM_his_keysort]
-    ATM_wevap_sic   = d_ATM_his ['wevap_sic'][..., ATM_his_keysort]
-
-    ATM_wrain_ter   = d_ATM_his ['wrain_ter'][..., ATM_his_keysort]
-    ATM_wrain_oce   = d_ATM_his ['wrain_oce'][..., ATM_his_keysort]
-    ATM_wrain_lic   = d_ATM_his ['wrain_lic'][..., ATM_his_keysort]
-    ATM_wrain_sic   = d_ATM_his ['wrain_sic'][..., ATM_his_keysort]
-
-    ATM_wsnow_ter   = d_ATM_his ['wsnow_ter'][..., ATM_his_keysort]
-    ATM_wsnow_oce   = d_ATM_his ['wsnow_oce'][..., ATM_his_keysort]
-    ATM_wsnow_lic   = d_ATM_his ['wsnow_lic'][..., ATM_his_keysort]
-    ATM_wsnow_sic   = d_ATM_his ['wsnow_sic'][..., ATM_his_keysort]
-
-print ( 'Step {Step}', end='' ) ; Step += 1
-
+    echo (' ico case')
+    ATM_wbilo_oce   = rprec (d_ATM_his ['wbilo_oce'])[..., ATM_his_keysort]
+    ATM_wbilo_sic   = rprec (d_ATM_his ['wbilo_sic'])[..., ATM_his_keysort]
+    ATM_wbilo_ter   = rprec (d_ATM_his ['wbilo_ter'])[..., ATM_his_keysort]
+    ATM_wbilo_lic   = rprec (d_ATM_his ['wbilo_lic'])[..., ATM_his_keysort]
+    ATM_runofflic   = rprec (d_ATM_his ['runofflic'])[..., ATM_his_keysort]
+    ATM_fqcalving   = rprec (d_ATM_his ['fqcalving'])[..., ATM_his_keysort]
+    ATM_fqfonte     = rprec (d_ATM_his ['fqfonte']  )[..., ATM_his_keysort]
+    ATM_precip      = rprec (d_ATM_his ['precip']   )[..., ATM_his_keysort]
+    ATM_snowf       = rprec (d_ATM_his ['snow']     )[..., ATM_his_keysort]
+    ATM_evap        = rprec (d_ATM_his ['evap']     )[..., ATM_his_keysort]
+    ATM_wevap_ter   = rprec (d_ATM_his ['wevap_ter'])[..., ATM_his_keysort]
+    ATM_wevap_oce   = rprec (d_ATM_his ['wevap_oce'])[..., ATM_his_keysort]
+    ATM_wevap_lic   = rprec (d_ATM_his ['wevap_lic'])[..., ATM_his_keysort]
+    ATM_wevap_sic   = rprec (d_ATM_his ['wevap_sic'])[..., ATM_his_keysort]
+    ATM_runofflic   = rprec (d_ATM_his ['runofflic'])[..., ATM_his_keysort]
+    ATM_wevap_ter   = rprec (d_ATM_his ['wevap_ter'])[..., ATM_his_keysort]
+    ATM_wevap_oce   = rprec (d_ATM_his ['wevap_oce'])[..., ATM_his_keysort]
+    ATM_wevap_lic   = rprec (d_ATM_his ['wevap_lic'])[..., ATM_his_keysort]
+    ATM_wevap_sic   = rprec (d_ATM_his ['wevap_sic'])[..., ATM_his_keysort]
+    ATM_wrain_ter   = rprec (d_ATM_his ['wrain_ter'])[..., ATM_his_keysort]
+    ATM_wrain_oce   = rprec (d_ATM_his ['wrain_oce'])[..., ATM_his_keysort]
+    ATM_wrain_lic   = rprec (d_ATM_his ['wrain_lic'])[..., ATM_his_keysort]
+    ATM_wrain_sic   = rprec (d_ATM_his ['wrain_sic'])[..., ATM_his_keysort]
+    ATM_wsnow_ter   = rprec (d_ATM_his ['wsnow_ter'])[..., ATM_his_keysort]
+    ATM_wsnow_oce   = rprec (d_ATM_his ['wsnow_oce'])[..., ATM_his_keysort]
+    ATM_wsnow_lic   = rprec (d_ATM_his ['wsnow_lic'])[..., ATM_his_keysort]
+    ATM_wsnow_sic   = rprec (d_ATM_his ['wsnow_sic'])[..., ATM_his_keysort]
+    echo ( f'End of ico case ')
+
+echo ( 'ATM wprecip_oce' )
 ATM_wprecip_oce = ATM_wrain_oce + ATM_wsnow_oce
 ATM_wprecip_ter = ATM_wrain_ter + ATM_wsnow_ter
@@ -1190,6 +1287,12 @@
 ATM_wprecip_lic = ATM_wrain_lic + ATM_wsnow_lic
 
-ATM_wbilo       = ATM_wbilo_oce + ATM_wbilo_sic + ATM_wbilo_ter + ATM_wbilo_lic
-ATM_emp         = ATM_evap - ATM_precip
+ATM_wbilo       = ATM_wbilo_oce   + ATM_wbilo_sic   + ATM_wbilo_ter   + ATM_wbilo_lic
+ATM_wevap       = ATM_wevap_oce   + ATM_wevap_sic   + ATM_wevap_ter   + ATM_wevap_lic
+ATM_wprecip     = ATM_wprecip_oce + ATM_wprecip_sic + ATM_wprecip_ter + ATM_wprecip_lic
+ATM_wsnow       = ATM_wsnow_oce   + ATM_wsnow_sic   + ATM_wsnow_ter   + ATM_wsnow_lic
+ATM_wrain       = ATM_wrain_oce   + ATM_wrain_sic   + ATM_wrain_ter   + ATM_wrain_lic
+ATM_wemp        = ATM_wevap - ATM_wprecip
+ATM_emp         = ATM_evap  - ATM_precip
+
 ATM_wprecip_sea = ATM_wprecip_oce + ATM_wprecip_sic
 ATM_wsnow_sea   = ATM_wsnow_oce   + ATM_wsnow_sic
@@ -1198,55 +1301,70 @@
 ATM_wevap_sea   = ATM_wevap_sic   + ATM_wevap_oce
 
-#ATM_wemp_ter = ATM_wevap_ter - ATM_precip * ATM_fter
-#ATM_wemp_oce = ATM_wevap_oce - ATM_precip * ATM_foce
-#ATM_wemp_sic = ATM_wevap_sic - ATM_precip * ATM_fsic
-#ATM_wemp_lic = ATM_wevap_lic - ATM_precip * ATM_flic
-#ATM_wemp_sea = ATM_wevap_sic + ATM_wevap_oce - ATM_precip * ATM_fsea
-
-ATM_wemp_ter = ATM_wevap_ter - ATM_wprecip_ter 
-ATM_wemp_oce = ATM_wevap_oce - ATM_wprecip_oce
-ATM_wemp_sic = ATM_wevap_sic - ATM_wprecip_sic
-ATM_wemp_lic = ATM_wevap_lic - ATM_wprecip_lic
-ATM_wemp_sea = ATM_wevap_sic - ATM_wprecip_oce
-
-print ( 'Step {Step}', end='' ) ; Step += 1
-if RUN_HIS == 'latlon' : 
-    RUN_coastalflow = lmdz.geo2point ( d_RUN_his ['coastalflow'], dim1D='cell_latlon' ) 
-    RUN_riverflow   = lmdz.geo2point ( d_RUN_his ['riverflow']  , dim1D='cell_latlon' )
-    RUN_runoff      = lmdz.geo2point ( d_RUN_his ['runoff']     , dim1D='cell_latlon' )
-    RUN_drainage    = lmdz.geo2point ( d_RUN_his ['drainage']   , dim1D='cell_latlon' )
-    RUN_riversret   = lmdz.geo2point ( d_RUN_his ['riversret']  , dim1D='cell_latlon' )
-    
-    RUN_coastalflow_cpl = lmdz.geo2point ( d_RUN_his ['coastalflow_cpl'], dim1D='cell_latlon' ) 
-    RUN_riverflow_cpl   = lmdz.geo2point ( d_RUN_his ['riverflow_cpl']  , dim1D='cell_latlon' )
-
-print ( 'Step {Step}', end='' ) ; Step += 1
+ATM_wemp_ter    = ATM_wevap_ter - ATM_wprecip_ter
+ATM_wemp_oce    = ATM_wevap_oce - ATM_wprecip_oce
+ATM_wemp_sic    = ATM_wevap_sic - ATM_wprecip_sic
+ATM_wemp_lic    = ATM_wevap_lic - ATM_wprecip_lic
+ATM_wemp_sea    = ATM_wevap_sic - ATM_wprecip_oce
+
+if RUN_HIS == 'latlon' :
+    echo ( f'RUN costalflow Grille LATLON' )
+    if TestInterp :
+         echo ( f'RUN runoff TestInterp' )
+         RUN_runoff      = lmdz.geo2point ( rprec (d_RUN_his ['runoff_contfrac_interp']  )   , dim1D='cell' )
+         RUN_drainage    = lmdz.geo2point ( rprec (d_RUN_his ['drainage_contfrac_interp'])   , dim1D='cell' )
+    else : 
+        echo ( f'RUN runoff' )
+        RUN_runoff      = lmdz.geo2point ( rprec (d_RUN_his ['runoff']         ), dim1D='cell' )
+        RUN_drainage    = lmdz.geo2point ( rprec (d_RUN_his ['drainage']       ), dim1D='cell' )
+        
+    RUN_coastalflow     = lmdz.geo2point ( rprec (d_RUN_his ['coastalflow']    ), dim1D='cell' ) 
+    RUN_riverflow       = lmdz.geo2point ( rprec (d_RUN_his ['riverflow']      ), dim1D='cell' )
+    RUN_riversret       = lmdz.geo2point ( rprec (d_RUN_his ['riversret']      ), dim1D='cell' )
+    RUN_coastalflow_cpl = lmdz.geo2point ( rprec (d_RUN_his ['coastalflow_cpl']), dim1D='cell' ) 
+    RUN_riverflow_cpl   = lmdz.geo2point ( rprec (d_RUN_his ['riverflow_cpl']  ), dim1D='cell' )
+
 if RUN_HIS == 'ico' :
-    RUN_coastalflow =  d_RUN_his ['coastalflow'][..., RUN_his_keysort]
-    RUN_riverflow   =  d_RUN_his ['riverflow']  [..., RUN_his_keysort]
-    RUN_runoff      =  d_RUN_his ['runoff']     [..., RUN_his_keysort]
-    RUN_drainage    =  d_RUN_his ['drainage']   [..., RUN_his_keysort]
-    RUN_riversret   =  d_RUN_his ['riversret']  [..., RUN_his_keysort]
-    
-    RUN_coastalflow_cpl = d_RUN_his ['coastalflow_cpl'][..., RUN_his_keysort]
-    RUN_riverflow_cpl   = d_RUN_his ['riverflow_cpl']  [..., RUN_his_keysort]
-
-print ( 'Step {Step}', end='' ) ; Step += 1
+    echo ( f'RUN costalflow Grille ICO' )
+    RUN_coastalflow =  rprec (d_RUN_his ['coastalflow'])[..., RUN_his_keysort]
+    RUN_riverflow   =  rprec (d_RUN_his ['riverflow']  )[..., RUN_his_keysort]
+    RUN_runoff      =  rprec (d_RUN_his ['runoff']     )[..., RUN_his_keysort]
+    RUN_drainage    =  rprec (d_RUN_his ['drainage']   )[..., RUN_his_keysort]
+    RUN_riversret   =  rprec (d_RUN_his ['riversret']  )[..., RUN_his_keysort]
+    
+    RUN_coastalflow_cpl = rprec (d_RUN_his ['coastalflow_cpl'])[..., RUN_his_keysort]
+    RUN_riverflow_cpl   = rprec (d_RUN_his ['riverflow_cpl']  )[..., RUN_his_keysort]
+
+Step = 0
+
 if SRF_HIS == 'latlon' :
-    SRF_rain     = lmdz.geo2point ( d_SRF_his ['rain']  , dim1D='cell_latlon')
-    SRF_evap     = lmdz.geo2point ( d_SRF_his ['evap']  , dim1D='cell_latlon')
-    SRF_snowf    = lmdz.geo2point ( d_SRF_his ['snowf'] , dim1D='cell_latlon')
-    SRF_subli    = lmdz.geo2point ( d_SRF_his ['subli'] , dim1D='cell_latlon')
-    SRF_transpir = lmdz.geo2point ( np.sum (d_SRF_his ['transpir'], axis=1), dim1D='cell_latlon' )
-
-print ( 'Step {Step}', end='' ) ; Step += 1
+    if TestInterp :
+         echo ( f'SRF rain TestInterp' )
+         SRF_rain     = lmdz.geo2point ( rprec (d_SRF_his ['rain_contfrac_interp'] ), dim1D='cell')
+         SRF_evap     = lmdz.geo2point ( rprec (d_SRF_his ['evap_contfrac_interp'] ), dim1D='cell')
+         SRF_snowf    = lmdz.geo2point ( rprec (d_SRF_his ['snow_contfrac_interp'] ), dim1D='cell')
+         SRF_subli    = lmdz.geo2point ( rprec (d_SRF_his ['subli_contfrac_interp']), dim1D='cell')
+         SRF_transpir = lmdz.geo2point ( rprec (d_SRF_his ['transpir_contfrac_interp']).sum(dim='veget'), dim1D='cell' )
+         SRF_rain.attrs     = d_SRF_his ['rain_contfrac_interp'].attrs
+         SRF_evap.attrs     = d_SRF_his ['evap_contfrac_interp'].attrs
+         SRF_snowf.attrs    = d_SRF_his ['snow_contfrac_interp'].attrs
+         SRF_subli.attrs    = d_SRF_his ['subli_contfrac_interp'].attrs
+         SRF_transpir.attrs = d_SRF_his ['transpir_contfrac_interp'].attrs
+    else : 
+        echo ( f'SRF rain' )
+        SRF_rain     = lmdz.geo2point ( rprec (d_SRF_his ['rain'] ) , dim1D='cell')
+        SRF_evap     = lmdz.geo2point ( rprec (d_SRF_his ['evap'] ) , dim1D='cell')
+        SRF_snowf    = lmdz.geo2point ( rprec (d_SRF_his ['snowf']) , dim1D='cell')
+        SRF_subli    = lmdz.geo2point ( rprec (d_SRF_his ['subli']) , dim1D='cell')
+        SRF_transpir = lmdz.geo2point ( rprec (d_SRF_his ['transpir']).sum(dim='veget'), dim1D='cell' )
+
 if SRF_HIS == 'ico' :
-    SRF_rain     = d_SRF_his ['rain'] [..., SRF_his_keysort]
-    SRF_evap     = d_SRF_his ['evap'] [..., SRF_his_keysort]
-    SRF_snowf    = d_SRF_his ['snowf'][..., SRF_his_keysort]
-    SRF_subli    = d_SRF_his ['subli'][..., SRF_his_keysort]
-    SRF_transpir = np.sum (d_SRF_his ['transpir'], axis=1)[..., SRF_his_keysort]
-
-print ( 'Step {Step}', end='' ) ; Step += 1
+    echo ( f'SRF rain')
+    SRF_rain     = rprec (d_SRF_his ['rain'] )[..., SRF_his_keysort]
+    SRF_evap     = rprec (d_SRF_his ['evap'] )[..., SRF_his_keysort]
+    SRF_snowf    = rprec (d_SRF_his ['snowf'])[..., SRF_his_keysort]
+    SRF_subli    = rprec (d_SRF_his ['subli'])[..., SRF_his_keysort]
+    SRF_transpir = rprec (d_SRF_his ['transpir']).sum(dim='veget')[..., SRF_his_keysort]
+
+echo ( f'SRF emp' )
 SRF_transpir.attrs['units'] = d_SRF_his ['transpir'].attrs['units']
 SRF_emp      = SRF_evap - SRF_rain - SRF_snowf ; SRF_emp.attrs['units'] = SRF_rain.attrs['units']
@@ -1271,10 +1389,16 @@
     mmd2SI (VarT)
 
-print ( 'Step {Step}', end='' ) ; Step += 1
+echo ( f'RUN input' )
 RUN_input  = RUN_runoff      + RUN_drainage
 RUN_output = RUN_coastalflow + RUN_riverflow
 
-print ( 'Step {Step}', end='' ) ; Step += 1
+echo ( f'ATM flw_wbilo' )
 ATM_flx_wbilo       = ATM_flux_int ( ATM_wbilo      )
+ATM_flx_wevap       = ATM_flux_int ( ATM_wevap      )
+ATM_flx_wprecip     = ATM_flux_int ( ATM_wprecip    )
+ATM_flx_wsnow       = ATM_flux_int ( ATM_wsnow      )
+ATM_flx_wrain       = ATM_flux_int ( ATM_wrain      )
+ATM_flx_wemp        = ATM_flux_int ( ATM_wemp       )
+
 ATM_flx_wbilo_lic   = ATM_flux_int ( ATM_wbilo_lic  )
 ATM_flx_wbilo_oce   = ATM_flux_int ( ATM_wbilo_oce  )
@@ -1285,5 +1409,8 @@
 ATM_flx_fqfonte     = ATM_flux_int ( ATM_fqfonte    )
 
-print ( 'Step {Step}', end='' ) ; Step += 1
+LIC_flx_calving     = LIC_flux_int ( ATM_fqcalving  )
+LIC_flx_fqfonte     = LIC_flux_int ( ATM_fqfonte    )
+
+echo ( f'ATM flx precip' )
 ATM_flx_precip      = ATM_flux_int ( ATM_precip     )
 ATM_flx_snowf       = ATM_flux_int ( ATM_snowf      )
@@ -1291,5 +1418,10 @@
 ATM_flx_runlic      = ATM_flux_int ( ATM_runofflic  )
 
-print ( 'Step {Step}', end='' ) ; Step += 1
+LIC_flx_precip      = LIC_flux_int ( ATM_precip     )
+LIC_flx_snowf       = LIC_flux_int ( ATM_snowf      )
+LIC_flx_evap        = LIC_flux_int ( ATM_evap       )
+LIC_flx_runlic      = LIC_flux_int ( ATM_runofflic  )
+
+echo ( f'ATM flx_wrain_ter' )
 ATM_flx_wrain_ter    = ATM_flux_int ( ATM_wrain_ter )
 ATM_flx_wrain_oce    = ATM_flux_int ( ATM_wrain_oce )
@@ -1303,10 +1435,6 @@
 ATM_flx_wsnow_sic    = ATM_flux_int ( ATM_wsnow_sic )
 ATM_flx_wsnow_sea    = ATM_flux_int ( ATM_wsnow_sea )
-print ( 'Step {Step}', end='' ) ; Step += 1
-ATM_flx_wrain_ter    = ATM_flux_int ( ATM_wrain_ter )
-ATM_flx_wrain_oce    = ATM_flux_int ( ATM_wrain_oce )
-ATM_flx_wrain_lic    = ATM_flux_int ( ATM_wrain_lic )
-ATM_flx_wrain_sic    = ATM_flux_int ( ATM_wrain_sic )
-ATM_flx_wrain_sea    = ATM_flux_int ( ATM_wrain_sea )
+
+echo ( f'ATM flx_evap_ter' ) 
 ATM_flx_wevap_ter    = ATM_flux_int ( ATM_wevap_ter )
 ATM_flx_wevap_oce    = ATM_flux_int ( ATM_wevap_oce )
@@ -1325,64 +1453,57 @@
 ATM_flx_wemp_sea     = ATM_flux_int ( ATM_wemp_sea )
 
-ATM_flx_emp          = ATM_flux_int ( ATM_emp)
-
-print ( 'Step {Step}', end='' ) ; Step += 1
+ATM_flx_emp          = ATM_flux_int ( ATM_emp )
+
+echo ( f'RUN flx_coastal' )
 RUN_flx_coastal     = ONE_flux_int ( RUN_coastalflow)
+echo ( f'RUN flx_river' )
 RUN_flx_river       = ONE_flux_int ( RUN_riverflow  )
+echo ( f'RUN flx_coastal_cpl' )
 RUN_flx_coastal_cpl = ONE_flux_int ( RUN_coastalflow_cpl)
+echo ( f'RUN flx_river_cpl' )
 RUN_flx_river_cpl   = ONE_flux_int ( RUN_riverflow_cpl  )
+echo ( f'RUN flx_drainage' )
 RUN_flx_drainage    = SRF_flux_int ( RUN_drainage   )
+echo ( f'RUN flx_riversset' )
 RUN_flx_riversret   = SRF_flux_int ( RUN_riversret  )
+echo ( f'RUN flx_runoff' )
 RUN_flx_runoff      = SRF_flux_int ( RUN_runoff     )
+echo ( f'RUN flx_input' )
 RUN_flx_input       = SRF_flux_int ( RUN_input      )
+echo ( f'RUN flx_output' )
 RUN_flx_output      = ONE_flux_int ( RUN_output     )
 
-print ( 'Step {Step}', end='' ) ; Step += 1
-RUN_flx_bil    = RUN_flx_input   - RUN_flx_output
-RUN_flx_rivcoa = RUN_flx_coastal + RUN_flx_river
-
-prtFlux ('wbilo_oce     ', ATM_flx_wbilo_oce  , 'f' )          
-prtFlux ('wbilo_sic     ', ATM_flx_wbilo_sic  , 'f' )          
-prtFlux ('wbilo_sic+oce ', ATM_flx_wbilo_sea  , 'f' )          
-prtFlux ('wbilo_ter     ', ATM_flx_wbilo_ter  , 'f' )          
-prtFlux ('wbilo_lic     ', ATM_flx_wbilo_lic  , 'f' )          
-prtFlux ('Sum wbilo_*   ', ATM_flx_wbilo      , 'f', True)  
-prtFlux ('E-P           ', ATM_flx_emp        , 'f', True)  
-prtFlux ('calving       ', ATM_flx_calving    , 'f' ) 
-prtFlux ('fqfonte       ', ATM_flx_fqfonte    , 'f' )       
-prtFlux ('precip        ', ATM_flx_precip     , 'f' )       
-prtFlux ('snowf         ', ATM_flx_snowf      , 'f' )        
-prtFlux ('evap          ', ATM_flx_evap       , 'f' )
-prtFlux ('runoff lic    ', ATM_flx_runlic     , 'f' )
-
-prtFlux ('ATM_flx_wemp_lic     ', ATM_flx_wemp_lic      , 'f' )
-prtFlux ('ATM_flx_wemp_oce     ', ATM_flx_wemp_oce      , 'f' )
-prtFlux ('ATM_flx_wemp_sic     ', ATM_flx_wemp_sic      , 'f' )
-prtFlux ('ATM_flx_wemp_ter     ', ATM_flx_wemp_ter      , 'f' )
-
-prtFlux ('ATM_flx_wprecip_lic  ', ATM_flx_wprecip_lic   , 'f' )
-prtFlux ('ATM_flx_wprecip_oce  ', ATM_flx_wprecip_oce   , 'f' )
-prtFlux ('ATM_flx_wprecip_sic  ', ATM_flx_wprecip_sic   , 'f' )
-prtFlux ('ATM_flx_wprecip_ter  ', ATM_flx_wprecip_ter   , 'f' )
-
-prtFlux ('ATM_flx_wrain_lic    ', ATM_flx_wrain_lic     , 'f' )
-prtFlux ('ATM_flx_wrain_oce    ', ATM_flx_wrain_oce     , 'f' )
-prtFlux ('ATM_flx_wrain_sic    ', ATM_flx_wrain_sic     , 'f' )
-prtFlux ('ATM_flx_wrain_ter    ', ATM_flx_wrain_ter     , 'f' )
-
-prtFlux ('ATM_flx_wsnow_lic    ', ATM_flx_wsnow_lic     , 'f' )
-prtFlux ('ATM_flx_wsnow_oce    ', ATM_flx_wsnow_oce     , 'f' )
-prtFlux ('ATM_flx_wsnow_sic    ', ATM_flx_wsnow_sic     , 'f' )
-prtFlux ('ATM_flx_wsnow_ter    ', ATM_flx_wsnow_ter     , 'f' )
-
-prtFlux ('ATM_flx_wevap_lic    ', ATM_flx_wevap_lic     , 'f' )
-prtFlux ('ATM_flx_wevap_oce    ', ATM_flx_wevap_oce     , 'f' )
-prtFlux ('ATM_flx_wevap_sic    ', ATM_flx_wevap_sic     , 'f' )
-prtFlux ('ATM_flx_wevap_ter    ', ATM_flx_wevap_ter     , 'f' )
-
-prtFlux ('ATM_flx_wevap_lic    ', ATM_flx_wevap_lic     , 'f' )
-prtFlux ('ATM_flx_wevap_oce    ', ATM_flx_wevap_oce     , 'f' )
-prtFlux ('ATM_flx_wevap_sic    ', ATM_flx_wevap_sic     , 'f' )
-prtFlux ('ATM_flx_wevap_ter    ', ATM_flx_wevap_ter     , 'f' )
+echo ( f'RUN flx_bil' ) ; Step += 1
+#RUN_flx_bil    = RUN_flx_input   - RUN_flx_output
+#RUN_flx_rivcoa = RUN_flx_coastal + RUN_flx_river
+
+RUN_flx_bil    = ONE_flux_int ( RUN_input       - RUN_output)
+RUN_flx_rivcoa = ONE_flux_int ( RUN_coastalflow + RUN_riverflow)
+
+prtFlux ('wbilo_oce            ', ATM_flx_wbilo_oce     , 'f' )          
+prtFlux ('wbilo_sic            ', ATM_flx_wbilo_sic     , 'f' )          
+prtFlux ('wbilo_sic+oce        ', ATM_flx_wbilo_sea     , 'f' )          
+prtFlux ('wbilo_ter            ', ATM_flx_wbilo_ter     , 'f' )          
+prtFlux ('wbilo_lic            ', ATM_flx_wbilo_lic     , 'f' )          
+prtFlux ('Sum wbilo_*          ', ATM_flx_wbilo         , 'f', True)  
+prtFlux ('E-P                  ', ATM_flx_emp           , 'f', True)  
+prtFlux ('calving              ', ATM_flx_calving       , 'f' ) 
+prtFlux ('fqfonte              ', ATM_flx_fqfonte       , 'f' )       
+prtFlux ('precip               ', ATM_flx_precip        , 'f' )       
+prtFlux ('snowf                ', ATM_flx_snowf         , 'f' )        
+prtFlux ('evap                 ', ATM_flx_evap          , 'f' )
+prtFlux ('runoff lic           ', ATM_flx_runlic        , 'f' )
+
+prtFlux ('ATM_flx_wevap*       ', ATM_flx_wevap         , 'f' )
+prtFlux ('ATM_flx_wrain*       ', ATM_flx_wrain         , 'f' )
+prtFlux ('ATM_flx_wsnow*       ', ATM_flx_wsnow         , 'f' )
+prtFlux ('ATM_flx_wprecip*     ', ATM_flx_wprecip       , 'f' )
+prtFlux ('ATM_flx_wemp*        ', ATM_flx_wemp          , 'f', True )
+
+prtFlux ('ERROR evap           ', ATM_flx_wevap   - ATM_flx_evap  , 'e', True )
+prtFlux ('ERROR precip         ', ATM_flx_wprecip - ATM_flx_precip, 'e', True )
+prtFlux ('ERROR snow           ', ATM_flx_wsnow   - ATM_flx_snowf , 'e', True )
+prtFlux ('ERROR emp            ', ATM_flx_wemp    - ATM_flx_emp   , 'e', True )
+
 
 echo ( '\n====================================================================================' )
@@ -1401,4 +1522,6 @@
 
 ATM_flx_budget = -ATM_flx_wbilo + ATM_flx_calving + ATM_flx_runlic #+ ATM_flx_fqfonte + RUN_flx_river
+
+
 echo ('')
 #echo ('  Global        {:12.3e} kg | {:12.4f} Sv | {:12.4f} m '.format ( ATM_flx_budget , ATM_flx_budget / dtime_sec*1E-9, ATM_flx_budget /ATM_aire_sea_tot/ATM_rho ))
@@ -1427,9 +1550,8 @@
 echo ( '\n====================================================================================' )
 
-ATM_flx_runofflic_lic = ATM_flux_int ( ATM_runofflic * ATM_flic )
-
-LIC_flx_budget1 = -ATM_flx_wemp_lic  - ATM_flx_calving - ATM_flx_fqfonte
-LIC_flx_budget2 = -ATM_flx_wbilo_lic - ATM_flx_calving - ATM_flx_fqfonte
-LIC_flx_budget3 = -ATM_flx_wbilo_lic - ATM_flx_runofflic_lic
+LIC_flx_budget1 = Sprec ( [-ATM_flx_wemp_lic  , -LIC_flx_calving , -LIC_flx_fqfonte] )
+LIC_flx_budget2 = Sprec ( [-ATM_flx_wbilo_lic , -LIC_flx_calving , -LIC_flx_fqfonte] )
+LIC_flx_budget3 = Sprec ( [-ATM_flx_wbilo_lic , -LIC_flx_runlic] )
+LIC_flx_budget4 = Sprec ( [-ATM_flx_wemp_lic  , -LIC_flx_runlic] )
 
 echo ( f'--  LIC  -- {Title} ' )
@@ -1438,20 +1560,21 @@
 echo ( f'Mass qs      begin = {LIC_mas_qs_beg     :12.6e} kg | Mass end = {LIC_mas_qs_end     :12.6e} kg' )
 echo ( f'Mass runlic0 begin = {LIC_mas_runlic0_beg:12.6e} kg | Mass end = {LIC_mas_runlic0_end:12.6e} kg' )
-prtFlux ( 'dmass (LIC sno)       ', dLIC_mas_sno          , 'f', True, width=65 )
-prtFlux ( 'dmass (LIC qs)        ', dLIC_mas_qs           , 'e', True, width=65 )
-prtFlux ( 'dmass (LIC wat)       ', dLIC_mas_wat          , 'f', True, width=65 )
-prtFlux ( 'dmass (LIC runlic0)   ', dLIC_mas_runlic0      , 'e', True, width=65 )
-prtFlux ( 'dmass (LIC total)     ', dLIC_mas_wat          , 'e', True, width=65 )
-prtFlux ( 'LIC ATM_flx_wemp_lic  ', ATM_flx_wemp_lic      , 'f', True, width=65 )
-prtFlux ( 'LIC ATM_flx_fqfonte   ', ATM_flx_fqfonte       , 'f', True, width=65 )
-prtFlux ( 'LIC ATM_flx_calving   ', ATM_flx_calving       , 'f', True, width=65 )
-prtFlux ( 'LIC ATM_flx_runofflic ', ATM_flx_runofflic_lic , 'f', True, width=65 )
-prtFlux ( 'LIC fqfonte + calving ', ATM_flx_calving+ATM_flx_fqfonte , 'f', True, width=65 )
-prtFlux ( 'LIC fluxes 1 (wevap - precip*frac_lic  - fqcalving - fqfonte) ', LIC_flx_budget1              , 'f', True, width=65 )
-prtFlux ( 'LIC fluxes 2 (-wbilo_lic - fqcalving - fqfonte)               ', LIC_flx_budget2              , 'f', True, width=65 )
-prtFlux ( 'LIC fluxes 3 (-wbilo_lic - runofflic*frac_lic)                ', LIC_flx_budget3              , 'f', True, width=65 )
-prtFlux ( 'LIC error 1                                                   ', LIC_flx_budget1-dLIC_mas_wat , 'e', True, width=65 )
-prtFlux ( 'LIC error 2                                                   ', LIC_flx_budget2-dLIC_mas_wat , 'e', True, width=65 )
-prtFlux ( 'LIC error 3                                                   ', LIC_flx_budget3-dLIC_mas_wat , 'e', True, width=65 )
+prtFlux ( 'dmass (LIC sno)       ', dLIC_mas_sno          , 'f', True, width=45 )
+prtFlux ( 'dmass (LIC qs)        ', dLIC_mas_qs           , 'e', True, width=45 )
+prtFlux ( 'dmass (LIC wat)       ', dLIC_mas_wat          , 'f', True, width=45 )
+prtFlux ( 'dmass (LIC runlic0)   ', dLIC_mas_runlic0      , 'e', True, width=45 )
+prtFlux ( 'dmass (LIC total)     ', dLIC_mas_wat          , 'e', True, width=45 )
+prtFlux ( 'LIC ATM_flx_wemp_lic  ', ATM_flx_wemp_lic      , 'f', True, width=45 )
+prtFlux ( 'LIC LIC_flx_fqfonte   ', LIC_flx_fqfonte       , 'f', True, width=45 )
+prtFlux ( 'LIC LIC_flx_calving   ', LIC_flx_calving       , 'f', True, width=45 )
+prtFlux ( 'LIC LIC_flx_runofflic ', LIC_flx_runlic        , 'f', True, width=45 )
+prtFlux ( 'LIC fqfonte + calving ', LIC_flx_calving+LIC_flx_fqfonte , 'f', True, width=45 )
+prtFlux ( 'LIC fluxes 1 ( wemp_lic   - fqcalving - fqfonte)) ', LIC_flx_budget1              , 'f', True, width=45 )
+prtFlux ( 'LIC fluxes 2 (-wbilo_lic - fqcalving - fqfonte)   ', LIC_flx_budget2              , 'f', True, width=45 )
+prtFlux ( 'LIC fluxes 3 (-wbilo_lic - runofflic*frac_lic)    ', LIC_flx_budget3              , 'f', True, width=45 )
+prtFlux ( 'LIC fluxes 3 ( wemp_lic  - runofflic*frac_lic)    ', LIC_flx_budget4              , 'f', True, width=45 )
+prtFlux ( 'LIC error 1                                       ', LIC_flx_budget1-dLIC_mas_wat , 'e', True, width=45 )
+prtFlux ( 'LIC error 2                                       ', LIC_flx_budget2-dLIC_mas_wat , 'e', True, width=45 )
+prtFlux ( 'LIC error 3                                       ', LIC_flx_budget3-dLIC_mas_wat , 'e', True, width=45 )
 echo ( 'LIC error (wevap - precip*frac_lic  - fqcalving - fqfonte)    = {:12.4e} (rel) '.format ( (LIC_flx_budget1-dLIC_mas_wat)/dLIC_mas_wat) )
 echo ( 'LIC error (-wbilo_lic - fqcalving - fqfonte)                  = {:12.4e} (rel) '.format ( (LIC_flx_budget2-dLIC_mas_wat)/dLIC_mas_wat) )
@@ -1468,8 +1591,8 @@
 SRF_flx_emp      = SRF_flux_int ( SRF_emp      )
 
-RUN_flx_torouting  =  RUN_flx_runoff  + RUN_flx_drainage
-RUN_flx_fromrouting = RUN_flx_coastal + RUN_flx_river
-
-SRF_flx_all = SRF_flx_rain + SRF_flx_snowf - SRF_flx_evap - RUN_flx_runoff - RUN_flx_drainage
+RUN_flx_torouting   = SRF_flux_int  ( RUN_runoff       + RUN_drainage)
+RUN_flx_fromrouting = ONE_flux_int  ( RUN_coastalflow + RUN_riverflow )
+
+SRF_flx_all =  SRF_flux_int  ( SRF_rain + SRF_snowf - SRF_evap - RUN_runoff - RUN_drainage )
 
 prtFlux ('rain         ', SRF_flx_rain       , 'f' )
Index: TOOLS/WATER_BUDGET/CPL_waterbudget.py
===================================================================
--- TOOLS/WATER_BUDGET/CPL_waterbudget.py	(revision 6620)
+++ TOOLS/WATER_BUDGET/CPL_waterbudget.py	(revision 6647)
@@ -12,5 +12,5 @@
 ##
 ##
-## SVN information
+# SVN information
 #  $Author$
 #  $Date$
@@ -19,5 +19,12 @@
 #  $HeadURL$
 
-
+# SVN Information
+SVN = {
+    'Author'  : "$Author$",
+    'Date'    : "$Date$",
+    'Revision': "$Revision$",
+    'Id'      : "$Id$",
+    'HeadURL' : "$HeadUrl:  $"
+    }
 ###
 ## Import system modules
@@ -27,4 +34,12 @@
 from pathlib import Path
 
+###
+## Import system modules
+import sys, os, shutil#, subprocess, platform
+import configparser, re
+
+## Import needed scientific modules
+import numpy as np, xarray as xr
+
 # Check python version
 if sys.version_info < (3, 8, 0) :
@@ -32,25 +47,53 @@
     raise Exception ( "Minimum Python version is 3.8" )
 
-## Import local module
+## Import local modules
 import WaterUtils as wu
+import libIGCM_sys
+import nemo, lmdz
+
+from WaterUtils import VarInt, Rho, Ra, Grav, ICE_rho_ice, ICE_rho_sno, OCE_rho_liq, ATM_rho, SRF_rho, RUN_rho, ICE_rho_pnd, YearLength
 
 ## Creates parser for reading .ini input file
-config = configparser.ConfigParser (interpolation=configparser.ExtendedInterpolation() )
+## -------------------------------------------
+config = configparser.ConfigParser ( interpolation=configparser.ExtendedInterpolation() )
 config.optionxform = str # To keep capitals
 
 ## Experiment parameters
-ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False ; OCE_icb=False ; Coupled=False ; Routing=None ;  TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None
+## ---------------------
+ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False
+OCE_icb=False ; Coupled=False ; Routing=None ; TestInterp=None
+TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None
+YearBegin=None ; YearEnd=None ; DateBegin=None ; DateEnd=None
 
 ##
-ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None
-TmpDir=None ; RunDir=None ; FileOut=None ; dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None ; FileCommon=None
-file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None ; file_OCE_his=None ;  file_ICE_his=None ; file_OCE_sca=None
-tar_restart_beg=None ; tar_restart_end=None ; file_ATM_beg=None ; file_ATM_end=None ; file_DYN_beg=None ; file_DYN_end=None ; file_SRF_beg=None ; file_SRF_end=None
-file_RUN_beg=None ; file_RUN_end=None ; file_RUN_end=None ; file_OCE_beg=None ; file_ICE_beg=None ; file_OCE_beg=None ; file_OCE_end=None ; file_OCE_srf=None ; file_OCE_sca=None ; file_ICE_beg=None ; file_OCE_end=None ; file_ICE_end=None
-
-# Read command line arguments
+ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None ; TmpDir=None
+FileDir=None ; FileOut=None
+dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None
+FileCommon=None ; file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None
+file_OCE_his=None ;  file_ICE_his=None ; file_OCE_sca=None ; file_OCE_srf=None
+tar_restart_beg=None ; tar_restart_end=None ; file_ATM_beg=None ; file_ATM_end=None ; file_DYN_beg=None
+file_DYN_end=None ; file_SRF_beg=None ; file_SRF_end=None
+file_RUN_beg=None ; file_RUN_end=None ; file_RUN_end=None ; file_OCE_beg=None
+file_ICE_beg=None ; file_OCE_beg=None
+file_OCE_end=None ; file_ICE_beg=None ; file_OCE_end=None ; file_ICE_end=None
+tar_restart_beg_ATM=None ; tar_restart_beg_DYN=None ; tar_restart_beg_SRF=None
+tar_restart_beg_RUN=None ; tar_restart_beg_OCE=None ; tar_restart_beg_ICE=None
+tar_restart_end_ATM=None ; tar_restart_end_DYN=None ; tar_restart_end_SRF=None
+tar_restart_end_RUN=None ; tar_restart_end_OCE=None ; tar_restart_end_ICE=None
+ContinueOnError=False ; ErrorCount=0 ; SortIco = False
+
+##
+## Precision of history file reading
+## ---------------------------------
+# Default is float (full precision). Degrade the precision by using np.float32
+# Restart file are always read at the full precision
+readPrec=float
+
+## Read command line arguments
+## ---------------------------
 print ( "Name of Python script:", sys.argv[0] )
 IniFile = sys.argv[1]
-# Text existence of IniFile
+
+# Test existence of IniFile
 if not os.path.exists (IniFile ) :
     raise FileExistsError ( f"File not found : {IniFile = }" )
@@ -63,33 +106,90 @@
 FullIniFile = 'full_' + IniFile
 
+## Reading config.card if possible
+## -------------------------------
+ConfigCard = None
+
+if 'Experiment' in config.keys ()  : ## Read Experiment on Config file if possible
+    if 'ConfigCard' in config['Experiment'].keys () :
+        ConfigCard = config['Experiment']['ConfigCard']
+        print ( f'{ConfigCard=}' )
+
+if ConfigCard : ## Read config card if it exists
+    # Text existence of ConfigCard
+    if os.path.exists ( ConfigCard ) :
+        print ( f'Reading Config Card : {ConfigCard}' )
+        ## Creates parser for reading .ini input file
+        MyReader = configparser.ConfigParser (interpolation=configparser.ExtendedInterpolation() )
+        MyReader.optionxform = str # To keep capitals
+        
+        MyReader.read (ConfigCard)
+
+        for VarName in ['JobName', 'ExperimentName', 'SpaceName', 'LongName', 'ModelName', 'TagName'] :
+            if VarName in MyReader['UserChoices'].keys() :
+                locals()[VarName] = MyReader['UserChoices'][VarName]
+                exec  ( f'{VarName} = wu.setBool ({VarName})' )
+                exec  ( f'{VarName} = wu.setNum  ({VarName})' )
+                exec  ( f'{VarName} = wu.setNone ({VarName})' )
+                exec  ( f'wu.{VarName} = {VarName}' )
+                print ( f'    {VarName:21} set to : {locals()[VarName]:}' )
+                
+        for VarName in ['PackFrequency'] :
+            if VarName in MyReader['Post'].keys() :
+                locals()[VarName] = MyReader['Post'][VarName]
+                exec  ( f'{VarName} = wu.setBool ({VarName})' )
+                exec  ( f'{VarName} = wu.setNum  ({VarName})' )
+                exec  ( f'{VarName} = wu.setNone ({VarName})' )
+                exec  ( f'wu.{VarName} = {VarName}' )
+                print ( f'    {VarName:21} set to : {locals()[VarName]:}' )
+    else :
+        raise FileExistsError ( f"File not found : {ConfigCard = }" )
+
+    
 ## Reading config file
-for Section in ['Experiment', 'libIGCM', 'Files', 'Physics' ] :
+## -------------------
+for Section in ['Config', 'Experiment', 'libIGCM', 'Files', 'Physics' ] :
    if Section in config.keys () : 
-        print ( f'Reading [{Section}]' )
+        print ( f'\nReading [{Section}]' )
         for VarName in config[Section].keys() :
             locals()[VarName] = config[Section][VarName]
-            exec ( f'{VarName} = wu.setBool ({VarName})' )
-            exec ( f'{VarName} = wu.setNum  ({VarName})' )
-            exec ( f'{VarName} = wu.setNone ({VarName})' )
-            exec (  f'wu.{VarName} = {VarName}' )
-            print ( '{:25} set to : {:}'.format (VarName, locals()[VarName]) )
+            exec  ( f'{VarName} = wu.setBool ({VarName})' )
+            exec  ( f'{VarName} = wu.setNum  ({VarName})' )
+            exec  ( f'{VarName} = wu.setNone ({VarName})' )
+            exec  ( f'wu.{VarName} = {VarName}' )
+            print ( f'    {VarName:21} set to : {locals()[VarName]}' )
             #exec ( f'del {VarName}' )
 
-#-- Some physical constants
-if wu.unDefined ( 'Ra' )           : Ra          = 6366197.7236758135 #-- Earth Radius (m)
-if wu.unDefined ( 'Grav' )         : Grav        = 9.81               #-- Gravity (m^2/s
-if wu.unDefined ( 'ICE_rho_ice' )  : ICE_rho_ice = 917.0              #-- Ice volumic mass (kg/m3) in LIM3
-if wu.unDefined ( 'ICE_rho_sno')   : ICE_rho_sno = 330.0              #-- Snow volumic mass (kg/m3) in LIM3
-if wu.unDefined ( 'OCE_rho_liq' )  : OCE_rho_liq = 1026.0             #-- Ocean water volumic mass (kg/m3) in NEMO
-if wu.unDefined ( 'ATM_rho' )      : ATM_rho     = 1000.0             #-- Water volumic mass in atmosphere (kg/m^3)
-if wu.unDefined ( 'SRF_rho' )      : SRF_rho     = 1000.0             #-- Water volumic mass in surface reservoir (kg/m^3)
-if wu.unDefined ( 'RUN_rho' )      : RUN_rho     = 1000.0             #-- Water volumic mass of rivers (kg/m^3)
-if wu.unDefined ( 'ICE_rho_pnd' )  : ICE_rho_pnd = 1000.              #-- Water volumic mass in ice ponds (kg/m^3)
-if wu.unDefined ( 'YearLength' )   : YearLength  = 365.25 * 24. * 60. * 60. #-- Year length (s) - Use only to compute drif in approximate unit 
-
-# Set libIGCM and machine dependant values
-if not 'Files' in config.keys() : config['Files'] = {}
-
-config['Physics'] = { 'Ra':Ra, 'Grav':Grav, 'ICE_rho_ice':ICE_rho_ice, 'ICE_rho_sno':ICE_rho_sno, 'OCE_rho_liq':OCE_rho_liq, 'ATM_rho':ATM_rho, 'SRF_rho':SRF_rho, 'RUN_rho':RUN_rho}
+print ( f'\nConfig file readed : {IniFile} ' )
+
+##
+## Reading prec
+if wu.unDefined ( 'readPrec' )  :
+    readPrec = np.float64
+else :
+    if readPrec in ["float", "float64", "r8", "double", "<class 'float'>"         ] : readPrec = float
+    if readPrec in [         "float32", "r4", "single", "<class 'numpy.float32'>" ] : readPrec = np.float32
+    if readPrec in [         "float16", "r2", "half"  , "<class 'numpy.float16'>" ] : readPrec = np.float16
+    
+## Some physical constants
+## =======================
+if wu.unDefined ( 'Ra' )           : Ra          = wu.Ra           #-- Earth Radius (m)
+if wu.unDefined ( 'Grav' )         : Grav        = wu.Grav         #-- Gravity (m^2/s
+if wu.unDefined ( 'ICE_rho_ice' )  : ICE_rho_ice = wu.ICE_rho_ice  #-- Ice volumic mass (kg/m3) in LIM3
+if wu.unDefined ( 'ICE_rho_sno')   : ICE_rho_sno = wu.ICE_rho_sno  #-- Snow volumic mass (kg/m3) in LIM3
+if wu.unDefined ( 'OCE_rho_liq' )  : OCE_rho_liq = wu.OCE_rho_liq  #-- Ocean water volumic mass (kg/m3) in NEMO
+if wu.unDefined ( 'ATM_rho' )      : ATM_rho     = wu.ATM_rho      #-- Water volumic mass in atmosphere (kg/m^3)
+if wu.unDefined ( 'SRF_rho' )      : SRF_rho     = wu.SRF_rho      #-- Water volumic mass in surface reservoir (kg/m^3)
+if wu.unDefined ( 'RUN_rho' )      : RUN_rho     = wu.RUN_rho      #-- Water volumic mass of rivers (kg/m^3)
+if wu.unDefined ( 'ICE_rho_pnd' )  : ICE_rho_pnd = wu.ICE_rho_pnd  #-- Water volumic mass in ice ponds (kg/m^3)
+if wu.unDefined ( 'YearLength' )   : YearLength  = wu.YearLength   #-- Year length (s)
+
+## Set libIGCM and machine dependant values
+## ----------------------------------------
+if not 'Files' in config.keys () : config['Files'] = {}
+
+config['Physics'] = { 'Ra':str(Ra), 'Grav':str(Grav), 'ICE_rho_ice':str(ICE_rho_ice), 'ICE_rho_sno':str(ICE_rho_sno),
+                      'OCE_rho_liq':str(OCE_rho_liq), 'ATM_rho':str(ATM_rho), 'SRF_rho':str(SRF_rho), 'RUN_rho':str(RUN_rho)}
+
+config['Config'] = { 'ContinueOnError':str(ContinueOnError), 'SortIco':str(SortIco), 'TestInterp':str(TestInterp), 'readPrec':str(readPrec) }
 
 ## --------------------------
@@ -97,22 +197,60 @@
 LMDZ = ( 'LMD' in wu.ATM )
 
-with open ('SetLibIGCM.py') as f: exec ( f.read() )
+mm = libIGCM_sys.config ( TagName=TagName, SpaceName=SpaceName, ExperimentName=ExperimentName, JobName=JobName, User=User, Group=Group,
+             ARCHIVE=None, SCRATCHDIR=None, STORAGE=None, R_IN=None, R_OUT=None, R_FIG=None, rebuild=None, TmpDir=None, 
+             R_SAVE=None, R_FIGR=None, R_BUFR=None, R_BUF_KSH=None, REBUILD_DIR=None, POST_DIR=None )
+globals().update(mm)
+
 config['Files']['TmpDir'] = TmpDir
-
-if libIGCM :
-    config['libIGCM'] = {'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'SCRATCHDIR':SCRATCHDIR, 'R_IN':R_IN, 'rebuild':rebuild }
-
-# Import specific module
-import nemo, lmdz
-## Now import needed scientific modules
-import xarray as xr
-    
-# Output file with water budget diagnostics
-if wu.unDefined ( 'FileOut' ) : FileOut = f'CPL_waterbudget_{JobName}_{YearBegin}_{YearEnd}.out'
+config['libIGCM'] = { 'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'TmpDir':TmpDir, 'R_IN':R_IN, 'rebuild':rebuild }
+    
+## Defines begining and end of experiment
+## --------------------------------------
+if wu.unDefined ( 'DateBegin' ) :
+    DateBegin = f'{YearBegin}0101'
+    config['Experiment']['DateBegin'] = str(DateBegin)
+else :
+    YearBegin, MonthBegin, DayBegin = wu.SplitDate ( DateBegin )
+    DateBegin = wu.FormatToGregorian (DateBegin)
+    config['Experiment']['YearBegin'] = str(YearBegin)
+
+if wu.unDefined ( 'DateEnd' )   :
+    DateEnd   = f'{YearEnd}1231'
+    config['Experiment']['DateEnd'] = str(DateEnd)
+else :
+    YearEnd, MonthEnd, DayEnd = wu.SplitDate ( DateEnd )
+    DateEnd   = wu.FormatToGregorian (DateEnd)
+    config['Experiment']['DateEnd'] = str(DateEnd)
+
+if wu.unDefined ( 'PackFrequency' ) :
+    PackFrequency = YearEnd - YearBegin + 1
+    config['Experiment']['PackFrequency']   = f'{PackFrequency}'
+
+if type ( PackFrequency ) == str : 
+    if 'Y' in PackFrequency : PackFrequency = PackFrequency.replace ( 'Y', '') 
+    if 'M' in PackFrequency : PackFrequency = PackFrequency.replace ( 'M', '')
+    PackFrequency = int ( PackFrequency )
+    
+## Output file with water budget diagnostics
+## -----------------------------------------
+if wu.unDefined ( 'FileOut' ) :
+    FileOut = f'CPL_waterbudget_{JobName}_{YearBegin}_{YearEnd}'
+    if ICO : 
+        if ATM_HIS == 'latlon' : FileOut = f'{FileOut}_LATLON'
+        if ATM_HIS == 'ico'    : FileOut = f'{FileOut}_ICO'
+    if readPrec == np.float32  : FileOut = f'{FileOut}_float32'
+    FileOut = f'{FileOut}.out'
+
 config['Files']['FileOut'] = FileOut
 
 f_out = open ( FileOut, mode = 'w' )
     
-# Useful functions
+## Useful functions
+## ----------------
+if readPrec == float :
+    def rprec (tab) : return tab
+else : 
+    def rprec (tab) : return tab.astype(readPrec).astype(float)
+    
 def kg2Sv    (val, rho=ATM_rho) :
     '''From kg to Sverdrup'''
@@ -124,15 +262,15 @@
 
 def var2prt (var, small=False, rho=ATM_rho) :
-    if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000.
+    if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000
     else     :  return var , kg2Sv(var, rho=rho)      , kg2myear(var, rho=rho)
 
 def prtFlux (Desc, var, Form='F', small=False, rho=ATM_rho, width=15) :
     if small :
-        if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} mSv | {:12.4f} mm/year "
-        if Form in ['e', 'E'] : ff=" {:12.4e} kg | {:12.4e} mSv | {:12.4e} mm/year "
+        if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} mSv | {:12.4f} mm/year "
+        if Form in ['e', 'E'] : ff=" {:14.6e} kg | {:12.4e} mSv | {:12.4e} mm/year "
     else :
-        if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} Sv  | {:12.4f} m/year  "
-        if Form in ['e', 'E'] : ff=" {:12.4e} kg | {:12.4e} Sv  | {:12.4e} m/year  "
-    echo ( (' {:>{width}} = ' +ff).format (Desc, *var2prt(var, small, rho=rho), width=width ) )
+        if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} Sv  | {:12.4f} m/year  "
+        if Form in ['e', 'E'] : ff=" {:14.6e} kg | {:12.4e} Sv  | {:12.4e} m/year  "
+    echo ( (' {:>{width}} = ' +ff).format (Desc, *var2prt(var, small=small, rho=rho), width=width ) )
     return None
 
@@ -144,6 +282,31 @@
     f_out.flush ()
     return None
-    
+
+echo ( f'{ContinueOnError = }' )
+echo ( f'{SortIco         = }' )
+echo ( f'{readPrec        = }' )
+
+echo ( f'{JobName         = }' )
+echo ( f'{ConfigCard      = }' )
+echo ( f'{libIGCM         = }' )     
+echo ( f'{User            = }' )       
+echo ( f'{Group           = }' )       
+echo ( f'{Freq            = }' )       
+echo ( f'{YearBegin       = }' )     
+echo ( f'{YearEnd         = }' )     
+echo ( f'{DateBegin       = }' )
+echo ( f'{DateEnd         = }' )
+echo ( f'{PackFrequency   = }' ) 
+echo ( f'{ATM             = }' )       
+echo ( f'{Routing         = }' )       
+echo ( f'{ORCA            = }' )      
+echo ( f'{NEMO            = }' )      
+echo ( f'{Coupled         = }' )      
+echo ( f'{ATM_HIS         = }' )      
+echo ( f'{SRF_HIS         = }' )      
+echo ( f'{RUN_HIS         = }' )
+
 ## Set libIGCM directories
+## -----------------------
 if wu.unDefined ('R_OUT'      ) : R_OUT       = os.path.join ( ARCHIVE   , 'IGCM_OUT' )
 if wu.unDefined ('R_BUF'      ) : R_BUF       = os.path.join ( SCRATCHDIR, 'IGCM_OUT' )
@@ -156,21 +319,29 @@
 if wu.unDefined ('R_FIGR'     ) : R_FIGR      = os.path.join ( STORAGE, 'IGCM_OUT', L_EXP )
 
-config['libIGCM'] = { 'R_OUT':R_OUT, 'R_BUF':R_BUF, 'L_EXP':L_EXP, 'R_BUFR':R_BUFR, 'POST_DIR':POST_DIR, 'REBUILD_DIR':REBUILD_DIR, 'R_BUF_KSH':R_BUF_KSH, 'R_FIGR':R_FIGR }
-
-# Set directory to extract filesa
-if RunDir == None : RunDir = os.path.join ( TmpDir, f'WATER_{JobName}_{YearBegin}_{YearEnd}' )
-config['Files']['RunDir'] = RunDir
-
-if not os.path.isdir ( RunDir ) : os.makedirs ( RunDir )
-
-# Set directories to rebuild ocean and ice restart files
-RunDirOCE = os.path.join ( RunDir, 'OCE' )
-RunDirICE = os.path.join ( RunDir, 'ICE' )
-#RunDirATM = os.path.join ( RunDir, 'ATM' )
-#RunDirSRF = os.path.join ( RunDir, 'SRF' )
-#RunDirRUN = os.path.join ( RunDir, 'RUN' )
-#RunDirDYN = os.path.join ( RunDir, 'DYN' )
-if not os.path.exists ( RunDirOCE ) : os.mkdir ( RunDirOCE )
-if not os.path.exists ( RunDirICE ) : os.mkdir ( RunDirICE )
+config['libIGCM'].update ( { 'R_OUT':R_OUT, 'R_BUF':R_BUF, 'L_EXP':L_EXP, 'R_BUFR':R_BUFR, 'POST_DIR':POST_DIR,
+                      'REBUILD_DIR':REBUILD_DIR, 'R_BUF_KSH':R_BUF_KSH, 'R_FIGR':R_FIGR, 'rebuild':rebuild } )
+
+## Set directory to extract files
+## ------------------------------
+if wu.unDefined ( 'FileDir' ) : FileDir = os.path.join ( TmpDir, f'WATER_{JobName}' )
+config['Files']['FileDir'] = FileDir
+
+if not os.path.isdir ( FileDir ) : os.makedirs ( FileDir )
+
+##- Set directories to rebuild ocean and ice restart files
+if wu.unDefined ( 'FileDirOCE' ) : FileDirOCE = os.path.join ( FileDir, 'OCE' )
+if wu.unDefined ( 'FileDirICE' ) : FileDirICE = os.path.join ( FileDir, 'ICE' )
+if not os.path.exists ( FileDirOCE ) : os.mkdir ( FileDirOCE )
+if not os.path.exists ( FileDirICE ) : os.mkdir ( FileDirICE )
+
+echo (' ')
+echo ( f'JobName     : {JobName}'    )
+echo ( f'Comment     : {Comment}'    )
+echo ( f'TmpDir      : {TmpDir}'     )
+echo ( f'FileDir     : {FileDir}'    )
+echo ( f'FileDirOCE  : {FileDirOCE}' )
+echo ( f'FileDirICE  : {FileDirICE}' )
+
+echo ( f'\nDealing with {L_EXP}'  )
 
 echo (' ')
@@ -178,10 +349,9 @@
 echo ( f'Comment   : {Comment}'   )
 echo ( f'TmpDir    : {TmpDir}'    )
-echo ( f'RunDirOCE : {RunDirOCE}' )
-echo ( f'RunDirICE : {RunDirICE}' )
 
 echo ( f'\nDealing with {L_EXP}'  )
 
-#-- Model output directories
+## Creates model output directory names
+## ------------------------------------
 if Freq == "MO" : FreqDir =  os.path.join ('Output' , 'MO' )
 if Freq == "SE" : FreqDir =  os.path.join ('Analyse', 'SE' )
@@ -205,57 +375,72 @@
 echo ( f'{dir_SRF_his}' )
 
-#-- Creates files names
-if Period == None :
-    if Freq == 'MO' : Period = f'{YearBegin}0101_{YearEnd}1231_1M'
-    if Freq == 'SE' : Period = f'SE_{YearBegin}0101_{YearEnd}1231_1M'
+##-- Creates files names
+if wu.unDefined ( 'Period' ) :
+    if Freq == 'MO' : Period = f'{DateBegin}_{DateEnd}_1M'
+    if Freq == 'SE' : Period = f'SE_{DateBegin}_{DateEnd}_1M'
     config['Files']['Period'] = Period
-if FileCommon == None :
+
+config['Files']['DateBegin'] = DateBegin
+config['Files']['DateBegin'] = DateEnd
+
+echo ( f'Period   : {Period}' )
+
+if wu.unDefined ( 'FileCommon' ) :
     FileCommon = f'{JobName}_{Period}'
     config['Files']['FileCommon'] = FileCommon
 
-if Title == None :
-    Title = f'{JobName} : {Freq} : {YearBegin}-01-01 - {YearEnd}-12-31'
+if wu.unDefined ( 'Title' ) :
+    Title = f'{JobName} : {Freq} : {DateBegin} - {DateEnd}'
     config['Files']['Title'] = Title
-
 echo ('\nOpen history files' )
-if file_ATM_his == None : 
-    file_ATM_his = os.path.join (  dir_ATM_his, f'{FileCommon}_histmth.nc' )
+if wu.unDefined ( 'file_ATM_his' ) :
+    if ATM_HIS == 'latlon' :
+        file_ATM_his = os.path.join ( dir_ATM_his, f'{FileCommon}_histmth.nc' )
+    if ATM_HIS == 'ico' :
+        file_ATM_his = os.path.join ( dir_ATM_his, f'{FileCommon}_histmth_ico.nc' )
     config['Files']['file_ATM_his'] = file_ATM_his
-if file_SRF_his == None :
-    file_SRF_his = os.path.join (  dir_SRF_his, f'{FileCommon}_sechiba_history.nc' )
+if wu.unDefined ( 'file_SRF_his' ) :
+    if ATM_HIS == 'latlon' :
+        file_SRF_his = os.path.join ( dir_SRF_his, f'{FileCommon}_sechiba_history.nc' )
+    if ATM_HIS == 'ico' :
+        file_SRF_his = os.path.join ( dir_SRF_his, f'{FileCommon}_sechiba_history_ico.nc' )
     config['Files']['file_SRF_his'] = file_SRF_his
-#if Routing == 'SECHIBA'  :
-#     file_RUN_his = os.path.join (  dir_SRF_his, f'{FileCommon}_sechiba_history.nc' )
+
 if Routing == 'SIMPLE' :
-    if file_RUN_his == None : 
-        file_RUN_his = os.path.join (  dir_SRF_his, f'{FileCommon}_sechiba_history.nc' )
+    if file_RUN_his == None :
+        if ATM_HIS == 'latlon' :
+            file_RUN_his = os.path.join ( dir_SRF_his, f'{FileCommon}_sechiba_history.nc' )
+        if ATM_HIS == 'ico' :
+            file_RUN_his = os.path.join ( dir_SRF_his, f'{FileCommon}_sechiba_history_ico.nc' )
         config['Files']['file_RUN_his'] = file_RUN_his
-if file_OCE_his == None :
-    file_OCE_his = os.path.join (  dir_OCE_his, f'{FileCommon}_grid_T.nc' )
-    config['Files']['file_OCE_his'] = file_OCE_his
-if file_OCE_sca == None :
-    file_OCE_sca = os.path.join (  dir_OCE_his, f'{FileCommon}_scalar.nc' )
-    config['Files']['file_OCE_sca'] = file_OCE_sca
-if file_ICE_his == None :
-    file_ICE_his = os.path.join (  dir_ICE_his, f'{FileCommon}_icemod.nc' )
-    config['Files']['file_ICE_his'] = file_ICE_his
-if file_OCE_srf == None :
-    file_OCE_srf = os.path.join (  dir_OCE_his, f'{FileCommon}_grid_T.nc' )
-    config['Files']['file_OCE_srf'] = file_OCE_srf
-
-d_ATM_his = xr.open_dataset ( file_ATM_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-d_OCE_his = xr.open_dataset ( file_OCE_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-d_OCE_sca = xr.open_dataset ( file_OCE_sca, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-d_ICE_his = xr.open_dataset ( file_ICE_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-if NEMO == '3.6' :d_ICE_his = d_ICE_his.rename ( {'y_grid_T':'y', 'x_grid_T':'x'} )
-d_SRF_his = xr.open_dataset ( file_SRF_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-d_OCE_srf = xr.open_dataset ( file_OCE_srf, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-if Routing == 'SECHIBA' : d_RUN_his = d_SRF_his
-if Routing == 'SIMPLE'  : d_RUN_his = xr.open_dataset ( file_RUN_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
-
-    
+
 echo ( f'{file_ATM_his = }' )
 echo ( f'{file_SRF_his = }' )
 if Routing == 'SIMPLE' : echo ( f'{file_RUN_his = }' )
+        
+d_ATM_his = xr.open_dataset ( file_ATM_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+d_SRF_his = xr.open_dataset ( file_SRF_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+if Routing == 'SECHIBA' : d_RUN_his = d_SRF_his
+if Routing == 'SIMPLE'  : d_RUN_his = xr.open_dataset ( file_RUN_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+    
+if wu.unDefined ('file_OCE_his' ) :
+    file_OCE_his = os.path.join ( dir_OCE_his, f'{FileCommon}_grid_T.nc' )
+    file_OCE_his = file_OCE_his
+if wu.unDefined ('file_OCE_sca' ) :    
+    file_OCE_sca = os.path.join ( dir_OCE_his, f'{FileCommon}_scalar.nc' )
+    config['Files']['file_OCE_sca'] = file_OCE_sca
+if wu.unDefined ('file_OCE_srf' ) :    
+    file_OCE_srf = os.path.join ( dir_OCE_his, f'{FileCommon}_sbc.nc' )
+    config['Files']['file_OCE_srf'] = file_OCE_srf
+if wu.unDefined ( 'file_ICE_hi' ) : 
+    file_ICE_his = os.path.join ( dir_ICE_his, f'{FileCommon}_icemod.nc' )
+    config['Files']['file_ICE_his'] = file_ICE_his
+
+d_OCE_his = xr.open_dataset ( file_OCE_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+d_OCE_sca = xr.open_dataset ( file_OCE_sca, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+#d_OCE_srf = xr.open_dataset ( file_OCE_srf, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+d_ICE_his = xr.open_dataset ( file_ICE_his, use_cftime=True, decode_times=True, decode_cf=True ).squeeze()
+if NEMO == '3.6' :d_ICE_his = d_ICE_his.rename ( {'y_grid_T':'y', 'x_grid_T':'x'} )
+
 echo ( f'{file_OCE_his = }' )
 echo ( f'{file_ICE_his = }' )
@@ -264,4 +449,5 @@
 
 ## Compute run length
+## ------------------
 dtime = ( d_ATM_his.time_counter_bounds.max() - d_ATM_his.time_counter_bounds.min() )
 echo ('\nRun length : {:8.2f} days'.format ( (dtime/np.timedelta64(1, "D")).values ) )
@@ -278,177 +464,4 @@
 NbYear = dtime_sec / YearLength
 
-#-- Open restart files
-YearRes = YearBegin - 1        # Year of the restart of beginning of simulation
-YearPre = YearBegin - PackFrequency  # Year to find the tarfile of the restart of beginning of simulation
-
-config['Files']['YearPre'] = f'{YearBegin}'
-
-echo (f'Restart dates - Start : {YearRes}-12-31  /  End : {YearEnd}-12-31 ')
-
-if TarRestartPeriod_beg == None : 
-    echo (f'Restart dates - Start : {YearRes}-12-31  /  End : {YearEnd}-12-31 ')
-    TarRestartPeriod_beg = f'{YearPre}0101_{YearRes}1231'
-    config['Files']['TarRestartPeriod_beg'] = TarRestartPeriod_beg
-
-if TarRestartPeriod_end == None : 
-    YearPre = YearBegin - PackFrequency  # Year to find the tarfile of the restart of beginning of simulation
-    echo (f'Restart dates - Start : {YearRes}-12-31  /  End : {YearEnd}-12-31 ')
-    TarRestartPeriod_end = f'{YearBegin}0101_{YearEnd}1231'
-    config['Files']['TarRestartPeriod_end'] = TarRestartPeriod_end
-
-if tar_restart_beg == None :
-    tar_restart_beg = os.path.join ( R_SAVE, 'RESTART', f'{JobName}_{TarRestartPeriod_beg}_restart.tar' )
-    config['Files']['tar_restart_beg'] = tar_restart_beg
-if tar_restart_end == None :
-    tar_restart_end = os.path.join ( R_SAVE, 'RESTART', f'{JobName}_{TarRestartPeriod_end}_restart.tar' )
-    config['Files']['tar_restart_end'] = tar_restart_end
-
-echo ( f'{tar_restart_beg}' )
-echo ( f'{tar_restart_end}' )
-
-if file_ATM_beg == None : 
-    file_ATM_beg = f'{RunDir}/ATM_{JobName}_{YearRes}1231_restartphy.nc'
-    config['Files']['file_ATM_beg'] = file_ATM_beg
-if file_ATM_end == None :
-    file_ATM_end = f'{RunDir}/ATM_{JobName}_{YearEnd}1231_restartphy.nc'
-    config['Files']['file_ATM_end'] = file_ATM_end
-
-if file_DYN_beg == None :
-    if LMDZ : file_DYN_beg = f'{RunDir}/ATM_{JobName}_{YearRes}1231_restart.nc'
-    if ICO  : file_DYN_beg = f'{RunDir}/ICO_{JobName}_{YearRes}1231_restart.nc'
-    config['Files']['file_DYN_beg'] = file_DYN_beg
-    
-if file_DYN_end == None : 
-    if LMDZ : file_DYN_end = f'{RunDir}/ATM_{JobName}_{YearEnd}1231_restart.nc'
-    if ICO  : file_DYN_end = f'{RunDir}/ICO_{JobName}_{YearEnd}1231_restart.nc'
-    config['Files']['file_DYN_end'] = file_DYN_end
-    
-if file_SRF_beg == None :
-    file_SRF_beg = f'{RunDir}/SRF_{JobName}_{YearRes}1231_sechiba_rest.nc'
-    config['Files']['file_SRF_beg'] = file_SRF_beg
-if file_SRF_end == None :
-    file_SRF_end = f'{RunDir}/SRF_{JobName}_{YearEnd}1231_sechiba_rest.nc'
-    config['Files']['file_SRF_end'] = file_SRF_end
-    
-if file_OCE_beg == None : 
-    file_OCE_beg = f'{RunDir}/OCE_{JobName}_{YearRes}1231_restart.nc'
-    config['Files']['file_OCE_beg'] = file_OCE_beg
-if file_OCE_end == None :
-    file_OCE_end = f'{RunDir}/OCE_{JobName}_{YearEnd}1231_restart.nc'
-    config['Files']['file_OCE_end'] = file_OCE_end
-if file_ICE_beg == None :
-    file_ICE_beg = f'{RunDir}/ICE_{JobName}_{YearRes}1231_restart_icemod.nc'
-    config['Files']['file_ICE_beg'] = file_ICE_beg
-if file_ICE_end == None : 
-    file_ICE_end = f'{RunDir}/ICE_{JobName}_{YearEnd}1231_restart_icemod.nc'
-    config['Files']['file_ICE_end'] = file_ICE_end
-
-liste_beg = [file_ATM_beg, file_DYN_beg, file_SRF_beg]
-liste_end = [file_ATM_end, file_DYN_end, file_SRF_end]
-
-if Routing == 'SIMPLE' :
-    if file_RUN_beg == None : 
-        file_RUN_beg = f'{RunDir}/SRF_{JobName}_{YearRes}1231_routing_restart.nc'
-        config['Files']['file_RUN_beg'] = file_RUN_beg
-    if file_RUN_end == None : 
-        file_RUN_end = f'{RunDir}/SRF_{JobName}_{YearEnd}1231_routing_restart.nc'
-        config['Files']['file_RUN_end'] = file_RUN_end
-        
-    liste_beg.append ( file_RUN_beg )
-    liste_end.append ( file_RUN_end )
-    echo ( f'{file_RUN_beg = }' )
-    echo ( f'{file_RUN_end = }' )
-
-echo ( f'{file_ATM_beg = }' )
-echo ( f'{file_ATM_end = }' )
-echo ( f'{file_DYN_beg = }' )
-echo ( f'{file_DYN_end = }' )
-echo ( f'{file_SRF_beg = }' )
-echo ( f'{file_SRF_end = }' )
-echo ( f'{file_RUN_beg = }' )
-echo ( f'{file_RUN_end = }' )
-echo ( f'{file_OCE_beg = }' )
-echo ( f'{file_OCE_end = }' )
-echo ( f'{file_ICE_beg = }' )
-echo ( f'{file_ICE_end = }' )
-
-echo ('\nExtract restart files from tar : ATM, ICO and SRF')
-for resFile in liste_beg + liste_end :
-    if os.path.exists ( os.path.join (RunDir, resFile) ) :
-        echo ( f'file found : {resFile = }' )
-    else :
-        base_file = Path (file_name).stem # basename, and remove suffix
-        command =  f'cd {RunDir} ; tar xf {tar_restart_beg} {base_resFile}.nc'
-        echo ( command )
-        ierr = os.system ( command )
-        if ierr == 0 : echo ( f'tar done : {base_resFile}')
-        else         : raise Exception ( f'command failed : {command}' )
-
-echo ('\nOpening ATM SRF and ICO restart files')
-d_ATM_beg = xr.open_dataset ( os.path.join (RunDir, file_ATM_beg), decode_times=False, decode_cf=True).squeeze()
-d_ATM_end = xr.open_dataset ( os.path.join (RunDir, file_ATM_end), decode_times=False, decode_cf=True).squeeze()
-d_SRF_beg = xr.open_dataset ( os.path.join (RunDir, file_SRF_beg), decode_times=False, decode_cf=True).squeeze()
-d_SRF_end = xr.open_dataset ( os.path.join (RunDir, file_SRF_end), decode_times=False, decode_cf=True).squeeze()
-d_DYN_beg = xr.open_dataset ( os.path.join (RunDir, file_DYN_beg), decode_times=False, decode_cf=True).squeeze()
-d_DYN_end = xr.open_dataset ( os.path.join (RunDir, file_DYN_end), decode_times=False, decode_cf=True).squeeze()
-
-echo ('\nExtract and rebuild OCE and ICE restarts')
-def get_ndomain (zfile) :
-    #d_zfile = xr.open_dataset (zfile, decode_times=False).squeeze()
-    #ndomain_opa = d_zfile.attrs['DOMAIN_number_total']
-    #d_zfile.close ()
-    ndomain_opa = subprocess.getoutput ( f'ls {zfile}_*.nc | wc -l' ) #.format()
-    return int (ndomain_opa)
-
-def extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_end, RunDirComp=RunDirOCE ) :
-    '''Extract restart file from tar. Rebuild ocean files if needed'''
-    echo ( f'file to extract : {file_name} ' )
-    if os.path.exists ( file_name ) :
-        echo ( f'-- File ready : {file_name}' )
-    else : 
-        echo ( f'-- Extracting {file_name}' )
-        base_resFile = Path (file_name).stem # basename, and remove suffix
-        # Try to extract the rebuilded file
-        command =  f'cd {RunDirComp} ; tar xf {tar_restart} {base_resFile}.nc'
-        echo ( command )
-        ierr = os.system ( command )
-        if ierr == 0 :
-            echo ( f'tar done : {base_resFile}')
-            command = f'cd {RunDirComp} ; mv {base_resFile}.nc {RunDir}'
-            ierr = os.system ( command )
-            if ierr == 0 : echo ( f'command done : {command}' )
-            else         : raise Exception ( f'command failed : {command}' )
-        else :
-            if not os.path.exists ( os.path.join (RunDir, f'{base_resFile}_0000.nc') ):
-                command =  f'cd {RunDirComp} ; tar xf {tar_restart_end} {base_resFile}_*.nc'
-                echo ( command )
-                ierr = os.system ( command )
-                if ierr == 0 : echo ( f'tar done : {file_OCE_beg}')
-                else         : raise Exception ( f'command failed : {command}' )
-                echo ('extract ndomain' )
-            ndomain_opa = get_ndomain ( os.path.join (RunDir, f'{base_resFile}') )
-            command = f'cd {RunDirComp} ; {rebuild} {base_resFile} {ndomain_opa} ; mv {base_resFile}.nc {RunDir}'
-            echo ( command )
-            ierr = os.system ( command )
-            if ierr == 0 : echo ( f'Rebuild done : {base_resFile}.nc')
-            else         : raise Exception ( f'command failed : {command}' )
-
-extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_beg, RunDirComp=RunDirOCE )
-extract_and_rebuild ( file_name=file_OCE_end, tar_restart=tar_restart_end, RunDirComp=RunDirOCE )
-extract_and_rebuild ( file_name=file_ICE_beg, tar_restart=tar_restart_beg, RunDirComp=RunDirICE )
-extract_and_rebuild ( file_name=file_ICE_end, tar_restart=tar_restart_end, RunDirComp=RunDirICE )
-
-echo ('Opening OCE and ICE restart files')
-if NEMO == 3.6 : 
-    d_OCE_beg = xr.open_dataset ( os.path.join (RunDir, file_OCE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()
-    d_OCE_end = xr.open_dataset ( os.path.join (RunDir, file_OCE_end), decode_times=False, decode_cf=True).squeeze()
-    d_ICE_beg = xr.open_dataset ( os.path.join (RunDir, file_ICE_beg), decode_times=False, decode_cf=True).squeeze()
-    d_ICE_end = xr.open_dataset ( os.path.join (RunDir, file_ICE_end), decode_times=False, decode_cf=True).squeeze()
-if NEMO == 4.0 or NEMO == 4.2 : 
-    d_OCE_beg = xr.open_dataset ( os.path.join (RunDir, file_OCE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()
-    d_OCE_end = xr.open_dataset ( os.path.join (RunDir, file_OCE_end), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()
-    d_ICE_beg = xr.open_dataset ( os.path.join (RunDir, file_ICE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()
-    d_ICE_end = xr.open_dataset ( os.path.join (RunDir, file_ICE_end), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()
-
 ## Write the full configuration
 config_out = open (FullIniFile, 'w')
@@ -456,64 +469,69 @@
 config_out.close ()
 
-for var in d_SRF_beg.variables :
-    d_SRF_beg[var] = d_SRF_beg[var].where (  d_SRF_beg[var]<1.e20, 0.)
-    d_SRF_end[var] = d_SRF_end[var].where (  d_SRF_end[var]<1.e20, 0.)
-
-if ICO :
-    d_RUN_beg = xr.open_dataset ( os.path.join (RunDir, file_RUN_beg), decode_times=False, decode_cf=True).squeeze()
-    d_RUN_end = xr.open_dataset ( os.path.join (RunDir, file_RUN_end), decode_times=False, decode_cf=True).squeeze()
-
-def kg2Sv  (val, rho=OCE_rho_liq) :
-    '''From kg to Sverdrup'''
-    return val/dtime_sec*1.0e-6/rho
-
-def kg2myear (val, rho=OCE_rho_liq) :
-    '''From kg to m/year'''
-    return val/OCE_aire_tot/rho/NbYear
-
-def var2prt (var, small=False) :
-    if small :  return var , kg2Sv(var)*1000., kg2myear(var)*1000.
-    else     :  return var , kg2Sv(var)      , kg2myear(var)
-
-def prtFlux (Desc, var, Form='F', small=False) :
-    if small :
-        if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} mSv | {:12.4f} mm/year "
-        if Form in ['e', 'E'] : ff=" {:12.4e} kg | {:12.4e} mSv | {:12.4e} mm/year "
-    else :
-        if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} Sv  | {:12.4f} m/year  "
-        if Form in ['e', 'E'] : ff=" {:12.4e} kg | {:12.4e} Sv  | {:12.4e} m/year  "
-    echo ( (' {:>15} = ' +ff).format (Desc, *var2prt(var, small) ) )
-    return None
-
-
-
 # ATM grid with cell surfaces
+if LMDZ :
+    echo ('ATM grid with cell surfaces : LMDZ')
+    ATM_lat       = lmdz.geo2point (   rprec (d_ATM_his ['lat'])+0*rprec (d_ATM_his ['lon']), dim1D='cell' )
+    ATM_lon       = lmdz.geo2point ( 0*rprec (d_ATM_his ['lat'])+  rprec (d_ATM_his ['lon']), dim1D='cell' )
+    ATM_aire      = lmdz.geo2point ( rprec (d_ATM_his ['aire'] )    [0], cumulPoles=True, dim1D='cell' )
+    ATM_fter      = lmdz.geo2point ( rprec (d_ATM_his ['fract_ter'][0]), dim1D='cell' )
+    ATM_foce      = lmdz.geo2point ( rprec (d_ATM_his ['fract_oce'][0]), dim1D='cell' )
+    ATM_fsic      = lmdz.geo2point ( rprec (d_ATM_his ['fract_sic'][0]), dim1D='cell' )
+    ATM_flic      = lmdz.geo2point ( rprec (d_ATM_his ['fract_lic'][0]), dim1D='cell' )
+    SRF_lat       = lmdz.geo2point (   rprec (d_SRF_his ['lat'])+0*rprec (d_SRF_his ['lon']), dim1D='cell' )
+    SRF_lon       = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat'])+  rprec (d_SRF_his ['lon']), dim1D='cell' )
+    SRF_aire      = lmdz.geo2point ( rprec (d_SRF_his ['Areas']) * rprec (d_SRF_his ['Contfrac']), dim1D='cell', cumulPoles=True )
+    SRF_areas     = lmdz.geo2point ( rprec (d_SRF_his ['Areas'])  ,  dim1D='cell', cumulPoles=True )
+    SRF_contfrac  = lmdz.geo2point ( rprec (d_SRF_his ['Contfrac']), dim1D='cell' )
 if ICO :
     if ATM_HIS == 'latlon' :
-        jpja, jpia = d_ATM_his['aire'][0].shape   
-        file_ATM_aire = os.path.join ( R_IN, 'ATM', 'GRID', f'aire_{ATM}_to_{jpia}x{jpja}.nc' )
-        config['Files']['file_ATM_aire'] = file_ATM_aire
-        echo ( f'Aire sur grille reguliere : {file_ATM_aire = }' )
-        d_ATM_aire = xr.open_dataset ( file_ATM_aire, decode_times=False ).squeeze()
-        ATM_aire = lmdz.geo2point ( d_ATM_aire ['aire'].squeeze(), cumulPoles=True )
-        ATM_fter = lmdz.geo2point ( d_ATM_his ['fract_ter'][0] )
-        ATM_foce = lmdz.geo2point ( d_ATM_his ['fract_oce'][0] )
-        ATM_fsic = lmdz.geo2point ( d_ATM_his ['fract_sic'][0] )
-        ATM_flic = lmdz.geo2point ( d_ATM_his ['fract_lic'][0] )
-        SRF_aire = lmdz.geo2point ( d_SRF_his ['Areas'] * d_SRF_his ['Contfrac'] )
-        #SRF_aire = ATM_aire * lmdz.geo2point (d_SRF_his ['Contfrac'] )
-        #SRF_aire = ATM_aire * ATM_fter
+        echo ( 'ATM areas and fractions on latlon grid' )
+        if 'lat_dom_out' in d_ATM_his.variables :
+            ATM_lat  = lmdz.geo2point (   rprec (d_ATM_his ['lat_dom_out'])+0*rprec (d_ATM_his ['lon_dom_out']), dim1D='cell' )
+            ATM_lon  = lmdz.geo2point ( 0*rprec (d_ATM_his ['lat_dom_out'])+  rprec (d_ATM_his ['lon_dom_out']), dim1D='cell' )
+        else :
+            ATM_lat  = lmdz.geo2point (   rprec (d_ATM_his ['lat'])+0*rprec (d_ATM_his ['lon']), dim1D='cell' )
+            ATM_lon  = lmdz.geo2point ( 0*rprec (d_ATM_his ['lat'])+  rprec (d_ATM_his ['lon']), dim1D='cell' )
+        ATM_aire = lmdz.geo2point ( rprec (d_ATM_his ['aire'][0]).squeeze(), cumulPoles=True, dim1D='cell' )
+        ATM_fter = lmdz.geo2point ( rprec (d_ATM_his ['fract_ter'][0]), dim1D='cell' )
+        ATM_foce = lmdz.geo2point ( rprec (d_ATM_his ['fract_oce'][0]), dim1D='cell' )
+        ATM_fsic = lmdz.geo2point ( rprec (d_ATM_his ['fract_sic'][0]), dim1D='cell' )
+        ATM_flic = lmdz.geo2point ( rprec (d_ATM_his ['fract_lic'][0]), dim1D='cell' )
+
     if ATM_HIS == 'ico' :
-        echo ( f'Aire sur grille icosaedre : {file_ATM_aire = }' )
-        
-if LMDZ :
-    ATM_aire = lmdz.geo2point ( d_ATM_his ['aire'][0], cumulPoles=True )
-    ATM_fter = lmdz.geo2point ( d_ATM_his ['fract_ter'][0] )
-    ATM_foce = lmdz.geo2point ( d_ATM_his ['fract_oce'][0] )
-    ATM_fsic = lmdz.geo2point ( d_ATM_his ['fract_sic'][0] )
-    ATM_flic = lmdz.geo2point ( d_ATM_his ['fract_lic'][0] )
-    #SRF_aire = lmdz.geo2point ( d_SRF_his['Areas'] * d_SRF_his['Contfrac'] )
-    SRF_aire = ATM_aire * lmdz.geo2point ( d_SRF_his['Contfrac'] )
-    
+        echo ( 'ATM areas and fractions on ICO grid' )
+        ATM_aire =  rprec (d_ATM_his ['aire']     [0]).squeeze()
+        ATM_lat  =  rprec (d_ATM_his ['lat']         )
+        ATM_lon  =  rprec (d_ATM_his ['lon']         )
+        ATM_fter =  rprec (d_ATM_his ['fract_ter'][0])
+        ATM_foce =  rprec (d_ATM_his ['fract_oce'][0])
+        ATM_fsic =  rprec (d_ATM_his ['fract_sic'][0])
+        ATM_flic =  rprec (d_ATM_his ['fract_lic'][0])
+
+    if SRF_HIS == 'latlon' :
+        echo ( 'SRF areas and fractions on latlon grid' )
+        if 'lat_domain_landpoints_out' in d_SRF_his  : 
+            SRF_lat  = lmdz.geo2point (   rprec (d_SRF_his ['lat_domain_landpoints_out'])+0*rprec (d_SRF_his ['lon_domain_landpoints_out']), dim1D='cell' )
+            SRF_lon  = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat_domain_landpoints_out'])+  rprec (d_SRF_his ['lon_domain_landpoints_out']), dim1D='cell' )
+        else : 
+            if 'lat_domain_landpoints_out' in d_SRF_his :
+                SRF_lat  = lmdz.geo2point (   rprec (d_SRF_his ['lat_dom_out'])+0*rprec (d_SRF_his ['lon_dom_out']), dim1D='cell' )
+                SRF_lon  = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat_dom_out'])+  rprec (d_SRF_his ['lon_dom_out']), dim1D='cell' )
+            else :
+                SRF_lat  = lmdz.geo2point (   rprec (d_SRF_his ['lat'])+0*rprec (d_SRF_his ['lon']), dim1D='cell' )
+                SRF_lon  = lmdz.geo2point ( 0*rprec (d_SRF_his ['lat'])+  rprec (d_SRF_his ['lon']), dim1D='cell' )
+                
+        SRF_areas     = lmdz.geo2point ( rprec (d_SRF_his ['Areas']   )   , dim1D='cell', cumulPoles=True )
+        SRF_areafrac  = lmdz.geo2point ( rprec (d_SRF_his ['AreaFrac'])   , dim1D='cell', cumulPoles=True )
+        SRF_contfrac  = lmdz.geo2point ( rprec (d_SRF_his ['Contfrac'])   , dim1D='cell', cumulPoles=True )
+        SRF_aire = SRF_areafrac
+ 
+    if SRF_HIS == 'ico' :
+        echo ( 'SRF areas and fractions on latlon grid' )
+        SRF_lat       =  rprec (d_SRF_his ['lat']     )
+        SRF_lon       =  rprec (d_SRF_his ['lon']     )
+        SRF_areas     =  rprec (d_SRF_his ['Areas']   ) 
+        SRF_contfrac  =  rprec (d_SRF_his ['Contfrac'])
+        SRF_aire      =  SRF_areas * SRF_contfrac
 ATM_fsea      = ATM_foce + ATM_fsic
 ATM_flnd      = ATM_fter + ATM_flic
@@ -525,28 +543,38 @@
 ATM_aire_fsea = ATM_aire * ATM_fsea
 
-SRF_aire = SRF_aire.where ( SRF_aire < 1E15, 0.)
-
-if ICO :
-    # Area on icosahedron grid
-    file_DYN_aire = os.path.join ( R_IN, 'ATM', 'GRID', ATM+'_grid.nc' )
-    d_DYN_aire = xr.open_dataset ( file_DYN_aire, decode_times=False).squeeze()
-    d_DYN_aire = d_DYN_aire.rename ( {'cell':'cell_mesh'} )
-    DYN_aire   = d_DYN_aire['aire']
-
-    DYN_fsea = d_DYN_aire ['fract_oce'] + d_DYN_aire ['fract_sic']
-    DYN_flnd = 1.0 - DYN_fsea
-    
-if LMDZ :
-    # Area on lon/lat grid
-    DYN_aire = ATM_aire
-    DYN_fsea = ATM_fsea
-    DYN_flnd = ATM_flnd
-    DYN_fter = d_ATM_beg['FTER']
-    DYN_flic = d_ATM_beg['FTER']
-
-def ATM_stock_int (stock) :
-    '''Integrate (* surface) stock on atmosphere grid'''
-    ATM_stock_int  = wu.Psum ( (stock * DYN_aire).to_masked_array().ravel() ) 
-    return ATM_stock_int
+#SRF_aire = SRF_aire.where ( SRF_aire < 1E15, 0.)
+
+# if ICO :
+#     if wu.unDefined ('file_DYN_aire') : file_DYN_aire = os.path.join ( R_IN, 'ATM', 'GRID', ATM+'_grid.nc' )
+#     config['Files']['file_DYN_aire'] = file_DYN_aire
+
+# if ICO :
+#     # Area on icosahedron grid
+#     d_DYN_aire = xr.open_dataset ( file_DYN_aire, decode_times=False ).squeeze()
+           
+#     DYN_lat = d_DYN_aire['lat']
+#     DYN_lon = d_DYN_aire['lon']
+
+#     DYN_aire = d_DYN_aire['aire']
+#     DYN_fsea = d_DYN_aire['fract_oce'] + d_DYN_aire['fract_sic']
+#     DYN_flnd = 1.0 - DYN_fsea
+#     DYN_fter = d_ATM_beg['FTER']
+#     DYN_flic = d_ATM_beg['FLIC']
+#     DYN_aire_fter = DYN_aire * DYN_fter
+    
+# if LMDZ :
+#     # Area on lon/lat grid
+#     DYN_aire = ATM_aire
+#     DYN_fsea = ATM_fsea
+#     DYN_flnd = ATM_flnd
+#     DYN_fter = rprec (d_ATM_beg['FTER'])
+#     DYN_flic = rprec (d_ATM_beg['FLIC'])
+#     DYN_aire_fter = DYN_aire * DYN_fter
+
+# Functions computing integrals and sum
+# def ATM_stock_int (stock) :
+#     '''Integrate (* surface) stock on atmosphere grid'''
+#     ATM_stock_int  = wu.Psum ( (stock * DYN_aire).to_masked_array().ravel() ) 
+#     return ATM_stock_int
 
 def ATM_flux_int (flux) :
@@ -555,8 +583,8 @@
     return ATM_flux_int
 
-def SRF_stock_int (stock) :
-    '''Integrate (* surface) stock on land grid'''
-    ATM_stock_int  = wu.Ksum (  ( (stock * DYN_aire_fter).to_masked_array().ravel()) )
-    return ATM_stock_int
+# def SRF_stock_int (stock) :
+#     '''Integrate (* surface) stock on land grid'''
+#     ATM_stock_int  = wu.Ksum (  ( (stock * DYN_aire_fter).to_masked_array().ravel()) )
+#     return ATM_stock_int
 
 def SRF_flux_int (flux) :
@@ -565,8 +593,13 @@
     return SRF_flux_int
 
-def OCE_stock_int (stock) :
-    '''Integrate stock on ocean grid'''
-    OCE_stock_int = np.sum (  np.sort ( (stock * OCE_aire ).to_masked_array().ravel()) )
-    return OCE_stock_int
+def LIC_flux_int (flux) :
+    '''Integrate (* time * surface) flux on land ice grid'''
+    LIC_flux_int  = wu.Psum ( (flux * dtime_per_sec * ATM_aire_flic).to_masked_array().ravel() )
+    return LIC_flux_int
+
+# def OCE_stock_int (stock) :
+#     '''Integrate stock on ocean grid'''
+#     OCE_stock_int = np.sum (  np.sort ( (stock * OCE_aire ).to_masked_array().ravel()) )
+#     return OCE_stock_int
 
 def ONE_stock_int (stock) :
@@ -584,7 +617,4 @@
     OCE_flux_int = np.sum (  np.sort ( (flux * dtime_per_sec).to_masked_array().ravel()) )
     return OCE_flux_int
-    
-#if LMDZ :
-#    d_ATM_beg = d_ATM_beg.assign ( coords={'lon':d_ATM_beg.lon*180./np.pi} )
 
 # Get mask and surfaces
@@ -607,366 +637,351 @@
 
 echo ( '\n====================================================================================' )
-echo ( '-- NEMO change in stores (for the records)' )
-#-- Note that the total number of days of the run should be diagnosed rather than assumed
-#-- Here the result is in Sv
-#
-#-- Change in ocean volume in freshwater equivalent
-
-OCE_ssh_beg = d_OCE_beg['sshn']
-OCE_ssh_end = d_OCE_end['sshn']
-OCE_sum_ssh_beg = OCE_stock_int ( OCE_ssh_beg )
-OCE_sum_ssh_end = OCE_stock_int ( OCE_ssh_end )
-
-OCE_mas_wat_beg = OCE_sum_ssh_beg * OCE_rho_liq
-OCE_mas_wat_end = OCE_sum_ssh_end * OCE_rho_liq
-
-echo ( 'OCE_sum_ssh_beg = {:12.6e} m^3 | OCE_sum_ssh_end = {:12.6e} m^3'.format (OCE_sum_ssh_beg, OCE_sum_ssh_end) )
-dOCE_vol_liq = ( OCE_sum_ssh_end - OCE_sum_ssh_beg )
-dOCE_mas_liq = dOCE_vol_liq * OCE_rho_liq
-dOCE_mas_wat = dOCE_mas_liq
-
-echo ( 'dOCE vol    = {:12.3e} m^3'.format (dOCE_vol_liq) )
-echo ( 'dOCE ssh    = {:12.3e} m  '.format (dOCE_vol_liq/OCE_aire_tot) )
-echo ( 'dOCE mass   = {:12.3e} kg '.format (dOCE_mas_liq) )
-echo ( 'dOCE mass   = {:12.3e} Sv '.format (dOCE_mas_liq/dtime_sec*1E-6/OCE_rho_liq) )
-
-## Glace et neige
+echo ( f'-- ATM Fluxes  -- {Title} ' )
+
+if ATM_HIS == 'latlon' :
+    echo ( ' latlon case' )
+    ATM_wbilo_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_oce']), dim1D='cell' )
+    ATM_wbilo_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_sic']), dim1D='cell' )
+    ATM_wbilo_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_ter']), dim1D='cell' )
+    ATM_wbilo_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wbilo_lic']), dim1D='cell' )
+    ATM_runofflic   = lmdz.geo2point ( rprec (d_ATM_his ['runofflic']), dim1D='cell' )
+    ATM_fqcalving   = lmdz.geo2point ( rprec (d_ATM_his ['fqcalving']), dim1D='cell' )
+    ATM_fqfonte     = lmdz.geo2point ( rprec (d_ATM_his ['fqfonte']  ), dim1D='cell' )
+    ATM_precip      = lmdz.geo2point ( rprec (d_ATM_his ['precip']   ), dim1D='cell' )
+    ATM_snowf       = lmdz.geo2point ( rprec (d_ATM_his ['snow']     ), dim1D='cell' )
+    ATM_evap        = lmdz.geo2point ( rprec (d_ATM_his ['evap']     ), dim1D='cell' )
+    ATM_wevap_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_ter']), dim1D='cell' )
+    ATM_wevap_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_oce']), dim1D='cell' )
+    ATM_wevap_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_lic']), dim1D='cell' )
+    ATM_wevap_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wevap_sic']), dim1D='cell' )
+    ATM_wrain_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_ter']), dim1D='cell' )
+    ATM_wrain_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_oce']), dim1D='cell' )
+    ATM_wrain_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_lic']), dim1D='cell' )
+    ATM_wrain_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wrain_sic']), dim1D='cell' )
+    ATM_wsnow_ter   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_ter']), dim1D='cell' )
+    ATM_wsnow_oce   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_oce']), dim1D='cell' )
+    ATM_wsnow_lic   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_lic']), dim1D='cell' )
+    ATM_wsnow_sic   = lmdz.geo2point ( rprec (d_ATM_his ['wsnow_sic']), dim1D='cell' )
+    ATM_runofflic   = lmdz.geo2point ( rprec (d_ATM_his ['runofflic']), dim1D='cell' )
+    echo ( f'End of LATLON case')
+    
+if ATM_HIS == 'ico' :
+    echo (' ico case')
+    ATM_wbilo_oce   = rprec (d_ATM_his ['wbilo_oce'])
+    ATM_wbilo_sic   = rprec (d_ATM_his ['wbilo_sic'])
+    ATM_wbilo_ter   = rprec (d_ATM_his ['wbilo_ter'])
+    ATM_wbilo_lic   = rprec (d_ATM_his ['wbilo_lic'])
+    ATM_runofflic   = rprec (d_ATM_his ['runofflic'])
+    ATM_fqcalving   = rprec (d_ATM_his ['fqcalving'])
+    ATM_fqfonte     = rprec (d_ATM_his ['fqfonte']  )
+    ATM_precip      = rprec (d_ATM_his ['precip']   )
+    ATM_snowf       = rprec (d_ATM_his ['snow']     )
+    ATM_evap        = rprec (d_ATM_his ['evap']     )
+    ATM_wevap_ter   = rprec (d_ATM_his ['wevap_ter'])
+    ATM_wevap_oce   = rprec (d_ATM_his ['wevap_oce'])
+    ATM_wevap_lic   = rprec (d_ATM_his ['wevap_lic'])
+    ATM_wevap_sic   = rprec (d_ATM_his ['wevap_sic'])
+    ATM_runofflic   = rprec (d_ATM_his ['runofflic'])
+    ATM_wevap_ter   = rprec (d_ATM_his ['wevap_ter'])
+    ATM_wevap_oce   = rprec (d_ATM_his ['wevap_oce'])
+    ATM_wevap_lic   = rprec (d_ATM_his ['wevap_lic'])
+    ATM_wevap_sic   = rprec (d_ATM_his ['wevap_sic'])
+    ATM_wrain_ter   = rprec (d_ATM_his ['wrain_ter'])
+    ATM_wrain_oce   = rprec (d_ATM_his ['wrain_oce'])
+    ATM_wrain_lic   = rprec (d_ATM_his ['wrain_lic'])
+    ATM_wrain_sic   = rprec (d_ATM_his ['wrain_sic'])
+    ATM_wsnow_ter   = rprec (d_ATM_his ['wsnow_ter'])
+    ATM_wsnow_oce   = rprec (d_ATM_his ['wsnow_oce'])
+    ATM_wsnow_lic   = rprec (d_ATM_his ['wsnow_lic'])
+    ATM_wsnow_sic   = rprec (d_ATM_his ['wsnow_sic'])
+    echo ( f'End of ico case ')
+
+
+    
+echo ( 'ATM wprecip_oce' )
+ATM_wprecip_oce = ATM_wrain_oce + ATM_wsnow_oce
+ATM_wprecip_ter = ATM_wrain_ter + ATM_wsnow_ter
+ATM_wprecip_sic = ATM_wrain_sic + ATM_wsnow_sic
+ATM_wprecip_lic = ATM_wrain_lic + ATM_wsnow_lic
+
+ATM_wbilo       = ATM_wbilo_oce   + ATM_wbilo_sic   + ATM_wbilo_ter   + ATM_wbilo_lic
+ATM_wevap       = ATM_wevap_oce   + ATM_wevap_sic   + ATM_wevap_ter   + ATM_wevap_lic
+ATM_wprecip     = ATM_wprecip_oce + ATM_wprecip_sic + ATM_wprecip_ter + ATM_wprecip_lic
+ATM_wsnow       = ATM_wsnow_oce   + ATM_wsnow_sic   + ATM_wsnow_ter   + ATM_wsnow_lic
+ATM_wrain       = ATM_wrain_oce   + ATM_wrain_sic   + ATM_wrain_ter   + ATM_wrain_lic
+ATM_wemp        = ATM_wevap - ATM_wprecip
+ATM_emp         = ATM_evap  - ATM_precip
+
+ATM_wprecip_sea = ATM_wprecip_oce + ATM_wprecip_sic
+ATM_wsnow_sea   = ATM_wsnow_oce   + ATM_wsnow_sic
+ATM_wrain_sea   = ATM_wrain_oce   + ATM_wrain_sic
+ATM_wbilo_sea   = ATM_wbilo_oce   + ATM_wbilo_sic
+ATM_wevap_sea   = ATM_wevap_sic   + ATM_wevap_oce
+
+ATM_wemp_ter    = ATM_wevap_ter - ATM_wprecip_ter
+ATM_wemp_oce    = ATM_wevap_oce - ATM_wprecip_oce
+ATM_wemp_sic    = ATM_wevap_sic - ATM_wprecip_sic
+ATM_wemp_lic    = ATM_wevap_lic - ATM_wprecip_lic
+ATM_wemp_sea    = ATM_wevap_sic - ATM_wprecip_oce
+
+if RUN_HIS == 'latlon' :
+    echo ( f'RUN costalflow Grille LATLON' )
+    if TestInterp :
+        echo ( f'RUN runoff TestInterp' )
+        RUN_runoff      = lmdz.geo2point ( rprec (d_RUN_his ['runoff_contfrac_interp']  )   , dim1D='cell' )
+        RUN_drainage    = lmdz.geo2point ( rprec (d_RUN_his ['drainage_contfrac_interp'])   , dim1D='cell' )
+    else : 
+        echo ( f'RUN runoff' )
+        RUN_runoff      = lmdz.geo2point ( rprec (d_RUN_his ['runoff']         ), dim1D='cell' )
+        RUN_drainage    = lmdz.geo2point ( rprec (d_RUN_his ['drainage']       ), dim1D='cell' )
+        
+    RUN_coastalflow     = lmdz.geo2point ( rprec (d_RUN_his ['coastalflow']    ), dim1D='cell' ) 
+    RUN_riverflow       = lmdz.geo2point ( rprec (d_RUN_his ['riverflow']      ), dim1D='cell' )
+    RUN_riversret       = lmdz.geo2point ( rprec (d_RUN_his ['riversret']      ), dim1D='cell' )
+    RUN_coastalflow_cpl = lmdz.geo2point ( rprec (d_RUN_his ['coastalflow_cpl']), dim1D='cell' ) 
+    RUN_riverflow_cpl   = lmdz.geo2point ( rprec (d_RUN_his ['riverflow_cpl']  ), dim1D='cell' )
+
+if RUN_HIS == 'ico' :
+    echo ( f'RUN costalflow Grille ICO' )
+    RUN_coastalflow =  rprec (d_RUN_his ['coastalflow'])
+    RUN_riverflow   =  rprec (d_RUN_his ['riverflow']  )
+    RUN_runoff      =  rprec (d_RUN_his ['runoff']     )
+    RUN_drainage    =  rprec (d_RUN_his ['drainage']   )
+    RUN_riversret   =  rprec (d_RUN_his ['riversret']  )
+    
+    RUN_coastalflow_cpl = rprec (d_RUN_his ['coastalflow_cpl'])
+    RUN_riverflow_cpl   = rprec (d_RUN_his ['riverflow_cpl']  )
+
+## Correcting units of SECHIBA variables
+def mmd2SI ( Var ) :
+    '''Change unit from mm/d or m^3/s to kg/s if needed'''
+    if 'units' in VarT.attrs : 
+        if VarT.attrs['units'] in ['m^3/s', 'm3/s', 'm3.s-1',] :
+            VarT.values = VarT.values  * ATM_rho                 ;  VarT.attrs['units'] = 'kg/s'
+        if VarT.attrs['units'] == 'mm/d' :
+            VarT.values = VarT.values  * ATM_rho * (1e-3/86400.) ;  VarT.attrs['units'] = 'kg/s'
+        if VarT.attrs['units'] in ['m^3', 'm3', ] :
+            VarT.values = VarT.values  * ATM_rho                 ;  VarT.attrs['units'] = 'kg'
+            
+for var in [ 'runoff', 'drainage', 'riversret', 'coastalflow', 'riverflow', 'coastalflow_cpl', 'riverflow_cpl' ] :
+    VarT = locals()['RUN_' + var]
+    mmd2SI (VarT)
+
+#for var in ['evap', 'snowf', 'subli', 'transpir', 'rain', 'emp' ] :
+#    VarT = locals()['SRF_' + var]
+#    mmd2SI (VarT)
+echo ( f'RUN input' )
+RUN_input  = RUN_runoff      + RUN_drainage
+RUN_output = RUN_coastalflow + RUN_riverflow
+
+echo ( f'ATM flw_wbilo' )
+ATM_flx_wbilo       = ATM_flux_int ( ATM_wbilo      )
+ATM_flx_wevap       = ATM_flux_int ( ATM_wevap      )
+ATM_flx_wprecip     = ATM_flux_int ( ATM_wprecip    )
+ATM_flx_wsnow       = ATM_flux_int ( ATM_wsnow      )
+ATM_flx_wrain       = ATM_flux_int ( ATM_wrain      )
+ATM_flx_wemp        = ATM_flux_int ( ATM_wemp       )
+
+ATM_flx_wbilo_lic   = ATM_flux_int ( ATM_wbilo_lic  )
+ATM_flx_wbilo_oce   = ATM_flux_int ( ATM_wbilo_oce  )
+ATM_flx_wbilo_sea   = ATM_flux_int ( ATM_wbilo_sea  )
+ATM_flx_wbilo_sic   = ATM_flux_int ( ATM_wbilo_sic  )
+ATM_flx_wbilo_ter   = ATM_flux_int ( ATM_wbilo_ter  )
+ATM_flx_calving     = ATM_flux_int ( ATM_fqcalving  )
+ATM_flx_fqfonte     = ATM_flux_int ( ATM_fqfonte    )
+
+LIC_flx_calving     = LIC_flux_int ( ATM_fqcalving  )
+LIC_flx_fqfonte     = LIC_flux_int ( ATM_fqfonte    )
+
+ATM_flx_precip      = ATM_flux_int ( ATM_precip     )
+ATM_flx_snowf       = ATM_flux_int ( ATM_snowf      )
+ATM_flx_evap        = ATM_flux_int ( ATM_evap       )
+ATM_flx_runlic      = ATM_flux_int ( ATM_runofflic  )
+
+LIC_flx_precip      = LIC_flux_int ( ATM_precip     )
+LIC_flx_snowf       = LIC_flux_int ( ATM_snowf      )
+LIC_flx_evap        = LIC_flux_int ( ATM_evap       )
+LIC_flx_runlic      = LIC_flux_int ( ATM_runofflic  )
+
+ATM_flx_wrain_ter   = ATM_flux_int ( ATM_wrain_ter )
+ATM_flx_wrain_oce   = ATM_flux_int ( ATM_wrain_oce )
+ATM_flx_wrain_lic   = ATM_flux_int ( ATM_wrain_lic )
+ATM_flx_wrain_sic   = ATM_flux_int ( ATM_wrain_sic )
+ATM_flx_wrain_sea   = ATM_flux_int ( ATM_wrain_sea )
+
+ATM_flx_wsnow_ter   = ATM_flux_int ( ATM_wsnow_ter )
+ATM_flx_wsnow_oce   = ATM_flux_int ( ATM_wsnow_oce )
+ATM_flx_wsnow_lic   = ATM_flux_int ( ATM_wsnow_lic )
+ATM_flx_wsnow_sic   = ATM_flux_int ( ATM_wsnow_sic )
+ATM_flx_wsnow_sea   = ATM_flux_int ( ATM_wsnow_sea )
+
+ATM_flx_wevap_ter   = ATM_flux_int ( ATM_wevap_ter )
+ATM_flx_wevap_oce   = ATM_flux_int ( ATM_wevap_oce )
+ATM_flx_wevap_lic   = ATM_flux_int ( ATM_wevap_lic )
+ATM_flx_wevap_sic   = ATM_flux_int ( ATM_wevap_sic )
+ATM_flx_wevap_sea   = ATM_flux_int ( ATM_wevap_sea )
+ATM_flx_wprecip_lic = ATM_flux_int ( ATM_wprecip_lic )
+ATM_flx_wprecip_oce = ATM_flux_int ( ATM_wprecip_oce )
+ATM_flx_wprecip_sic = ATM_flux_int ( ATM_wprecip_sic )
+ATM_flx_wprecip_ter = ATM_flux_int ( ATM_wprecip_ter )
+ATM_flx_wprecip_sea = ATM_flux_int ( ATM_wprecip_sea )
+ATM_flx_wemp_lic    = ATM_flux_int ( ATM_wemp_lic )
+ATM_flx_wemp_oce    = ATM_flux_int ( ATM_wemp_oce )
+ATM_flx_wemp_sic    = ATM_flux_int ( ATM_wemp_sic )
+ATM_flx_wemp_ter    = ATM_flux_int ( ATM_wemp_ter )
+ATM_flx_wemp_sea    = ATM_flux_int ( ATM_wemp_sea )
+
+ATM_flx_emp          = ATM_flux_int ( ATM_emp )
+
+RUN_flx_coastal     = ONE_flux_int ( RUN_coastalflow)
+RUN_flx_river       = ONE_flux_int ( RUN_riverflow  )
+RUN_flx_coastal_cpl = ONE_flux_int ( RUN_coastalflow_cpl)
+RUN_flx_river_cpl   = ONE_flux_int ( RUN_riverflow_cpl  )
+RUN_flx_drainage    = SRF_flux_int ( RUN_drainage   )
+RUN_flx_riversret   = SRF_flux_int ( RUN_riversret  )
+RUN_flx_runoff      = SRF_flux_int ( RUN_runoff     )
+RUN_flx_input       = SRF_flux_int ( RUN_input      )
+RUN_flx_output      = ONE_flux_int ( RUN_output     )
+
+RUN_flx_bil    = ONE_flux_int ( RUN_input       - RUN_output)
+RUN_flx_rivcoa = ONE_flux_int ( RUN_coastalflow + RUN_riverflow)
+
+prtFlux ('wbilo_oce            ', ATM_flx_wbilo_oce     , 'f' )          
+prtFlux ('wbilo_sic            ', ATM_flx_wbilo_sic     , 'f' )          
+prtFlux ('wbilo_sic+oce        ', ATM_flx_wbilo_sea     , 'f' )          
+prtFlux ('wbilo_ter            ', ATM_flx_wbilo_ter     , 'f' )          
+prtFlux ('wbilo_lic            ', ATM_flx_wbilo_lic     , 'f' )          
+prtFlux ('Sum wbilo_*          ', ATM_flx_wbilo         , 'f', True)  
+prtFlux ('E-P                  ', ATM_flx_emp           , 'f', True)  
+prtFlux ('calving              ', ATM_flx_calving       , 'f' ) 
+prtFlux ('fqfonte              ', ATM_flx_fqfonte       , 'f' )       
+prtFlux ('precip               ', ATM_flx_precip        , 'f' )       
+prtFlux ('snowf                ', ATM_flx_snowf         , 'f' )        
+prtFlux ('evap                 ', ATM_flx_evap          , 'f' )
+prtFlux ('runoff lic           ', ATM_flx_runlic        , 'f' )
+
+prtFlux ('ATM_flx_wevap*       ', ATM_flx_wevap         , 'f' )
+prtFlux ('ATM_flx_wrain*       ', ATM_flx_wrain         , 'f' )
+prtFlux ('ATM_flx_wsnow*       ', ATM_flx_wsnow         , 'f' )
+prtFlux ('ATM_flx_wprecip*     ', ATM_flx_wprecip       , 'f' )
+prtFlux ('ATM_flx_wemp*        ', ATM_flx_wemp          , 'f', True )
+
+prtFlux ('ERROR evap           ', ATM_flx_wevap   - ATM_flx_evap  , 'e', True )
+prtFlux ('ERROR precip         ', ATM_flx_wprecip - ATM_flx_precip, 'e', True )
+prtFlux ('ERROR snow           ', ATM_flx_wsnow   - ATM_flx_snowf , 'e', True )
+prtFlux ('ERROR emp            ', ATM_flx_wemp    - ATM_flx_emp   , 'e', True )
+
+
+echo ( '\n====================================================================================' )
+echo ( f'-- RUNOFF Fluxes  -- {Title} ' )
+prtFlux ('coastalflow   ', RUN_flx_coastal    , 'f' ) 
+prtFlux ('riverflow     ', RUN_flx_river      , 'f' )        
+prtFlux ('coastal_cpl   ', RUN_flx_coastal_cpl, 'f' )  
+prtFlux ('riverf_cpl    ', RUN_flx_river_cpl  , 'f' )    
+prtFlux ('river+coastal ', RUN_flx_rivcoa     , 'f' )   
+prtFlux ('drainage      ', RUN_flx_drainage   , 'f' )   
+prtFlux ('riversret     ', RUN_flx_riversret  , 'f' )   
+prtFlux ('runoff        ', RUN_flx_runoff     , 'f' )   
+prtFlux ('river in      ', RUN_flx_input      , 'f' )   
+prtFlux ('river out     ', RUN_flx_output     , 'f' )   
+prtFlux ('river bil     ', RUN_flx_bil        , 'f' ) 
+    
+echo ( '\n====================================================================================' )
+echo ( f'-- OCE Fluxes  -- {Title} ' )
+
+# Read variable and computes integral over space and time
+OCE_empmr      = rprec (d_OCE_his['wfo']     )    ; OCE_mas_empmr    = OCE_flux_int ( OCE_empmr    )
+OCE_wfob       = rprec (d_OCE_his['wfob']    )    ; OCE_mas_wfob     = OCE_flux_int ( OCE_wfob     )
+OCE_emp_oce    = rprec (d_OCE_his['emp_oce'] )    ; OCE_mas_emp_oce  = OCE_flux_int ( OCE_emp_oce  )
+OCE_emp_ice    = rprec (d_OCE_his['emp_ice'] )    ; OCE_mas_emp_ice  = OCE_flux_int ( OCE_emp_ice  )
+OCE_iceshelf   = rprec (d_OCE_his['iceshelf'])    ; OCE_mas_iceshelf = OCE_flux_int ( OCE_iceshelf )
+OCE_calving    = rprec (d_OCE_his['calving'] )    ; OCE_mas_calving  = OCE_flux_int ( OCE_calving  )
+OCE_iceberg    = rprec (d_OCE_his['iceberg'] )    ; OCE_mas_iceberg  = OCE_flux_int ( OCE_iceberg  )
+OCE_friver     = rprec (d_OCE_his['friver']  )    ; OCE_mas_friver   = OCE_flux_int ( OCE_friver   )
+OCE_runoffs    = rprec (d_OCE_his['runoffs'] )    ; OCE_mas_runoffs  = OCE_flux_int ( OCE_runoffs  )
+if NEMO == 4.0 or NEMO == 4.2 :
+    OCE_wfxice     = rprec (d_OCE_his['vfxice']) ; OCE_mas_wfxice   = OCE_flux_int ( OCE_wfxice )
+    OCE_wfxsnw     = rprec (d_OCE_his['vfxsnw']) ; OCE_mas_wfxsnw   = OCE_flux_int ( OCE_wfxsnw )
+    OCE_wfxsub     = rprec (d_OCE_his['vfxsub']) ; OCE_mas_wfxsub   = OCE_flux_int ( OCE_wfxsub )
 if NEMO == 3.6 :
-    ICE_ice_beg = d_ICE_beg['v_i_htc1']+d_ICE_beg['v_i_htc2']+d_ICE_beg['v_i_htc3']+d_ICE_beg['v_i_htc4']+d_ICE_beg['v_i_htc5']
-    ICE_ice_end = d_ICE_end['v_i_htc1']+d_ICE_end['v_i_htc2']+d_ICE_end['v_i_htc3']+d_ICE_end['v_i_htc4']+d_ICE_end['v_i_htc5']
-
-    ICE_sno_beg = d_ICE_beg['v_s_htc1']+d_ICE_beg['v_s_htc2']+d_ICE_beg['v_s_htc3']+d_ICE_beg['v_s_htc4']+d_ICE_beg['v_s_htc5']
-    ICE_sno_end = d_ICE_end['v_s_htc1']+d_ICE_end['v_s_htc2']+d_ICE_end['v_s_htc3']+d_ICE_end['v_s_htc4']+d_ICE_end['v_s_htc5']
-    
-    ICE_pnd_beg = 0.0 ; ICE_pnd_end = 0.0
-    ICE_fzl_beg = 0.0 ; ICE_fzl_end = 0.0
-
-    ICE_mas_wat_beg = OCE_stock_int ( (ICE_ice_beg*ICE_rho_ice + ICE_sno_beg*ICE_rho_sno) )
-    ICE_mas_wat_end = OCE_stock_int ( (ICE_ice_end*ICE_rho_ice + ICE_sno_end*ICE_rho_sno) )
-    
+    OCE_wfxice     = rprec (d_OCE_his['vfxice'])/86400.*ICE_rho_ice ; OCE_mas_wfxice   = OCE_flux_int ( OCE_wfxice )
+    OCE_wfxsnw     = rprec (d_OCE_his['vfxsnw'])/86400.*ICE_rho_sno ; OCE_mas_wfxsnw   = OCE_flux_int ( OCE_wfxsnw )
+    OCE_wfxsub     = rprec (d_OCE_his['vfxsub'])/86400.*ICE_rho_sno ; OCE_mas_wfxsub   = OCE_flux_int ( OCE_wfxsub )
+# Additional checks
+OCE_evap_oce   = rprec (d_OCE_his['evap_ao_cea']) ; OCE_mas_evap_oce   = OCE_flux_int ( OCE_evap_oce )
+ICE_evap_ice   = rprec (d_OCE_his['subl_ai_cea']) ; ICE_mas_evap_ice   = OCE_flux_int ( ICE_evap_ice )
+OCE_snow_oce   = rprec (d_OCE_his['snow_ao_cea']) ; OCE_mas_snow_oce   = OCE_flux_int ( OCE_snow_oce )
+OCE_snow_ice   = rprec (d_OCE_his['snow_ai_cea']) ; OCE_mas_snow_ice   = OCE_flux_int ( OCE_snow_ice )
+OCE_rain       = rprec (d_OCE_his['rain']       ) ; OCE_mas_rain       = OCE_flux_int ( OCE_rain     )
+ICE_wfxsub_err = rprec (d_ICE_his['vfxsub_err'] ) ; ICE_mas_wfxsub_err = OCE_flux_int ( ICE_wfxsub_err )
 if NEMO == 4.0 or NEMO == 4.2 :
-    ICE_ice_beg = d_ICE_beg ['v_i']  ; ICE_ice_end = d_ICE_end ['v_i']
-    ICE_sno_beg = d_ICE_beg ['v_s']  ; ICE_sno_end = d_ICE_end ['v_s']
-    ICE_pnd_beg = d_ICE_beg ['v_ip'] ; ICE_pnd_end = d_ICE_end ['v_ip']
-    ICE_fzl_beg = d_ICE_beg ['v_il'] ; ICE_fzl_end = d_ICE_end ['v_il']
-    
-    ICE_mas_wat_beg = OCE_stock_int ( d_ICE_beg['snwice_mass'] )
-    ICE_mas_wat_end = OCE_stock_int ( d_ICE_end['snwice_mass'] )
-    
-    
-ICE_vol_ice_beg = OCE_stock_int ( ICE_ice_beg )
-ICE_vol_ice_end = OCE_stock_int ( ICE_ice_end )
-
-ICE_vol_sno_beg = OCE_stock_int ( ICE_sno_beg )
-ICE_vol_sno_end = OCE_stock_int ( ICE_sno_end )
-
-ICE_vol_pnd_beg = OCE_stock_int ( ICE_pnd_beg )
-ICE_vol_pnd_end = OCE_stock_int ( ICE_pnd_end )
-
-ICE_vol_fzl_beg = OCE_stock_int ( ICE_fzl_beg )
-ICE_vol_fzl_end = OCE_stock_int ( ICE_fzl_end )
-
-#-- Converting to freswater volume
-dICE_vol_ice = ICE_vol_ice_end - ICE_vol_ice_beg
-dICE_mas_ice = dICE_vol_ice * ICE_rho_ice
-
-dICE_vol_sno = ICE_vol_sno_end - ICE_vol_sno_beg
-dICE_mas_sno = dICE_vol_sno * ICE_rho_sno
-
-dICE_vol_pnd = ICE_vol_pnd_end - ICE_vol_pnd_beg
-dICE_mas_pnd = dICE_vol_pnd * ICE_rho_pnd
-
-dICE_vol_fzl= ICE_vol_fzl_end - ICE_vol_fzl_beg
-dICE_mas_fzl = dICE_vol_fzl * ICE_rho_pnd
-
+    ICE_wfxpnd     = rprec (d_ICE_his['vfxpnd']    ) ; ICE_mas_wfxpnd     = OCE_flux_int ( ICE_wfxpnd     )
+    ICE_wfxsnw_sub = rprec (d_ICE_his['vfxsnw_sub']) ; ICE_mas_wfxsnw_sub = OCE_flux_int ( ICE_wfxsnw_sub )
+    ICE_wfxsnw_pre = rprec (d_ICE_his['vfxsnw_pre']) ; ICE_mas_wfxsnw_pre = OCE_flux_int ( ICE_wfxsnw_pre )
 if NEMO == 3.6 :
-    dICE_mas_wat = dICE_mas_ice + dICE_mas_sno
-    dSEA_mas_wat = dOCE_mas_wat + dICE_mas_ice + dICE_mas_sno
-
-if NEMO == 4.0 or NEMO == 4.2 :
-    dICE_mas_wat = ICE_mas_wat_end - ICE_mas_wat_beg
-    dSEA_mas_wat = dOCE_mas_wat + dICE_mas_wat
-
-echo ( f'ICE_vol_ice_beg = {ICE_vol_ice_beg:12.6e} m^3 | ICE_vol_ice_end = {ICE_vol_ice_end:12.6e} m^3' )
-echo ( f'ICE_vol_sno_beg = {ICE_vol_sno_beg:12.6e} m^3 | ICE_vol_sno_end = {ICE_vol_sno_end:12.6e} m^3' )
-echo ( f'ICE_vol_pnd_beg = {ICE_vol_pnd_beg:12.6e} m^3 | ICE_vol_pnd_end = {ICE_vol_pnd_end:12.6e} m^3' )
-echo ( f'ICE_vol_fzl_beg = {ICE_vol_fzl_beg:12.6e} m^3 | ICE_vol_fzl_end = {ICE_vol_fzl_end:12.6e} m^3' )
-
-echo ( f'dICE_vol_ice   = {dICE_vol_ice:12.3e} m^3' )
-echo ( f'dICE_vol_sno   = {dICE_vol_sno:12.3e} m^3' )
-echo ( f'dICE_vol_pnd   = {dICE_vol_pnd:12.3e} m^3' )
-echo ( f'dICE_mas_ice   = {dICE_mas_ice:12.3e} m^3' )
-echo ( f'dICE_mas_sno   = {dICE_mas_sno:12.3e} m^3' )  
-echo ( f'dICE_mas_pnd   = {dICE_mas_pnd:12.3e} m^3' )  
-echo ( f'dICE_mas_fzl   = {dICE_mas_fzl:12.3e} m^3' )  
-echo ( f'dICE_mas_wat   = {dICE_mas_wat:12.3e} m^3' ) 
-
-
-SEA_mas_wat_beg = OCE_mas_wat_beg + ICE_mas_wat_beg
-SEA_mas_wat_end = OCE_mas_wat_end + ICE_mas_wat_end
-
-echo ( '\n------------------------------------------------------------')
-echo ( 'Variation du contenu en eau ocean + glace ' )
-echo ( 'dMass (ocean)   = {:12.6e} kg '.format(dSEA_mas_wat) )
-echo ( 'dVol  (ocean)   = {:12.3e} Sv '.format(dSEA_mas_wat/dtime_sec*1E-6/OCE_rho_liq) )
-echo ( 'dVol  (ocean)   = {:12.3e} m  '.format(dSEA_mas_wat*1E-3/OCE_aire_tot) )
-
-
-echo ( '\n------------------------------------------------------------------------------------' )
-echo ( '-- ATM changes in stores ' )
-
-#-- Change in precipitable water from the atmosphere daily and monthly files
-#-- Compute sum weighted by gridcell area (kg/m2) then convert to Sv
-
-# ATM vertical grid
-ATM_Ahyb = d_ATM_his['Ahyb'].squeeze()
-ATM_Bhyb = d_ATM_his['Bhyb'].squeeze()
-klevp1 = ATM_Ahyb.shape[0]
-
-# Surface pressure
-if ICO : 
-    DYN_ps_beg = d_DYN_beg['ps']
-    DYN_ps_end = d_DYN_end['ps']
-    
-if LMDZ : 
-    DYN_ps_beg =  lmdz.geo2point ( d_DYN_beg['ps'].isel(rlonv=slice(0,-1)) )
-    DYN_ps_end =  lmdz.geo2point ( d_DYN_end['ps'].isel(rlonv=slice(0,-1)) )
-    
-# 3D Pressure
-DYN_p_beg = ATM_Ahyb + ATM_Bhyb * DYN_ps_beg
-DYN_p_end = ATM_Ahyb + ATM_Bhyb * DYN_ps_end
-
-# Layer thickness
-DYN_sigma_beg = DYN_p_beg[0:-1]*0.
-DYN_sigma_end = DYN_p_end[0:-1]*0. 
-
-for k in np.arange (klevp1-1) :
-    DYN_sigma_beg[k,:] = (DYN_p_beg[k,:] - DYN_p_beg[k+1,:]) / Grav
-    DYN_sigma_end[k,:] = (DYN_p_end[k,:] - DYN_p_end[k+1,:]) / Grav
-
-DYN_sigma_beg = DYN_sigma_beg.rename ( {'klevp1':'sigs'} )
-DYN_sigma_end = DYN_sigma_end.rename ( {'klevp1':'sigs'} )
-
-##-- Vertical and horizontal integral, and sum of liquid, solid and vapor water phases
-if LMDZ :
-    try : 
-        DYN_wat_beg = lmdz.geo3point ( (d_DYN_beg['H2Ov'] + d_DYN_beg['H2Ol'] + d_DYN_beg['H2Oi']).isel(rlonv=slice(0,-1) ) )
-        DYN_wat_end = lmdz.geo3point ( (d_DYN_end['H2Ov'] + d_DYN_end['H2Ol'] + d_DYN_end['H2Oi']).isel(rlonv=slice(0,-1) ) )
-    except :
-        DYN_wat_beg = lmdz.geo3point ( (d_DYN_beg['H2O_g'] + d_DYN_beg['H2O_l'] + d_DYN_beg['H2O_s']).isel(rlonv=slice(0,-1) ) )
-        DYN_wat_end = lmdz.geo3point ( (d_DYN_end['H2O_g'] + d_DYN_end['H2O_l'] + d_DYN_end['H2O_s']).isel(rlonv=slice(0,-1) ) )
-if ICO :
-    try :
-        DYN_wat_beg = (d_DYN_beg['H2O_g'] + d_DYN_beg['H2O_l'] + d_DYN_beg['H2O_s']).rename ( {'lev':'sigs'} )
-        DYN_wat_end = (d_DYN_end['H2O_g'] + d_DYN_end['H2O_l'] + d_DYN_end['H2O_s']).rename ( {'lev':'sigs'} )
-    except : 
-        DYN_wat_beg = (d_DYN_beg['q'].isel(nq=0) + d_DYN_beg['q'].isel(nq=1) + d_DYN_beg['q'].isel(nq=2) ).rename ( {'lev':'sigs'} )
-        DYN_wat_end = (d_DYN_end['q'].isel(nq=0) + d_DYN_end['q'].isel(nq=1) + d_DYN_end['q'].isel(nq=2) ).rename ( {'lev':'sigs'} )
-    
-DYN_mas_wat_beg = ATM_stock_int (DYN_sigma_beg * DYN_wat_beg)
-DYN_mas_wat_end = ATM_stock_int (DYN_sigma_end * DYN_wat_end)
-
-dDYN_mas_wat = DYN_mas_wat_end - DYN_mas_wat_beg
-
-echo ( '\nVariation du contenu en eau atmosphere (dynamique) ' )
-echo ( 'DYN_mas_beg = {:12.6e} kg | DYN_mas_end = {:12.6e} kg'.format (DYN_mas_wat_beg, DYN_mas_wat_end) )
-echo ( 'dMass (atm)   = {:12.3e} kg '.format (dDYN_mas_wat) )
-echo ( 'dMass (atm)   = {:12.3e} Sv '.format (dDYN_mas_wat/dtime_sec*1.e-6/ATM_rho) )
-echo ( 'dMass (atm)   = {:12.3e} m  '.format (dDYN_mas_wat/ATM_aire_sea_tot/ATM_rho) )
-
-ATM_sno_beg = d_ATM_beg['SNOW01']*d_ATM_beg['FTER']+d_ATM_beg['SNOW02']*d_ATM_beg['FLIC']+d_ATM_beg['SNOW03']*d_ATM_beg['FOCE']+d_ATM_beg['SNOW04']*d_ATM_beg['FSIC']
-ATM_sno_end = d_ATM_end['SNOW01']*d_ATM_end['FTER']+d_ATM_end['SNOW02']*d_ATM_end['FLIC']+d_ATM_end['SNOW03']*d_ATM_end['FOCE']+d_ATM_end['SNOW04']*d_ATM_end['FSIC']
-
-ATM_qs_beg  = d_ATM_beg['QS01']*d_ATM_beg['FTER']+d_ATM_beg['QS02']*d_ATM_beg['FLIC']+d_ATM_beg['QS03']*d_ATM_beg['FOCE']+d_ATM_beg['QS04']*d_ATM_beg['FSIC']
-ATM_qs_end  = d_ATM_end['QS01']*d_ATM_end['FTER']+d_ATM_end['QS02']*d_ATM_end['FLIC']+d_ATM_end['QS03']*d_ATM_end['FOCE']+d_ATM_end['QS04']*d_ATM_end['FSIC']
-
-ATM_qsol_beg = d_ATM_beg['QSOL']
-ATM_qsol_end = d_ATM_end['QSOL']
-
-ATM_qs01_beg  = d_ATM_beg['QS01'] * d_ATM_beg['FTER']
-ATM_qs01_end  = d_ATM_end['QS01'] * d_ATM_end['FTER']
-ATM_qs02_beg  = d_ATM_beg['QS02'] * d_ATM_beg['FLIC']
-ATM_qs02_end  = d_ATM_end['QS02'] * d_ATM_end['FLIC']
-ATM_qs03_beg  = d_ATM_beg['QS03'] * d_ATM_beg['FOCE']
-ATM_qs03_end  = d_ATM_end['QS03'] * d_ATM_end['FOCE']
-ATM_qs04_beg  = d_ATM_beg['QS04'] * d_ATM_beg['FSIC']
-ATM_qs04_end  = d_ATM_end['QS04'] * d_ATM_end['FSIC']  
-
-if ICO :
-   ATM_sno_beg   = ATM_sno_beg .rename ( {'points_physiques':'cell_mesh'} )
-   ATM_sno_end   = ATM_sno_end .rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs_beg    = ATM_qs_beg  .rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs_end    = ATM_qs_end  .rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qsol_beg  = ATM_qsol_beg.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qsol_end  = ATM_qsol_end.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs01_beg  = ATM_qs01_beg.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs01_end  = ATM_qs01_end.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs02_beg  = ATM_qs02_beg.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs02_end  = ATM_qs02_end.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs03_beg  = ATM_qs03_beg.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs03_end  = ATM_qs03_end.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs04_beg  = ATM_qs04_beg.rename ( {'points_physiques':'cell_mesh'} )
-   ATM_qs04_end  = ATM_qs04_end.rename ( {'points_physiques':'cell_mesh'} ) 
-
-echo ('Computing atmosphere integrals')
-ATM_mas_sno_beg   = ATM_stock_int ( ATM_sno_beg  )
-ATM_mas_sno_end   = ATM_stock_int ( ATM_sno_end  )
-ATM_mas_qs_beg    = ATM_stock_int ( ATM_qs_beg   )
-ATM_mas_qs_end    = ATM_stock_int ( ATM_qs_end   )
-ATM_mas_qsol_beg  = ATM_stock_int ( ATM_qsol_beg )
-ATM_mas_qsol_end  = ATM_stock_int ( ATM_qsol_end )
-ATM_mas_qs01_beg  = ATM_stock_int ( ATM_qs01_beg )
-ATM_mas_qs01_end  = ATM_stock_int ( ATM_qs01_end )
-ATM_mas_qs02_beg  = ATM_stock_int ( ATM_qs02_beg )
-ATM_mas_qs02_end  = ATM_stock_int ( ATM_qs02_end )
-ATM_mas_qs03_beg  = ATM_stock_int ( ATM_qs03_beg )
-ATM_mas_qs03_end  = ATM_stock_int ( ATM_qs03_end )
-ATM_mas_qs04_beg  = ATM_stock_int ( ATM_qs04_beg )
-ATM_mas_qs04_end  = ATM_stock_int ( ATM_qs04_end )
-
-dATM_mas_sno  = ATM_mas_sno_end  - ATM_mas_sno_beg
-dATM_mas_qs   = ATM_mas_qs_end   - ATM_mas_qs_beg
-dATM_mas_qsol = ATM_mas_qsol_end - ATM_mas_qsol_beg
-
-dATM_mas_qs01 = ATM_mas_qs01_end - ATM_mas_qs01_beg
-dATM_mas_qs02 = ATM_mas_qs02_end - ATM_mas_qs02_beg
-dATM_mas_qs03 = ATM_mas_qs03_end - ATM_mas_qs03_beg
-dATM_mas_qs04 = ATM_mas_qs04_end - ATM_mas_qs04_beg
-
-echo ( '\nVariation du contenu en neige atmosphere (calottes)' )
-echo ( 'ATM_mas_sno_beg  = {:12.6e} kg | ATM_mas_sno_end  = {:12.6e} kg'.format (ATM_mas_sno_beg, ATM_mas_sno_end) )
-echo ( 'dMass (neige atm) = {:12.3e} kg '.format (dATM_mas_sno ) )
-echo ( 'dMass (neige atm) = {:12.3e} Sv '.format (dATM_mas_sno/dtime_sec*1e-6/ICE_rho_ice) )
-echo ( 'dMass (neige atm) = {:12.3e} m  '.format (dATM_mas_sno/ATM_aire_sea_tot/ATM_rho) )
-
-echo ( '\nVariation du contenu humidite du sol' )
-echo ( 'ATM_mas_qs_beg  = {:12.6e} kg | ATM_mas_qs_end  = {:12.6e} kg'.format (ATM_mas_qs_beg, ATM_mas_qs_end) )
-echo ( 'dMass (neige atm) = {:12.3e} kg '.format (dATM_mas_qs ) )
-echo ( 'dMass (neige atm) = {:12.3e} Sv '.format (dATM_mas_qs/dtime_sec*1e-6/ATM_rho) )
-echo ( 'dMass (neige atm) = {:12.3e} m  '.format (dATM_mas_qs/ATM_aire_sea_tot/ATM_rho) )
-
-echo ( '\nVariation du contenu en eau+neige atmosphere ' )
-echo ( 'dMass (eau + neige atm) = {:12.3e} kg '.format (  dDYN_mas_wat + dATM_mas_sno) )
-echo ( 'dMass (eau + neige atm) = {:12.3e} Sv '.format ( (dDYN_mas_wat + dATM_mas_sno)/dtime_sec*1E-6/ATM_rho) )
-echo ( 'dMass (eau + neige atm) = {:12.3e} m  '.format ( (dDYN_mas_wat + dATM_mas_sno)/ATM_aire_sea_tot/ATM_rho) )
-
-echo ( '\n------------------------------------------------------------------------------------' )
-echo ( '-- SRF changes ' )
-
-if Routing == 'SIMPLE' :
-    RUN_mas_wat_beg = ONE_stock_int ( d_RUN_beg ['fast_reservoir'] +  d_RUN_beg ['slow_reservoir'] +  d_RUN_beg ['stream_reservoir'])
-    RUN_mas_wat_end = ONE_stock_int ( d_RUN_end ['fast_reservoir'] +  d_RUN_end ['slow_reservoir'] +  d_RUN_end ['stream_reservoir'])
-
-if Routing == 'SECHIBA' : 
-    RUN_mas_wat_beg = ONE_stock_int ( d_SRF_beg['fastres']  + d_SRF_beg['slowres'] + d_SRF_beg['streamres'] \
-                                    + d_SRF_beg['floodres'] + d_SRF_beg['lakeres'] + d_SRF_beg['pondres'] )
-    RUN_mas_wat_end = ONE_stock_int ( d_SRF_end['fastres']  + d_SRF_end['slowres'] + d_SRF_end['streamres'] \
-                                    + d_SRF_end['floodres'] + d_SRF_end['lakeres'] + d_SRF_end['pondres'] )
-
-dRUN_mas_wat = RUN_mas_wat_end - RUN_mas_wat_beg
-    
-echo ( '\nWater content in routing ' )
-echo ( 'RUN_mas_wat_beg = {:12.6e} kg | RUN_mas_wat_end = {:12.6e} kg '.format (RUN_mas_wat_end, RUN_mas_wat_end) )
-echo ( 'dMass (routing)  = {:12.3e} kg '.format(dRUN_mas_wat) )
-echo ( 'dMass (routing)  = {:12.3e} Sv '.format(dRUN_mas_wat/dtime_sec*1E-9) )
-echo ( 'dMass (routing)  = {:12.3e} m  '.format(dRUN_mas_wat/OCE_aire_tot*1E-3) )
-
-print ('Reading SRF restart')
-tot_watveg_beg  = d_SRF_beg['tot_watveg_beg']  ; tot_watveg_beg  = tot_watveg_beg .where (tot_watveg_beg < 1E10, 0.)
-tot_watsoil_beg = d_SRF_beg['tot_watsoil_beg'] ; tot_watsoil_beg = tot_watsoil_beg.where (tot_watsoil_beg< 1E10, 0.)
-snow_beg        = d_SRF_beg['snow_beg']        ; snow_beg        = snow_beg       .where (snow_beg       < 1E10, 0.)
-
-tot_watveg_end  = d_SRF_end['tot_watveg_beg']  ; tot_watveg_end  = tot_watveg_end .where (tot_watveg_end < 1E10, 0.)
-tot_watsoil_end = d_SRF_end['tot_watsoil_beg'] ; tot_watsoil_end = tot_watsoil_end.where (tot_watsoil_end< 1E10, 0.)
-snow_end        = d_SRF_end['snow_beg']        ; snow_end        = snow_end       .where (snow_end       < 1E10, 0.)
-
-if LMDZ :
-    tot_watveg_beg  = lmdz.geo2point (tot_watveg_beg)
-    tot_watsoil_beg = lmdz.geo2point (tot_watsoil_beg)
-    snow_beg        = lmdz.geo2point (snow_beg)
-    tot_watveg_end  = lmdz.geo2point (tot_watveg_end)
-    tot_watsoil_end = lmdz.geo2point (tot_watsoil_end)
-    snow_end        = lmdz.geo2point (snow_end)
-
-SRF_wat_beg = tot_watveg_beg + tot_watsoil_beg + snow_beg
-SRF_wat_end = tot_watveg_end + tot_watsoil_end + snow_end
-
-#SRF_mas_wat_beg = d_SRF_beg['tot_watveg_beg']+d_SRF_beg['tot_watsoil_beg'] + d_SRF_beg['snow_beg']
-#SRF_mas_wat_end = d_SRF_end['tot_watveg_beg']+d_SRF_end['tot_watsoil_beg'] + d_SRF_end['snow_beg']
-
-#if LMDZ :
-#    tot_watveg_beg  = tot_watveg_beg .rename ( {'y':'points_phyiques'} )
-#    tot_watsoil_beg = tot_watsoil_beg.rename ( {'y':'points_phyiques'} )
-#    snow_beg        = snow_beg       .rename ( {'y':'points_phyiques'} )
-#    tot_watveg_end  = tot_watveg_end .rename ( {'y':'points_phyiques'} )
-#    tot_watsoil_end = tot_watsoil_end.rename ( {'y':'points_phyiques'} )
-#    snow_end        = snow_end       .rename ( {'y':'points_phyiques'} )
-#    SRF_wat_beg     = SRF_wat_beg    .rename ( {'y':'points_phyiques'} )
-#    SRF_wat_end     = SRF_wat_end    .rename ( {'y':'points_phyiques'} )
-if ICO :
-    tot_watveg_beg  = tot_watveg_beg .rename ( {'y':'cell_mesh'} )
-    tot_watsoil_beg = tot_watsoil_beg.rename ( {'y':'cell_mesh'} )
-    snow_beg        = snow_beg       .rename ( {'y':'cell_mesh'} )
-    tot_watveg_end  = tot_watveg_end .rename ( {'y':'cell_mesh'} )
-    tot_watsoil_end = tot_watsoil_end.rename ( {'y':'cell_mesh'} )
-    snow_end        = snow_end       .rename ( {'y':'cell_mesh'} )
-    SRF_wat_beg     = SRF_wat_beg    .rename ( {'y':'cell_mesh'} )
-    SRF_wat_end     = SRF_wat_end    .rename ( {'y':'cell_mesh'} )  
-
-print ('Computing integrals')
-
-print ( ' 1/6', end='' ) ; sys.stdout.flush ()
-SRF_mas_watveg_beg   = ATM_stock_int ( tot_watveg_beg  )
-print ( ' 2/6', end='' ) ; sys.stdout.flush ()
-SRF_mas_watsoil_beg  = ATM_stock_int ( tot_watsoil_beg )
-print ( ' 3/6', end='' ) ; sys.stdout.flush ()
-SRF_mas_snow_beg     = ATM_stock_int ( snow_beg        )
-print ( ' 4/6', end='' ) ; sys.stdout.flush ()
-SRF_mas_watveg_end   = ATM_stock_int ( tot_watveg_end  )
-print ( ' 5/6', end='' ) ; sys.stdout.flush ()
-SRF_mas_watsoil_end  = ATM_stock_int ( tot_watsoil_end )
-print ( ' 6/6', end='' ) ; sys.stdout.flush ()
-SRF_mas_snow_end     = ATM_stock_int ( snow_end        )
-print (' -- ') ; sys.stdout.flush ()
-
-dSRF_mas_watveg   = SRF_mas_watveg_end   - SRF_mas_watveg_beg
-dSRF_mas_watsoil  = SRF_mas_watsoil_end  - SRF_mas_watsoil_beg
-dSRF_mas_snow     = SRF_mas_snow_end     - SRF_mas_snow_beg
-
-echo ('\nLes differents reservoirs')
-echo ( f'SRF_mas_watveg_beg   = {SRF_mas_watveg_beg :12.6e} kg | SRF_mas_watveg_end   = {SRF_mas_watveg_end :12.6e} kg ' )
-echo ( f'SRF_mas_watsoil_beg  = {SRF_mas_watsoil_beg:12.6e} kg | SRF_mas_watsoil_end  = {SRF_mas_watsoil_end:12.6e} kg ' )
-echo ( f'SRF_mas_snow_beg     = {SRF_mas_snow_beg   :12.6e} kg | SRF_mas_snow_end     = {SRF_mas_snow_end   :12.6e} kg ' )
-
-echo ( 'dMass (watveg)  = {:12.3e} kg | {:12.2e} Sv | {:12.2e} m '.format (dSRF_mas_watveg , dSRF_mas_watveg /dtime_sec*1E-9, dSRF_mas_watveg /OCE_aire_tot*1E-3) )
-echo ( 'dMass (watsoil) = {:12.3e} kg | {:12.2e} Sv | {:12.2e} m '.format (dSRF_mas_watsoil, dSRF_mas_watsoil/dtime_sec*1E-9, dSRF_mas_watsoil/OCE_aire_tot*1E-3) )
-echo ( 'dMass (sno)     = {:12.3e} kg | {:12.2e} Sv | {:12.2e} m '.format (dSRF_mas_snow   , dSRF_mas_snow   /dtime_sec*1E-9, dSRF_mas_snow   /OCE_aire_tot*1E-3  ) )
-
-SRF_mas_wat_beg = SRF_mas_watveg_beg + SRF_mas_watsoil_beg + SRF_mas_snow_beg 
-SRF_mas_wat_end = SRF_mas_watveg_end + SRF_mas_watsoil_end + SRF_mas_snow_end
-dSRF_mas_wat = SRF_mas_wat_end - SRF_mas_wat_beg
-
-echo ( '\nWater content in surface ' )
-echo ( 'SRF_mas_wat_beg  = {:12.6e} kg | SRF_mas_wat_end  = {:12.6e} kg '.format (SRF_mas_wat_beg, SRF_mas_wat_end) )
-echo ( 'dMass (water srf) = {:12.3e} kg '.format (dSRF_mas_wat) )
-echo ( 'dMass (water srf) = {:12.3e} Sv '.format (dSRF_mas_wat/dtime_sec*1E-6/ATM_rho) )
-echo ( 'dMass (water srf) = {:12.3e} m  '.format (dSRF_mas_wat/ATM_aire_sea_tot/ATM_rho) )
-
-echo ( '\nWater content in  ATM + SRF + RUN ' )
-echo ( 'mas_wat_beg = {:12.6e} kg | mas_wat_end = {:12.6e} kg '.
-           format (DYN_mas_wat_beg + ATM_mas_sno_beg + RUN_mas_wat_beg + SRF_mas_wat_beg,
-                   DYN_mas_wat_end + ATM_mas_sno_end + RUN_mas_wat_end + SRF_mas_wat_end) )
-echo ( 'dMass (water atm+srf+run) = {:12.6e} kg '.format ( dDYN_mas_wat + dATM_mas_sno + dRUN_mas_wat + dSRF_mas_wat) )
-echo ( 'dMass (water atm+srf+run) = {:12.3e} Sv '.format ((dDYN_mas_wat + dATM_mas_sno + dRUN_mas_wat + dSRF_mas_wat)/dtime_sec*1E-6/ATM_rho) )
-echo ( 'dMass (water atm+srf+run) = {:12.3e} m  '.format ((dDYN_mas_wat + dATM_mas_sno + dRUN_mas_wat + dSRF_mas_wat)/ATM_aire_sea_tot/ATM_rho) )
-
-echo ( '\n------------------------------------------------------------------------------------' )
-echo ( '-- Change in all components' )
-echo ( 'mas_wat_beg = {:12.6e} kg | mas_wat_end = {:12.6e} kg'.
-           format (SEA_mas_wat_beg + DYN_mas_wat_beg + ATM_mas_sno_beg + RUN_mas_wat_beg + SRF_mas_wat_beg,
-                   SEA_mas_wat_end + DYN_mas_wat_end + ATM_mas_sno_end + RUN_mas_wat_end + SRF_mas_wat_end) )
-echo ( 'dMass (water CPL)         = {:12.3e} kg '.format ( dSEA_mas_wat + dDYN_mas_wat + dATM_mas_sno + dRUN_mas_wat + dSRF_mas_wat) )
-echo ( 'dMass (water CPL)         = {:12.3e} Sv '.format ((dSEA_mas_wat + dDYN_mas_wat + dATM_mas_sno + dRUN_mas_wat + dSRF_mas_wat)/dtime_sec*1E-9) )
-echo ( 'dMass (water CPL)         = {:12.3e} m  '.format ((dSEA_mas_wat + dDYN_mas_wat + dATM_mas_sno + dRUN_mas_wat + dSRF_mas_wat)/OCE_aire_tot*1E-3) )
-
-
+    ICE_wfxpnd = 0.0 ; ICE_mas_wfxpnd = 0.0
+    ICE_wfxsnw_sub = rprec (d_ICE_his['vfxsub'])/86400.*ICE_rho_sno  ; ICE_mas_wfxsnw_sub = OCE_flux_int ( ICE_wfxsnw_sub )
+    ICE_wfxsnw_pre = rprec (d_ICE_his['vfxspr'])/86400.*ICE_rho_sno  ; ICE_mas_wfxsnw_pre = OCE_flux_int ( ICE_wfxsnw_pre     )
+
+OCE_wfcorr    = rprec (d_OCE_his['wfcorr']) ; OCE_mas_wfcorr  = OCE_flux_int ( OCE_wfcorr )
+if OCE_relax  :
+    # ssr and fwb are included in emp=>empmr but not in emp_oce (outputed by sea-ice)
+    OCE_vflx_fwb = rprec (d_OCE_his['vflx_fwb']) ; OCE_mas_vflx_fwb   = OCE_flux_int ( OCE_vflx_fwb )
+    OCE_vflx_ssr = rprec (d_OCE_his['vflx_ssr']) ; OCE_mas_vflx_ssr   = OCE_flux_int ( OCE_vflx_ssr )
+else : 
+    OCE_fwb = 0.0 ; OCE_mas_fwb = 0.0
+    OCE_ssr = 0.0 ; OCE_mas_ssr = 0.0
+if OCE_icb :
+    OCE_berg_icb    = rprec (d_OCE_his['berg_floating_melt']) ; OCE_mas_berg_icb = OCE_flux_int ( OCE_berg_icb    )
+    OCE_calving_icb = rprec (d_OCE_his['calving_icb']       ) ; OCE_mas_calv_icb = OCE_flux_int ( OCE_calving_icb )
+else :
+    OCE_berg_icb = 0. ; OCE_mas_berg_icb = 0.
+    OCE_calv_icb = 0. ; OCE_mas_calv_icb = 0.
+
+OCE_mas_emp = OCE_mas_emp_oce - OCE_mas_wfxice  - OCE_mas_wfxsnw  - ICE_mas_wfxpnd - ICE_mas_wfxsub_err
+OCE_mas_all = OCE_mas_emp_oce + OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf
+
+prtFlux ('OCE+ICE budget ', OCE_mas_all       , 'e', True)
+prtFlux ('  EMPMR        ', OCE_mas_empmr     , 'e', True)
+prtFlux ('  WFOB         ', OCE_mas_wfob      , 'e', True)
+prtFlux ('  EMP_OCE      ', OCE_mas_emp_oce   , 'e', True)
+prtFlux ('  EMP_ICE      ', OCE_mas_emp_ice   , 'e', True)
+prtFlux ('  EMP          ', OCE_mas_emp       , 'e', True)
+prtFlux ('  ICEBERG      ', OCE_mas_iceberg   , 'e',     )
+prtFlux ('  ICESHELF     ', OCE_mas_iceshelf  , 'e', True)
+prtFlux ('  CALVING      ', OCE_mas_calving   , 'e', True)
+prtFlux ('  FRIVER       ', OCE_mas_friver    , 'e',     )  
+prtFlux ('  RUNOFFS      ', OCE_mas_runoffs   , 'e', True)
+prtFlux ('  WFXICE       ', OCE_mas_wfxice    , 'e', True)
+prtFlux ('  WFXSNW       ', OCE_mas_wfxsnw    , 'e', True)
+prtFlux ('  WFXSUB       ', OCE_mas_wfxsub    , 'e', True)
+prtFlux ('  WFXPND       ', ICE_mas_wfxpnd    , 'e', True)
+prtFlux ('  WFXSNW_SUB   ', ICE_mas_wfxsnw_sub, 'e', True)
+prtFlux ('  WFXSNW_PRE   ', ICE_mas_wfxsnw_pre, 'e', True)
+prtFlux ('  WFXSUB_ERR   ', ICE_mas_wfxsub_err, 'e', True)
+prtFlux ('  EVAP_OCE     ', OCE_mas_evap_oce  , 'e'      )
+prtFlux ('  EVAP_ICE     ', ICE_mas_evap_ice  , 'e', True)
+prtFlux ('  SNOW_OCE     ', OCE_mas_snow_oce  , 'e', True)
+prtFlux ('  SNOW_ICE     ', OCE_mas_snow_ice  , 'e', True)
+prtFlux ('  RAIN         ', OCE_mas_rain      , 'e'      )
+prtFlux ('  FWB          ', OCE_mas_fwb       , 'e', True)
+prtFlux ('  SSR          ', OCE_mas_ssr       , 'e', True)
+prtFlux ('  WFCORR       ', OCE_mas_wfcorr    , 'e', True)
+prtFlux ('  BERG_ICB     ', OCE_mas_berg_icb  , 'e', True)
+prtFlux ('  CALV_ICB     ', OCE_mas_calv_icb  , 'e', True)
+
+
+echo (' ')
+
+prtFlux ( 'wbilo sea  ', ATM_flux_int (ATM_wbilo_sea), 'e',   )
+prtFlux ( 'costalflow ', ONE_flux_int (RUN_coastalflow), 'e',   )
+prtFlux ( 'riverflow  ', RUN_flx_river  , 'e',   )
+prtFlux ( 'costalflow ', RUN_flx_coastal, 'e',   )
+prtFlux ( 'runoff     ', RUN_flx_river+RUN_flx_coastal, 'e',   )
+
+ATM_to_OCE   =  ATM_flux_int (ATM_wbilo_sea) - RUN_flx_river - RUN_flx_coastal - ATM_flx_calving
+#OCE_from_ATM = -OCE_mas_emp_oce - OCE_mas_emp_ice + OCE_mas_runoffs + OCE_mas_iceberg + OCE_mas_calving + OCE_mas_iceshelf
+OCE_from_ATM = OCE_mas_all
+
+prtFlux ( 'ATM_to_OCE  ', ATM_to_OCE  , 'e', True )
+prtFlux ( 'OCE_from_ATM', OCE_from_ATM, 'e', True )
Index: TOOLS/WATER_BUDGET/OCE_waterbudget.py
===================================================================
--- TOOLS/WATER_BUDGET/OCE_waterbudget.py	(revision 6620)
+++ TOOLS/WATER_BUDGET/OCE_waterbudget.py	(revision 6647)
@@ -39,4 +39,6 @@
 import nemo, lmdz
 
+from WaterUtils import VarInt, Rho, Ra, Grav, ICE_rho_ice, ICE_rho_sno, OCE_rho_liq, ATM_rho, SRF_rho, RUN_rho, ICE_rho_pnd, YearLength
+
 ## Creates parser for reading .ini input file
 ## -------------------------------------------
@@ -47,6 +49,7 @@
 ## ---------------------
 ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False
-OCE_icb=False ; Coupled=False ; Routing=None
+OCE_icb=False ; Coupled=False ; Routing=None ; TestInterp=None
 TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None
+YearBegin=None ; YearEnd=None ; DateBegin=None ; DateEnd=None
 
 ##
@@ -66,4 +69,11 @@
 tar_restart_end_RUN=None ; tar_restart_end_OCE=None ; tar_restart_end_ICE=None
 ContinueOnError=False ; ErrorCount=0 ; SortIco = False
+
+##
+## Precision of history file reading
+## ---------------------------------
+# Default is float (full precision). Degrade the precision by using np.float32
+# Restart file are always read at the full precision
+readPrec=float
 
 ## Read command line arguments
@@ -137,5 +147,14 @@
 
 print ( f'\nConfig file readed : {IniFile} ' )
-            
+
+##
+## Reading prec
+if wu.unDefined ( 'readPrec' )  :
+    readPrec = np.float64
+else :
+    if readPrec in ["float", "float64", "r8", "double", "<class 'float'>"         ] : readPrec = float
+    if readPrec in [         "float32", "r4", "single", "<class 'numpy.float32'>" ] : readPrec = np.float32
+    if readPrec in [         "float16", "r2", "half"  , "<class 'numpy.float16'>" ] : readPrec = np.float16
+              
 ## Some physical constants
 ## =======================
@@ -155,8 +174,8 @@
 if not 'Files' in config.keys () : config['Files'] = {}
 
-config['Physics'] = { 'Ra':Ra, 'Grav':Grav, 'ICE_rho_ice':ICE_rho_ice, 'ICE_rho_sno':ICE_rho_sno,
-                      'OCE_rho_liq':OCE_rho_liq, 'ATM_rho':ATM_rho, 'SRF_rho':SRF_rho, 'RUN_rho':RUN_rho}
-
-config['Config'] = { 'ContinueOnError':ContinueOnError, 'SortIco':SortIco }
+config['Physics'] = { 'Ra':str(Ra), 'Grav':str(Grav), 'ICE_rho_ice':str(ICE_rho_ice), 'ICE_rho_sno':str(ICE_rho_sno),
+                      'OCE_rho_liq':str(OCE_rho_liq), 'ATM_rho':str(ATM_rho), 'SRF_rho':str(SRF_rho), 'RUN_rho':str(RUN_rho)}
+
+config['Config'] = { 'ContinueOnError':ContinueOnError, 'SortIco':SortIco, 'TestInterp':str(TestInterp), 'readPrec':str(readPrec) }
 
 ## --------------------------
@@ -178,14 +197,15 @@
     config['Experiment']['DateBegin'] = DateBegin
 else :
-    YearBegin, MonthBegin, DayBegin = wu.DateSplit ( DateBegin )
+    YearBegin, MonthBegin, DayBegin = wu.SplitDate ( DateBegin )
     DateBegin = wu.FormatToGregorian ( DateBegin)
-    config['Experiment']['YearBegin'] = YearBegin
+    config['Experiment']['YearBegin'] = str(YearBegin)
 
 if wu.unDefined ( 'DateEnd' )   :
     DateEnd   = f'{YearEnd}1231'
-    config['Experiment']['DateEnd']   = DateEnd
+    config['Experiment']['DateEnd']   = str(DateEnd)
 else :
-    YearEnd, MonthEnd, DayEnd = wu.DateSplit ( DateEnd )
+    YearEnd, MonthEnd, DayEnd = wu.SplitDate ( DateEnd )
     DateEnd   = wu.FormatToGregorian ( DateEnd)
+    config['Experiment']['DateEnd']   = str(DateEnd)
 
 if wu.unDefined ( 'PackFrequency' ) :
@@ -204,6 +224,10 @@
 ## Output file with water budget diagnostics
 ## -----------------------------------------
-if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{DateBegin}_{DateEnd}.out'
-config['Files']['FileOut'] = FileOut
+if wu.unDefined ( 'FileOut' ) :
+    FileOut = f'OCE_waterbudget_{JobName}_{YearBegin}_{YearEnd}'
+    if readPrec == np.float32 : FileOut = f'{FileOut}_float32'
+    FileOut = f'{FileOut}.out'
+
+    config['Files']['FileOut'] = FileOut
 
 f_out = open ( FileOut, mode = 'w' )
@@ -211,17 +235,24 @@
 ## Useful functions
 ## ----------------
-def kg2Sv  (val, rho=OCE_rho_liq) :
+
+# Degrades precision 
+if readPrec == float :
+    def rprec (tab) : return tab
+else : 
+    def rprec (tab) : return tab.astype(readPrec).astype(float)
+        
+def kg2Sv  (val, rho=ATM_rho) :
     '''From kg to Sverdrup'''
     return val/dtime_sec*1.0e-6/rho
 
-def kg2myear (val, rho=OCE_rho_liq) :
+def kg2myear (val, rho=ATM_rho) :
     '''From kg to m/year'''
     return val/OCE_aire_tot/rho/NbYear
 
-def var2prt (var, small=False, rho=OCE_rho_liq) :
+def var2prt (var, small=False, rho=ATM_rho) :
     if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000.
     else     :  return var , kg2Sv(var, rho=rho)      , kg2myear(var, rho=rho)
 
-def prtFlux (Desc, var, Form='F', small=False, rho=OCE_rho_liq, width=15) :
+def prtFlux (Desc, var, Form='F', small=False, rho=ATM_rho, width=15) :
     if small :
         if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} mSv | {:12.4f} mm/year "
@@ -330,7 +361,7 @@
 if NEMO == 3.6 :d_ICE_his = d_ICE_his.rename ( {'y_grid_T':'y', 'x_grid_T':'x'} )
 
-echo ( file_OCE_his )
-echo ( file_OCE_sca )
-echo ( file_ICE_his )
+echo ( f'{file_OCE_his = }' )
+echo ( f'{file_OCE_sca = }' )
+echo ( f'{file_ICE_his = }' )
 
 ## Compute run length
@@ -666,48 +697,48 @@
 
 # Read variable and computes integral over space and time
-OCE_empmr      = d_OCE_his['wfo']         ; OCE_mas_empmr    = OCE_flux_int ( OCE_empmr    )
-OCE_wfob       = d_OCE_his['wfob']        ; OCE_mas_wfob     = OCE_flux_int ( OCE_wfob     )
-OCE_emp_oce    = d_OCE_his['emp_oce']     ; OCE_mas_emp_oce  = OCE_flux_int ( OCE_emp_oce  )
-OCE_emp_ice    = d_OCE_his['emp_ice']     ; OCE_mas_emp_ice  = OCE_flux_int ( OCE_emp_ice  )
-OCE_iceshelf   = d_OCE_his['iceshelf']    ; OCE_mas_iceshelf = OCE_flux_int ( OCE_iceshelf )
-OCE_calving    = d_OCE_his['calving']     ; OCE_mas_calving  = OCE_flux_int ( OCE_calving  )
-OCE_iceberg    = d_OCE_his['iceberg']     ; OCE_mas_iceberg  = OCE_flux_int ( OCE_iceberg  )
-OCE_friver     = d_OCE_his['friver']      ; OCE_mas_friver   = OCE_flux_int ( OCE_friver   )
-OCE_runoffs    = d_OCE_his['runoffs']     ; OCE_mas_runoffs  = OCE_flux_int ( OCE_runoffs  )
+OCE_empmr      = rprec (d_OCE_his['wfo']     )    ; OCE_mas_empmr    = OCE_flux_int ( OCE_empmr    )
+OCE_wfob       = rprec (d_OCE_his['wfob']    )    ; OCE_mas_wfob     = OCE_flux_int ( OCE_wfob     )
+OCE_emp_oce    = rprec (d_OCE_his['emp_oce'] )    ; OCE_mas_emp_oce  = OCE_flux_int ( OCE_emp_oce  )
+OCE_emp_ice    = rprec (d_OCE_his['emp_ice'] )    ; OCE_mas_emp_ice  = OCE_flux_int ( OCE_emp_ice  )
+OCE_iceshelf   = rprec (d_OCE_his['iceshelf'])    ; OCE_mas_iceshelf = OCE_flux_int ( OCE_iceshelf )
+OCE_calving    = rprec (d_OCE_his['calving'] )    ; OCE_mas_calving  = OCE_flux_int ( OCE_calving  )
+OCE_iceberg    = rprec (d_OCE_his['iceberg'] )    ; OCE_mas_iceberg  = OCE_flux_int ( OCE_iceberg  )
+OCE_friver     = rprec (d_OCE_his['friver']  )    ; OCE_mas_friver   = OCE_flux_int ( OCE_friver   )
+OCE_runoffs    = rprec (d_OCE_his['runoffs'] )    ; OCE_mas_runoffs  = OCE_flux_int ( OCE_runoffs  )
 if NEMO == 4.0 or NEMO == 4.2 :
-    OCE_wfxice     = d_OCE_his['vfxice'] ; OCE_mas_wfxice   = OCE_flux_int ( OCE_wfxice )
-    OCE_wfxsnw     = d_OCE_his['vfxsnw'] ; OCE_mas_wfxsnw   = OCE_flux_int ( OCE_wfxsnw )
-    OCE_wfxsub     = d_OCE_his['vfxsub'] ; OCE_mas_wfxsub   = OCE_flux_int ( OCE_wfxsub )
+    OCE_wfxice     = rprec (d_OCE_his['vfxice']) ; OCE_mas_wfxice   = OCE_flux_int ( OCE_wfxice )
+    OCE_wfxsnw     = rprec (d_OCE_his['vfxsnw']) ; OCE_mas_wfxsnw   = OCE_flux_int ( OCE_wfxsnw )
+    OCE_wfxsub     = rprec (d_OCE_his['vfxsub']) ; OCE_mas_wfxsub   = OCE_flux_int ( OCE_wfxsub )
 if NEMO == 3.6 :
-    OCE_wfxice     = d_OCE_his['vfxice']/86400.*ICE_rho_ice ; OCE_mas_wfxice   = OCE_flux_int ( OCE_wfxice )
-    OCE_wfxsnw     = d_OCE_his['vfxsnw']/86400.*ICE_rho_sno ; OCE_mas_wfxsnw   = OCE_flux_int ( OCE_wfxsnw )
-    OCE_wfxsub     = d_OCE_his['vfxsub']/86400.*ICE_rho_sno ; OCE_mas_wfxsub   = OCE_flux_int ( OCE_wfxsub )
+    OCE_wfxice     = rprec (d_OCE_his['vfxice'])/86400.*ICE_rho_ice ; OCE_mas_wfxice   = OCE_flux_int ( OCE_wfxice )
+    OCE_wfxsnw     = rprec (d_OCE_his['vfxsnw'])/86400.*ICE_rho_sno ; OCE_mas_wfxsnw   = OCE_flux_int ( OCE_wfxsnw )
+    OCE_wfxsub     = rprec (d_OCE_his['vfxsub'])/86400.*ICE_rho_sno ; OCE_mas_wfxsub   = OCE_flux_int ( OCE_wfxsub )
 # Additional checks
-OCE_evap_oce   = d_OCE_his['evap_ao_cea'] ; OCE_mas_evap_oce   = OCE_flux_int ( OCE_evap_oce )
-ICE_evap_ice   = d_OCE_his['subl_ai_cea'] ; ICE_mas_evap_ice   = OCE_flux_int ( ICE_evap_ice )
-OCE_snow_oce   = d_OCE_his['snow_ao_cea'] ; OCE_mas_snow_oce   = OCE_flux_int ( OCE_snow_oce )
-OCE_snow_ice   = d_OCE_his['snow_ai_cea'] ; OCE_mas_snow_ice   = OCE_flux_int ( OCE_snow_ice )
-OCE_rain       = d_OCE_his['rain']        ; OCE_mas_rain       = OCE_flux_int ( OCE_rain     )
-ICE_wfxsub_err = d_ICE_his['vfxsub_err']  ; ICE_mas_wfxsub_err = OCE_flux_int ( ICE_wfxsub_err )
+OCE_evap_oce   = rprec (d_OCE_his['evap_ao_cea']) ; OCE_mas_evap_oce   = OCE_flux_int ( OCE_evap_oce )
+ICE_evap_ice   = rprec (d_OCE_his['subl_ai_cea']) ; ICE_mas_evap_ice   = OCE_flux_int ( ICE_evap_ice )
+OCE_snow_oce   = rprec (d_OCE_his['snow_ao_cea']) ; OCE_mas_snow_oce   = OCE_flux_int ( OCE_snow_oce )
+OCE_snow_ice   = rprec (d_OCE_his['snow_ai_cea']) ; OCE_mas_snow_ice   = OCE_flux_int ( OCE_snow_ice )
+OCE_rain       = rprec (d_OCE_his['rain']       ) ; OCE_mas_rain       = OCE_flux_int ( OCE_rain     )
+ICE_wfxsub_err = rprec (d_ICE_his['vfxsub_err'] ) ; ICE_mas_wfxsub_err = OCE_flux_int ( ICE_wfxsub_err )
 if NEMO == 4.0 or NEMO == 4.2 :
-    ICE_wfxpnd     = d_ICE_his['vfxpnd']     ; ICE_mas_wfxpnd     = OCE_flux_int ( ICE_wfxpnd     )
-    ICE_wfxsnw_sub = d_ICE_his['vfxsnw_sub'] ; ICE_mas_wfxsnw_sub = OCE_flux_int ( ICE_wfxsnw_sub )
-    ICE_wfxsnw_pre = d_ICE_his['vfxsnw_pre'] ; ICE_mas_wfxsnw_pre = OCE_flux_int ( ICE_wfxsnw_pre )
+    ICE_wfxpnd     = rprec (d_ICE_his['vfxpnd']    ) ; ICE_mas_wfxpnd     = OCE_flux_int ( ICE_wfxpnd     )
+    ICE_wfxsnw_sub = rprec (d_ICE_his['vfxsnw_sub']) ; ICE_mas_wfxsnw_sub = OCE_flux_int ( ICE_wfxsnw_sub )
+    ICE_wfxsnw_pre = rprec (d_ICE_his['vfxsnw_pre']) ; ICE_mas_wfxsnw_pre = OCE_flux_int ( ICE_wfxsnw_pre )
 if NEMO == 3.6 :
     ICE_wfxpnd = 0.0 ; ICE_mas_wfxpnd = 0.0
-    ICE_wfxsnw_sub = d_ICE_his['vfxsub']/86400.*ICE_rho_sno  ; ICE_mas_wfxsnw_sub = OCE_flux_int ( ICE_wfxsnw_sub )
-    ICE_wfxsnw_pre = d_ICE_his['vfxspr']/86400.*ICE_rho_sno  ; ICE_mas_wfxsnw_pre = OCE_flux_int ( ICE_wfxsnw_pre     )
-
-OCE_wfcorr    = d_OCE_his['wfcorr'] ; OCE_mas_wfcorr  = OCE_flux_int ( OCE_wfcorr )
+    ICE_wfxsnw_sub = rprec (d_ICE_his['vfxsub'])/86400.*ICE_rho_sno  ; ICE_mas_wfxsnw_sub = OCE_flux_int ( ICE_wfxsnw_sub )
+    ICE_wfxsnw_pre = rprec (d_ICE_his['vfxspr'])/86400.*ICE_rho_sno  ; ICE_mas_wfxsnw_pre = OCE_flux_int ( ICE_wfxsnw_pre     )
+
+OCE_wfcorr    = rprec (d_OCE_his['wfcorr']) ; OCE_mas_wfcorr  = OCE_flux_int ( OCE_wfcorr )
 if OCE_relax  :
     # ssr and fwb are included in emp=>empmr but not in emp_oce (outputed by sea-ice)
-    OCE_vflx_fwb = d_OCE_his['vflx_fwb'] ; OCE_mas_vflx_fwb   = OCE_flux_int ( OCE_vflx_fwb )
-    OCE_vflx_ssr = d_OCE_his['vflx_ssr'] ; OCE_mas_vflx_ssr   = OCE_flux_int ( OCE_vflx_ssr )
+    OCE_vflx_fwb = rprec (d_OCE_his['vflx_fwb']) ; OCE_mas_vflx_fwb   = OCE_flux_int ( OCE_vflx_fwb )
+    OCE_vflx_ssr = rprec (d_OCE_his['vflx_ssr']) ; OCE_mas_vflx_ssr   = OCE_flux_int ( OCE_vflx_ssr )
 else : 
     OCE_fwb = 0.0 ; OCE_mas_fwb = 0.0
     OCE_ssr = 0.0 ; OCE_mas_ssr = 0.0
 if OCE_icb :
-    OCE_berg_icb    = d_OCE_his['berg_floating_melt'] ; OCE_mas_berg_icb = OCE_flux_int ( OCE_berg_icb    )
-    OCE_calving_icb = d_OCE_his['calving_icb']        ; OCE_mas_calv_icb = OCE_flux_int ( OCE_calving_icb )
+    OCE_berg_icb    = rprec (d_OCE_his['berg_floating_melt']) ; OCE_mas_berg_icb = OCE_flux_int ( OCE_berg_icb    )
+    OCE_calving_icb = rprec (d_OCE_his['calving_icb']       ) ; OCE_mas_calv_icb = OCE_flux_int ( OCE_calving_icb )
 else :
     OCE_berg_icb = 0. ; OCE_mas_berg_icb = 0.
@@ -715,6 +746,5 @@
 
 OCE_mas_emp = OCE_mas_emp_oce - OCE_mas_wfxice - OCE_mas_wfxsnw - ICE_mas_wfxpnd - ICE_mas_wfxsub_err
-
-OCE_mas_all = OCE_mas_emp_oce +OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf
+OCE_mas_all = OCE_mas_emp_oce + OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf
 
 echo ('\n-- Fields:' ) 
@@ -748,4 +778,11 @@
 prtFlux ('  CALV_ICB     ', OCE_mas_calv_icb  , 'e', True)
 
+echo (' ')
+if Coupled :
+    prtFlux ( 'Bilan ocean :', -OCE_mas_emp_oce - OCE_mas_emp_ice + OCE_mas_runoffs + OCE_mas_iceshelf, 'e', True )
+else :
+    prtFlux ( 'Bilan ocean :', -OCE_mas_emp_oce - OCE_mas_emp_ice + OCE_mas_runoffs + OCE_mas_iceberg + OCE_mas_calving + OCE_mas_iceshelf, 'e', True )
+
+
 echo     ('\n===>  Comparing ===>' ) 
 echo     ('  WFX OCE                     = -empmr + iceshelf                                            = {:12.5e} (kg) '.format ( -OCE_mas_empmr + OCE_mas_iceshelf) )
@@ -770,7 +807,7 @@
 echo ('                        = (dSEA_mas_wat + emp_oce + emp_ice - runoffs - iceshelf)*/abs(dSEA_mas_wat)      = {:12.1e} (-)  '.format ( (dSEA_mas_wat + OCE_mas_emp_oce + OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf)/abs(dSEA_mas_wat) ) )
 
-prtFlux ('   Leak OCE             ', ( dOCE_mas_wat + OCE_mas_empmr - OCE_mas_iceshelf) , 'e' )
-prtFlux ('   Leak ICE+SNW+PND     ', ( dICE_mas_wat + OCE_mas_emp_ice + OCE_mas_wfxice + OCE_mas_wfxsnw + ICE_mas_wfxpnd + ICE_mas_wfxsub_err ) , 'e' )
-prtFlux ('   Leak OCE+ICE+SNW+PND ',  ( dSEA_mas_wat + OCE_mas_emp_oce +OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf ) , 'e' )
+prtFlux ('   Leak OCE             ', ( dOCE_mas_wat + OCE_mas_empmr - OCE_mas_iceshelf) , 'e', True )
+prtFlux ('   Leak ICE+SNW+PND     ', ( dICE_mas_wat + OCE_mas_emp_ice + OCE_mas_wfxice + OCE_mas_wfxsnw + ICE_mas_wfxpnd + ICE_mas_wfxsub_err ) , 'e', True )
+prtFlux ('   Leak OCE+ICE+SNW+PND ',  ( dSEA_mas_wat + OCE_mas_emp_oce +OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf ) , 'e', True )
 
 
Index: TOOLS/WATER_BUDGET/WaterUtils.py
===================================================================
--- TOOLS/WATER_BUDGET/WaterUtils.py	(revision 6620)
+++ TOOLS/WATER_BUDGET/WaterUtils.py	(revision 6647)
@@ -70,6 +70,7 @@
 def unDefined (char) :
     '''True if a variable is not defined, or set to None'''
-    if char in locals () :
-        if locals()[char] == None : unDefined = True
+    if char in globals () :
+        if globals()[char] == None :
+                unDefined = True
         else            : unDefined = False
     else                : unDefined = True
@@ -79,5 +80,6 @@
     '''True if a variable is defined and not equal to None'''
     if char in globals () :
-        if globals()[char] == None : Defined = False
+        if globals()[char] == None :
+                Defined = False
         else            : Defined = True
     else                : Defined = False
Index: TOOLS/WATER_BUDGET/lmdz.py
===================================================================
--- TOOLS/WATER_BUDGET/lmdz.py	(revision 6620)
+++ TOOLS/WATER_BUDGET/lmdz.py	(revision 6647)
@@ -28,5 +28,5 @@
 __Date__     = "$Date$"
 __Revision__ = "$Revision$"
-__Id__       = "$Id: lmdz.py 6508 2023-06-13 10:58:38Z omamce $"
+__Id__       = "$Id: $"
 __HeadURL    = "$HeadURL$"
 
@@ -36,11 +36,11 @@
 except ImportError : pass
 
-#try    : import numba
-#except ImportError : pass
+try    : import numba
+except ImportError : pass
 
 rpi = np.pi ; rad = np.deg2rad (1.0) ; dar = np.rad2deg (1.0)
 
 
-def __math__ (tab) :
+def __mmath__ (tab) :
     '''
     Determines the type of tab : i.e. numpy or xarray
@@ -71,5 +71,5 @@
     
     '''
-    math = __math__ (tab)
+    math = __mmath__ (tab)
     if tab.shape[-1] == 1 : extend = tab
 
@@ -99,5 +99,5 @@
     return extend
 
-def interp1d (x, xp, yp, zdim='presnivs', verbose=False, method='linear') :
+def interp1d (x, xp, yp, zdim='presnivs', units=None, verbose=False, method='linear') :
     '''
     One-dimensionnal interpolation of a multi-dimensionnal field
@@ -118,5 +118,5 @@
 
        \!/ xp should be decreasing values along zdim axis \!/
-    '''    
+    '''
     # Get the number of dimension with dim==zdim
     axis = list(xp.dims).index(zdim)
@@ -128,22 +128,28 @@
     # Define the result array
     in_shape       = np.array (xp.shape)
-    if verbose : print ( 'in_shape    : ', in_shape   )
+    if verbose : print ( f'{in_shape=}' )
     ou_shape       = np.array (in_shape)
-    if verbose : print ( 'ou_shape    : ', ou_shape   )
+    if verbose : print ( f'{ou_shape=}' )
     ou_shape[axis] = nk_ou
     
     in_dims        = list (yp.dims)
-    if verbose : print ( 'in_dims     : ', in_dims    )
+    if verbose : print ( f'{in_dims=}' )
     ou_dims        = in_dims
-    if verbose : print ( 'ou_dims     : ', ou_dims    )
+  
     pdim           = x.dims[0]
     ou_dims[axis]  = pdim
 
     new_coords = []
-    for coord in yp.dims :
-        if coord == zdim : new_coords.append (x.coords[pdim].values)
-        else             : new_coords.append (yp.coords[coord].values)
+    for i, dim in enumerate (yp.dims) :
+        if dim == zdim :
+            ou_dims[i] = x.dims[0]
+            if units != None : yp[dim].attrs['units'] = units
+            new_coords.append (x             .values)
+        else :
+            new_coords.append (yp.coords[dim].values)
    
-    if verbose : print ( 'new_coords  : ', new_coords )
+    if verbose :
+        print ( f'{ou_dims   =}'     )
+        print ( f'{new_coords=}' )
         
     ou_tab = xr.DataArray (np.empty (ou_shape), dims=ou_dims, coords=new_coords)
@@ -159,38 +165,40 @@
 
     # Optimized (pre-compiled) interpolation loop
-    #@numba.jit(nopython=True)
-    def __interp (nk_ou, x, xp, yp, result) :
+    #@numba.jit (nopython=True)
+    def __interp (nk_ou, x, xp, yp) :
         # Interpolate
-        for k in np.arange (nk_ou) :
-            # Find index of the just above level
-            idk1 = np.minimum ( (x[k]-xp), 0.).argmax (dim=zdim)
-            idk2 = idk1 - 1
-            idk2 = np.maximum (idk2, 0)
-            
-            x1   = xp[{zdim:idk1}]
-            x2   = xp[{zdim:idk2}]
-            
-            dx1  = x[k] - x1
-            dx2  = x2   - x[k]
-            dx   = x2   - x1
-            dx1  = dx1/dx ; dx2 = dx2/dx
-            
-            y1   = yp[{zdim:idk1}]
-            y2   = yp[{zdim:idk2}]
-            
-            if 'linear'  in method : 
-                result = (dx1*y2 + dx2*y1)
-            if 'log'     in method :
-                if yp_min > 0. : 
-                    result = np.power(y2, dx1) * np.power(y1, dx2)
-                if yp_max < 0. :
-                    result = -np.power(-y2, dx1) * np.power(-y1, dx2)
-            if 'nearest' in method :
-                result = xr.where ( dx2>=dx1, y1, y2)
+        # Find index of the just above level
+        idk1 = np.minimum ( (x-xp), 0.).argmax (dim=zdim)
+        idk2 = idk1 - 1
+        idk2 = np.maximum (idk2, 0)
+        
+        x1   = xp[{zdim:idk1}]
+        x2   = xp[{zdim:idk2}]
+        
+        dx1  = x  - x1
+        dx2  = x2 - x
+        dx   = x2 - x1
+        dx1  = dx1/dx ; dx2 = dx2/dx
+        
+        y1   = yp[{zdim:idk1}]
+        y2   = yp[{zdim:idk2}]
+        
+        #print ( f'{k=} {idk1=} {idk2=} {x1=} {x2=} {dx=1} {dx2=} {y1=} {y2}' )
+        
+        if 'linear'  in method : 
+            result = (dx1*y2 + dx2*y1)
+        if 'log'     in method :
+            if yp_min > 0. : 
+                result = np.power(y2, dx1) * np.power(y1, dx2)
+            if yp_max < 0. :
+                result = -np.power(-y2, dx1) * np.power(-y1, dx2)
+        if 'nearest' in method :
+            result = xr.where ( dx2>=dx1, y1, y2)
                 
-            return result
-
-        result = __interp  (nk_ou, x, xp, yp, result)
-            
+        return result
+
+    for k in np.arange (nk_ou) :
+        result = __interp  (nk_ou, x[{pdim:k}], xp, yp)
+           
         # Put result in the final array
         ou_tab [{pdim:k}] = result
@@ -198,4 +206,25 @@
     return ou_tab.squeeze()
 
+def fixed_lon (lon, center_lon=0.0) :
+    '''
+    Returns corrected longitudes for nicer plots
+
+    lon        : longitudes of the grid. At least 1D.
+    center_lon : center longitude. Default=0.
+
+    Designed by Phil Pelson. See https://gist.github.com/pelson/79cf31ef324774c97ae7
+    '''
+    mmath = __mmath__ (lon)
+    
+    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)
+    
+    start = np.argmax (np.abs (np.diff (fixed_lon, axis=-1)) > 180., axis=-1)
+    fixed_lon [start+1:] += 360.
+
+    return fixed_lon
+
 def nord2sud (p2D) :
     '''
@@ -210,5 +239,5 @@
     From 1D (restart type) to 2D
     '''
-    math = __math__ (p1D)
+    math = __mmath__ (p1D)
 
     # Get the dimensions
@@ -244,9 +273,9 @@
     return p2D
 
-def geo2point ( p2D, cumulPoles=False, dim1D='cell', debug=False ) : 
+def geo2point ( p2D, cumulPoles=False, dim1D='points_physiques' ) : 
     '''
     From 2D (lat, lon) to 1D (points_phyiques)
     '''
-    math = __math__ (p2D)
+    math = __mmath__ (p2D)
     #
     # Get the dimension
@@ -260,7 +289,4 @@
 
     jpn = jpi*(jpj-2) + 2
-
-    if debug :
-        print ( f'{jpi=} {jpj=} {jpn=} {jpt=}' )
 
     if jpt == -1 :
@@ -281,5 +307,5 @@
     if math == xr :
         p1D       = xr.DataArray (p1D)
-        for attr in p2D.attrs :
+        for attr in p2D.attrs : 
             p1D.attrs[attr] = p2D.attrs[attr]
         p1D       = p1D.rename ( {p1D.dims[0]:p2D.dims[0], p1D.dims[-1]:dim1D} )
@@ -291,9 +317,9 @@
     return p1D
 
-def geo3point ( p3D, cumulPoles=False, dim1D='cell' ) : 
+def geo3point ( p3D, cumulPoles=False, dim1D='points_physiques' ) : 
     '''
     From 3D (lev, lat, lon) to 2D (lev, points_phyiques)
     '''
-    math = __math__ (p3D)
+    math = __mmath__ (p3D)
     #
     # Get the dimensions
Index: TOOLS/WATER_BUDGET/nemo.py
===================================================================
--- TOOLS/WATER_BUDGET/nemo.py	(revision 6620)
+++ TOOLS/WATER_BUDGET/nemo.py	(revision 6647)
@@ -22,6 +22,8 @@
 Periodicity and other stuff
 
+- Lots of tests for xarray object
+- Not much testerd for numpy objects
+
 olivier.marti@lsce.ipsl.fr
-'''
 
 ## SVN information
@@ -29,6 +31,7 @@
 __Date__     = "$Date$"
 __Revision__ = "$Revision$"
-__Id__       = "$Id: nemo.py 6265 2022-11-02 12:45:56Z omamce $"
+__Id__       = "$Id: $"
 __HeadURL    = "$HeadURL$"
+'''
 
 import numpy as np
@@ -36,12 +39,9 @@
 except ImportError : pass
 
-try    : import f90nml
-except : pass
-
-try : from sklearn.impute import SimpleImputer
-except : pass
-
-try    : import numba
-except : pass
+#try    : import f90nml
+#except : pass
+
+#try : from sklearn.impute import SimpleImputer
+#except : pass
 
 rpi = np.pi ; rad = np.deg2rad (1.0) ; dar = np.rad2deg (1.0)
@@ -61,24 +61,39 @@
 repsi  = np.finfo (1.0).eps
 
-xList = [ 'x', 'X', 'lon'   , 'longitude' ]
-yList = [ 'y', 'Y', 'lat'   , 'latitude'  ]
-zList = [ 'z', 'Z', 'depth' , ]
-tList = [ 't', 'T', 'time'  , ]
+## Default names of dimensions
+dim_names = {'x':'xx', 'y':'yy', 'z':'olevel', 't':None}
+
+## 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 ]
+yLength = [ 148, 149, 331, 332 ]
+zLength = [31, 75]
 
 ## ===========================================================================
 def __mmath__ (tab, default=None) :
+    '''
+    Determines the type of tab : xarray or numpy object ?
+    '''
     mmath = default
     try    :
         if type (tab) == xr.core.dataarray.DataArray : mmath = xr
-    except :
-        pass
+    except : pass
 
     try    :
         if type (tab) == np.ndarray : mmath = np
-    except :
-        pass
+    except : pass
             
     return mmath
-
 
 def __guessNperio__ (jpj, jpi, nperio=None, out='nperio') :
@@ -99,5 +114,5 @@
     '''
     Tries to guess the value of nperio (periodicity parameter. See NEMO documentation for details)
-    
+
     Inputs
     jpj    : number of latitudes
@@ -105,11 +120,12 @@
     nperio : periodicity parameter
     '''
+    print ( jpi, jpj)
     if nperio == None :
         ## Values for NEMO version < 4.2
-        if jpj ==  149 and jpi ==  182 :
+        if (jpj ==  149 and jpi == 182) or (jpj == None and jpi == 182) or (jpj == 149 or jpi == None) :
             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.
+        if (jpj == 332 and jpi == 362) or (jpj == None and jpi == 362) or (jpj ==  332 and jpi == None) : # eORCA1.
             config = 'eORCA1.2'
             nperio = 6  
@@ -125,9 +141,9 @@
             
         ## Values for NEMO version >= 4.2. No more halo points
-        if jpj == 148 and jpi ==  180 :
+        if (jpj == 148 and jpi == 180) or (jpj == None and jpi == 180) or (jpj == 148 and jpi == None) :
             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.
+        if (jpj == 331 and jpi == 360) or (jpj == None and jpi == 360) or (jpj == 331 and jpi == None) : # eORCA1.
             config = 'eORCA1.4'
             nperio = 6.2
@@ -142,7 +158,7 @@
         else :
             if nperio in nperio_valid_range :
-                print ('nperio set as {:} (deduced from jpj={:d} jpi={:d})'.format (nperio, jpj, jpi))
+                print ( f'nperio set as {nperio} (deduced from {jpj=} and {jpi=})' )
             else : 
-                raise ValueError ('nperio set as {:} (deduced from jpi={:d}) : nemo.py is not ready for this value'.format (nperio, jpi))
+                raise ValueError ( f'nperio set as {nperio} (deduced from {jpi=} and {jpj=}) : nemo.py is not ready for this value' )
 
     if out == 'nperio' : return nperio
@@ -162,4 +178,5 @@
     Credits : who is the original author ?
     '''
+    
     gP = None
     mmath = __mmath__ (ptab)
@@ -178,9 +195,29 @@
             raise Exception ('in nemo module : cd_type not found, and cannot by guessed')
         else :
-            print ('Grid set as', gP, 'deduced from dims ', ptab.dims)
+            print ( f'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')
 
+def get_shape ( ptab ) :
+    '''
+    Get shape of ptab : 
+    shape main contain X, Y, Z or T
+    Y is missing for a latitudinal slice
+    X is missing for on longitudinal slice
+    etc ...
+    '''
+    
+    get_shape = ''
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
+    kz, az = __findAxis__ (ptab, 'z')
+    lt, at = __findAxis__ (ptab, 't')
+    if ax : get_shape = 'X'
+    if ay : get_shape = 'Y' + get_shape
+    if az : get_shape = 'Z' + get_shape
+    if at : get_shape = 'T' + get_shape
+    return get_shape
+     
 def lbc_diag (nperio) :
     lperio = nperio ; aperio = False
@@ -190,36 +227,20 @@
         lperio = 6 ; aperio = True
         
-    return lperio, aperio 
+    return lperio, aperio
 
 def __findAxis__ (tab, axis='z') :
     '''
-    Find number and name of the requested axis
+    Find order 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' ]
+    if axis in xName : axName = xName ; unList = xUnit ; Length = xLength
+    if axis in yName : axName = yName ; unList = yUnit ; Length = yLength
+    if axis in zName : axName = zName ; unList = zUnit ; Length = zLength
+    if axis in tName : axName = tName ; unList = tUnit ; Length = None
     
     if mmath == xr :
-        for Name in axList :
+        for Name in axName :
             try    :
                 ix = tab.dims.index (Name)
@@ -231,19 +252,25 @@
                 for name in unList :
                     if name in tab.coords[dim].attrs['units'] :
-                        ix = i
-                        ax = dim
+                        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
+        #if axis in xName : ix=-1
+        #if axis in yName :
+        #    if len(tab.shape) >= 2 : ix=-2
+        #if axis in zName :
+        #    if len(tab.shape) >= 3 : ix=-3
+        #if axis in tName :
+        #    if len(tab.shape) >=3  : ix=-3
+        #    if len(tab.shape) >=4  : ix=-4
+
+        l_shape = tab.shape
+        for nn in np.arange ( len(l_shape)) :
+            if l_shape[nn] in Length : ix = nn
        
     return ix, ax
 
-#@numba.jit(forceobj=True)
+def findAxis ( tab, axis= 'z' ) :
+  ix, xx = __findAxis__ (tab, axis)
+  return xx
+
 def fixed_lon (lon, center_lon=0.0) :
     '''
@@ -277,5 +304,44 @@
     return fixed_lon
 
-#@numba.jit(forceobj=True)
+def bounds_clolon ( bounds_lon, lon, rad=False, deg=True) :
+    '''Choose closest to lon0 longitude, adding or substacting 360Â° if needed'''
+
+    if rad : lon_range = 2.0*np.pi
+    if deg : lon_range = 360.0
+    bounds_clolon = bounds_lon.copy ()
+
+    bounds_clolon = xr.where ( bounds_clolon < lon-lon_range/2., bounds_clolon+lon_range, bounds_clolon )
+    bounds_clolon = xr.where ( bounds_clolon > lon+lon_range/2., bounds_clolon-lon_range, bounds_clolon )
+
+    return bounds_clolon
+
+def UnifyDims ( dd, udims=dim_names, verbose=False ) :
+    '''
+    Rename dimensions to unify them between NEMO versions
+    '''
+    
+    if udims['x'] :
+        for xx in xName :
+            if xx in dd.dims and xx != udims['x'] :
+                if verbose : print ( f"{xx} renamed to {udims['x']}" )
+                dd = dd.rename ( {xx:udims['x']})
+    if udims['y'] :
+        for yy in yName :
+            if yy in dd.dims and yy != udims['y']  :
+                if verbose : print ( f"{yy} renamed to {udims['y']}" )
+                dd = dd.rename ( {yy:udims['y']} )
+    if udims['z'] :
+        for zz in zName :
+            if zz in dd.dims and zz != udims['z'] :
+                if verbose : print ( f"{zz} renamed to {udims['z']}" )
+                dd = dd.rename ( {zz:udims['z']} )
+    if udims['t'] :
+        for tt in tName  :
+            if tt in dd.dims and tt != udims['t'] :
+                if verbose : print ( f"{tt} renamed to {udims['t']}" )
+                dd = dd.rename ( {tt:udims['t']} )
+
+    return dd
+
 def fill_empty (ztab, sval=np.nan, transpose=False) :
     '''
@@ -283,7 +349,8 @@
 
     Useful when NEMO has run with no wet points options : 
-    some parts of the domain, with no ocean points, has no
-    lon/lat values
-    '''
+    some parts of the domain, with no ocean points, have no
+    values
+    '''
+    from sklearn.impute import SimpleImputer
     mmath = __mmath__ (ztab)
 
@@ -302,5 +369,4 @@
     return ptab
 
-#@numba.jit(forceobj=True)
 def fill_lonlat (lon, lat, sval=-1) :
     '''
@@ -308,7 +374,8 @@
 
     Useful when NEMO has run with no wet points options : 
-    some parts of the domain, with no ocean points, as no
+    some parts of the domain, with no ocean points, have no
     lon/lat values
     '''
+    from sklearn.impute import SimpleImputer
     mmath = __mmath__ (lon)
 
@@ -328,5 +395,32 @@
     return plon, plat
 
-#@numba.jit(forceobj=True)
+def fill_bounds_lonlat (bounds_lon, bounds_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__ (bounds_lon)
+
+    p_bounds_lon = np.empty ( bounds_lon.shape )
+    p_bounds_lat = np.empty ( bounds_lat.shape )
+
+    imp = SimpleImputer (missing_values=sval, strategy='mean')
+    
+    for n in np.arange (4) : 
+        imp.fit (bounds_lon[:,:,n])
+        p_bounds_lon[:,:,n] = imp.transform (bounds_lon[:,:,n])
+        imp.fit (bounds_lat[:,:,n].T)
+        p_bounds_lat[:,:,n] = imp.transform (bounds_lat[:,:,n].T).T
+        
+    if mmath == xr :
+        p_bounds_lon = xr.DataArray (bounds_lon, dims=bounds_lon.dims, coords=bounds_lon.coords)
+        p_bounds_lat = xr.DataArray (bounds_lat, dims=bounds_lat.dims, coords=bounds_lat.coords)
+        p_bounds_lon.attrs = bounds_lat.attrs ; p_bounds_lat.attrs = bounds_lat.attrs
+        
+    return p_bounds_lon, p_bounds_lat
+
 def jeq (lat) :
     '''
@@ -337,13 +431,12 @@
     mmath = __mmath__ (lat)
     ix, ax = __findAxis__ (lat, 'x')
-    iy, ay = __findAxis__ (lat, 'y')
+    jy, ay = __findAxis__ (lat, 'y')
 
     if mmath == xr :
-        jeq = int ( np.mean ( np.argmin (np.abs (np.float64 (lat)), axis=iy) ) )
+        jeq = int ( np.mean ( np.argmin (np.abs (np.float64 (lat)), axis=jy) ) )
     else : 
         jeq = np.argmin (np.abs (np.float64 (lat[...,:, 0])))
     return jeq
 
-#@numba.jit(forceobj=True)
 def lon1D (lon, lat=None) :
     '''
@@ -354,21 +447,28 @@
     '''
     mmath = __mmath__ (lon)
-    if np.max (lat) != None :
+    jpj, jpi  = lon.shape [-2:]
+    if np.max (lat) :
         je    = jeq (lat)
-        lon1D = lon.copy() [..., je, :]
+        #lon1D = lon.copy() [..., je, :]
+        lon0 = lon [..., je, 0].copy()
+        dlon = lon [..., je, 1].copy() - lon [..., je, 0].copy()
+        lon1D = np.linspace ( start=lon0, stop=lon0+360.+2*dlon, num=jpi )
     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
+        lon0 = lon [..., jpj//3, 0].copy()
+        dlon = lon [..., jpj//3, 1].copy() - lon [..., jpj//3, 0].copy()
+        lon1D = 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 = xr.DataArray( lon1D, dims=('lon',), coords=(lon1D,))
         lon1D.attrs = lon.attrs
-        lon1D = lon1D.assign_coords ( {'x':lon1D} )
+        lon1D.attrs['units']         = 'degrees_east'
+        lon1D.attrs['standard_name'] = 'longitude'
+        lon1D.attrs['long_name :']   = 'Longitude'
         
     return lon1D
 
-#@numba.jit(forceobj=True)
 def latreg (lat, diff=0.1) :
     '''
@@ -381,6 +481,7 @@
     if diff == None :
         dy   = np.float64 (np.mean (np.abs (lat - np.roll (lat,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
@@ -390,5 +491,4 @@
     return jreg, latreg
 
-#@numba.jit(forceobj=True)
 def lat1D (lat) :
     '''
@@ -403,23 +503,32 @@
     je     = jeq (lat)
     lat_eq = np.float64 (lat[...,je,:].mean(axis=-1))
-      
+     
     jreg, lat_reg = latreg (lat)
     lat_ave = np.mean (lat, axis=-1)
 
+    #print ( f'{dy=} {jpj=} {je=} {lat_eq=} {jreg=} ' )
+    
     if (np.abs (lat_eq) < dy/100.) : # T, U or W grid
-        dys    = (90.-lat_reg) / (jpj-jreg-1)*0.5
-        yrange = 90.-dys-lat_reg
+        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 :
+        lat1D = mmath.where (lat_ave<lat_reg, lat_ave, lat_reg + yrange * (np.arange(jpj)-jreg)/(jpj-jreg-1) )
+    else :
+        lat1D = lat_ave
+    lat1D[-1] = 90.0
+
     if mmath == xr :
+        lat1D = xr.DataArray( lat1D.values, dims=('lat',), coords=(lat1D,))
         lat1D.attrs = lat.attrs
-        lat1D = lat1D.assign_coords ( {'y':lat1D} )
-
+        lat1D.attrs ['units']         = 'degrees_north'
+        lat1D.attrs ['standard_name'] = 'latitude'
+        lat1D.attrs ['long_name :']   = 'Latitude'
+        
     return lat1D
 
-#@numba.jit(forceobj=True)
 def latlon1D (lat, lon) :
     '''
@@ -430,5 +539,4 @@
     return lat1D (lat),  lon1D (lon, lat)
 
-#@numba.jit(forceobj=True)
 def mask_lonlat (ptab, x0, x1, y0, y1, lon, lat, sval=np.nan) :
     mmath = __mmath__ (ptab)
@@ -445,9 +553,10 @@
     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
     Works only for xarray and numpy data (?)
+
+    Useful for vertical sections in OCE and ATM.
 
     tab : field to extend.
@@ -539,13 +648,17 @@
     See NEMO documentation for further details
     '''
-    jpj, jpi = ptab.shape[-2:]
+    jpi = None ; jpj = None
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
+    if ax : jpi = ptab.shape[ix]
+    if ay : jpj = ptab.shape[jy]
+        
     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)
+        raise Exception ( 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) :
     '''
@@ -559,4 +672,6 @@
     '''
     jpj, jpi, nperio = lbc_init (ptab, nperio)
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
     psgn   = ptab.dtype.type (psgn)
     mmath = __mmath__ (ptab)
@@ -565,87 +680,89 @@
     else           : 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] = 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  ]
+            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 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 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 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 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) :
     #
@@ -659,73 +776,76 @@
     '''
     jpj, jpi, nperio = lbc_init (ptab, nperio)
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
     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
+            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 == '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
+                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) :
     '''
@@ -738,73 +858,76 @@
     See NEMO documentation for further details
     '''
-
     jpj, jpi, nperio = lbc_init (ptab, nperio)
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
     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
+    Handles NEMO domain changes between NEMO 4.0 to NEMO 4.2
       Peridodicity halo has been removed
     This routine adds the halos if needed
@@ -818,4 +941,7 @@
     mmath = __mmath__ (ptab) 
     jpj, jpi, nperio = lbc_init (ptab, nperio)
+    lshape = get_shape (ptab)
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
 
     t_shape = np.array (ptab.shape)
@@ -823,22 +949,31 @@
     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
+        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 '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
+            kz, az = __findAxis__ (ptab, 'z')
+            it, at = __findAxis__ (ptab, 't')
+            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)
@@ -848,5 +983,5 @@
 def lbc_del (ptab, nperio=None, cd_type='T', psgn=1) :
     '''
-    Handle NEMO domain changes between NEMO 4.0 to NEMO 4.2
+    Handles NEMO domain changes between NEMO 4.0 to NEMO 4.2
       Periodicity halo has been removed
     This routine removes the halos if needed
@@ -858,13 +993,23 @@
     See NEMO documentation for further details
     '''
-
     jpj, jpi, nperio = lbc_init (ptab, nperio)
+    lshape = get_shape (ptab)
+    ix, ax = __findAxis__ (ptab, 'x')
+    jy, ay = __findAxis__ (ptab, 'y')
 
     if nperio == 4.2 or nperio == 6.2 :
-        return lbc (ptab[..., :-1, 1:-1], nperio=nperio, cd_type=cd_type, psgn=psgn)
+        if ax or ay : 
+            if ax and ay : 
+                return lbc (ptab[..., :-1, 1:-1], nperio=nperio, cd_type=cd_type, psgn=psgn)
+            else : 
+                if ax :
+                    return lbc (ptab[...,      1:-1], nperio=nperio, cd_type=cd_type, psgn=psgn)
+                if ay :
+                    return lbc (ptab[..., -1], nperio=nperio, cd_type=cd_type, psgn=psgn)
+        else :
+            return ptab
     else :
         return ptab
 
-#@numba.jit(forceobj=True)
 def lbc_index (jj, ii, jpj, jpi, nperio=None, cd_type='T') :
     '''
@@ -951,5 +1096,61 @@
     return jy, ix
     
-#def geo2en (pxx, pyy, pzz, glam, gphi) : 
+def findJI (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]
+    <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
+    
+    # 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 - Grid:{lat_grid[jmin,imin]:4.1f}Â°N '   \
+            +   f'{lon_grid[jmin,imin]:4.1f}Â°E - Dist: {ra*distance[jmin,imin]:6.1f}km {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=='array' or out=='numpy'  or out=='np': return np.array ( [jmin, imin] )
+    elif out=='xarray' or out=='xr'                : return xr.DataArray ( [jmin, imin] )
+    elif out=='list'                               : return [jmin, imin]
+    elif out=='tuple'                              : return jmin, imin
+    else                                           : return jmin, imin
+
+def geo2en (pxx, pyy, pzz, glam, gphi) : 
     '''
     Change vector from geocentric to east/north
@@ -970,5 +1171,5 @@
     return pte, ptn
 
-#def en2geo (pte, ptn, glam, gphi) :
+def en2geo (pte, ptn, glam, gphi) :
     '''
     Change vector from east/north to geocentric
@@ -990,68 +1191,200 @@
     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) :
+
+def clo_lon (lon, lon0=0., rad=False, deg=True) :
     '''Choose closest to lon0 longitude, adding or substacting 360Â° if needed'''
     mmath = __mmath__ (lon, np)
-        
+    if rad : lon_range = 2.*np.pi
+    if deg : lon_range = 360.
     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)
+    clo_lon = mmath.where (clo_lon > lon0 + lon_range*0.5, clo_lon-lon_range, clo_lon)
+    clo_lon = mmath.where (clo_lon < lon0 - lon_range*0.5, clo_lon+lon_range, clo_lon)
+    clo_lon = mmath.where (clo_lon > lon0 + lon_range*0.5, clo_lon-lon_range, clo_lon)
+    clo_lon = mmath.where (clo_lon < lon0 - lon_range*0.5, clo_lon+lon_range, clo_lon)
     if clo_lon.shape == () : clo_lon = clo_lon.item ()
+    if mmath == xr :
+        try : 
+            for attr in lon.attrs : clo_lon.attrs[attr] = lon.attrs[attr]
+        except :
+            pass
     return clo_lon
 
-#def angle_full (glamt, gphit, glamu, gphiu, glamv, gphiv, glamf, gphif, nperio=None) :
+
+def index2depth (pk, gdept_0) :
+    '''
+    From index (real, continuous), get depth
+    '''
+    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)
+    '''
+    jpk  = gdept_0.shape[0]
+    if type (pz) == xr.core.dataarray.DataArray :
+        zz   = xr.DataArray (pz.values, dims=('zz',))
+    elif type (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))
+    
+    ff = (zz - gdept_0[idk2])/(gdept_0[idk1]-gdept_0[idk2])
+    idk = ff*idk1 + (1.0-ff)*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
+    '''
+    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
+    '''
+    jpk = gdept_0.shape[0]
+    if type (pz) == xr.core.dataarray.DataArray :
+        zz   = xr.DataArray (pz.values , dims=('zz',))
+    elif type (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))
+     
+    ff = (zz_comp - gdept_0[idk2])/(gdept_0[idk1]-gdept_0[idk2])
+    idk = ff*idk1 + (1.0-ff)*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
+    '''
+    #print ('start depth2comp')
+    if type (pz) == xr.core.dataarray.DataArray :
+        zz   = pz.values
+    elif type(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
+    #print ('end depth2comp')
+
+def comp2depth (pz, depth0, fact ) :
+    '''
+    Form compressed depth, get depth, with bottom part compressed
+    '''
+    if type (pz) == xr.core.dataarray.DataArray :
+        zz   = pz.values
+    elif type(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] : return gz.item()
+    else : return gz
+
+def index2lon (pi, lon1D) :
+    '''
+    From index (real, continuous), get longitude
+    '''
+    jpi = lon1D.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)*lon1D[i0]+ xx*lon1D[i1]
+    return gx.values
+
+def lon2index (px, lon1D) :
+    '''
+    From longitude, get index (real, continuous)
+    '''
+    jpi  = lon1D.shape[0]
+    if type (px) == xr.core.dataarray.DataArray :
+        xx   = xr.DataArray (px.values , dims=('xx',))
+    elif type (px) == np.ndarray :
+        xx   = xr.DataArray (px.ravel(), dims=('xx',))
+    else : 
+        xx   = xr.DataArray (np.array([px]).ravel(), dims=('xx',))
+    xx   = xr.where ( xx>lon1D.max(), xx-360.0, xx)
+    xx   = xr.where ( xx<lon1D.min(), xx+360.0, xx)
+    xx   = np.minimum (lon1D.max(), np.maximum(xx, lon1D.min() ))
+    idi1 = np.minimum ( (lon1D-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))
+    
+    ff = (xx - lon1D[idi2])/(lon1D[idi1]-lon1D[idi2])
+    idi = ff*idi1 + (1.0-ff)*idi2
+    idi = xr.where ( np.isnan(idi), idi1, idi)
+    return idi.values
+
+def index2lat (pj, lat1D) :
+    '''
+    From index (real, continuous), get latitude
+    '''
+    jpj = lat1D.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)*lat1D[j0]+ yy*lat1D[j1]
+    return gy.values
+
+def lat2index (py, lat1D) :
+    '''
+    From latitude, get index (real, continuous)
+    '''
+    jpj = lat1D.shape[0]
+    if type (py) == xr.core.dataarray.DataArray :
+        yy   = xr.DataArray (py.values , dims=('yy',))
+    elif type (py) == np.ndarray :
+        yy   = xr.DataArray (py.ravel(), dims=('yy',))
+    else : 
+        yy   = xr.DataArray (np.array([py]).ravel(), dims=('yy',))
+    yy   = np.minimum (lat1D.max(), np.minimum(yy, lat1D.max() ))
+    idj1 = np.minimum ( (lat1D-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))
+    
+    ff = (yy - lat1D[idj2])/(lat1D[idj1]-lat1D[idj2])
+    idj = ff*idj1 + (1.0-ff)*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) :
     '''Compute sinus and cosinus of model line direction with respect to east'''
     mmath = __mmath__ (glamt)
@@ -1234,10 +1567,10 @@
     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)
+    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' ) :
+def rot_uv2en ( uo, vo, gsint, gcost, nperio, zdim=None ) :
     '''
     ** Purpose :   Rotate the Repere: Change vector componantes from
@@ -1247,5 +1580,5 @@
     '''
     mmath = __mmath__ (uo)
-
+    
     ut = U2T (uo, nperio=nperio, psgn=-1.0, zdim=zdim)
     vt = V2T (vo, nperio=nperio, psgn=-1.0, zdim=zdim)
@@ -1259,5 +1592,5 @@
     return u_e, v_n
 
-def rot_uv2enF ( uo, vo, gsinf, gcosf, nperio, zdim='deptht' ) :
+def rot_uv2enF ( uo, vo, gsinf, gcosf, nperio, zdim=None ) :
     '''
     ** Purpose : Rotate the Repere: Change vector componantes from
@@ -1279,6 +1612,5 @@
     return u_e, v_n
 
-#@numba.jit(forceobj=True)
-def U2T (utab, nperio=None, psgn=-1.0, zdim='deptht', action='ave') :
+def U2T (utab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
     '''Interpolate an array from U grid to T grid i-mean)'''
     mmath = __mmath__ (utab)
@@ -1287,20 +1619,23 @@
     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)
-    
+    kz, az = __findAxis__ (utab_0, 'z')
+
+    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') :
+def V2T (vtab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
     '''Interpolate an array from V grid to T grid (j-mean)'''
     mmath = __mmath__ (vtab)
@@ -1308,29 +1643,31 @@
     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)
+    jy, ay = __findAxis__ (vtab_0, 'y')
+    kz, az = __findAxis__ (vtab_0, 'z')
+    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') :
+def F2T (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
     '''Interpolate 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') :
+def T2U (ttab, nperio=None, psgn=1.0, zdim=None, action='ave') :
     '''Interpolate an array from T grid to U grid (i-mean)'''
     mmath = __mmath__ (ttab)
@@ -1338,41 +1675,45 @@
     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)
-
+    kz, az = __findAxis__ (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 != None : 
+        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') :
+def T2V (ttab, nperio=None, psgn=1.0, zdim=None, action='ave') :
     '''Interpolate 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)
+    jy, ay = __findAxis__ (ttab_0, 'y')
+    kz, az = __findAxis__ (ttab_0, 'z')
+    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') :
+def V2F (vtab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
     '''Interpolate an array from V grid to F grid (i-mean)'''
     mmath = __mmath__ (vtab)
@@ -1380,41 +1721,45 @@
     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)
-    
+    kz, az = __findAxis__ (vtab_0, 'z')
+    if ix : 
+        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)
+    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') :
+def U2F (utab, nperio=None, psgn=-1.0, zdim=None, action='ave') :
     '''Interpolate 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)
-
+    jy, ay = __findAxis__ (utab_0, 'y')
+    kz, az = __findAxis__ (utab_0, 'z')
+    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') :
+def F2T (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
     '''Interpolate an array on F grid to T grid (i- and j- means)'''
     mmath = __mmath__ (ftab)
@@ -1424,37 +1769,36 @@
     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') :
+def T2F (ttab, nperio=None, psgn=1.0, zdim=None, action='mean') :
     '''Interpolate 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') :
+def F2U (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
     '''Interpolate an array on F grid to FUgrid (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)
-    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)
-    
+    jy, ay = __findAxis__ (ftab_0, 'y')
+    kz, az = __findAxis__ (ftab_0, 'z')
+    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 zz :
+            if 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') :
+def F2V (ftab, nperio=None, psgn=1.0, zdim=None, action='ave') :
     '''Interpolate an array from F grid to V grid (i-mean)'''
     mmath = __mmath__ (ftab)
@@ -1462,19 +1806,21 @@
     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)
+    kz, az = __findAxis__ (ftab_0, 'z')
+    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) :
+def W2T (wtab, zcoord=None, zdim=None, sval=np.nan) :
     '''
     Interpolate an array on W grid to T grid (k-mean)
@@ -1484,14 +1830,17 @@
     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) )
-    
+    kz, az = __findAxis__ (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,6 +1848,5 @@
     return ttab
 
-#@numba.jit(forceobj=True)
-def T2W (ttab, zcoord=None, zdim='depthw', sval=np.nan, extrap_surf=False) :
+def T2W (ttab, zcoord=None, zdim=None, sval=np.nan, extrap_surf=False) :
     '''Interpolate an array from T grid to W grid (k-mean)
     sval is the surface value
@@ -1507,6 +1855,6 @@
     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) )
+    kz, az = __findAxis__ (ttab_0, 'z')
+    wtab = 0.5 * ( ttab_0 + np.roll (ttab_0, axis=kz, shift=1) )
 
     if mmath == xr :
@@ -1518,11 +1866,12 @@
 
     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 :
+            if az != zdim : wtab = wtab.rename ( {az:zdim})
+        if zcoord is not None :
+            wtab = wtab.assign_coords ( {zdim:zcoord})
+        else :
+            ztab = 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.) :
     '''
@@ -1584,8 +1933,7 @@
     return ztab
 
-#@numba.jit(forceobj=True)
 def correct_uv (u, v, lat) :
     '''
-    Correct a Cartopy bug in Orthographic projection
+    Correct a Cartopy bug in orthographic projection
 
     See https://github.com/SciTools/cartopy/issues/1179
@@ -1593,7 +1941,8 @@
     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)
 
@@ -1608,57 +1957,73 @@
     return uc, vc
 
-def msf (v_e1v_e3v, lat1d, depthw) :
+def norm_uv (u, v) :
+    '''
+    Return norm of a 2 components vector
+    '''
+    return np.sqrt (u*u + v*v)
+
+def normalize_uv (u, v) :
+    '''
+    Normalize 2 components vector
+    '''
+    uv = norm_uv (u, v)
+    return u/uv, v/uv
+
+def msf (vv, 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'})
+ 
+    v_e1v_e3v = vv * e1v_e3v
+    v_e1v_e3v.attrs = vv.attrs
+    
+    ix, ax = __findAxis__ (v_e1v_e3v, 'x')
+    kz, az = __findAxis__ (v_e1v_e3v, 'z')
+    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} )
+    
+    jy, ay = __findAxis__ (zomsf, 'y' )
+    zomsf = zomsf.assign_coords ( {az:depthw.values, ay:lat1d.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[new_az].attrs  = depthw.attrs
     zomsf.lat.attrs=lat1d.attrs
         
     return zomsf
 
-def bsf (u_e2u_e3u, mask, nperio=None, bsf0=None ) :
+def bsf (uu, 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 :
+    bsf0 is the point with bsf=0 
+    (ex: bsf0={'x':3, 'y':120} for orca2, 
+         bsf0={'x':5, 'y':300} for eeORCA1
+    '''
+    u_e2u_e3u       = uu * e2u_e3u
+    u_e2u_e3u.attrs = uu.attrs
+
+    iy, ay = __findAxis__ (u_e2u_e3u, 'y')
+    kz, az = __findAxis__ (u_e2u_e3u, 'z')
+    
+    bsf = -u_e2u_e3u.cumsum ( dim=ay, keep_attrs=True )
+    bsf = bsf.sum (dim=az, keep_attrs=True)*1.E-6
+        
+    if bsf0 :
         bsf = bsf - bsf.isel (bsf0)
        
     bsf = bsf.where (mask !=0, np.nan)
-    bsf.attrs['long_name'] = 'Barotropic stream function'
-    bsf.attrs['units'] = 'Sv'
+    for attr in uu.attrs :
+        bsf.attrs[attr] = uu.attrs[attr]
+    bsf.attrs['standard_name'] = 'barotropic_stream_function'
+    bsf.attrs['long_name']     = 'Barotropic stream function'
+    bsf.attrs['units']         = 'Sv'
     bsf = lbc (bsf, nperio=nperio, cd_type='F')
        
@@ -1679,10 +2044,11 @@
     
     '''
-
-    if ref != None :
+    
+    import f90nml
+    if ref :
         if isinstance (ref, str) : nml_ref = f90nml.read (ref)
         if isinstance (ref, f90nml.namelist.Namelist) : nml_ref = ref
         
-    if cfg != None :
+    if cfg :
         if isinstance (cfg, str) : nml_cfg = f90nml.read (cfg)
         if isinstance (cfg, f90nml.namelist.Namelist) : nml_cfg = cfg
@@ -1693,8 +2059,6 @@
     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')
+    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) :
@@ -1719,5 +2083,4 @@
     if out == 'xr'   : return xr_namelist
 
-
 def fill_closed_seas (imask, nperio=None,  cd_type='T') :
     '''Fill closed seas with image processing library
@@ -1730,4 +2093,71 @@
 
     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 ) :
+    '''
+    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 ) :
+    '''
+    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
 
 ## ===========================================================================
