Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg	(revision 14055)
@@ -90,13 +90,4 @@
    !                       !    =2 annual global mean of e-p-r set to zero
    ln_wave     = .false.   !  Activate coupling with wave  (T => fill namsbc_wave)
-   ln_cdgw     = .false.   !  Neutral drag coefficient read from wave model (T => ln_wave=.true. & fill namsbc_wave)
-   ln_sdw      = .false.   !  Read 2D Surf Stokes Drift & Computation of 3D stokes drift (T => ln_wave=.true. & fill namsbc_wave) 
-   nn_sdrift   =  0        !  Parameterization for the calculation of 3D-Stokes drift from the surface Stokes drift
-      !                    !   = 0 Breivik 2015 parameterization: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
-      !                    !   = 1 Phillips:                      v_z=v_o*[exp(2*k*z)-beta*sqrt(-2*k*pi*z)*erfc(sqrt(-2*k*z))]
-      !                    !   = 2 Phillips as (1) but using the wave frequency from a wave model
-   ln_tauwoc   = .false.   !  Activate ocean stress modified by external wave induced stress (T => ln_wave=.true. & fill namsbc_wave)
-   ln_tauw     = .false.   !  Activate ocean stress components from wave model
-   ln_stcor    = .false.   !  Activate Stokes Coriolis term (T => ln_wave=.true. & ln_sdw=.true. & fill namsbc_wave)
 /
 !-----------------------------------------------------------------------
@@ -167,4 +158,27 @@
 &namsbc_wave   ! External fields from wave model                        (ln_wave=T)
 !-----------------------------------------------------------------------
+   ln_sdw      = .false.    !  get the 2D Surf Stokes Drift & Compute the 3D stokes drift
+   ln_stcor    = .false.    !  add Stokes Coriolis and tracer advection terms
+   ln_cdgw     = .false.    !  Neutral drag coefficient read from wave model
+   ln_tauoc    = .false.    !  ocean stress is modified by wave induced stress
+   ln_wave_test= .false.    !  Test case with constant wave fields
+!
+   ln_charn    = .false.     !  Charnock coefficient read from wave model (IFS only)
+   ln_taw      = .false.     !  ocean stress is modified by wave induced stress (coupled mode)
+   ln_phioc    = .false.     !  TKE flux from wave model
+   ln_bern_srfc= .false.     ! wave induced pressure. Bernoulli head J term
+   ln_breivikFV_2016 = .false. ! breivik 2016 vertical stokes profile
+   ln_vortex_force = .false.
+!
+   cn_dir      = './'      !  root directory for the waves data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_cdg      =  'sdw_ecwaves_orca2'    ,        6.         , 'drag_coeff' ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_usd      =  'sdw_ecwaves_orca2'    ,        6.         , 'u_sd2d'     ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_vsd      =  'sdw_ecwaves_orca2'    ,        6.         , 'v_sd2d'     ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_hsw      =  'sdw_ecwaves_orca2'    ,        6.         , 'hs'         ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wmp      =  'sdw_ecwaves_orca2'    ,        6.         , 'wmp'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wnum     =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_num'   ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
 /
 !-----------------------------------------------------------------------
@@ -378,4 +392,5 @@
                                !        = 2 add a tke source just at the base of the ML
                                !        = 3 as = 1 applied on HF part of the stress           (ln_cpl=T)
+      ln_mxhsw    = .false.   !  surface mixing length scale = F(wave height)
 /
 !-----------------------------------------------------------------------
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_cfg	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_cfg	(revision 14055)
@@ -20,31 +20,31 @@
 !
    ln_trcdta     =  .true.  !  Initialisation from data input file (T) or not (F)
-   ln_trcbc      =  .false. !  Enables Boundary conditions
+   ln_trcbc      =  .true.  !  Enables Boundary conditions
 !                !           !                                           !             !         !
-!                !    name   !           title of the field              !   units     ! init    ! sbc    ! cbc    !  obc  ! 
-   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' , .true.  , .false., .true. , .false. 
-   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   , .true.  , .false., .true. , .false.
-   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' , .true.  , .false., .false., .false. 
-   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' , .true.  , .false., .true. , .false.
-   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' , .false. , .false., .false., .false.
+!                !    name   !           title of the field              !   units     ! init    ! sbc    ! cbc    !  obc    !  ais
+   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' , .true.  , .false., .true. , .false. , .false.
+   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   , .true.  , .false., .true. , .false. , .false.
+   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' , .true.  , .false., .false., .false. , .false.
+   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .false.
+   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .false.
+   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' , .true.  , .false., .true. , .false. , .false.
+   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .true.
+   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .false.
+   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
 /
 !-----------------------------------------------------------------------
@@ -57,19 +57,19 @@
 !          !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
 !          !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_trcdta(1)  = 'data_DIC_nomask'        ,        -12.       ,  'DIC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(2)  = 'data_Alkalini_nomask'   ,        -12.       ,  'Alkalini',    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(3)  = 'data_O2_nomask'         ,        -1.        ,  'O2'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(5)  = 'data_PO4_nomask'        ,        -1.        ,  'PO4'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(7)  = 'data_Si_nomask'         ,        -1.        ,  'Si'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(10) = 'data_DOC_nomask'        ,        -12.       ,  'DOC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(14) = 'data_Fer_nomask'        ,        -12.       ,  'Fer'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(23) = 'data_NO3_nomask'        ,        -1.        ,  'NO3'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   rn_trfac(1)   =   1.0e-06  !  multiplicative factor
-   rn_trfac(2)   =   1.0e-06  !  -      -      -     -
+   sn_trcdta(1)  = 'data_DIC_nomask.nc',        -12        ,  'PiDIC'  ,    .false.   , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(2)  = 'data_ALK_nomask.nc',        -12        ,  'TALK'   ,    .false.   , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(3)  = 'data_OXY_nomask.nc',        -1         ,  'O2'     ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(5)  = 'data_PO4_nomask.nc',        -1         ,  'PO4'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(7)  = 'data_SIL_nomask.nc',        -1         ,  'Si'     ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(10) = 'data_DOC_nomask.nc',        -1         ,  'DOC'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(14) = 'data_FER_nomask.nc',        -1         ,  'Fer'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(23) = 'data_NO3_nomask.nc',        -1         ,  'NO3'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   rn_trfac(1)   =   1.028e-06  !  multiplicative factor
+   rn_trfac(2)   =   1.028e-06  !  -      -      -     -
    rn_trfac(3)   =  44.6e-06  !  -      -      -     -
    rn_trfac(5)   = 122.0e-06  !  -      -      -     -
    rn_trfac(7)   =   1.0e-06  !  -      -      -     -
-   rn_trfac(10)  =   1.0      !  -      -      -     -
-   rn_trfac(14)  =   1.0      !  -      -      -     -
+   rn_trfac(10)  =   1.0e-06  !  -      -      -     -
+   rn_trfac(14)  =   1.0e-06  !  -      -      -     -
    rn_trfac(23)  =   7.6e-06  !  -      -      -     -
 /
@@ -110,8 +110,8 @@
 !                !  file name        ! frequency (hours) ! variable      ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
 !                !                   !  (if <0  months)  !   name        !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_trcsbc(5)  = 'dust.orca.new'   ,       -1          , 'dustpo4'     ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trcsbc(7)  = 'dust.orca.new'   ,       -1          , 'dustsi'      ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trcsbc(14) = 'dust.orca.new'   ,       -1          , 'dustfer'     ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trcsbc(23) = 'ndeposition.orca',      -12          , 'ndep'        ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trcsbc(5)  = 'dust.orca.new'   ,       -1          , 'dustpo4'     ,  .true.      , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
+   sn_trcsbc(7)  = 'dust.orca.new'   ,       -1          , 'dustsi'      ,  .true.      , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
+   sn_trcsbc(14) = 'dust.orca.new'   ,       -1          , 'dustfer'     ,  .true.      , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
+   sn_trcsbc(23) = 'ndeposition.orca',      -12          , 'ndep2'       ,  .false.     , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
    rn_trsfac(5)  = 8.264e-02   !  (  0.021 / 31. * 122 )
    rn_trsfac(7)  = 3.313e-01     !  ( 8.8   / 28.1 )
@@ -120,11 +120,11 @@
    rn_sbc_time   =  1.          !  Time scaling factor for SBC and CBC data (seconds in a day)
    !
-   sn_trccbc(1)  = 'river.orca'      ,    120            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(2)  = 'river.orca'      ,    120            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(5)  = 'river.orca'      ,    120            , 'riverdip'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(7)  = 'river.orca'      ,    120            , 'riverdsi'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(10) = 'river.orca'      ,    120            , 'riverdoc'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(14) = 'river.orca'      ,    120            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(23) = 'river.orca'      ,    120            , 'riverdin'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(1)  = 'river.orca'      ,    -12            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(2)  = 'river.orca'      ,    -12            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(5)  = 'river.orca'      ,    -12            , 'riverdip'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(7)  = 'river.orca'      ,    -12            , 'riverdsi'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(10) = 'river.orca'      ,    -12            , 'riverdoc'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(14) = 'river.orca'      ,    -12            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(23) = 'river.orca'      ,    -12            , 'riverdin'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
    rn_trcfac(1)  = 8.333e+01   !  ( data in Mg/m2/yr : 1e3/12/ryyss)
    rn_trcfac(2)  = 8.333e+01   !  ( 1e3 /12 )
@@ -140,2 +140,6 @@
 !-----------------------------------------------------------------------
 /
+!-----------------------------------------------------------------------
+&namtrc_ais      !  Representation of Antarctic Ice Sheet tracers supply
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_cfg	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_cfg	(revision 14055)
@@ -19,32 +19,32 @@
    ln_c14        =  .false.
 !
-   ln_trcdta     =  .true.   !  Initialisation from data input file (T) or not (F)
-   ln_trcbc      =  .false.  !  Enables Boundary conditions
+   ln_trcdta     =  .true.  !  Initialisation from data input file (T) or not (F)
+   ln_trcbc      =  .true.  !  Enables Boundary conditions
 !                !           !                                           !             !         !
-!                !    name   !           title of the field              !   units     ! init    ! sbc    ! cbc    !  obc  ! 
-   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' , .true.  , .false., .true. , .false. 
-   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   , .true.  , .false., .true. , .false.
-   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' , .true.  , .false., .false., .false. 
-   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' , .true.  , .false., .true. , .false.
-   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' , .false. , .false., .false., .false.
-   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false.
-   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' , .false. , .false., .false., .false.
+!                !    name   !           title of the field              !   units     ! init    ! sbc    ! cbc    !  obc    !  ais
+   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' , .true.  , .false., .true. , .false. , .false.
+   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   , .true.  , .false., .true. , .false. , .false.
+   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' , .true.  , .false., .false., .false. , .false.
+   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .false.
+   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .false.
+   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' , .true.  , .false., .true. , .false. , .false.
+   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .true.
+   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
+   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' , .true.  , .true. , .true. , .false. , .false.
+   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' , .false. , .false., .false., .false. , .false.
 /
 !-----------------------------------------------------------------------
@@ -57,19 +57,19 @@
 !          !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
 !          !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_trcdta(1)  = 'data_DIC_nomask'        ,        -12.       ,  'DIC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(2)  = 'data_Alkalini_nomask'   ,        -12.       ,  'Alkalini',    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(3)  = 'data_O2_nomask'         ,        -1.        ,  'O2'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(5)  = 'data_PO4_nomask'        ,        -1.        ,  'PO4'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(7)  = 'data_Si_nomask'         ,        -1.        ,  'Si'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(10) = 'data_DOC_nomask'        ,        -12.       ,  'DOC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(14) = 'data_Fer_nomask'        ,        -12.       ,  'Fer'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
-   sn_trcdta(23) = 'data_NO3_nomask'        ,        -1.        ,  'NO3'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
-   rn_trfac(1)   =   1.0e-06  !  multiplicative factor
-   rn_trfac(2)   =   1.0e-06  !  -      -      -     -
+   sn_trcdta(1)  = 'data_DIC_nomask.nc',        -12        ,  'PiDIC'  ,    .false.   , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(2)  = 'data_ALK_nomask.nc',        -12        ,  'TALK'   ,    .false.   , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(3)  = 'data_OXY_nomask.nc',        -1         ,  'O2'     ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(5)  = 'data_PO4_nomask.nc',        -1         ,  'PO4'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(7)  = 'data_SIL_nomask.nc',        -1         ,  'Si'     ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(10) = 'data_DOC_nomask.nc',        -1         ,  'DOC'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(14) = 'data_FER_nomask.nc',        -1         ,  'Fer'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   sn_trcdta(23) = 'data_NO3_nomask.nc',        -1         ,  'NO3'    ,    .true.    , .true. , 'yearly'  , 'weights_3D_r360x180_bilin.nc'       , ''   , ''
+   rn_trfac(1)   =   1.028e-06  !  multiplicative factor
+   rn_trfac(2)   =   1.028e-06  !  -      -      -     -
    rn_trfac(3)   =  44.6e-06  !  -      -      -     -
    rn_trfac(5)   = 122.0e-06  !  -      -      -     -
    rn_trfac(7)   =   1.0e-06  !  -      -      -     -
-   rn_trfac(10)  =   1.0      !  -      -      -     -
-   rn_trfac(14)  =   1.0      !  -      -      -     -
+   rn_trfac(10)  =   1.0e-06  !  -      -      -     -
+   rn_trfac(14)  =   1.0e-06  !  -      -      -     -
    rn_trfac(23)  =   7.6e-06  !  -      -      -     -
 /
@@ -110,8 +110,8 @@
 !                !  file name        ! frequency (hours) ! variable      ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
 !                !                   !  (if <0  months)  !   name        !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_trcsbc(5)  = 'dust.orca.new'   ,       -1          , 'dustpo4'     ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trcsbc(7)  = 'dust.orca.new'   ,       -1          , 'dustsi'      ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trcsbc(14) = 'dust.orca.new'   ,       -1          , 'dustfer'     ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trcsbc(23) = 'ndeposition.orca',      -12          , 'ndep'        ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trcsbc(5)  = 'dust.orca.new'   ,       -1          , 'dustpo4'     ,  .true.      , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
+   sn_trcsbc(7)  = 'dust.orca.new'   ,       -1          , 'dustsi'      ,  .true.      , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
+   sn_trcsbc(14) = 'dust.orca.new'   ,       -1          , 'dustfer'     ,  .true.      , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
+   sn_trcsbc(23) = 'ndeposition.orca',      -12          , 'ndep2'       ,  .false.     , .true. , 'yearly'  , 'weights_2D_r360x180_bilin.nc'       , ''    , ''
    rn_trsfac(5)  = 8.264e-02   !  (  0.021 / 31. * 122 )
    rn_trsfac(7)  = 3.313e-01     !  ( 8.8   / 28.1 )
@@ -120,11 +120,11 @@
    rn_sbc_time   =  1.          !  Time scaling factor for SBC and CBC data (seconds in a day)
    !
-   sn_trccbc(1)  = 'river.orca'      ,    120            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(2)  = 'river.orca'      ,    120            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(5)  = 'river.orca'      ,    120            , 'riverdip'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(7)  = 'river.orca'      ,    120            , 'riverdsi'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(10) = 'river.orca'      ,    120            , 'riverdoc'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(14) = 'river.orca'      ,    120            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
-   sn_trccbc(23) = 'river.orca'      ,    120            , 'riverdin'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(1)  = 'river.orca'      ,    -12            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(2)  = 'river.orca'      ,    -12            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(5)  = 'river.orca'      ,    -12            , 'riverdip'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(7)  = 'river.orca'      ,    -12            , 'riverdsi'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(10) = 'river.orca'      ,    -12            , 'riverdoc'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(14) = 'river.orca'      ,    -12            , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_trccbc(23) = 'river.orca'      ,    -12            , 'riverdin'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
    rn_trcfac(1)  = 8.333e+01   !  ( data in Mg/m2/yr : 1e3/12/ryyss)
    rn_trcfac(2)  = 8.333e+01   !  ( 1e3 /12 )
@@ -140,2 +140,6 @@
 !-----------------------------------------------------------------------
 /
+!-----------------------------------------------------------------------
+&namtrc_ais      !  Representation of Antarctic Ice Sheet tracers supply
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/field_def_nemo-ice.xml	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/field_def_nemo-ice.xml	(revision 14055)
@@ -51,4 +51,8 @@
           <field id="icehlid"      long_name="melt pond lid depth"                                     standard_name="sea_ice_meltpondlid_depth"                 unit="m" /> 
           <field id="icevlid"      long_name="melt pond lid volume"                                    standard_name="sea_ice_meltpondlid_volume"                unit="m" /> 
+          <field id="dvpn_mlt"     long_name="pond volume tendency due to surface melt"                standard_name="sea_ice_pondvolume_tendency_melt"          unit="kg/m2/s" />
+          <field id="dvpn_lid"     long_name="pond volume tendency due to exchanges with lid"          standard_name="sea_ice_pondvolume_tendency_lids"          unit="kg/m2/s" />
+          <field id="dvpn_rnf"     long_name="pond volume tendency due to runoff"                      standard_name="sea_ice_pondvolume_tendency_runoff"        unit="kg/m2/s" />
+          <field id="dvpn_drn"     long_name="pond volume tendency due to drainage"                    standard_name="sea_ice_pondvolume_tendency_drainage"      unit="kg/m2/s" />  
 	  
 	  <!-- heat -->
@@ -77,4 +81,5 @@
           <field id="sig1_pnorm"   long_name="P-normalized 1st principal stress component"                                                                       unit=""     />
           <field id="sig2_pnorm"   long_name="P-normalized 2nd principal stress component"                                                                       unit=""     />
+          <field id="icedlt"       long_name="delta"                                                   standard_name="delta"                                     unit=""     />
           <field id="normstr"      long_name="Average normal stress in sea ice"                        standard_name="average_normal_stress"                     unit="N/m"  />
           <field id="sheastr"      long_name="Maximum shear stress in sea ice"                         standard_name="maximum_shear_stress"                      unit="N/m"  />
@@ -82,4 +87,8 @@
           <field id="icediv"       long_name="Divergence of the sea-ice velocity field"                standard_name="divergence_of_sea_ice_velocity"            unit="s-1"  />
           <field id="iceshe"       long_name="Maximum shear of sea-ice velocity field"                 standard_name="maximum_shear_of_sea_ice_velocity"         unit="s-1"  />
+          <field id="aniso"        long_name="anisotropy of sea ice floe orientation (0.5 - 1)"        standard_name="anisotropy"                                unit=""     />
+          <field id="yield11"      long_name="yield surface tensor component 11"                       standard_name="yield11"                                   unit="N/m"  />
+          <field id="yield22"      long_name="yield surface tensor component 22"                       standard_name="yield22"                                   unit="N/m"  />
+          <field id="yield12"      long_name="yield surface tensor component 12"                       standard_name="yield12"                                   unit="N/m"  />
           <field id="beta_evp"     long_name="Relaxation parameter of ice rheology (beta)"             standard_name="relaxation_parameter_of_ice_rheology"      unit=""  />	 
  
@@ -297,8 +306,9 @@
           <field id="snwtemp_cat"  long_name="Snow temperature per category"                     unit="degC"    detect_missing_value="true" />
           <field id="icettop_cat"  long_name="Ice/snow surface temperature per category"         unit="degC"    detect_missing_value="true" />
-          <field id="iceapnd_cat"  long_name="Ice melt pond concentration per category"          unit=""        /> 
+          <field id="iceapnd_cat"  long_name="Ice melt pond grid fraction per category"          unit=""        /> 
+          <field id="icevpnd_cat"  long_name="Ice melt pond volume per grid area per category"   unit="m"       />  
           <field id="icehpnd_cat"  long_name="Ice melt pond thickness per category"              unit="m"       detect_missing_value="true" /> 
           <field id="icehlid_cat"  long_name="Ice melt pond lid thickness per category"          unit="m"       detect_missing_value="true" /> 
-          <field id="iceafpnd_cat" long_name="Ice melt pond fraction per category"               unit=""        /> 
+          <field id="iceafpnd_cat" long_name="Ice melt pond ice fraction per category"           unit=""        /> 
           <field id="iceaepnd_cat" long_name="Ice melt pond effective fraction per category"     unit=""        /> 
           <field id="icemask_cat"  long_name="Fraction of time step with sea ice (per category)" unit=""        />
@@ -405,4 +415,5 @@
 	  <field field_ref="sig1_pnorm"       name="sig1_pnorm"/>
 	  <field field_ref="sig2_pnorm"       name="sig2_pnorm"/>
+	  <field field_ref="icedlt"           name="sidelta" />
 	  
 	  <!-- heat fluxes -->
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/field_def_nemo-oce.xml	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/field_def_nemo-oce.xml	(revision 14055)
@@ -234,4 +234,9 @@
         <field id="cfl_cw"       long_name="w-courant number"   unit="#" />
 
+        <!-- variables available with ln_zdfmfc=.true. -->
+         <field id="mf_Tp"       long_name="plume_temperature"      standard_name="plume_temperature"     unit="degC"   grid_ref="grid_T_3D" />
+         <field id="mf_Sp"       long_name="plume_salinity"         standard_name="plume_salinity"        unit="1e-3"   grid_ref="grid_T_3D" />
+         <field id="mf_mf"       long_name="mass flux"              standard_name="mf_mass_flux"          unit="m"      grid_ref="grid_T_3D" />
+
       </field_group> <!-- grid_T -->
 
@@ -265,41 +270,96 @@
 
       <field_group id="OSMOSIS_T" grid_ref="grid_T_2D">
+        <field id="hml"                 long_name="mixed layr depth"                         unit="m"       />
+        <field id="hbl"                 long_name="boundary layer depth"                     unit="m"       />
+        <field id="dh"                  long_name="Pycnocline thickness"                     unit=" m"      />
+        <field id="ibld"                long_name="index of boundary layer depth"            unit="#"       />
+        <field id="imld"                long_name="index of mixed layer depth"            unit="#"       />
+        <field id="zhbl"                long_name="boundary layer depth -grid"                     unit="m"       />
+        <field id="zhml"                long_name="mixed layer depth - grid"                        unit="m"       />
+        <field id="zdh"                 long_name="Pycnocline  depth - grid"                 unit=" m"      />
+        <field id="zustke"              long_name="magnitude of stokes drift  at T-points"   unit="m/s"     />
+        <field id="us_x"        long_name="i component of active Stokes drift"                      unit="m/s"     />
+        <field id="us_y"        long_name="j component of active Stokes drift"                      unit="m/s"     />
+        <field id="dstokes"             long_name="stokes drift  depth scale"                unit="m"       />
         <field id="zwth0"               long_name="surface non-local temperature flux"       unit="deg m/s" />
         <field id="zws0"                long_name="surface non-local salinity flux"          unit="psu m/s" />
-        <field id="hbl"                 long_name="boundary layer depth"                     unit="m"       />
-        <field id="hbli"                long_name="initial boundary layer depth"             unit="m"       />
-        <field id="dstokes"             long_name="stokes drift  depth scale"                unit="m"       />
-        <field id="zustke"              long_name="magnitude of stokes drift  at T-points"   unit="m/s"     />
         <field id="zwstrc"              long_name="convective velocity scale"                unit="m/s"     />
+        <field id="zustar"              long_name="friction velocity"                        unit="m/s"     />
         <field id="zwstrl"              long_name="langmuir velocity scale"                  unit="m/s"     />
-        <field id="zustar"              long_name="friction velocity"                        unit="m/s"     />
-        <field id="zhbl"                long_name="boundary layer depth"                     unit="m"       />
-        <field id="zhml"                long_name="mixed layer depth"                        unit="m"       />
+        <field id="zvstr"               long_name="mixed velocity scale"                     unit="m/s"     />
+        <field id="zla"                 long_name="langmuir number"                          unit="m/s"     />
         <field id="wind_wave_abs_power" long_name="\rho |U_s| x u*^2"                        unit="mW"      />
         <field id="wind_wave_power"     long_name="U_s \dot  tau"                            unit="mW"      />
         <field id="wind_power"          long_name="\rho  u*^3"                               unit="mW"      />
 
-        <!-- extra OSMOSIS diagnostics -->
+       <!-- interior BL OSMOSIS diagnostics -->
         <field id="zwthav"              long_name="av turb flux of T in ml"                  unit="deg m/s" />
         <field id="zt_ml"               long_name="av T in ml"                               unit="deg"     />
+        <field id="zhol"                long_name="Hoenekker number"                         unit="#"       />
+        <field id="zws_ent"            long_name="entrainment turb flux of S"                unit="10^-3 m/s" />
         <field id="zwth_ent"            long_name="entrainment turb flux of T"               unit="deg m/s" />
-        <field id="zhol"                long_name="Hoenekker number"                         unit="#"       />
-        <field id="zdh"                 long_name="Pycnocline  depth - grid"                 unit=" m"      />
-      </field_group>
-
-      <field_group id="OSMOSIS_W" grid_ref="grid_W_3D" operation="instant" >
+        <field id="zwb_ent"            long_name="entrainment turb flux of buoyancy"         unit="m^2/s^-3" />
+ 
+        <field id="zdt_bl"             long_name="temperature jump at base of BL"                 unit="deg"      />
+        <field id="zds_bl"             long_name="salinity jump at base of BL"                 unit="10^-3"      />
+        <field id="zdb_bl"             long_name="buoyancy jump at base of BL"                 unit="m/s^2"      />
+        <field id="zdu_bl"             long_name="u jump at base of BL"                       unit="m/s"      />
+        <field id="zdv_bl"             long_name="v jump at base of BL"                       unit="m/s"      />
+
+        <!-- extra OSMOSIS diagnostics for debugging -->
+       <field id="zsc_uw_1_0"       long_name="zsc u-momentum flux on T after Stokes"                       unit="m^2/s^2" />
+        <field id="zsc_uw_1_f"       long_name="zsc u-momentum flux on T after Coriolis"                       unit="m^2/s^2" />
+        <field id="zsc_vw_1_f"       long_name="zsc v-momentum flux on T after Coriolis"                       unit="m^2/s^2" />
+        <field id="zsc_uw_2_f"       long_name="2nd zsc u-momentum flux on T after Coriolis"                       unit="m^2/s^2" />
+        <field id="zsc_vw_2_f"       long_name="2nd zsc v-momentum flux on T after Coriolis"                       unit="m^2/s^2" />
+        <field id="zuw_bse"       long_name="base u-flux T-points"                          unit="m^2/s^2" />
+        <field id="zvw_bse"       long_name="base v-flux T-points"                          unit="m^2/s^2" />
+
+       <!-- FK_OSM OSMOSIS diagnostics (require also ln_osm_mle=.true.-->
+         <field id="hmle"          long_name="OBL FK-layer thickness"                                     unit="m"        />
+        <field id="mld_prof"              long_name="FK-layer depth index"                  unit="#" />
+        <field id="zmld"          long_name="target FK-layer thickness"                                     unit="m"        />
+        <field id="zwb_fk"          long_name="FK b-flux"                                     unit="m^2 s^-3"        />
+        <field id="zwb_fk_b"          long_name="layer averaged FK b-flux"                 unit="m^2 s^-3"       />
+        <field id="zdiff_mle"          long_name="max FK diffusivity in MLE"       unit=" 10^-4 m^2 s^-1"       />
+        <field id="zvel_mle"          long_name="FK velocity scale in MLE"       unit=" m s^-1"       />
+    </field_group>
+
+      <field_group id="OSMOSIS_W" grid_ref="grid_W_3D" >
+        <field id="zviscos"       long_name="BL viscosity"   unit="m^2/s" />
         <field id="ghamt"       long_name="non-local temperature flux"                       unit="deg m/s" />
         <field id="ghams"       long_name="non-local salinity flux"                          unit="psu m/s" />
         <field id="zdtdz_pyc"   long_name="Pycnocline temperature gradient"                  unit=" deg/m"  />
-      </field_group>
+        <field id="zdsdz_pyc"   long_name="Pycnocline salinity gradient"                  unit=" 10^-3/m"  />
+        <field id="zdbdz_pyc"   long_name="Pycnocline buoyancy gradient"                  unit=" s^-2"  />
+        <field id="zdudz_pyc"   long_name="Pycnocline u gradient"                  unit=" s^-2"  />
+        <field id="zdvdz_pyc"   long_name="Pycnocline v gradient"                  unit=" s^-2"  />
+
+        <!-- extra OSMOSIS diagnostics for debugging -->
+         <field id="ghamu_00"       long_name="initial non-local u-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamv_00"       long_name="initial non-local v-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamu_0"       long_name="after dstokes non-local u-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamu_f"       long_name="after Coriolis non-local u-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamv_f"       long_name="after Coriolis  non-local v-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamu_b"       long_name="after buoyancy added non-local u-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamv_b"       long_name="after buoyancy added  non-local v-momentum flux"  unit="m^2/s^2" />
+        <field id="ghamu_1"       long_name="after entrainment non-local u-momentum flux"   unit="m^2/s^2" />
+        <field id="ghamv_1"       long_name="after entrainment  non-local v-momentum flux"  unit="m^2/s^2" />
+     </field_group>
 
       <field_group id="OSMOSIS_U" grid_ref="grid_U_2D" >
         <field id="ghamu"       long_name="non-local u-momentum flux"   grid_ref="grid_U_3D" unit="m^2/s^2" />
-        <field id="us_x"        long_name="i component of Stokes drift"                      unit="m/s"     />
-      </field_group>
+       <!-- FK_OSM OSMOSIS diagnostics (require also ln_osm_mle=.true.-->
+       <field id="zdtdx"          long_name="FK  T x-gradient"                                     unit=" deg C m^-1"        />
+        <field id="zdsdx"          long_name="FK  S x-gradient"                                     unit=" 10^-3 m^-1"        />
+        <field id="dbdx_mle"          long_name="FK  B x-gradient"                                     unit=" s^-2"        />
+     </field_group>
 
       <field_group id="OSMOSIS_V" grid_ref="grid_V_2D" >
         <field id="ghamv"       long_name="non-local v-momentum flux"   grid_ref="grid_V_3D" unit="m^2/s^2" />
-        <field id="us_y"        long_name="j component of Stokes drift"                      unit="m/s"     />
+        <!-- FK_OSM OSMOSIS diagnostics (require also ln_osm_mle=.true.-->
+        <field id="zdtdy"          long_name="FK T y-gradient"                                     unit=" deg C m^-1"        />
+        <field id="zdsdy"          long_name="FK S y-gradient"                                     unit=" 10^-3 m^-1"        />
+        <field id="dbdy_mle"          long_name="FK B y-gradient"                                     unit=" s^-2"        />
       </field_group>
 
@@ -649,4 +709,9 @@
 	<field id="avm_evd"      long_name="convective enhancement of vertical viscosity"   standard_name="ocean_vertical_momentum_diffusivity_due_to_convection"   unit="m2/s" />
 
+        <!-- mf_app and mf_wp: available with ln_zdfmfc -->
+         <field id="mf_app"      long_name="convective area"        standard_name="mf_convective_area"    unit="%"      grid_ref="grid_W_3D" />
+         <field id="mf_wp"       long_name="convective velocity"    standard_name="mf_convective_velo"    unit="m/s"    grid_ref="grid_W_3D" />
+
+
         <!-- avt_tide: available with ln_zdfiwm=T -->
         <field id="av_ratio"     long_name="S over T diffusivity ratio"                     standard_name="salinity_over_temperature_diffusivity_ratio"                     unit="1"    />
@@ -831,5 +896,10 @@
      <field id="strd_zdfp"     long_name="salinity   -trend: pure vert. diffusion"   unit="1e-3/s" />
 
-     <!-- -->
+     <!-- ln_zdfosm=T only (OSMOSIS-OBL) -->
+     <field id="ttrd_osm"      long_name="temperature-trend: OSM-OSBL non-local forcing"                             unit="degC/s" />
+     <field id="strd_osm"      long_name="salinity   -trend: OSM-OSBL non-local forcing"                             unit="1e-3/s" />
+
+
+    <!-- -->
      <field id="ttrd_dmp"      long_name="temperature-trend: interior restoring"        unit="degC/s" />
      <field id="strd_dmp"      long_name="salinity   -trend: interior restoring"        unit="1e-3/s" />
@@ -867,4 +937,8 @@
      <field id="strd_zdfp_e3t"     unit="1e-3/s * m"  >  strd_zdfp * e3t </field>
 
+          <!-- ln_zdfosm=T only (OSMOSIS-OBL) -->
+     <field id="ttrd_osm_e3t"      long_name="temperature-trend: OSM-OSBL non-local forcing"                             unit="degC/s * m" >  ttrd_osm * e3t </field>
+     <field id="strd_osm_e3t"      long_name="salinity   -trend: OSM-OSBL non-local forcing"                             unit="1e-3/s * m" >  strd_osm * e3t </field>
+     
      <!-- -->
      <field id="ttrd_dmp_e3t"      unit="degC/s * m"  >  ttrd_dmp * e3t </field>
@@ -882,4 +956,6 @@
      <field id="ttrd_totad_li"    long_name="layer integrated heat-trend: total advection"         unit="W/m^2"     > ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
      <field id="strd_totad_li"    long_name="layer integrated salt-trend: total advection"         unit="kg/(m^2 s)"    > strd_totad_e3t * 1026.0 * 0.001  </field>
+     <field id="ttrd_osm_li"    long_name="layer integrated heat-trend: non-local OSM"         unit="W/m^2"     > ttrd_osm_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_osm_li"    long_name="layer integrated salt-trend: non-local OSM"         unit="kg/(m^2 s)"    > strd_osm_e3t * 1026.0 * 0.001  </field>
      <field id="ttrd_evd_li"      long_name="layer integrated heat-trend: EVD convection"          unit="W/m^2"    > ttrd_evd_e3t * 1026.0 * 3991.86795711963 </field>
      <field id="strd_evd_li"      long_name="layer integrated salt-trend: EVD convection"          unit="kg/(m^2 s)"  > strd_evd_e3t * 1026.0 * 0.001  </field>
@@ -1089,4 +1165,15 @@
     </field_group>
 
+    <!-- TMB diagnostic output -->
+    <field_group  id="1h_grid_T_tmb" grid_ref="grid_T_2D" operation="instant">
+      <field id="top_temp"           name="votemper_top"  unit="degC"  />
+      <field id="mid_temp"           name="votemper_mid"  unit="degC"  />
+      <field id="bot_temp"           name="votemper_bot"  unit="degC"  />
+      <field id="top_sal"            name="vosaline_top"  unit="psu"   />
+      <field id="mid_sal"            name="vosaline_mid"  unit="psu"   />
+      <field id="bot_sal"            name="vosaline_bot"  unit="psu"   />
+      <field id="sshnmasked"         name="sossheig"      unit="m"     /> 
+    </field_group>
+
     <field_group  id="1h_grid_U_tmb" grid_ref="grid_U_2D" operation="instant">
       <field id="top_u"           name="vozocrtx_top"  unit="m/s"  />
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_ice_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_ice_ref	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_ice_ref	(revision 14055)
@@ -24,5 +24,5 @@
    jpl              =   5             !  number of ice  categories
    nlay_i           =   2             !  number of ice  layers
-   nlay_s           =   1             !  number of snow layers (only 1 is working)
+   nlay_s           =   2             !  number of snow layers
    ln_virtual_itd   =   .false.       !  virtual ITD mono-category parameterization (jpl=1 only)
                                       !     i.e. enhanced thermal conductivity & virtual thin ice melting
@@ -62,4 +62,10 @@
       rn_lf_relax   =   1.e-5         !        relaxation time scale to reach static friction [s-1]
       rn_lf_tensile =   0.05          !        isotropic tensile strength [0-0.5??]
+
+   cn_dir           = './'      !  root directory for the grounded icebergs mask data location
+   !___________!________________!___________________!___________!_____________!________!___________!__________!__________!_______________!
+   !           !  file name     ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
+   !           !                !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' ! filename ! pairing  !    filename   !
+   sn_icbmsk       = 'NOT USED' ,       -12.        , 'icb_mask',   .false.   , .true. , 'yearly'  , ''       , ''       , ''
 /
 !------------------------------------------------------------------------------
@@ -92,4 +98,5 @@
 !------------------------------------------------------------------------------
    ln_rhg_EVP       = .true.          !  EVP rheology
+   ln_rhg_EAP       = .false.         !  EAP rheology
       ln_aEVP       = .true.          !     adaptive rheology (Kimmritz et al. 2016 & 2017)
       rn_creepl     =   2.0e-9        !     creep limit [1/s]
@@ -98,9 +105,13 @@
       rn_relast     =   0.333         !     ratio of elastic timescale to ice time step: Telast = dt_ice * rn_relast 
                                       !        advised value: 1/3 (nn_nevp=100) or 1/9 (nn_nevp=300)
-   nn_rhg_chkcvg    =   0             !  check convergence of rheology
+      nn_rhg_chkcvg =   0             !     check convergence of rheology
                                       !     = 0  no check
                                       !     = 1  check at the main time step (output xml: uice_cvg)
                                       !     = 2  check at both main and rheology time steps (additional output: ice_cvg.nc)
                                       !          this option 2 asks a lot of communications between cpu
+   ln_rhg_VP        = .false.         !  VP rheology
+      nn_vp_nout    = 10              !     number of outer iterations
+      nn_vp_ninn    = 1500            !     number of inner iterations
+      nn_vp_chkcvg  = 5               !     iteration step for convergence check
 /
 !------------------------------------------------------------------------------
@@ -195,7 +206,9 @@
 !------------------------------------------------------------------------------
    ln_pnd            = .true.         !  activate melt ponds or not
-      ln_pnd_LEV     = .true.         !  level ice melt ponds (from Flocco et al 2007,2010 & Holland et al 2012)
-         rn_apnd_min =   0.15         !     minimum ice fraction that contributes to melt pond. range: 0.0 -- 0.15 ??
-         rn_apnd_max =   0.85         !     maximum ice fraction that contributes to melt pond. range: 0.7 -- 0.85 ??
+      ln_pnd_TOPO    = .false.        !  topographic melt ponds
+      ln_pnd_LEV     = .true.         !  level ice melt ponds
+         rn_apnd_min =   0.15         !     minimum meltwater fraction contributing to pond growth (TOPO and LEV)
+         rn_apnd_max =   0.85         !     maximum meltwater fraction contributing to pond growth (TOPO and LEV)
+         rn_pnd_flush=   0.01         !     pond flushing efficiency (tuning parameter) (LEV)
       ln_pnd_CST     = .false.        !  constant  melt ponds
          rn_apnd     =   0.2          !     prescribed pond fraction, at Tsu=0 degC
@@ -261,6 +274,6 @@
    ln_icediachk     = .false.         !  check online heat, mass & salt budgets
       !                               !   rate of ice spuriously gained/lost at each time step => rn_icechk=1 <=> 1.e-6 m/hour
-      rn_icechk_cel =  100.           !     check at each gridcell          (1.e-4m/h)=> stops the code if violated (and writes a file)
-      rn_icechk_glo =  1.             !     check over the entire ice cover (1.e-6m/h)=> only prints warnings
+      rn_icechk_cel =  1.             !     check at each gridcell          (1.e-06m/h)=> stops the code if violated (and writes a file)
+      rn_icechk_glo =  1.e-04         !     check over the entire ice cover (1.e-10m/h)=> only prints warnings
    ln_icediahsb     = .false.         !  output the heat, mass & salt budgets (T) or not (F)
    ln_icectl        = .false.         !  ice points output for debug (T or F)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_ref	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_ref	(revision 14055)
@@ -96,4 +96,11 @@
 /
 !-----------------------------------------------------------------------
+&namtile        !   parameters of the tiling
+!-----------------------------------------------------------------------
+   ln_tile = .false.     !  Use tiling (T) or not (F)
+   nn_ltile_i = 10       !  Length of tiles in i
+   nn_ltile_j = 10       !  Length of tiles in j
+/
+!-----------------------------------------------------------------------
 &namclo        !   parameters of the closed sea (cs) behavior                (default: OFF)
 !-----------------------------------------------------------------------
@@ -230,13 +237,4 @@
    ln_apr_dyn  = .false.   !  Patm gradient added in ocean & ice Eqs.   (T => fill namsbc_apr )
    ln_wave     = .false.   !  Activate coupling with wave  (T => fill namsbc_wave)
-   ln_cdgw     = .false.   !  Neutral drag coefficient read from wave model (T => ln_wave=.true. & fill namsbc_wave)
-   ln_sdw      = .false.   !  Read 2D Surf Stokes Drift & Computation of 3D stokes drift (T => ln_wave=.true. & fill namsbc_wave)
-   nn_sdrift   =  0        !  Parameterization for the calculation of 3D-Stokes drift from the surface Stokes drift
-      !                    !   = 0 Breivik 2015 parameterization: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
-      !                    !   = 1 Phillips:                      v_z=v_o*[exp(2*k*z)-beta*sqrt(-2*k*pi*z)*erfc(sqrt(-2*k*z))]
-      !                    !   = 2 Phillips as (1) but using the wave frequency from a wave model
-   ln_tauwoc   = .false.   !  Activate ocean stress modified by external wave induced stress (T => ln_wave=.true. & fill namsbc_wave)
-   ln_tauw     = .false.   !  Activate ocean stress components from wave model
-   ln_stcor    = .false.   !  Activate Stokes Coriolis term (T => ln_wave=.true. & ln_sdw=.true. & fill namsbc_wave)
    nn_lsm      = 0         !  =0 land/sea mask for input fields is not applied (keep empty land/sea mask filename field) ,
                            !  =1:n number of iterations of land/sea mask application for input fields (fill land/sea mask filename field)
@@ -369,20 +367,22 @@
    sn_rcv_cal    =   'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
    sn_rcv_co2    =   'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_hsig   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
    sn_rcv_iceflx =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
    sn_rcv_mslp   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_phioc  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_sdrfx  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_sdrfy  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_wper   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_wnum   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_wfreq  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
    sn_rcv_ts_ice =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
    sn_rcv_isf    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
    sn_rcv_icb    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
-   sn_rcv_tauwoc =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
-   sn_rcv_tauw   =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
-   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_hsig   =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_phioc  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   'T'
+   sn_rcv_sdrfx  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   'T'
+   sn_rcv_sdrfy  =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_wper   =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_wnum   =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_wstrf  =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_charn  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   'T'
+   sn_rcv_taw    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   'U,V'
+   sn_rcv_bhd    =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_tusd   =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
+   sn_rcv_tvsd   =   'none'                 ,    'no'    ,     ''      '         ''           ,   'T'
 /
 !-----------------------------------------------------------------------
@@ -564,4 +564,18 @@
 &namsbc_wave   ! External fields from wave model                        (ln_wave=T)
 !-----------------------------------------------------------------------
+   ln_sdw      = .false.       !  get the 2D Surf Stokes Drift & Compute the 3D stokes drift
+   ln_stcor    = .false.       !  add Stokes Coriolis and tracer advection terms
+   ln_cdgw     = .false.       !  Neutral drag coefficient read from wave model
+   ln_tauoc    = .false.       !  ocean stress is modified by wave induced stress
+   ln_wave_test= .false.       !  Test case with constant wave fields
+!
+   ln_charn    = .false.       !  Charnock coefficient read from wave model (IFS only)
+   ln_taw      = .false.       !  ocean stress is modified by wave induced stress (coupled mode)
+   ln_phioc    = .false.       !  TKE flux from wave model
+   ln_bern_srfc= .false.       !  wave induced pressure. Bernoulli head J term
+   ln_breivikFV_2016 = .false. !  breivik 2016 vertical stokes profile
+   ln_vortex_force = .false.   !  Vortex Force term 
+   ln_stshear  = .false.       !  include stokes shear in EKE computation
+!
    cn_dir      = './'      !  root directory for the waves data location
    !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
@@ -573,9 +587,6 @@
    sn_hsw      =  'sdw_ecwaves_orca2'    ,        6.         , 'hs'         ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
    sn_wmp      =  'sdw_ecwaves_orca2'    ,        6.         , 'wmp'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
-   sn_wfr      =  'sdw_ecwaves_orca2'    ,        6.         , 'wfr'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
    sn_wnum     =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_num'   ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
-   sn_tauwoc   =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
-   sn_tauwx    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
-   sn_tauwy    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauoc    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
 /
 !-----------------------------------------------------------------------
@@ -618,5 +629,8 @@
    ln_use_calving          = .false. ! Use calving data even when nn_test_icebergs > 0
    rn_speed_limit          = 0.      ! CFL speed limit for a berg
-
+   !
+   ln_M2016                = .false. ! use Merino et al. (2016) modification (use of 3d ocean data instead of only sea surface data)
+      ln_icb_grd           = .false. ! ground icb when icb bottom level hit oce bottom level (need ln_M2016 to be activated)
+   !
    cn_dir      = './'      !  root directory for the calving data location
    !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
@@ -1105,4 +1119,5 @@
       nn_npc      =    1         ! frequency of application of npc
       nn_npcp     =  365         ! npc control print frequency
+   ln_zdfmfc   = .false.      !  Mass Flux Convection
    !
    ln_zdfddm   = .false.   ! double diffusive mixing
@@ -1155,4 +1170,5 @@
       rn_mxlice   = 10.       ! max constant ice thickness value when scaling under sea-ice ( nn_mxlice=1)
    rn_mxl0     =   0.04    !  surface  buoyancy lenght scale minimum value
+   ln_mxhsw    = .false.   !  surface mixing length scale = F(wave height)
    ln_lc       = .true.    !  Langmuir cell parameterisation (Axell 2002)
       rn_lc       =   0.15    !  coef. associated to Langmuir cells
@@ -1170,4 +1186,6 @@
    !                       !           = 2 weighted by 1-fr_i
    !                       !           = 3 weighted by 1-MIN(1,4*fr_i)   
+   nn_bc_surf   =     1    !  surface condition (0/1=Dir/Neum) ! Only applicable for wave coupling (ln_cplwave=1)
+   nn_bc_bot    =     1    !  bottom condition (0/1=Dir/Neum) ! Only applicable for wave coupling (ln_cplwave=1)
 /
 !-----------------------------------------------------------------------
@@ -1199,7 +1217,9 @@
 &namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
 !-----------------------------------------------------------------------
-   ln_use_osm_la = .false.      !  Use namelist  rn_osm_la
+   ln_use_osm_la = .false.     !  Use   rn_osm_la
    rn_osm_la     = 0.3         !  Turbulent Langmuir number
-   rn_osm_dstokes     = 5.     !  Depth scale of Stokes drift (m)
+   rn_zdfosm_adjust_sd = 1.0   ! Stokes drift reduction factor
+   rn_osm_hblfrac = 0.1        ! specify top part of hbl for nn_osm_wave = 3 or 4
+   rn_osm_bl_thresh   = 5.e-5      !Threshold buoyancy for deepening of OSBL base
    nn_ave = 0                  ! choice of horizontal averaging on avt, avmu, avmv
    ln_dia_osm = .true.         ! output OSMOSIS-OBL variables
@@ -1209,9 +1229,41 @@
    rn_difri  =  0.005          ! max Ri# diffusivity at Ri_g = 0 (m^2/s)
    ln_convmix  = .true.        ! Use convective instability mixing below BL
-   rn_difconv = 1.             ! diffusivity when unstable below BL  (m2/s)
+   rn_difconv = 1. !0.01 !1.             ! diffusivity when unstable below BL  (m2/s)
+   rn_osm_dstokes     = 5.     !  Depth scale of Stokes drift (m)
    nn_osm_wave = 0             ! Method used to calculate Stokes drift
       !                        !  = 2: Use ECMWF wave fields
       !                        !  = 1: Pierson Moskowitz wave spectrum
       !                        !  = 0: Constant La# = 0.3
+   nn_osm_SD_reduce = 0        ! Method used to get active Stokes drift from surface value
+      !                        !  = 0: No reduction
+                               !  = 1: use SD avged over top 10% hbl
+                               !  = 2:use surface value of SD fit to slope at rn_osm_hblfrac*hbl below surface
+   ln_zdfosm_ice_shelter = .true.  ! reduce surface SD and depth scale under ice
+   ln_osm_mle = .false.        !  Use integrated FK-OSM model
+/
+!-----------------------------------------------------------------------
+&namosm_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+   rn_osm_mle_ce       = 0.06      ! magnitude of the MLE (typical value: 0.06 to 0.08)
+   nn_osm_mle          = 0         ! MLE type: =0 standard Fox-Kemper ; =1 new formulation
+   rn_osm_mle_lf       = 5.e+3     ! typical scale of mixed layer front (meters)                      (case rn_osm_mle=0)
+   rn_osm_mle_time     = 172800.   ! time scale for mixing momentum across the mixed layer (seconds)  (case rn_osm_mle=0)
+   rn_osm_mle_lat      = 20.       ! reference latitude (degrees) of MLE coef.                        (case rn_mle=1)
+   rn_osm_mle_rho_c =    0.01      ! delta rho criterion used to calculate MLD for FK
+   rn_osm_mle_thresh  = 0.0005     ! delta b criterion used for FK MLE criterion
+   rn_osm_mle_tau     = 172800.    ! time scale for FK-OSM (seconds)  (case rn_osm_mle=0)
+   ln_osm_hmle_limit   = .false.   ! limit hmle to rn_osm_hmle_limit*hbl
+   rn_osm_hmle_limit   = 1.2
+   /
+!-----------------------------------------------------------------------
+&namzdf_mfc     !   Mass Flux Convection
+!-----------------------------------------------------------------------
+   ln_edmfuv  = .false.        ! Activate on velocity fields (Not available yet)
+   rn_cemf    =  1.            ! entrain/detrain coef. (<0 => cte; >0 % depending on dW/dz
+   rn_cwmf    = -0.            ! entrain/detrain coef. (<0 => cte; >0 % depending on dW/dz
+   rn_cent    = 2.e-5          ! entrain of convective area
+   rn_cdet    = 3.e-5          ! detrain of convective area 
+   rn_cap     = 0.9            ! Coef. for CAP estimation
+   App_max    = 0.1            ! Maximum convection area (% of the cell)
 /
 !-----------------------------------------------------------------------
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_top_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_top_ref	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/cfgs/SHARED/namelist_top_ref	(revision 14055)
@@ -41,4 +41,5 @@
    ln_trcdmp_clo =  .false.  !  damping term (T) or not (F) on closed seas
    ln_trcbc      =  .false.  !  Surface, Lateral or Open Boundaries conditions
+   ln_trcais     =  .false.  !  Antarctic Ice Sheet nutrient supply
    !
    jp_dia3d      = 0         ! Number of 3D diagnostic variables
@@ -149,2 +150,10 @@
                              !  = 2 Damping applied to all tracers
 /
+!-----------------------------------------------------------------------
+&namtrc_ais      !  Representation of Antarctic Ice Sheet tracers supply
+!-----------------------------------------------------------------------
+   nn_ais_tr     =  1        !  tracer concentration in iceberg and ice shelf
+                             !    = 0 (null concentrations)
+                             !    = 1 prescribed concentrations
+   rn_icbdep     =  120.     ! Mean underwater depth of iceberg (m)
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/main/bibliography.bib
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/main/bibliography.bib	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/main/bibliography.bib	(revision 14055)
@@ -1906,4 +1906,14 @@
 }
 
+@Article{        love_PRSLA1909,
+  author       = "A. E. H. Love",
+  title        = "The Yielding of the Earth to Disturbing Forces",
+  journal      = "Proc. R. Soc. Lond. A",
+  year         = "1909",
+  volume       = "82",
+  pages        = "73-88",
+  doi          = "10.1098/rspa.1909.0008"
+}
+
 @article{         losch_JGR08,
   title         = "Modeling ice shelf cavities in a z coordinate Ocean
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_DIA.tex
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_DIA.tex	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_DIA.tex	(revision 14055)
@@ -119,6 +119,7 @@
 \subsection{XIOS: Reading and writing restart file}
 
-XIOS may be used to read single file restart produced by \NEMO. Currently only the variables written to
-file \forcode{numror} can be handled by XIOS. To activate restart reading using XIOS, set \np[=.true. ]{ln_xios_read}{ln\_xios\_read}
+XIOS may be used to read single file restart produced by \NEMO. The variables written to
+file \forcode{numror} (OCE), \forcode{numrir} (SI3), \forcode{numrtr} (TOP), \forcode{numrsr} (SED) can be handled by XIOS. 
+To activate restart reading using XIOS, set \np[=.true. ]{ln_xios_read}{ln\_xios\_read}
 in \textit{namelist\_cfg}. This setting will be ignored when multiple restart files are present, and default \NEMO
 functionality will be used for reading. There is no need to change iodef.xml file to use XIOS to read
@@ -142,15 +143,4 @@
 have to be rebuild before continuing the run. This option aims to reduce number of restart files generated by \NEMO\ only,
 and may be useful when there is a need to change number of processors used to run simulation.
-
-If an additional variable must be written to a restart file, the following steps are needed:
-\begin{enumerate}
-\item Add variable name to a list of restart variables (in subroutine \rou{iom\_set\_rst\_vars,} \mdl{iom}) and
-define correct grid for the variable (\forcode{grid_N_3D} - 3D variable, \forcode{grid_N} - 2D variable, \forcode{grid_vector} -
-1D variable, \forcode{grid_scalar} - scalar),
-\item Add variable to the list of fields written by restart.  This can be done either in subroutine
-\rou{iom\_set\_rstw\_core} (\mdl{iom}) or by calling  \rou{iom\_set\_rstw\_active} (\mdl{iom}) with the name of a variable
-as an argument. This convention follows approach for writing restart using iom, where variables are
-written either by \rou{rst\_write} or by calling \rou{iom\_rstput} from individual routines.
-\end{enumerate}
 
 An older versions of XIOS do not support reading functionality. It's recommended to use at least XIOS2@1451.
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_DYN.tex
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_DYN.tex	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_DYN.tex	(revision 14055)
@@ -1245,5 +1245,5 @@
 the atmospheric pressure is taken into account when computing the surface pressure gradient.
 
-(2) When \np[=.true.]{ln_tide_pot}{ln\_tide\_pot} and \np[=.true.]{ln_tide}{ln\_tide} (see \autoref{sec:SBC_tide}),
+(2) When \np[=.true.]{ln_tide_pot}{ln\_tide\_pot} and \np[=.true.]{ln_tide}{ln\_tide} (see \autoref{sec:SBC_TDE}),
 the tidal potential is taken into account when computing the surface pressure gradient.
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_LBC.tex
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_LBC.tex	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_LBC.tex	(revision 14055)
@@ -16,4 +16,5 @@
     Release & Author(s) & Modifications \\
     \hline
+    {\em  next} & {\em Simon M{\" u}ller} & {\em Minor update of \autoref{subsec:LBC_bdy_tides}} \\[2mm]
     {\em   4.0} & {\em ...} & {\em ...} \\
     {\em   3.6} & {\em ...} & {\em ...} \\
@@ -665,38 +666,33 @@
 
 Tidal forcing at open boundaries requires the activation of surface
-tides (i.e., in \nam{_tide}{\_tide}, \np{ln_tide}{ln\_tide} needs to be set to
-\forcode{.true.} and the required constituents need to be activated by
-including their names in the \np{clname}{clname} array; see
-\autoref{sec:SBC_tide}). Specific options related to the reading in of
+tides (i.e., in \nam{_tide}{\_tide}, \np[=.true.]{ln_tide}{ln\_tide} with the active tidal
+constituents listed in the \np{sn_tide_cnames}{sn\_tide\_cnames} array; see
+\autoref{sec:SBC_TDE}). The specific options related to the reading in of
 the complex harmonic amplitudes of elevation (SSH) and barotropic
-velocity (u,v) at open boundaries are defined through the
-\nam{bdy_tide}{bdy\_tide} namelist parameters.\\
+velocity components (u,v) at the open boundaries are defined through the
+\nam{bdy_tide}{bdy\_tide} namelist parameters.\par
 
 The tidal harmonic data at open boundaries can be specified in two
 different ways, either on a two-dimensional grid covering the entire
 model domain or along open boundary segments; these two variants can
-be selected by setting \np{ln_bdytide_2ddta }{ln\_bdytide\_2ddta } to \forcode{.true.} or
-\forcode{.false.}, respectively. In either case, the real and
-imaginary parts of SSH and the two barotropic velocity components for
-each activated tidal constituent \textit{tcname} have to be provided
-separately: when two-dimensional data is used, variables
-\textit{tcname\_z1} and \textit{tcname\_z2} for real and imaginary SSH,
-respectively, are expected in input file \np{filtide}{filtide} with suffix
-\ifile{\_grid\_T}, variables \textit{tcname\_u1} and
-\textit{tcname\_u2} for real and imaginary u, respectively, are
-expected in input file \np{filtide}{filtide} with suffix \ifile{\_grid\_U}, and
-\textit{tcname\_v1} and \textit{tcname\_v2} for real and imaginary v,
-respectively, are expected in input file \np{filtide}{filtide} with suffix
-\ifile{\_grid\_V}; when data along open boundary segments is used,
-variables \textit{z1} and \textit{z2} (real and imaginary part of SSH)
-are expected to be available from file \np{filtide}{filtide} with suffix
-\ifile{tcname\_grid\_T}, variables \textit{u1} and \textit{u2} (real
-and imaginary part of u) are expected to be available from file
-\np{filtide}{filtide} with suffix \ifile{tcname\_grid\_U}, and variables
-\textit{v1} and \textit{v2} (real and imaginary part of v) are
-expected to be available from file \np{filtide}{filtide} with suffix
-\ifile{tcname\_grid\_V}. If \np{ln_bdytide_conj}{ln\_bdytide\_conj} is set to
-\forcode{.true.}, the data is expected to be in complex conjugate
-form.
+be selected by setting \np[=.true.]{ln_bdytide_2ddta}{ln\_bdytide\_2ddta} or
+\np[=.false.]{ln_bdytide_2ddta}{ln\_bdytide\_2ddta}, respectively. In either
+case, the real and imaginary parts of SSH, u, and v amplitudes associated with
+each activated tidal constituent \texttt{<constituent>} have to be provided
+separately as fields in input files with names based on
+\np[=<input>]{filtide}{filtide}: when two-dimensional data is used, variables
+\texttt{<constituent>\_z1} and \texttt{<constituent>\_z2} for the real and imaginary parts of
+SSH, respectively, are expected to be available in file
+\ifile{<input>\_grid\_T}, variables \texttt{<constituent>\_u1} and
+\texttt{<constituent>\_u2} for the real and imaginary parts of u, respectively, in file
+\ifile{<input>\_grid\_U}, and \texttt{<constituent>\_v1} and
+\texttt{<constituent>\_v2} for the real and imaginary parts of v, respectively, in file
+\ifile{<input>\_grid\_V}; when data along open boundary segments is used,
+variables \texttt{z1} and \texttt{z2} (real and imaginary part of SSH) are
+expected to be available in file \ifile{<input><constituent>\_grid\_T},
+variables \texttt{u1} and \texttt{u2} (real and imaginary part of u) in file
+\ifile{<input><constituent>\_grid\_U}, and variables \texttt{v1} and \texttt{v2}
+(real and imaginary part of v) in file
+\ifile{<input><constituent>\_grid\_V}.\par
 
 Note that the barotropic velocity components are assumed to be defined
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_SBC.tex
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_SBC.tex	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/latex/NEMO/subfiles/chap_SBC.tex	(revision 14055)
@@ -5,5 +5,5 @@
 \begin{document}
 
-\chapter{Surface Boundary Condition (SBC, SAS, ISF, ICB)}
+\chapter{Surface Boundary Condition (SBC, SAS, ISF, ICB, TDE)}
 \label{chap:SBC}
 
@@ -18,4 +18,5 @@
     Release & Author(s) & Modifications \\
     \hline
+    {\em  next} & {\em Simon M{\" u}ller} & {\em Update of \autoref{sec:SBC_TDE}}\\[2mm]
     {\em   4.0} & {\em ...} & {\em ...} \\
     {\em   3.6} & {\em ...} & {\em ...} \\
@@ -1013,6 +1014,6 @@
 
 %% =================================================================================================
-\section[Surface tides (\textit{sbctide.F90})]{Surface tides (\protect\mdl{sbctide})}
-\label{sec:SBC_tide}
+\section{Surface tides (TDE)}
+\label{sec:SBC_TDE}
 
 \begin{listing}
@@ -1022,43 +1023,80 @@
 \end{listing}
 
-The tidal forcing, generated by the gravity forces of the Earth-Moon and Earth-Sun sytems,
-is activated if \np{ln_tide}{ln\_tide} and \np{ln_tide_pot}{ln\_tide\_pot} are both set to \forcode{.true.} in \nam{_tide}{\_tide}.
-This translates as an additional barotropic force in the momentum \autoref{eq:MB_PE_dyn} such that:
+\subsection{Tidal constituents}
+Ocean model component TDE provides the common functionality for tidal forcing
+and tidal analysis in the model framework. This includes the computation of the gravitational
+surface forcing, as well as support for lateral forcing at open boundaries (see
+\autoref{subsec:LBC_bdy_tides}) and tidal harmonic analysis (see
+\autoref{subsec:DIA_diamlr} and \autoref{subsec:DIA_diadetide}). The module is
+activated with \np[=.true.]{ln_tide}{ln\_tide} in namelist
+\nam{_tide}{\_tide}. It provides the same 34 tidal constituents that are
+included in the
+\href{https://www.aviso.altimetry.fr/en/data/products/auxiliary-products/global-tide-fes.html}{FES2014
+  ocean tide model}: Mf, Mm, Ssa, Mtm, Msf, Msqm, Sa, K1, O1, P1, Q1, J1, S1,
+M2, S2, N2, K2, nu2, mu2, 2N2, L2, T2, eps2, lam2, R2, M3, MKS2, MN4, MS4, M4,
+N4, S4, M6, and M8; see file \hf{tide} and \mdl{tide\_mod} for further
+information and references\footnote{As a legacy option \np{ln_tide_var} can be
+  set to \forcode{0}, in which case the 19 tidal constituents (M2, N2, 2N2, S2,
+  K2, K1, O1, Q1, P1, M4, Mf, Mm, Msqm, Mtm, S1, MU2, NU2, L2, and T2; see file
+  \hf{tide}) and associated parameters that have been available in NEMO version
+  4.0 and earlier are available}. Constituents to be included in the tidal forcing
+(surface and lateral boundaries) are selected by enumerating their respective
+names in namelist array \np{sn_tide_cnames}{sn\_tide\_cnames}.\par
+
+\subsection{Surface tidal forcing}
+Surface tidal forcing can be represented in the model through an additional
+barotropic force in the momentum equation (\autoref{eq:MB_PE_dyn}) such that:
 \[
-  % \label{eq:SBC_PE_dyn_tides}
-  \frac{\partial {\mathrm {\mathbf U}}_h }{\partial t}= ...
-  +g\nabla (\Pi_{eq} + \Pi_{sal})
+  \frac{\partial {\mathrm {\mathbf U}}_h }{\partial t} = \ldots +g\nabla (\gamma
+  \Pi_{eq} + \Pi_{sal})
 \]
-where $\Pi_{eq}$ stands for the equilibrium tidal forcing and
-$\Pi_{sal}$ is a self-attraction and loading term (SAL).
-
-The equilibrium tidal forcing is expressed as a sum over a subset of
-constituents chosen from the set of available tidal constituents
-defined in file \hf{SBC/tide} (this comprises the tidal
-constituents \textit{M2, N2, 2N2, S2, K2, K1, O1, Q1, P1, M4, Mf, Mm,
-  Msqm, Mtm, S1, MU2, NU2, L2}, and \textit{T2}). Individual
-constituents are selected by including their names in the array
-\np{clname}{clname} in \nam{_tide}{\_tide} (e.g., \np{clname}{clname}\forcode{(1)='M2', }
-\np{clname}{clname}\forcode{(2)='S2'} to select solely the tidal consituents \textit{M2}
-and \textit{S2}). Optionally, when \np{ln_tide_ramp}{ln\_tide\_ramp} is set to
-\forcode{.true.}, the equilibrium tidal forcing can be ramped up
-linearly from zero during the initial \np{rdttideramp}{rdttideramp} days of the
-model run.
+where $\gamma \Pi_{eq}$ stands for the equilibrium tidal forcing scaled by a spatially
+uniform tilt factor $\gamma$, and $\Pi_{sal}$ is an optional
+self-attraction and loading term (SAL). These additional terms are enabled when,
+in addition to \np[=.true.]{ln_tide}{ln\_tide}),
+\np[=.true.]{ln_tide_pot}{ln\_tide\_pot}.\par
+
+The equilibrium tidal forcing is expressed as a sum over the subset of
+constituents listed in \np{sn_tide_cnames}{sn\_tide\_cnames} of
+\nam{_tide} (e.g.,
+\begin{forlines}
+      sn_tide_cnames(1) = 'M2'
+      sn_tide_cnames(2) = 'K1'
+      sn_tide_cnames(3) = 'S2'
+      sn_tide_cnames(4) = 'O1'
+\end{forlines}
+to select the four tidal constituents of strongest equilibrium tidal
+potential). The tidal tilt factor $\gamma = 1 + k - h$ includes the
+Love numbers $k$ and $h$ \citep{love_prsla1909}; this factor is
+configurable using \np{rn_tide_gamma} (default value 0.7). Optionally,
+when \np[=.true.]{ln_tide_ramp}{ln\_tide\_ramp}, the equilibrium tidal
+forcing can be ramped up linearly from zero during the initial
+\np{rn_tide_ramp_dt}{rn\_tide\_ramp\_dt} days of the model run.\par
 
 The SAL term should in principle be computed online as it depends on
 the model tidal prediction itself (see \citet{arbic.garner.ea_DSR04} for a
-discussion about the practical implementation of this term).
-Nevertheless, the complex calculations involved would make this
-computationally too expensive. Here, two options are available:
-$\Pi_{sal}$ generated by an external model can be read in
-(\np[=.true.]{ln_read_load}{ln\_read\_load}), or a ``scalar approximation'' can be
-used (\np[=.true.]{ln_scal_load}{ln\_scal\_load}). In the latter case
+discussion about the practical implementation of this term). The complex
+calculations involved in such computations, however, are computationally very
+expensive. Here, two mutually exclusive simpler variants are available:
+amplitudes generated by an external model for oscillatory $\Pi_{sal}$
+contributions from each of the selected tidal constituents can be read in
+(\np[=.true.]{ln_read_load}{ln\_read\_load}) from the file specified in
+\np{cn_tide_load}{cn\_tide\_load} (the variable names are comprised of the
+tidal-constituent name and suffixes \forcode{_z1} and \forcode{_z2} for the two
+orthogonal components, respectively); alternatively, a ``scalar approximation''
+can be used (\np[=.true.]{ln_scal_load}{ln\_scal\_load}), where
 \[
   \Pi_{sal} = \beta \eta,
 \]
-where $\beta$ (\np{rn_scal_load}{rn\_scal\_load} with a default value of 0.094) is a
-spatially constant scalar, often chosen to minimize tidal prediction
-errors. Setting both \np{ln_read_load}{ln\_read\_load} and \np{ln_scal_load}{ln\_scal\_load} to
-\forcode{.false.} removes the SAL contribution.
+with a spatially uniform coefficient $\beta$, which can be configured
+via \np{rn_scal_load}{rn\_scal\_load} (default value 0.094) and is
+often tuned to minimize tidal prediction errors.\par
+
+For diagnostic purposes, the forcing potential of the individual tidal
+constituents (incl. load ptential, if activated) and the total forcing
+potential (incl. load potential, if activated) can be made available
+as diagnostic output by setting
+\np[=.true.]{ln_tide_dia}{ln\_tide\_dia} (fields
+\forcode{tide_pot_<constituent>} and \forcode{tide_pot}).\par
 
 %% =================================================================================================
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/nam_tide
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/nam_tide	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/nam_tide	(revision 14055)
@@ -3,12 +3,16 @@
 !-----------------------------------------------------------------------
    ln_tide     = .false.      ! Activate tides
-      ln_tide_pot   = .true.                !  use tidal potential forcing
+      nn_tide_var   = 1          !  Variant of tidal parameter set and tide-potential computation
+      !                          !     (1: default; 0: compatibility with previous versions)
+      ln_tide_dia   = .false.    !  Enable tidal diagnostic output
+      ln_tide_pot   = .false.               !  use tidal potential forcing
+         rn_tide_gamma = 0.7                   ! Tidal tilt factor
          ln_scal_load  = .false.               ! Use scalar approximation for
             rn_scal_load = 0.094               !     load potential
          ln_read_load  = .false.               ! Or read load potential from file
             cn_tide_load = 'tide_LOAD_grid_T.nc'  ! filename for load potential
-            !      
+            !
       ln_tide_ramp  = .false.               !  Use linear ramp for tides at startup
-         rdttideramp   =    0.                 !  ramp duration in days
-      clname(1)     = 'DUMMY'               !  name of constituent - all tidal components must be set in namelist_cfg
+         rn_tide_ramp_dt = 0.               !  ramp duration in days
+      sn_tide_cnames(1) = 'DUMMY'               !  name of constituent - all tidal components must be set in namelist_cfg
 /
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/nambdy_tide
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/nambdy_tide	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/nambdy_tide	(revision 14055)
@@ -4,4 +4,3 @@
    filtide          = 'bdydta/amm12_bdytide_'   !  file name root of tidal forcing files
    ln_bdytide_2ddta = .false.                   !
-   ln_bdytide_conj  = .false.                   ! 
 /
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/namdyn_rhg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/namdyn_rhg	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/doc/namelists/namdyn_rhg	(revision 14055)
@@ -3,4 +3,5 @@
 !------------------------------------------------------------------------------
    ln_rhg_EVP       = .true.          !  EVP rheology
+   ln_rhg_EAP       = .false.          !  EAP rheology
       ln_aEVP       = .false.         !     adaptive rheology (Kimmritz et al. 2016 & 2017)
       rn_creepl     =   2.0e-9        !     creep limit [1/s]
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/ice.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/ice.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/ice.F90	(revision 14055)
@@ -150,10 +150,18 @@
    !
    !                                     !!** ice-rheology namelist (namdyn_rhg) **
+   ! -- evp
+   LOGICAL , PUBLIC ::   ln_rhg_EVP       ! EVP rheology switch, used for rdgrft and rheology
+   LOGICAL , PUBLIC ::   ln_rhg_EAP       ! EAP rheology switch, used for rdgrft and rheology
    LOGICAL , PUBLIC ::   ln_aEVP          !: using adaptive EVP (T or F) 
-   REAL(wp), PUBLIC ::   rn_creepl        !: creep limit : has to be under 1.0e-9
+   REAL(wp), PUBLIC ::   rn_creepl        !: creep limit (has to be low enough, circa 10-9 m/s, depending on rheology)
    REAL(wp), PUBLIC ::   rn_ecc           !: eccentricity of the elliptical yield curve
    INTEGER , PUBLIC ::   nn_nevp          !: number of iterations for subcycling
    REAL(wp), PUBLIC ::   rn_relast        !: ratio => telast/rDt_ice (1/3 or 1/9 depending on nb of subcycling nevp) 
    INTEGER , PUBLIC ::   nn_rhg_chkcvg    !: check ice rheology convergence 
+   ! -- vp
+   LOGICAL , PUBLIC ::   ln_rhg_VP        !: VP rheology
+   INTEGER , PUBLIC ::   nn_vp_nout       !: Number of outer iterations
+   INTEGER , PUBLIC ::   nn_vp_ninn       !: Number of inner iterations (linear system solver)
+   INTEGER , PUBLIC ::   nn_vp_chkcvg     !: Number of iterations every each convergence is checked
    !
    !                                     !!** ice-advection namelist (namdyn_adv) **
@@ -208,7 +216,9 @@
    !                                     !!** ice-ponds namelist (namthd_pnd)
    LOGICAL , PUBLIC ::   ln_pnd           !: Melt ponds (T) or not (F)
-   LOGICAL , PUBLIC ::   ln_pnd_LEV       !: Melt ponds scheme from Holland et al (2012), Flocco et al (2007, 2010)
-   REAL(wp), PUBLIC ::   rn_apnd_min      !: Minimum ice fraction that contributes to melt ponds
-   REAL(wp), PUBLIC ::   rn_apnd_max      !: Maximum ice fraction that contributes to melt ponds
+   LOGICAL , PUBLIC ::   ln_pnd_TOPO      !: Topographic Melt ponds scheme (Flocco et al 2007, 2010)
+   LOGICAL , PUBLIC ::   ln_pnd_LEV       !: Simple melt pond scheme
+   REAL(wp), PUBLIC ::   rn_apnd_min      !: Minimum fraction of melt water contributing to ponds
+   REAL(wp), PUBLIC ::   rn_apnd_max      !: Maximum fraction of melt water contributing to ponds
+   REAL(wp), PUBLIC ::   rn_pnd_flush     !: Pond flushing efficiency (tuning parameter)
    LOGICAL , PUBLIC ::   ln_pnd_CST       !: Melt ponds scheme with constant fraction and depth
    REAL(wp), PUBLIC ::   rn_apnd          !: prescribed pond fraction (0<rn_apnd<1)
@@ -246,4 +256,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   divu_i          !: Divergence of the velocity field             [s-1]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   shear_i         !: Shear of the velocity field                  [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   aniso_11, aniso_12   !: structure tensor elements
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdg_conv
    !
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   t_bo            !: Sea-Ice bottom temperature [Kelvin]     
@@ -341,4 +353,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   om_i          !: mean ice age over all categories                        (s)
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   tau_icebfr    !: ice friction on ocean bottom (landfast param activated)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   icb_mask      !: mask of grounded icebergs if landfast [0-1]
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   t_s           !: Snow temperatures     [K]
@@ -362,8 +375,13 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   vt_il         !: total melt pond lid volume per gridcell area [m]
 
+   ! meltwater arrays to save for melt ponds (mv - could be grouped in a single meltwater volume array)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   dh_i_sum_2d   !: surface melt (2d arrays for ponds)       [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   dh_s_mlt_2d   !: snow surf melt (2d arrays for ponds)     [m]
+
    !!----------------------------------------------------------------------
    !! * Global variables at before time step
    !!----------------------------------------------------------------------
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_s_b, v_i_b, h_s_b, h_i_b !: snow and ice volumes/thickness
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_ip_b, v_il_b             !: ponds and lids volumes
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_i_b, sv_i_b              !:
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   e_s_b                      !: snow heat content
@@ -392,4 +410,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_vsnw         !: snw volume variation   [m/s] 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_aice         !: ice conc.  variation   [s-1] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_vpnd         !: pond volume variation  [m/s] 
    !
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_adv_mass     !: advection of mass (kg/m2/s)
@@ -436,5 +455,6 @@
       ALLOCATE( u_oce    (jpi,jpj) , v_oce    (jpi,jpj) , ht_i_new  (jpi,jpj) , strength(jpi,jpj) ,  &
          &      stress1_i(jpi,jpj) , stress2_i(jpi,jpj) , stress12_i(jpi,jpj) ,                      &
-         &      delta_i  (jpi,jpj) , divu_i   (jpi,jpj) , shear_i   (jpi,jpj) , STAT=ierr(ii) )
+         &      delta_i  (jpi,jpj) , divu_i   (jpi,jpj) , shear_i   (jpi,jpj) ,                      &
+         &      aniso_11 (jpi,jpj) , aniso_12 (jpi,jpj) , rdg_conv  (jpi,jpj) , STAT=ierr(ii) )
 
       ii = ii + 1
@@ -468,5 +488,5 @@
          &      et_i (jpi,jpj) , et_s (jpi,jpj) , tm_i(jpi,jpj) , tm_s(jpi,jpj) ,  &
          &      sm_i (jpi,jpj) , tm_su(jpi,jpj) , hm_i(jpi,jpj) , hm_s(jpi,jpj) ,  &
-         &      om_i (jpi,jpj) , bvm_i(jpi,jpj) , tau_icebfr(jpi,jpj)            , STAT=ierr(ii) )
+         &      om_i (jpi,jpj) , bvm_i(jpi,jpj) , tau_icebfr(jpi,jpj), icb_mask(jpi,jpj), STAT=ierr(ii) )
 
       ii = ii + 1
@@ -478,5 +498,6 @@
       ii = ii + 1
       ALLOCATE( a_ip(jpi,jpj,jpl) , v_ip(jpi,jpj,jpl) , a_ip_frac(jpi,jpj,jpl) , h_ip(jpi,jpj,jpl),  &
-         &      v_il(jpi,jpj,jpl) , h_il(jpi,jpj,jpl) , a_ip_eff (jpi,jpj,jpl) , STAT = ierr(ii) )
+         &      v_il(jpi,jpj,jpl) , h_il(jpi,jpj,jpl) , a_ip_eff (jpi,jpj,jpl) ,                     &
+         &      dh_i_sum_2d(jpi,jpj,jpl) , dh_s_mlt_2d(jpi,jpj,jpl) , STAT = ierr(ii) )
 
       ii = ii + 1
@@ -486,4 +507,5 @@
       ii = ii + 1
       ALLOCATE( v_s_b (jpi,jpj,jpl) , v_i_b (jpi,jpj,jpl) , h_s_b(jpi,jpj,jpl)        , h_i_b(jpi,jpj,jpl),         &
+         &      v_ip_b(jpi,jpj,jpl) , v_il_b(jpi,jpj,jpl) ,                                                         &
          &      a_i_b (jpi,jpj,jpl) , sv_i_b(jpi,jpj,jpl) , e_i_b(jpi,jpj,nlay_i,jpl) , e_s_b(jpi,jpj,nlay_s,jpl) , &
          &      STAT=ierr(ii) )
@@ -500,5 +522,5 @@
       ALLOCATE( diag_trp_vi(jpi,jpj) , diag_trp_vs (jpi,jpj) , diag_trp_ei(jpi,jpj),                      & 
          &      diag_trp_es(jpi,jpj) , diag_trp_sv (jpi,jpj) , diag_heat  (jpi,jpj),                      &
-         &      diag_sice  (jpi,jpj) , diag_vice   (jpi,jpj) , diag_vsnw  (jpi,jpj), diag_aice(jpi,jpj),  &
+         &      diag_sice  (jpi,jpj) , diag_vice   (jpi,jpj) , diag_vsnw  (jpi,jpj), diag_aice(jpi,jpj), diag_vpnd(jpi,jpj),  &
          &      diag_adv_mass(jpi,jpj), diag_adv_salt(jpi,jpj), diag_adv_heat(jpi,jpj), STAT=ierr(ii) )
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icectl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icectl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icectl.F90	(revision 14055)
@@ -85,5 +85,6 @@
       !!
       REAL(wp) ::   zdiag_mass, zdiag_salt, zdiag_heat, &
-         &          zdiag_vmin, zdiag_amin, zdiag_amax, zdiag_eimin, zdiag_esmin, zdiag_smin
+         &          zdiag_vimin, zdiag_vsmin, zdiag_vpmin, zdiag_vlmin, zdiag_aimin, zdiag_aimax, &
+         &          zdiag_eimin, zdiag_esmin, zdiag_simin
       REAL(wp) ::   zvtrp, zetrp
       REAL(wp) ::   zarea
@@ -92,5 +93,5 @@
       IF( icount == 0 ) THEN
 
-         pdiag_v = glob_sum( 'icectl',   SUM( v_i * rhoi + v_s * rhos, dim=3 ) * e1e2t )
+         pdiag_v = glob_sum( 'icectl',   SUM( v_i * rhoi + v_s * rhos + ( v_ip + v_il ) * rhow, dim=3 ) * e1e2t )
          pdiag_s = glob_sum( 'icectl',   SUM( sv_i * rhoi            , dim=3 ) * e1e2t )
          pdiag_t = glob_sum( 'icectl', ( SUM( SUM( e_i, dim=4 ), dim=3 ) + SUM( SUM( e_s, dim=4 ), dim=3 ) ) * e1e2t )
@@ -112,5 +113,6 @@
 
          ! -- mass diag -- !
-         zdiag_mass = ( glob_sum( 'icectl', SUM( v_i * rhoi + v_s * rhos, dim=3 ) * e1e2t ) - pdiag_v ) * r1_Dt_ice       &
+         zdiag_mass = ( glob_sum( 'icectl', SUM( v_i * rhoi + v_s * rhos + ( v_ip + v_il ) * rhow, dim=3 ) * e1e2t )      &
+            &            - pdiag_v ) * r1_Dt_ice                                                                          &
             &         + glob_sum( 'icectl', ( wfx_bog + wfx_bom + wfx_sum + wfx_sni + wfx_opw + wfx_res + wfx_dyn +       &
             &                                 wfx_lam + wfx_pnd + wfx_snw_sni + wfx_snw_sum + wfx_snw_dyn + wfx_snw_sub + &
@@ -132,8 +134,11 @@
 
          ! -- min/max diag -- !
-         zdiag_amax  = glob_max( 'icectl', SUM( a_i, dim=3 ) )
-         zdiag_vmin  = glob_min( 'icectl', v_i )
-         zdiag_amin  = glob_min( 'icectl', a_i )
-         zdiag_smin  = glob_min( 'icectl', sv_i )
+         zdiag_aimax = glob_max( 'icectl', SUM( a_i, dim=3 ) )
+         zdiag_vimin = glob_min( 'icectl', v_i  )
+         zdiag_vsmin = glob_min( 'icectl', v_s  )
+         zdiag_vpmin = glob_min( 'icectl', v_ip )
+         zdiag_vlmin = glob_min( 'icectl', v_il )
+         zdiag_aimin = glob_min( 'icectl', a_i  )
+         zdiag_simin = glob_min( 'icectl', sv_i )
          zdiag_eimin = glob_min( 'icectl', SUM( e_i, dim=3 ) )
          zdiag_esmin = glob_min( 'icectl', SUM( e_s, dim=3 ) )
@@ -155,17 +160,20 @@
                &                   WRITE(numout,*)   cd_routine,' : violation heat cons. [J]  = ',zdiag_heat * rDt_ice
             ! check negative values
-            IF( zdiag_vmin  < 0. ) WRITE(numout,*)   cd_routine,' : violation v_i < 0         = ',zdiag_vmin
-            IF( zdiag_amin  < 0. ) WRITE(numout,*)   cd_routine,' : violation a_i < 0         = ',zdiag_amin
-            IF( zdiag_smin  < 0. ) WRITE(numout,*)   cd_routine,' : violation s_i < 0         = ',zdiag_smin
-            IF( zdiag_eimin < 0. ) WRITE(numout,*)   cd_routine,' : violation e_i < 0         = ',zdiag_eimin
-            IF( zdiag_esmin < 0. ) WRITE(numout,*)   cd_routine,' : violation e_s < 0         = ',zdiag_esmin
+            IF( zdiag_vimin < 0. ) WRITE(numout,*)   cd_routine,' : violation v_i  < 0        = ',zdiag_vimin
+            IF( zdiag_vsmin < 0. ) WRITE(numout,*)   cd_routine,' : violation v_s  < 0        = ',zdiag_vsmin
+            IF( zdiag_vpmin < 0. ) WRITE(numout,*)   cd_routine,' : violation v_ip < 0        = ',zdiag_vpmin
+            IF( zdiag_vlmin < 0. ) WRITE(numout,*)   cd_routine,' : violation v_il < 0        = ',zdiag_vlmin
+            IF( zdiag_aimin < 0. ) WRITE(numout,*)   cd_routine,' : violation a_i  < 0        = ',zdiag_aimin
+            IF( zdiag_simin < 0. ) WRITE(numout,*)   cd_routine,' : violation s_i  < 0        = ',zdiag_simin
+            IF( zdiag_eimin < 0. ) WRITE(numout,*)   cd_routine,' : violation e_i  < 0        = ',zdiag_eimin
+            IF( zdiag_esmin < 0. ) WRITE(numout,*)   cd_routine,' : violation e_s  < 0        = ',zdiag_esmin
             ! check maximum ice concentration
-            IF( zdiag_amax > MAX(rn_amax_n,rn_amax_s)+epsi10 .AND. cd_routine /= 'icedyn_adv' .AND. cd_routine /= 'icedyn_rdgrft' ) &
-               &                   WRITE(numout,*)   cd_routine,' : violation a_i > amax      = ',zdiag_amax
+            IF( zdiag_aimax>MAX(rn_amax_n,rn_amax_s)+epsi10 .AND. cd_routine /= 'icedyn_adv' .AND. cd_routine /= 'icedyn_rdgrft' ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation a_i > amax      = ',zdiag_aimax
             ! check if advection scheme is conservative
             IF( ABS(zvtrp) > zchk_m * rn_icechk_glo * zarea .AND. cd_routine == 'icedyn_adv' ) &
-               &                   WRITE(numout,*)   cd_routine,' : violation adv scheme [kg] = ',zvtrp * rdt_ice
+               &                   WRITE(numout,*)   cd_routine,' : violation adv scheme [kg] = ',zvtrp * rDt_ice
             IF( ABS(zetrp) > zchk_t * rn_icechk_glo * zarea .AND. cd_routine == 'icedyn_adv' ) &
-               &                   WRITE(numout,*)   cd_routine,' : violation adv scheme [J]  = ',zetrp * rdt_ice
+               &                   WRITE(numout,*)   cd_routine,' : violation adv scheme [J]  = ',zetrp * rDt_ice
          ENDIF
          !
@@ -193,6 +201,6 @@
       ! water flux
       ! -- mass diag -- !
-      zdiag_mass = glob_sum( 'icectl', (  wfx_ice   + wfx_snw   + wfx_spr + wfx_sub &
-         &                              + diag_vice + diag_vsnw - diag_adv_mass ) * e1e2t )
+      zdiag_mass = glob_sum( 'icectl', (  wfx_ice   + wfx_snw   + wfx_spr   + wfx_sub + wfx_pnd &
+         &                              + diag_vice + diag_vsnw + diag_vpnd - diag_adv_mass ) * e1e2t )
 
       ! -- salt diag -- !
@@ -200,5 +208,5 @@
 
       ! -- heat diag -- !
-      zdiag_heat  = glob_sum( 'icectl', ( qt_oce_ai - qt_atm_oi + diag_heat - diag_adv_heat ) * e1e2t )
+      zdiag_heat = glob_sum( 'icectl', ( qt_oce_ai - qt_atm_oi + diag_heat - diag_adv_heat ) * e1e2t )
       ! equivalent to this:
       !!zdiag_heat = glob_sum( 'icectl', ( -diag_heat + hfx_sum + hfx_bom + hfx_bog + hfx_dif + hfx_opw + hfx_snw &
@@ -245,6 +253,6 @@
       IF( icount == 0 ) THEN
 
-         pdiag_v = SUM( v_i  * rhoi + v_s * rhos, dim=3 )
-         pdiag_s = SUM( sv_i * rhoi             , dim=3 )
+         pdiag_v = SUM( v_i  * rhoi + v_s * rhos + ( v_ip + v_il ) * rhow, dim=3 )
+         pdiag_s = SUM( sv_i * rhoi , dim=3 )
          pdiag_t = SUM( SUM( e_i, dim=4 ), dim=3 ) + SUM( SUM( e_s, dim=4 ), dim=3 )
 
@@ -261,5 +269,5 @@
 
          ! -- mass diag -- !
-         zdiag_mass =   ( SUM( v_i * rhoi + v_s * rhos, dim=3 ) - pdiag_v ) * r1_Dt_ice                             &
+         zdiag_mass =   ( SUM( v_i * rhoi + v_s * rhos + ( v_ip + v_il ) * rhow, dim=3 ) - pdiag_v ) * r1_Dt_ice    &
             &         + ( wfx_bog + wfx_bom + wfx_sum + wfx_sni + wfx_opw + wfx_res + wfx_dyn + wfx_lam + wfx_pnd + &
             &             wfx_snw_sni + wfx_snw_sum + wfx_snw_dyn + wfx_snw_sub + wfx_ice_sub + wfx_spr )           &
@@ -352,4 +360,10 @@
       CALL iom_rstput( 0, 0, inum, 'sneg_count', pdiag_smin(:,:) , ktype = jp_r8 )    ! 
       CALL iom_rstput( 0, 0, inum, 'eneg_count', pdiag_emin(:,:) , ktype = jp_r8 )    ! 
+      ! mean state
+      CALL iom_rstput( 0, 0, inum, 'icecon'    , SUM(a_i ,dim=3) , ktype = jp_r8 )    !
+      CALL iom_rstput( 0, 0, inum, 'icevol'    , SUM(v_i ,dim=3) , ktype = jp_r8 )    !
+      CALL iom_rstput( 0, 0, inum, 'snwvol'    , SUM(v_s ,dim=3) , ktype = jp_r8 )    !
+      CALL iom_rstput( 0, 0, inum, 'pndvol'    , SUM(v_ip,dim=3) , ktype = jp_r8 )    !
+      CALL iom_rstput( 0, 0, inum, 'lidvol'    , SUM(v_il,dim=3) , ktype = jp_r8 )    !
       
       CALL iom_close( inum )
@@ -776,9 +790,9 @@
       ! -- mass diag -- !
       zdiag_mass     = glob_sum( 'icectl', (  wfx_ice   + wfx_snw   + wfx_spr + wfx_sub &
-         &                                  + diag_vice + diag_vsnw - diag_adv_mass ) * e1e2t ) * rdt_ice
+         &                                  + diag_vice + diag_vsnw - diag_adv_mass ) * e1e2t ) * rDt_ice
       zdiag_adv_mass = glob_sum( 'icectl', diag_adv_mass * e1e2t ) * rDt_ice
 
       ! -- salt diag -- !
-      zdiag_salt     = glob_sum( 'icectl', ( sfx + diag_sice - diag_adv_salt ) * e1e2t ) * rdt_ice * 1.e-3
+      zdiag_salt     = glob_sum( 'icectl', ( sfx + diag_sice - diag_adv_salt ) * e1e2t ) * rDt_ice * 1.e-3
       zdiag_adv_salt = glob_sum( 'icectl', diag_adv_salt * e1e2t ) * rDt_ice * 1.e-3
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedia.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedia.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedia.F90	(revision 14055)
@@ -261,9 +261,9 @@
          ! Write in numriw (if iter == nitrst)
          ! ------------------ 
-         CALL iom_rstput( iter, nitrst, numriw, 'frc_voltop' , frc_voltop  )
-         CALL iom_rstput( iter, nitrst, numriw, 'frc_volbot' , frc_volbot  )
-         CALL iom_rstput( iter, nitrst, numriw, 'frc_temtop' , frc_temtop  )
-         CALL iom_rstput( iter, nitrst, numriw, 'frc_tembot' , frc_tembot  )
-         CALL iom_rstput( iter, nitrst, numriw, 'frc_sal'    , frc_sal     )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_voltop' , frc_voltop )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_volbot' , frc_volbot )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_temtop' , frc_temtop )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_tembot' , frc_tembot )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_sal'    , frc_sal    )
          CALL iom_rstput( iter, nitrst, numriw, 'vol_loc_ini', vol_loc_ini )
          CALL iom_rstput( iter, nitrst, numriw, 'tem_loc_ini', tem_loc_ini )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn.F90	(revision 14055)
@@ -29,4 +29,5 @@
    USE lbclnk         ! lateral boundary conditions (or mpp links)
    USE timing         ! Timing
+   USE fldread        ! read input fields
 
    IMPLICIT NONE
@@ -51,4 +52,6 @@
    REAL(wp) ::   rn_vice          !    prescribed v-vel (case np_dynADV1D & np_dynADV2D)
    
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_icbmsk   ! structure of input grounded icebergs mask (file informations, fields read)
+
    !! * Substitutions
 #  include "do_loop_substitute.h90"
@@ -81,5 +84,5 @@
       !
       ! controls
-      IF( ln_timing )   CALL timing_start('icedyn')
+      IF( ln_timing )   CALL timing_start('ice_dyn')
       !
       IF( kt == nit000 .AND. lwp ) THEN
@@ -106,4 +109,8 @@
       END WHERE
       !
+      IF( ln_landfast_L16 ) THEN
+         CALL fld_read( kt, 1, sf_icbmsk )
+         icb_mask(:,:) = sf_icbmsk(1)%fnow(:,:,1)
+      ENDIF
       !
       SELECT CASE( nice_dyn )          !-- Set which dynamics is running
@@ -172,5 +179,5 @@
       !
       ! controls
-      IF( ln_timing )   CALL timing_stop ('icedyn')
+      IF( ln_timing )   CALL timing_stop ('ice_dyn')
       !
    END SUBROUTINE ice_dyn
@@ -216,9 +223,13 @@
       !! ** input   :   Namelist namdyn
       !!-------------------------------------------------------------------
-      INTEGER ::   ios, ioptio   ! Local integer output status for namelist read
+      INTEGER ::   ios, ioptio, ierror   ! Local integer output status for namelist read
+      !
+      CHARACTER(len=256) ::   cn_dir     ! Root directory for location of ice files
+      TYPE(FLD_N)        ::   sn_icbmsk  ! informations about the grounded icebergs field to be read
       !!
       NAMELIST/namdyn/ ln_dynALL, ln_dynRHGADV, ln_dynADV1D, ln_dynADV2D, rn_uice, rn_vice,  &
          &             rn_ishlat ,                                                           &
-         &             ln_landfast_L16, rn_lf_depfra, rn_lf_bfr, rn_lf_relax, rn_lf_tensile
+         &             ln_landfast_L16, rn_lf_depfra, rn_lf_bfr, rn_lf_relax, rn_lf_tensile, &
+         &             sn_icbmsk, cn_dir
       !!-------------------------------------------------------------------
       !
@@ -269,4 +280,21 @@
       IF( .NOT.ln_landfast_L16 )   tau_icebfr(:,:) = 0._wp
       !
+      !                                      !--- allocate and fill structure for grounded icebergs mask
+      IF( ln_landfast_L16 ) THEN
+         ALLOCATE( sf_icbmsk(1), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'ice_dyn_init: unable to allocate sf_icbmsk structure' ) ; RETURN
+         ENDIF
+         !
+         CALL fld_fill( sf_icbmsk, (/ sn_icbmsk /), cn_dir, 'ice_dyn_init',   &
+            &                                               'landfast ice is a function of read grounded icebergs', 'icedyn' )
+         !
+         ALLOCATE( sf_icbmsk(1)%fnow(jpi,jpj,1) )
+         IF( sf_icbmsk(1)%ln_tint )   ALLOCATE( sf_icbmsk(1)%fdta(jpi,jpj,1,2) )
+         IF( TRIM(sf_icbmsk(1)%clrootname) == 'NOT USED' ) sf_icbmsk(1)%fnow(:,:,1) = 0._wp   ! not used field  (set to 0)         
+      ELSE
+         icb_mask(:,:) = 0._wp
+      ENDIF
+      !                                      !--- other init 
       CALL ice_dyn_rdgrft_init          ! set ice ridging/rafting parameters
       CALL ice_dyn_rhg_init             ! set ice rheology parameters
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_adv_pra.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_adv_pra.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_adv_pra.F90	(revision 14055)
@@ -156,5 +156,6 @@
 
          ! diagnostics
-         zdiag_adv_mass(:,:) =   SUM(  pv_i(:,:,:) , dim=3 ) * rhoi + SUM(  pv_s(:,:,:) , dim=3 ) * rhos
+         zdiag_adv_mass(:,:) =   SUM( pv_i (:,:,:) , dim=3 ) * rhoi + SUM( pv_s (:,:,:) , dim=3 ) * rhos &
+            &                  + SUM( pv_ip(:,:,:) , dim=3 ) * rhow + SUM( pv_il(:,:,:) , dim=3 ) * rhow
          zdiag_adv_salt(:,:) =   SUM( psv_i(:,:,:) , dim=3 ) * rhoi
          zdiag_adv_heat(:,:) = - SUM(SUM( pe_i(:,:,1:nlay_i,:) , dim=4 ), dim=3 ) &
@@ -178,5 +179,5 @@
                z0ei(:,:,jk,jl) = pe_i(:,:,jk,jl) * e1e2t(:,:) ! Ice  heat content
             END DO
-            IF ( ln_pnd_LEV ) THEN
+            IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                z0ap(:,:,jl) = pa_ip(:,:,jl) * e1e2t(:,:)      ! Melt pond fraction
                z0vp(:,:,jl) = pv_ip(:,:,jl) * e1e2t(:,:)      ! Melt pond volume
@@ -214,5 +215,5 @@
             END DO
             !
-            IF ( ln_pnd_LEV ) THEN
+            IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                CALL adv_x( zdt , zudy , 1._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap )    !--- melt pond fraction
                CALL adv_y( zdt , zvdx , 0._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap ) 
@@ -249,5 +250,5 @@
                   &                                 sxxe(:,:,jk,:), sye(:,:,jk,:), syye(:,:,jk,:), sxye(:,:,jk,:) )
             END DO
-            IF ( ln_pnd_LEV ) THEN
+            IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                CALL adv_y( zdt , zvdx , 1._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap )    !--- melt pond fraction
                CALL adv_x( zdt , zudy , 0._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap )
@@ -278,5 +279,5 @@
          CALL lbc_lnk_multi( 'icedyn_adv_pra', z0ei  , 'T', 1._wp, sxe   , 'T', -1._wp, sye   , 'T', -1._wp  & ! ice enthalpy
             &                                , sxxe  , 'T', 1._wp, syye  , 'T',  1._wp, sxye  , 'T',  1._wp  )
-         IF ( ln_pnd_LEV ) THEN
+         IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
             CALL lbc_lnk_multi( 'icedyn_adv_pra', z0ap , 'T', 1._wp, sxap , 'T', -1._wp, syap , 'T', -1._wp  & ! melt pond fraction
                &                                , sxxap, 'T', 1._wp, syyap, 'T',  1._wp, sxyap, 'T',  1._wp  &
@@ -302,5 +303,5 @@
                pe_i(:,:,jk,jl) = z0ei(:,:,jk,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
             END DO
-            IF ( ln_pnd_LEV ) THEN
+            IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                pa_ip(:,:,jl) = z0ap(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
                pv_ip(:,:,jl) = z0vp(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
@@ -320,5 +321,6 @@
          !
          ! --- diagnostics --- !
-         diag_adv_mass(:,:) = diag_adv_mass(:,:) + (   SUM( pv_i(:,:,:) , dim=3 ) * rhoi + SUM( pv_s(:,:,:) , dim=3 ) * rhos &
+         diag_adv_mass(:,:) = diag_adv_mass(:,:) + (   SUM( pv_i (:,:,:) , dim=3 ) * rhoi + SUM( pv_s (:,:,:) , dim=3 ) * rhos &
+            &                                        + SUM( pv_ip(:,:,:) , dim=3 ) * rhow + SUM( pv_il(:,:,:) , dim=3 ) * rhow &
             &                                        - zdiag_adv_mass(:,:) ) * z1_dt
          diag_adv_salt(:,:) = diag_adv_salt(:,:) + (   SUM( psv_i(:,:,:) , dim=3 ) * rhoi &
@@ -769,5 +771,5 @@
                !                               ! -- check h_ip -- !
                ! if h_ip is larger than the surrounding 9 pts => reduce h_ip and increase a_ip
-               IF( ln_pnd_LEV .AND. pv_ip(ji,jj,jl) > 0._wp ) THEN
+               IF( ln_pnd_LEV .OR. ln_pnd_TOPO .AND. pv_ip(ji,jj,jl) > 0._wp ) THEN
                   zhip = pv_ip(ji,jj,jl) / MAX( epsi20, pa_ip(ji,jj,jl) )
                   IF( zhip > phip_max(ji,jj,jl) .AND. pa_ip(ji,jj,jl) < 0.15 ) THEN
@@ -989,21 +991,31 @@
             DO jk = 1, nlay_s
                WRITE(zchar1,'(I2.2)') jk
-               znam = 'sxc0'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   sxc0 (:,:,jk,:) = z3d(:,:,:)
-               znam = 'syc0'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   syc0 (:,:,jk,:) = z3d(:,:,:)
-               znam = 'sxxc0'//'_l'//zchar1 ;   CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxxc0(:,:,jk,:) = z3d(:,:,:)
-               znam = 'syyc0'//'_l'//zchar1 ;   CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   syyc0(:,:,jk,:) = z3d(:,:,:)
-               znam = 'sxyc0'//'_l'//zchar1 ;   CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxyc0(:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxc0'//'_l'//zchar1  
+               CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   sxc0 (:,:,jk,:) = z3d(:,:,:)
+               znam = 'syc0'//'_l'//zchar1  
+               CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   syc0 (:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxxc0'//'_l'//zchar1 
+               CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxxc0(:,:,jk,:) = z3d(:,:,:)
+               znam = 'syyc0'//'_l'//zchar1 
+               CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   syyc0(:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxyc0'//'_l'//zchar1 
+               CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxyc0(:,:,jk,:) = z3d(:,:,:)
             END DO
             !                                                        ! ice layers heat content
             DO jk = 1, nlay_i
                WRITE(zchar1,'(I2.2)') jk
-               znam = 'sxe'//'_l'//zchar1   ;   CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   sxe (:,:,jk,:) = z3d(:,:,:)
-               znam = 'sye'//'_l'//zchar1   ;   CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   sye (:,:,jk,:) = z3d(:,:,:)
-               znam = 'sxxe'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxxe(:,:,jk,:) = z3d(:,:,:)
-               znam = 'syye'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   syye(:,:,jk,:) = z3d(:,:,:)
-               znam = 'sxye'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxye(:,:,jk,:) = z3d(:,:,:)
-            END DO
-            !
-            IF( ln_pnd_LEV ) THEN                                    ! melt pond fraction
+               znam = 'sxe'//'_l'//zchar1   
+               CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   sxe (:,:,jk,:) = z3d(:,:,:)
+               znam = 'sye'//'_l'//zchar1   
+               CALL iom_get( numrir, jpdom_auto, znam , z3d, psgn = -1._wp )   ;   sye (:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxxe'//'_l'//zchar1  
+               CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxxe(:,:,jk,:) = z3d(:,:,:)
+               znam = 'syye'//'_l'//zchar1  
+               CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   syye(:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxye'//'_l'//zchar1  
+               CALL iom_get( numrir, jpdom_auto, znam , z3d )   ;   sxye(:,:,jk,:) = z3d(:,:,:)
+            END DO
+            !
+            IF( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN                                    ! melt pond fraction
                IF( iom_varid( numrir, 'sxap', ldstop = .FALSE. ) > 0 ) THEN
                   CALL iom_get( numrir, jpdom_auto, 'sxap' , sxap , psgn = -1._wp )
@@ -1047,5 +1059,5 @@
             sxc0  = 0._wp   ;   syc0  = 0._wp   ;   sxxc0  = 0._wp   ;   syyc0  = 0._wp   ;   sxyc0  = 0._wp      ! snow layers heat content
             sxe   = 0._wp   ;   sye   = 0._wp   ;   sxxe   = 0._wp   ;   syye   = 0._wp   ;   sxye   = 0._wp      ! ice layers heat content
-            IF( ln_pnd_LEV ) THEN
+            IF( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                sxap = 0._wp ;   syap = 0._wp    ;   sxxap = 0._wp    ;   syyap = 0._wp    ;   sxyap = 0._wp       ! melt pond fraction
                sxvp = 0._wp ;   syvp = 0._wp    ;   sxxvp = 0._wp    ;   syyvp = 0._wp    ;   sxyvp = 0._wp       ! melt pond volume
@@ -1067,53 +1079,63 @@
          !
          !                                                           ! ice thickness
-         CALL iom_rstput( iter, nitrst, numriw, 'sxice' , sxice  )
-         CALL iom_rstput( iter, nitrst, numriw, 'syice' , syice  )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxxice', sxxice )
-         CALL iom_rstput( iter, nitrst, numriw, 'syyice', syyice )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxyice', sxyice )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxice' , sxice)
+         CALL iom_rstput( iter, nitrst, numriw, 'syice' , syice)
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxice', sxxice)
+         CALL iom_rstput( iter, nitrst, numriw, 'syyice', syyice)
+         CALL iom_rstput( iter, nitrst, numriw, 'sxyice', sxyice)
          !                                                           ! snow thickness
-         CALL iom_rstput( iter, nitrst, numriw, 'sxsn'  , sxsn   )
-         CALL iom_rstput( iter, nitrst, numriw, 'sysn'  , sysn   )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxxsn' , sxxsn  )
-         CALL iom_rstput( iter, nitrst, numriw, 'syysn' , syysn  )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxysn' , sxysn  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxsn'  , sxsn )
+         CALL iom_rstput( iter, nitrst, numriw, 'sysn'  , sysn )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxsn' , sxxsn )
+         CALL iom_rstput( iter, nitrst, numriw, 'syysn' , syysn )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxysn' , sxysn )
          !                                                           ! ice concentration
-         CALL iom_rstput( iter, nitrst, numriw, 'sxa'   , sxa    )
-         CALL iom_rstput( iter, nitrst, numriw, 'sya'   , sya    )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxxa'  , sxxa   )
-         CALL iom_rstput( iter, nitrst, numriw, 'syya'  , syya   )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxya'  , sxya   )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxa'   , sxa  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sya'   , sya  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxa'  , sxxa  )
+         CALL iom_rstput( iter, nitrst, numriw, 'syya'  , syya  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxya'  , sxya  )
          !                                                           ! ice salinity
-         CALL iom_rstput( iter, nitrst, numriw, 'sxsal' , sxsal  )
-         CALL iom_rstput( iter, nitrst, numriw, 'sysal' , sysal  )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxxsal', sxxsal )
-         CALL iom_rstput( iter, nitrst, numriw, 'syysal', syysal )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxysal', sxysal )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxsal' , sxsal)
+         CALL iom_rstput( iter, nitrst, numriw, 'sysal' , sysal)
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxsal', sxxsal)
+         CALL iom_rstput( iter, nitrst, numriw, 'syysal', syysal)
+         CALL iom_rstput( iter, nitrst, numriw, 'sxysal', sxysal)
          !                                                           ! ice age
-         CALL iom_rstput( iter, nitrst, numriw, 'sxage' , sxage  )
-         CALL iom_rstput( iter, nitrst, numriw, 'syage' , syage  )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxxage', sxxage )
-         CALL iom_rstput( iter, nitrst, numriw, 'syyage', syyage )
-         CALL iom_rstput( iter, nitrst, numriw, 'sxyage', sxyage )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxage' , sxage)
+         CALL iom_rstput( iter, nitrst, numriw, 'syage' , syage)
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxage', sxxage)
+         CALL iom_rstput( iter, nitrst, numriw, 'syyage', syyage)
+         CALL iom_rstput( iter, nitrst, numriw, 'sxyage', sxyage)
          !                                                           ! snow layers heat content
          DO jk = 1, nlay_s
             WRITE(zchar1,'(I2.2)') jk
-            znam = 'sxc0'//'_l'//zchar1  ;   z3d(:,:,:) = sxc0 (:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'syc0'//'_l'//zchar1  ;   z3d(:,:,:) = syc0 (:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'sxxc0'//'_l'//zchar1 ;   z3d(:,:,:) = sxxc0(:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'syyc0'//'_l'//zchar1 ;   z3d(:,:,:) = syyc0(:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'sxyc0'//'_l'//zchar1 ;   z3d(:,:,:) = sxyc0(:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sxc0'//'_l'//zchar1  ;   z3d(:,:,:) = sxc0 (:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'syc0'//'_l'//zchar1  ;   z3d(:,:,:) = syc0 (:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'sxxc0'//'_l'//zchar1 ;   z3d(:,:,:) = sxxc0(:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'syyc0'//'_l'//zchar1 ;   z3d(:,:,:) = syyc0(:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'sxyc0'//'_l'//zchar1 ;   z3d(:,:,:) = sxyc0(:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
          END DO
          !                                                           ! ice layers heat content
          DO jk = 1, nlay_i
             WRITE(zchar1,'(I2.2)') jk
-            znam = 'sxe'//'_l'//zchar1   ;   z3d(:,:,:) = sxe (:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'sye'//'_l'//zchar1   ;   z3d(:,:,:) = sye (:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'sxxe'//'_l'//zchar1  ;   z3d(:,:,:) = sxxe(:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'syye'//'_l'//zchar1  ;   z3d(:,:,:) = syye(:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
-            znam = 'sxye'//'_l'//zchar1  ;   z3d(:,:,:) = sxye(:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sxe'//'_l'//zchar1   ;   z3d(:,:,:) = sxe (:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'sye'//'_l'//zchar1   ;   z3d(:,:,:) = sye (:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'sxxe'//'_l'//zchar1  ;   z3d(:,:,:) = sxxe(:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'syye'//'_l'//zchar1  ;   z3d(:,:,:) = syye(:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
+            znam = 'sxye'//'_l'//zchar1  ;   z3d(:,:,:) = sxye(:,:,jk,:)
+            CALL iom_rstput( iter, nitrst, numriw, znam , z3d)
          END DO
          !
-         IF( ln_pnd_LEV ) THEN                                       ! melt pond fraction
+         IF( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN                                       ! melt pond fraction
             CALL iom_rstput( iter, nitrst, numriw, 'sxap' , sxap  )
             CALL iom_rstput( iter, nitrst, numriw, 'syap' , syap  )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_adv_umx.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_adv_umx.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_adv_umx.F90	(revision 14055)
@@ -182,5 +182,6 @@
 
          ! diagnostics
-         zdiag_adv_mass(:,:) =   SUM(  pv_i(:,:,:) , dim=3 ) * rhoi + SUM(  pv_s(:,:,:) , dim=3 ) * rhos
+         zdiag_adv_mass(:,:) =   SUM( pv_i (:,:,:) , dim=3 ) * rhoi + SUM( pv_s (:,:,:) , dim=3 ) * rhos &
+            &                  + SUM( pv_ip(:,:,:) , dim=3 ) * rhow + SUM( pv_il(:,:,:) , dim=3 ) * rhow
          zdiag_adv_salt(:,:) =   SUM( psv_i(:,:,:) , dim=3 ) * rhoi
          zdiag_adv_heat(:,:) = - SUM(SUM( pe_i(:,:,1:nlay_i,:) , dim=4 ), dim=3 ) &
@@ -338,5 +339,5 @@
          !
          !== melt ponds ==!
-         IF ( ln_pnd_LEV ) THEN
+         IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
             ! concentration
             zamsk = 1._wp
@@ -358,8 +359,8 @@
 
          ! --- Lateral boundary conditions --- !
-         IF    ( ln_pnd_LEV .AND. ln_pnd_lids ) THEN
+         IF    ( ( ln_pnd_LEV .OR. ln_pnd_TOPO ) .AND. ln_pnd_lids ) THEN
             CALL lbc_lnk_multi( 'icedyn_adv_umx', pa_i,'T',1._wp, pv_i,'T',1._wp, pv_s,'T',1._wp, psv_i,'T',1._wp, poa_i,'T',1._wp &
                &                                , pa_ip,'T',1._wp, pv_ip,'T',1._wp, pv_il,'T',1._wp )
-         ELSEIF( ln_pnd_LEV .AND. .NOT.ln_pnd_lids ) THEN
+         ELSEIF( ( ln_pnd_LEV .OR. ln_pnd_TOPO ) .AND. .NOT.ln_pnd_lids ) THEN
             CALL lbc_lnk_multi( 'icedyn_adv_umx', pa_i,'T',1._wp, pv_i,'T',1._wp, pv_s,'T',1._wp, psv_i,'T',1._wp, poa_i,'T',1._wp &
                &                                , pa_ip,'T',1._wp, pv_ip,'T',1._wp )
@@ -379,5 +380,6 @@
          !
          ! --- diagnostics --- !
-         diag_adv_mass(:,:) = diag_adv_mass(:,:) + (   SUM( pv_i(:,:,:) , dim=3 ) * rhoi + SUM( pv_s(:,:,:) , dim=3 ) * rhos &
+         diag_adv_mass(:,:) = diag_adv_mass(:,:) + (   SUM( pv_i (:,:,:) , dim=3 ) * rhoi + SUM( pv_s (:,:,:) , dim=3 ) * rhos &
+            &                                        + SUM( pv_ip(:,:,:) , dim=3 ) * rhow + SUM( pv_il(:,:,:) , dim=3 ) * rhow &
             &                                        - zdiag_adv_mass(:,:) ) * z1_dt
          diag_adv_salt(:,:) = diag_adv_salt(:,:) + (   SUM( psv_i(:,:,:) , dim=3 ) * rhoi &
@@ -1497,5 +1499,5 @@
                !                               ! -- check h_ip -- !
                ! if h_ip is larger than the surrounding 9 pts => reduce h_ip and increase a_ip
-               IF( ln_pnd_LEV .AND. pv_ip(ji,jj,jl) > 0._wp ) THEN
+               IF( ( ln_pnd_LEV .OR. ln_pnd_TOPO ) .AND. pv_ip(ji,jj,jl) > 0._wp ) THEN
                   zhip = pv_ip(ji,jj,jl) / MAX( epsi20, pa_ip(ji,jj,jl) )
                   IF( zhip > phip_max(ji,jj,jl) .AND. pa_ip(ji,jj,jl) < 0.15 ) THEN
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rdgrft.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rdgrft.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rdgrft.F90	(revision 14055)
@@ -140,4 +140,5 @@
       INTEGER , DIMENSION(jpij) ::   iptidx        ! compute ridge/raft or not
       REAL(wp), DIMENSION(jpij) ::   zdivu, zdelt  ! 1D divu_i & delta_i
+      REAL(wp), DIMENSION(jpij) ::   zconv         ! 1D rdg_conv (if EAP rheology)
       !
       INTEGER, PARAMETER ::   jp_itermax = 20    
@@ -175,4 +176,5 @@
          ! just needed here
          CALL tab_2d_1d( npti, nptidx(1:npti), zdelt   (1:npti)      , delta_i )
+         CALL tab_2d_1d( npti, nptidx(1:npti), zconv   (1:npti)      , rdg_conv )
          ! needed here and in the iteration loop
          CALL tab_2d_1d( npti, nptidx(1:npti), zdivu   (1:npti)      , divu_i) ! zdivu is used as a work array here (no change in divu_i)
@@ -184,5 +186,7 @@
             ! closing_net = rate at which open water area is removed + ice area removed by ridging 
             !                                                        - ice area added in new ridges
-            closing_net(ji) = rn_csrdg * 0.5_wp * ( zdelt(ji) - ABS( zdivu(ji) ) ) - MIN( zdivu(ji), 0._wp )
+            IF( ln_rhg_EVP .OR. ln_rhg_VP ) & 
+               &               closing_net(ji) = rn_csrdg * 0.5_wp * ( zdelt(ji) - ABS( zdivu(ji) ) ) - MIN( zdivu(ji), 0._wp )
+            IF( ln_rhg_EAP )   closing_net(ji) = zconv(ji)
             !
             IF( zdivu(ji) < 0._wp )   closing_net(ji) = MAX( closing_net(ji), -zdivu(ji) )   ! make sure the closing rate is large enough
@@ -575,5 +579,5 @@
                oirft2(ji) = oa_i_2d(ji,jl1)   * afrft * hi_hrft 
 
-               IF ( ln_pnd_LEV ) THEN
+               IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                   aprdg1     = a_ip_2d(ji,jl1) * afrdg
                   aprdg2(ji) = a_ip_2d(ji,jl1) * afrdg * hi_hrdg(ji,jl1)
@@ -612,5 +616,5 @@
                sv_i_2d(ji,jl1) = sv_i_2d(ji,jl1) - sirdg1    - sirft(ji)
                oa_i_2d(ji,jl1) = oa_i_2d(ji,jl1) - oirdg1    - oirft1
-               IF ( ln_pnd_LEV ) THEN
+               IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                   a_ip_2d(ji,jl1) = a_ip_2d(ji,jl1) - aprdg1    - aprft1
                   v_ip_2d(ji,jl1) = v_ip_2d(ji,jl1) - vprdg(ji) - vprft(ji)
@@ -709,5 +713,5 @@
                   v_s_2d (ji,jl2) = v_s_2d (ji,jl2) + ( vsrdg (ji) * rn_fsnwrdg * fvol(ji)  +  &
                      &                                  vsrft (ji) * rn_fsnwrft * zswitch(ji) )
-                  IF ( ln_pnd_LEV ) THEN
+                  IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                      v_ip_2d (ji,jl2) = v_ip_2d(ji,jl2) + (   vprdg (ji) * rn_fpndrdg * fvol   (ji)   &
                         &                                   + vprft (ji) * rn_fpndrft * zswitch(ji)   )
@@ -776,5 +780,6 @@
       !                              !--------------------------------------------------!
          strength(:,:) = rn_pstar * SUM( v_i(:,:,:), dim=3 ) * EXP( -rn_crhg * ( 1._wp - SUM( a_i(:,:,:), dim=3 ) ) )
-         ismooth = 1
+         ismooth = 1    ! original code
+!        ismooth = 0    ! try for EAP stability
          !                           !--------------------------------------------------!
       ELSE                           ! Zero strength                                    !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg.F90	(revision 14055)
@@ -17,4 +17,6 @@
    USE ice            ! sea-ice: variables
    USE icedyn_rhg_evp ! sea-ice: EVP rheology
+   USE icedyn_rhg_eap ! sea-ice: EAP rheology
+   USE icedyn_rhg_vp  ! sea-ice: VP  rheology
    USE icectl         ! sea-ice: control prints
    !
@@ -33,8 +35,7 @@
    !                                        ! associated indices:
    INTEGER, PARAMETER ::   np_rhgEVP = 1   ! EVP rheology
-!! INTEGER, PARAMETER ::   np_rhgEAP = 2   ! EAP rheology
+   INTEGER, PARAMETER ::   np_rhgEAP = 2   ! EAP rheology
+   INTEGER, PARAMETER ::   np_rhgVP  = 3   ! VP rheology
 
-   ! ** namelist (namrhg) **
-   LOGICAL ::   ln_rhg_EVP       ! EVP rheology
    !
    !!----------------------------------------------------------------------
@@ -77,9 +78,20 @@
          !                             !------------------------!
          CALL ice_dyn_rhg_evp( kt, Kmm, stress1_i, stress2_i, stress12_i, shear_i, divu_i, delta_i )
-         !         
+         !        
+         !                             !------------------------!
+      CASE( np_rhgVP  )                ! Viscous-Plastic        !
+         !                             !------------------------!
+         CALL ice_dyn_rhg_vp ( kt, shear_i, divu_i, delta_i )
+         !
+         !                             !----------------------------!
+      CASE( np_rhgEAP )                ! Elasto-Anisotropic-Plastic !
+         !                             !----------------------------!
+         CALL ice_dyn_rhg_eap( kt, Kmm, stress1_i, stress2_i, stress12_i, shear_i, divu_i, delta_i, aniso_11, aniso_12, rdg_conv )
       END SELECT
       !
-      IF( lrst_ice ) THEN                       !* write EVP fields in the restart file
-         IF( ln_rhg_EVP )   CALL rhg_evp_rst( 'WRITE', kt )
+      IF( lrst_ice ) THEN
+         IF( ln_rhg_EVP )   CALL rhg_evp_rst( 'WRITE', kt ) !* write EVP fields in the restart file
+         IF( ln_rhg_EAP )   CALL rhg_eap_rst( 'WRITE', kt ) !* write EAP fields in the restart file
+         ! MV note: no restart needed for VP as there is no time equation for stress tensor
       ENDIF
       !
@@ -108,5 +120,6 @@
       INTEGER ::   ios, ioptio   ! Local integer output status for namelist read
       !!
-      NAMELIST/namdyn_rhg/  ln_rhg_EVP, ln_aEVP, rn_creepl, rn_ecc , nn_nevp, rn_relast, nn_rhg_chkcvg
+      NAMELIST/namdyn_rhg/  ln_rhg_EVP, ln_aEVP, ln_rhg_EAP, rn_creepl, rn_ecc , nn_nevp, rn_relast, nn_rhg_chkcvg, &  !-- evp
+         &                  ln_rhg_VP, nn_vp_nout, nn_vp_ninn, nn_vp_chkcvg                                            !-- vp 
       !!-------------------------------------------------------------------
       !
@@ -124,13 +137,20 @@
          WRITE(numout,*) '      rheology EVP (icedyn_rhg_evp)                        ln_rhg_EVP    = ', ln_rhg_EVP
          WRITE(numout,*) '         use adaptive EVP (aEVP)                           ln_aEVP       = ', ln_aEVP
-         WRITE(numout,*) '         creep limit                                       rn_creepl     = ', rn_creepl
-         WRITE(numout,*) '         eccentricity of the elliptical yield curve        rn_ecc        = ', rn_ecc
+         WRITE(numout,*) '         creep limit                                       rn_creepl     = ', rn_creepl ! also used by vp
+         WRITE(numout,*) '         eccentricity of the elliptical yield curve        rn_ecc        = ', rn_ecc    ! also used by vp
          WRITE(numout,*) '         number of iterations for subcycling               nn_nevp       = ', nn_nevp
          WRITE(numout,*) '         ratio of elastic timescale over ice time step     rn_relast     = ', rn_relast
-         WRITE(numout,*) '      check convergence of rheology                        nn_rhg_chkcvg = ', nn_rhg_chkcvg
-         IF    ( nn_rhg_chkcvg == 0 ) THEN   ;   WRITE(numout,*) '         no check'
-         ELSEIF( nn_rhg_chkcvg == 1 ) THEN   ;   WRITE(numout,*) '         check cvg at the main time step'
-         ELSEIF( nn_rhg_chkcvg == 2 ) THEN   ;   WRITE(numout,*) '         check cvg at both main and rheology time steps'
+         WRITE(numout,*) '         check convergence of rheology                     nn_rhg_chkcvg = ', nn_rhg_chkcvg
+         WRITE(numout,*) '      rheology VP   (icedyn_rhg_VP)                        ln_rhg_VP     = ', ln_rhg_VP
+         WRITE(numout,*) '         number of outer iterations                        nn_vp_nout    = ', nn_vp_nout
+         WRITE(numout,*) '         number of inner iterations                        nn_vp_ninn    = ', nn_vp_ninn
+         WRITE(numout,*) '         iteration step for convergence check              nn_vp_chkcvg  = ', nn_vp_chkcvg
+         IF( ln_rhg_EVP ) THEN
+            IF    ( nn_rhg_chkcvg == 0 ) THEN   ;   WRITE(numout,*) '         no check cvg'
+            ELSEIF( nn_rhg_chkcvg == 1 ) THEN   ;   WRITE(numout,*) '         check cvg at the main time step'
+            ELSEIF( nn_rhg_chkcvg == 2 ) THEN   ;   WRITE(numout,*) '         check cvg at both main and rheology time steps'
+            ENDIF
          ENDIF
+         WRITE(numout,*) '      rheology EAP (icedyn_rhg_eap)                        ln_rhg_EAP = ', ln_rhg_EAP
       ENDIF
       !
@@ -138,8 +158,11 @@
       ioptio = 0 
       IF( ln_rhg_EVP ) THEN   ;   ioptio = ioptio + 1   ;   nice_rhg = np_rhgEVP    ;   ENDIF
-!!    IF( ln_rhg_EAP ) THEN   ;   ioptio = ioptio + 1   ;   nice_rhg = np_rhgEAP    ;   ENDIF
+      IF( ln_rhg_EAP ) THEN   ;   ioptio = ioptio + 1   ;   nice_rhg = np_rhgEAP    ;   ENDIF
+      IF( ln_rhg_VP  ) THEN   ;   ioptio = ioptio + 1   ;   nice_rhg = np_rhgVP     ;   ENDIF 
       IF( ioptio /= 1 )   CALL ctl_stop( 'ice_dyn_rhg_init: choose one and only one ice rheology' )
       !
       IF( ln_rhg_EVP  )   CALL rhg_evp_rst( 'READ' )  !* read or initialize all required files
+      IF( ln_rhg_EAP  )   CALL rhg_eap_rst( 'READ' )  !* read or initialize all required files
+      ! no restart for VP as there is no explicit time dependency in the equation
       !
    END SUBROUTINE ice_dyn_rhg_init
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_eap.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_eap.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_eap.F90	(revision 14055)
@@ -0,0 +1,1991 @@
+MODULE icedyn_rhg_eap
+   !!======================================================================
+   !!                     ***  MODULE  icedyn_rhg_eap  ***
+   !!   Sea-Ice dynamics : rheology Elasto-Viscous-Plastic
+   !!======================================================================
+   !! History :   -   !  2007-03  (M.A. Morales Maqueda, S. Bouillon) Original code
+   !!            3.0  !  2008-03  (M. Vancoppenolle) adaptation to new model
+   !!             -   !  2008-11  (M. Vancoppenolle, S. Bouillon, Y. Aksenov) add surface tilt in ice rheolohy 
+   !!            3.3  !  2009-05  (G.Garric)    addition of the evp case
+   !!            3.4  !  2011-01  (A. Porter)   dynamical allocation 
+   !!            3.5  !  2012-08  (R. Benshila) AGRIF
+   !!            3.6  !  2016-06  (C. Rousset)  Rewriting + landfast ice + mEVP (Bouillon 2013)
+   !!            3.7  !  2017     (C. Rousset)  add aEVP (Kimmritz 2016-2017)
+   !!            4.0  !  2018     (many people) SI3 [aka Sea Ice cube]
+   !!                 !  2019     (S. Rynders, Y. Aksenov, C. Rousset)  change into eap rheology from
+   !!                                           CICE code (Tsamados, Heorton) 
+   !!----------------------------------------------------------------------
+#if defined key_si3 && ! defined key_agrif
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_rhg_eap : computes ice velocities from EVP rheology
+   !!   rhg_eap_rst     : read/write EVP fields in ice restart
+   !!----------------------------------------------------------------------
+   USE phycst         ! Physical constant
+   USE dom_oce        ! Ocean domain
+   USE sbc_oce , ONLY : ln_ice_embd, nn_fsbc, ssh_m
+   USE sbc_ice , ONLY : utau_ice, vtau_ice, snwice_mass, snwice_mass_b
+   USE ice            ! sea-ice: ice variables
+   USE icevar         ! ice_var_sshdyn
+   USE icedyn_rdgrft  ! sea-ice: ice strength
+   USE bdy_oce , ONLY : ln_bdy 
+   USE bdyice 
+#if defined key_agrif
+   USE agrif_ice_interp
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE prtctl         ! Print control
+
+   USE netcdf         ! NetCDF library for convergence test
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rhg_eap   ! called by icedyn_rhg.F90
+   PUBLIC   rhg_eap_rst       ! called by icedyn_rhg.F90
+
+   REAL(wp), PARAMETER ::   pphi = 3.141592653589793_wp/12._wp    ! diamond shaped floe smaller angle (default phi = 30 deg)
+
+   ! look-up table for calculating structure tensor
+   INTEGER, PARAMETER ::   nx_yield = 41
+   INTEGER, PARAMETER ::   ny_yield = 41
+   INTEGER, PARAMETER ::   na_yield = 21
+
+   REAL(wp), DIMENSION(nx_yield, ny_yield, na_yield) ::   s11r, s12r, s22r, s11s, s12s, s22s
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+#  include "domzgr_substitute.h90"
+
+   !! for convergence tests
+   INTEGER ::   ncvgid   ! netcdf file id
+   INTEGER ::   nvarid   ! netcdf variable id
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zmsk00, zmsk15
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id: icedyn_rhg_eap.F90 11536 2019-09-11 13:54:18Z smasson $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_rhg_eap( kt, Kmm, pstress1_i, pstress2_i, pstress12_i, pshear_i, pdivu_i, pdelta_i, paniso_11, paniso_12, prdg_conv )
+      !!-------------------------------------------------------------------
+      !!                 ***  SUBROUTINE ice_dyn_rhg_eap  ***
+      !!                             EAP-C-grid
+      !!
+      !! ** purpose : determines sea ice drift from wind stress, ice-ocean
+      !!  stress and sea-surface slope. Ice-ice interaction is described by 
+      !!  a non-linear elasto-anisotropic-plastic (EAP) law including shear 
+      !!  strength and a bulk rheology .	
+      !!
+      !!  The points in the C-grid look like this, dear reader
+      !!
+      !!                              (ji,jj)
+      !!                                 |
+      !!                                 |
+      !!                      (ji-1,jj)  |  (ji,jj)
+      !!                             ---------   
+      !!                            |         |
+      !!                            | (ji,jj) |------(ji,jj)
+      !!                            |         |
+      !!                             ---------   
+      !!                     (ji-1,jj-1)     (ji,jj-1)
+      !!
+      !! ** Inputs  : - wind forcing (stress), oceanic currents
+      !!                ice total volume (vt_i) per unit area
+      !!                snow total volume (vt_s) per unit area
+      !!
+      !! ** Action  : - compute u_ice, v_ice : the components of the 
+      !!                sea-ice velocity vector
+      !!              - compute delta_i, shear_i, divu_i, which are inputs
+      !!                of the ice thickness distribution
+      !!
+      !! ** Steps   : 0) compute mask at F point
+      !!              1) Compute ice snow mass, ice strength 
+      !!              2) Compute wind, oceanic stresses, mass terms and
+      !!                 coriolis terms of the momentum equation
+      !!              3) Solve the momentum equation (iterative procedure)
+      !!              4) Recompute delta, shear and divergence
+      !!                 (which are inputs of the ITD) & store stress
+      !!                 for the next time step
+      !!              5) Diagnostics including charge ellipse
+      !!
+      !! ** Notes   : There is the possibility to use aEVP from the nice work of Kimmritz et al. (2016 & 2017)
+      !!              by setting up ln_aEVP=T (i.e. changing alpha and beta parameters).
+      !!              This is an upgraded version of mEVP from Bouillon et al. 2013
+      !!              (i.e. more stable and better convergence)
+      !!
+      !! References : Hunke and Dukowicz, JPO97
+      !!              Bouillon et al., Ocean Modelling 2009
+      !!              Bouillon et al., Ocean Modelling 2013
+      !!              Kimmritz et al., Ocean Modelling 2016 & 2017
+      !!-------------------------------------------------------------------
+      INTEGER                 , INTENT(in   ) ::   kt                                    ! time step
+      INTEGER                 , INTENT(in   ) ::   Kmm                                   ! ocean time level index
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pstress1_i, pstress2_i, pstress12_i   !
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pshear_i  , pdivu_i   , pdelta_i      !
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   paniso_11 , paniso_12                 ! structure tensor components
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   prdg_conv                             ! for ridging
+      !!
+      INTEGER ::   ji, jj       ! dummy loop indices
+      INTEGER ::   jter         ! local integers
+      !
+      REAL(wp) ::   zrhoco                                              ! rau0 * rn_cio
+      REAL(wp) ::   zdtevp, z1_dtevp                                    ! time step for subcycling
+      REAL(wp) ::   ecc2, z1_ecc2                                       ! square of yield ellipse eccenticity
+      REAL(wp) ::   zalph1, z1_alph1, zalph2, z1_alph2                  ! alpha coef from Bouillon 2009 or Kimmritz 2017
+      REAl(wp) ::   zbetau, zbetav
+      REAL(wp) ::   zm1, zm2, zm3, zmassU, zmassV, zvU, zvV             ! ice/snow mass and volume
+      REAL(wp) ::   zds2, zdt, zdt2, zdiv, zdiv2, zdsT                  ! temporary scalars
+      REAL(wp) ::   zTauO, zTauB, zRHS, zvel                            ! temporary scalars
+      REAL(wp) ::   zkt                                                 ! isotropic tensile strength for landfast ice
+      REAL(wp) ::   zvCr                                                ! critical ice volume above which ice is landfast
+      !
+      REAL(wp) ::   zintb, zintn                                        ! dummy argument
+      REAL(wp) ::   zfac_x, zfac_y
+      REAL(wp) ::   zshear, zdum1, zdum2
+      REAL(wp) ::   zstressptmp, zstressmtmp, zstress12tmpF             ! anisotropic stress tensor components
+      REAL(wp) ::   zalphar, zalphas                                    ! for mechanical redistribution
+      REAL(wp) ::   zmresult11, zmresult12, z1dtevpkth, zp5kth, z1_dtevp_A  ! for structure tensor evolution
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zstress12tmp                    ! anisotropic stress tensor component for regridding
+      REAL(wp), DIMENSION(jpi,jpj) ::   zyield11, zyield22, zyield12    ! yield surface tensor for history
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdelta, zp_delt                 ! delta and P/delta at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zten_i                          ! tension
+      REAL(wp), DIMENSION(jpi,jpj) ::   zbeta                           ! beta coef from Kimmritz 2017
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdt_m                           ! (dt / ice-snow_mass) on T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zaU  , zaV                      ! ice fraction on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmU_t, zmV_t                    ! (ice-snow_mass / dt) on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmf                             ! coriolis parameter at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   v_oceU, u_oceV, v_iceU, u_iceV  ! ocean/ice u/v component on V/U points                           
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zds                             ! shear
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1, zs2, zs12                  ! stress tensor components
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsshdyn                         ! array used for the calculation of ice surface slope:
+      !                                                                 !    ocean surface (ssh_m) if ice is not embedded
+      !                                                                 !    ice bottom surface if ice is embedded   
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfU  , zfV                      ! internal stresses
+      REAL(wp), DIMENSION(jpi,jpj) ::   zspgU, zspgV                    ! surface pressure gradient at U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCorU, zCorV                    ! Coriolis stress array
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_ai, ztauy_ai              ! ice-atm. stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_oi, ztauy_oi              ! ice-ocean stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_bi, ztauy_bi              ! ice-OceanBottom stress at U-V points (landfast)
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_base, ztauy_base          ! ice-bottom stress at U-V points (landfast)
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk01x, zmsk01y                ! dummy arrays
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk00x, zmsk00y                ! mask for ice presence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfmask                          ! mask at F points for the ice
+
+      REAL(wp), PARAMETER          ::   zepsi  = 1.0e-20_wp             ! tolerance parameter
+      REAL(wp), PARAMETER          ::   zmmin  = 1._wp                  ! ice mass (kg/m2)  below which ice velocity becomes very small
+      REAL(wp), PARAMETER          ::   zamin  = 0.001_wp               ! ice concentration below which ice velocity becomes very small
+      !! --- check convergence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_ice, zv_ice
+      !! --- diags
+      REAL(wp) ::   zsig1, zsig2, zsig12, zfac, z1_strength
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zsig_I, zsig_II, zsig1_p, zsig2_p         
+      !! --- SIMIP diags
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_ice ! X-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_ice ! Y-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_snw ! X-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_snw ! Y-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xatrp     ! X-component of area transport (m2/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_yatrp     ! Y-component of area transport (m2/s)      
+      !!-------------------------------------------------------------------
+
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_rhg_eap: EAP sea-ice rheology'
+      !
+      ! for diagnostics and convergence tests
+      ALLOCATE( zmsk00(jpi,jpj), zmsk15(jpi,jpj) )
+      DO_2D( 1, 1, 1, 1 )
+         zmsk00(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06  ) ) ! 1 if ice    , 0 if no ice
+         zmsk15(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.15_wp ) ) ! 1 if 15% ice, 0 if less
+      END_2D
+      !
+!!gm for Clem:  OPTIMIZATION:  I think zfmask can be computed one for all at the initialization....
+      !------------------------------------------------------------------------------!
+      ! 0) mask at F points for the ice
+      !------------------------------------------------------------------------------!
+      ! ocean/land mask
+      DO_2D( 1, 0, 1, 0 )
+         zfmask(ji,jj) = tmask(ji,jj,1) * tmask(ji+1,jj,1) * tmask(ji,jj+1,1) * tmask(ji+1,jj+1,1)
+      END_2D
+      CALL lbc_lnk( 'icedyn_rhg_eap', zfmask, 'F', 1._wp )
+
+      ! Lateral boundary conditions on velocity (modify zfmask)
+      DO_2D( 0, 0, 0, 0 )
+         IF( zfmask(ji,jj) == 0._wp ) THEN
+            zfmask(ji,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(ji,jj,1), umask(ji,jj+1,1), &
+               &                                          vmask(ji,jj,1), vmask(ji+1,jj,1) ) )
+         ENDIF
+      END_2D
+      DO jj = 2, jpjm1
+         IF( zfmask(1,jj) == 0._wp ) THEN
+            zfmask(1  ,jj) = rn_ishlat * MIN( 1._wp , MAX( vmask(2,jj,1), umask(1,jj+1,1), umask(1,jj,1) ) )
+         ENDIF
+         IF( zfmask(jpi,jj) == 0._wp ) THEN
+            zfmask(jpi,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(jpi,jj+1,1), vmask(jpim1,jj,1), umask(jpi,jj-1,1) ) )
+         ENDIF
+      END DO
+      DO ji = 2, jpim1
+         IF( zfmask(ji,1) == 0._wp ) THEN
+            zfmask(ji, 1 ) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,1,1), umask(ji,2,1), vmask(ji,1,1) ) )
+         ENDIF
+         IF( zfmask(ji,jpj) == 0._wp ) THEN
+            zfmask(ji,jpj) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,jpj,1), vmask(ji-1,jpj,1), umask(ji,jpjm1,1) ) )
+         ENDIF
+      END DO
+      CALL lbc_lnk( 'icedyn_rhg_eap', zfmask, 'F', 1.0_wp )
+
+      !------------------------------------------------------------------------------!
+      ! 1) define some variables and initialize arrays
+      !------------------------------------------------------------------------------!
+      zrhoco = rho0 * rn_cio 
+
+      ! ecc2: square of yield ellipse eccenticrity
+      ecc2    = rn_ecc * rn_ecc
+      z1_ecc2 = 1._wp / ecc2
+
+      ! alpha parameters (Bouillon 2009)
+      IF( .NOT. ln_aEVP ) THEN
+         zdtevp   = rDt_ice / REAL( nn_nevp )
+         zalph1 =   2._wp * rn_relast * REAL( nn_nevp )
+         zalph2 = zalph1 * z1_ecc2
+
+         z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+         z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+      ELSE
+         zdtevp   = rdt_ice
+         ! zalpha parameters set later on adaptatively
+      ENDIF
+      z1_dtevp = 1._wp / zdtevp
+         
+      ! Initialise stress tensor 
+      zs1 (:,:) = pstress1_i (:,:) 
+      zs2 (:,:) = pstress2_i (:,:)
+      zs12(:,:) = pstress12_i(:,:)
+
+      ! constants for structure tensor
+      z1_dtevp_A = z1_dtevp/10.0_wp
+      z1dtevpkth = 1._wp / (z1_dtevp_A + 0.00002_wp)
+      zp5kth = 0.5_wp * 0.00002_wp
+
+      ! Ice strength
+      CALL ice_strength
+
+      ! landfast param from Lemieux(2016): add isotropic tensile strength (following Konig Beatty and Holland, 2010)
+      IF( ln_landfast_L16 ) THEN   ;   zkt = rn_lf_tensile
+      ELSE                         ;   zkt = 0._wp
+      ENDIF
+      !
+      !------------------------------------------------------------------------------!
+      ! 2) Wind / ocean stress, mass terms, coriolis terms
+      !------------------------------------------------------------------------------!
+      ! sea surface height
+      !    embedded sea ice: compute representative ice top surface
+      !    non-embedded sea ice: use ocean surface for slope calculation
+      zsshdyn(:,:) = ice_var_sshdyn( ssh_m, snwice_mass, snwice_mass_b)
+
+      DO_2D( 0, 0, 0, 0 )
+
+         ! ice fraction at U-V points
+         zaU(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+         zaV(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+         ! Ice/snow mass at U-V points
+         zm1 = ( rhos * vt_s(ji  ,jj  ) + rhoi * vt_i(ji  ,jj  ) )
+         zm2 = ( rhos * vt_s(ji+1,jj  ) + rhoi * vt_i(ji+1,jj  ) )
+         zm3 = ( rhos * vt_s(ji  ,jj+1) + rhoi * vt_i(ji  ,jj+1) )
+         zmassU = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm2 * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+         zmassV = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm3 * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+         ! Ocean currents at U-V points
+         v_oceU(ji,jj)   = 0.25_wp * ( v_oce(ji,jj) + v_oce(ji,jj-1) + v_oce(ji+1,jj) + v_oce(ji+1,jj-1) ) * umask(ji,jj,1)
+         u_oceV(ji,jj)   = 0.25_wp * ( u_oce(ji,jj) + u_oce(ji-1,jj) + u_oce(ji,jj+1) + u_oce(ji-1,jj+1) ) * vmask(ji,jj,1)
+
+         ! Coriolis at T points (m*f)
+         zmf(ji,jj)      = zm1 * ff_t(ji,jj)
+
+         ! dt/m at T points (for alpha and beta coefficients)
+         zdt_m(ji,jj)    = zdtevp / MAX( zm1, zmmin )
+         
+         ! m/dt
+         zmU_t(ji,jj)    = zmassU * z1_dtevp
+         zmV_t(ji,jj)    = zmassV * z1_dtevp
+         
+         ! Drag ice-atm.
+         ztaux_ai(ji,jj) = zaU(ji,jj) * utau_ice(ji,jj)
+         ztauy_ai(ji,jj) = zaV(ji,jj) * vtau_ice(ji,jj)
+
+         ! Surface pressure gradient (- m*g*GRAD(ssh)) at U-V points
+         zspgU(ji,jj)    = - zmassU * grav * ( zsshdyn(ji+1,jj) - zsshdyn(ji,jj) ) * r1_e1u(ji,jj)
+         zspgV(ji,jj)    = - zmassV * grav * ( zsshdyn(ji,jj+1) - zsshdyn(ji,jj) ) * r1_e2v(ji,jj)
+
+         ! masks
+         zmsk00x(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassU ) )  ! 0 if no ice
+         zmsk00y(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassV ) )  ! 0 if no ice
+
+         ! switches
+         IF( zmassU <= zmmin .AND. zaU(ji,jj) <= zamin ) THEN   ;   zmsk01x(ji,jj) = 0._wp
+         ELSE                                                   ;   zmsk01x(ji,jj) = 1._wp   ;   ENDIF
+         IF( zmassV <= zmmin .AND. zaV(ji,jj) <= zamin ) THEN   ;   zmsk01y(ji,jj) = 0._wp
+         ELSE                                                   ;   zmsk01y(ji,jj) = 1._wp   ;   ENDIF
+
+      END_2D
+      CALL lbc_lnk_multi( 'icedyn_rhg_eap', zmf, 'T', 1.0_wp, zdt_m, 'T', 1.0_wp )
+      !
+      !                                  !== Landfast ice parameterization ==!
+      !
+      IF( ln_landfast_L16 ) THEN         !-- Lemieux 2016
+         DO_2D( 0, 0, 0, 0 )
+            ! ice thickness at U-V points
+            zvU = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            zvV = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+            ! ice-bottom stress at U points
+            zvCr = zaU(ji,jj) * rn_lf_depfra * hu(ji,jj,Kmm)
+            ztaux_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvU - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaU(ji,jj) ) )
+            ! ice-bottom stress at V points
+            zvCr = zaV(ji,jj) * rn_lf_depfra * hv(ji,jj,Kmm)
+            ztauy_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvV - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaV(ji,jj) ) )
+            ! ice_bottom stress at T points
+            zvCr = at_i(ji,jj) * rn_lf_depfra * ht(ji,jj)
+            tau_icebfr(ji,jj) = - rn_lf_bfr * MAX( 0._wp, vt_i(ji,jj) - zvCr ) * EXP( -rn_crhg * ( 1._wp - at_i(ji,jj) ) )
+         END_2D
+         CALL lbc_lnk( 'icedyn_rhg_eap', tau_icebfr(:,:), 'T', 1.0_wp )
+         !
+      ELSE                               !-- no landfast
+         DO_2D( 0, 0, 0, 0 )
+            ztaux_base(ji,jj) = 0._wp
+            ztauy_base(ji,jj) = 0._wp
+         END_2D
+      ENDIF
+
+      !------------------------------------------------------------------------------!
+      ! 3) Solution of the momentum equation, iterative procedure
+      !------------------------------------------------------------------------------!
+      !
+      !                                               ! ==================== !
+      DO jter = 1 , nn_nevp                           !    loop over jter    !
+         !                                            ! ==================== !        
+         l_full_nf_update = jter == nn_nevp   ! false: disable full North fold update (performances) for iter = 1 to nn_nevp-1
+         !
+         ! convergence test
+         IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2  ) THEN
+            DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
+               zu_ice(ji,jj) = u_ice(ji,jj) * umask(ji,jj,1) ! velocity at previous time step
+               zv_ice(ji,jj) = v_ice(ji,jj) * vmask(ji,jj,1)
+            END_2D
+         ENDIF
+
+         ! --- divergence, tension & shear (Appendix B of Hunke & Dukowicz, 2002) --- !
+         DO_2D( 1, 0, 1, 0 )
+
+            ! shear at F points
+            zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+               &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+               &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+         END_2D
+
+         DO_2D( 0, 0, 0, 0 )
+
+            ! shear**2 at T points (doc eq. A16)
+            zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+           
+            ! divergence at T points
+            zdiv  = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &    + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &    ) * r1_e1e2t(ji,jj)
+            zdiv2 = zdiv * zdiv
+            
+            ! tension at T points
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+            zdt2 = zdt * zdt
+
+            ! delta at T points
+            zdelta(ji,jj) = SQRT( zdiv2 + ( zdt2 + zds2 ) * z1_ecc2 )  
+
+         END_2D
+         CALL lbc_lnk( 'icedyn_rhg_eap', zdelta, 'T', 1.0_wp )
+               
+         ! P/delta at T points
+         DO_2D( 1, 1, 1, 1 )
+            zp_delt(ji,jj) = strength(ji,jj) / ( zdelta(ji,jj) + rn_creepl )
+         END_2D
+
+         DO_2D( 0, 1, 0, 1 )   ! loop ends at jpi,jpj so that no lbc_lnk are needed for zs1 and zs2
+
+             ! shear at T points 
+            zdsT = ( zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+            
+           ! divergence at T points (duplication to avoid communications)
+            zdiv  = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &    + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &    ) * r1_e1e2t(ji,jj)
+            
+            ! tension at T points (duplication to avoid communications)
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+
+            ! --- anisotropic stress calculation --- !
+            CALL update_stress_rdg (jter, nn_nevp, zdiv, zdt, zdsT, paniso_11(ji,jj), paniso_12(ji,jj), &
+                                    zstressptmp, zstressmtmp, zstress12tmp(ji,jj), strength(ji,jj), zalphar, zalphas)
+
+            ! structure tensor update
+               CALL calc_ffrac(zstressptmp, zstressmtmp, zstress12tmp(ji,jj), paniso_11(ji,jj), paniso_12(ji,jj), zmresult11,  zmresult12)
+
+               paniso_11(ji,jj) = (paniso_11(ji,jj)  + 0.5*2.e-5*zdtevp + zmresult11*zdtevp) / (1. + 2.e-5*zdtevp) ! implicit
+               paniso_12(ji,jj) = (paniso_12(ji,jj)                     + zmresult12*zdtevp) / (1. + 2.e-5*zdtevp) ! implicit
+
+            IF (jter == nn_nevp) THEN
+               zyield11(ji,jj) = 0.5_wp * (zstressptmp + zstressmtmp)
+               zyield22(ji,jj) = 0.5_wp * (zstressptmp - zstressmtmp)
+               zyield12(ji,jj) = zstress12tmp(ji,jj)
+               prdg_conv(ji,jj) = -min( zalphar, 0._wp)    
+            ENDIF
+
+            ! alpha for aEVP
+            !   gamma = 0.5*P/(delta+creepl) * (c*pi)**2/Area * dt/m
+            !   alpha = beta = sqrt(4*gamma)
+            IF( ln_aEVP ) THEN
+               zalph1   = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+               z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+               zalph2   = zalph1
+               z1_alph2 = z1_alph1
+               ! explicit:
+               ! z1_alph1 = 1._wp / zalph1
+               ! z1_alph2 = 1._wp / zalph1
+               ! zalph1 = zalph1 - 1._wp
+               ! zalph2 = zalph1
+            ENDIF
+
+            ! stress at T points (zkt/=0 if landfast)
+            zs1(ji,jj) = ( zs1(ji,jj) * zalph1 + zstressptmp ) * z1_alph1
+            zs2(ji,jj) = ( zs2(ji,jj) * zalph1 + zstressmtmp ) * z1_alph1
+         END_2D
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zstress12tmp, 'T', 1.0_wp , paniso_11, 'T', 1.0_wp , paniso_12, 'T', 1.0_wp)
+
+        ! Save beta at T-points for further computations
+         IF( ln_aEVP ) THEN
+            DO_2D( 1, 1, 1, 1 )
+               zbeta(ji,jj) = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+            END_2D
+         ENDIF
+
+         DO_2D( 1, 0, 1, 0 )
+            ! stress12tmp at F points 
+            zstress12tmpF = ( zstress12tmp(ji,jj+1) * e1e2t(ji,jj+1) + zstress12tmp(ji+1,jj+1) * e1e2t(ji+1,jj+1)  &
+               &            + zstress12tmp(ji,jj  ) * e1e2t(ji,jj  ) + zstress12tmp(ji+1,jj  ) * e1e2t(ji+1,jj  )  &
+               &            ) * 0.25_wp * r1_e1e2f(ji,jj)
+
+            ! alpha for aEVP
+            IF( ln_aEVP ) THEN
+               zalph2   = MAX( zbeta(ji,jj), zbeta(ji+1,jj), zbeta(ji,jj+1), zbeta(ji+1,jj+1) )
+               z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+               ! explicit:
+               ! z1_alph2 = 1._wp / zalph2
+               ! zalph2 = zalph2 - 1._wp
+            ENDIF
+            
+            ! stress at F points (zkt/=0 if landfast)
+            zs12(ji,jj) = ( zs12(ji,jj) * zalph1 + zstress12tmpF ) * z1_alph1
+
+         END_2D
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zs1, 'T', 1.0_wp, zs2, 'T', 1.0_wp, zs12, 'F', 1.0_wp )
+
+         ! --- Ice internal stresses (Appendix C of Hunke and Dukowicz, 2002) --- !
+         DO_2D( 0, 0, 0, 0 )
+            !                   !--- U points
+            zfU(ji,jj) = 0.5_wp * ( ( zs1(ji+1,jj) - zs1(ji,jj) ) * e2u(ji,jj)                                             &
+               &                  + ( zs2(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) - zs2(ji,jj) * e2t(ji,jj) * e2t(ji,jj)    &
+               &                    ) * r1_e2u(ji,jj)                                                                      &
+               &                  + ( zs12(ji,jj) * e1f(ji,jj) * e1f(ji,jj) - zs12(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1)  &
+               &                    ) * 2._wp * r1_e1u(ji,jj)                                                              &
+               &                  ) * r1_e1e2u(ji,jj)
+            !
+            !                !--- V points
+            zfV(ji,jj) = 0.5_wp * ( ( zs1(ji,jj+1) - zs1(ji,jj) ) * e1v(ji,jj)                                             &
+               &                  - ( zs2(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) - zs2(ji,jj) * e1t(ji,jj) * e1t(ji,jj)    &
+               &                    ) * r1_e1v(ji,jj)                                                                      &
+               &                  + ( zs12(ji,jj) * e2f(ji,jj) * e2f(ji,jj) - zs12(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj)  &
+               &                    ) * 2._wp * r1_e2v(ji,jj)                                                              &
+               &                  ) * r1_e1e2v(ji,jj)
+            !
+            !                !--- ice currents at U-V point
+            v_iceU(ji,jj) = 0.25_wp * ( v_ice(ji,jj) + v_ice(ji,jj-1) + v_ice(ji+1,jj) + v_ice(ji+1,jj-1) ) * umask(ji,jj,1)
+            u_iceV(ji,jj) = 0.25_wp * ( u_ice(ji,jj) + u_ice(ji-1,jj) + u_ice(ji,jj+1) + u_ice(ji-1,jj+1) ) * vmask(ji,jj,1)
+            !
+         END_2D
+         !
+         ! --- Computation of ice velocity --- !
+         !  Bouillon et al. 2013 (eq 47-48) => unstable unless alpha, beta vary as in Kimmritz 2016 & 2017
+         !  Bouillon et al. 2009 (eq 34-35) => stable
+         IF( MOD(jter,2) == 0 ) THEN ! even iterations
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(v_oce - v_ice)
+               zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                  &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/v_ice
+               zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+               zTauB = ztauy_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+               !
+               !                 !--- Coriolis at V-points (energy conserving formulation)
+               zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                  &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                  &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   & 
+                     &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetav + 1._wp )                                              &
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  v_ice(ji,jj) = ( (         rswitch   * ( zmV_t(ji,jj)  * v_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )   * zmsk00y(ji,jj)
+               ENDIF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', v_ice, 'V', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(u_oce - u_ice)
+               zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                  &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/u_ice
+               zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+               zTauB = ztaux_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+               !
+               !                 !--- Coriolis at U-points (energy conserving formulation)
+               zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                  &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                  &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                     &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetau + 1._wp )                                              &
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  u_ice(ji,jj) = ( (         rswitch   * ( zmU_t(ji,jj)  * u_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &            )   * zmsk00x(ji,jj)
+               ENDIF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', u_ice, 'U', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+         ELSE ! odd iterations
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(u_oce - u_ice)
+               zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                  &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/u_ice
+               zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+               zTauB = ztaux_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+               !
+               !                 !--- Coriolis at U-points (energy conserving formulation)
+               zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                  &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                  &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                     &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetau + 1._wp )                                              &
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  u_ice(ji,jj) = ( (         rswitch   * ( zmU_t(ji,jj)  * u_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )   * zmsk00x(ji,jj)
+               ENDIF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', u_ice, 'U', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(v_oce - v_ice)
+               zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                  &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/v_ice
+               zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+               zTauB = ztauy_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+               !
+               !                 !--- Coriolis at v-points (energy conserving formulation)
+               zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                  &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                  &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   &
+                     &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetav + 1._wp )                                              & 
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  v_ice(ji,jj) = ( (         rswitch   * ( zmV_t(ji,jj)  * v_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )   * zmsk00y(ji,jj)
+               ENDIF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', v_ice, 'V', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+         ENDIF
+
+         ! convergence test
+         IF( nn_rhg_chkcvg == 2 )   CALL rhg_cvg( kt, jter, nn_nevp, u_ice, v_ice, zu_ice, zv_ice )
+         !
+         !                                                ! ==================== !
+      END DO                                              !  end loop over jter  !
+      !                                                   ! ==================== !
+      IF( ln_aEVP )   CALL iom_put( 'beta_evp' , zbeta )
+      !
+      CALL lbc_lnk( 'icedyn_rhg_eap', prdg_conv, 'T', 1.0_wp )  ! only need this in ridging module after rheology completed
+      !
+      !------------------------------------------------------------------------------!
+      ! 4) Recompute delta, shear and div (inputs for mechanical redistribution) 
+      !------------------------------------------------------------------------------!
+      DO_2D( 1, 0, 1, 0 )
+
+         ! shear at F points
+         zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+            &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+            &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+      END_2D
+      
+      DO_2D( 0, 0, 0, 0 )
+         
+         ! tension**2 at T points
+         zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+            &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+            &   ) * r1_e1e2t(ji,jj)
+         zdt2 = zdt * zdt
+         
+         zten_i(ji,jj) = zdt
+
+         ! shear**2 at T points (doc eq. A16)
+         zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+            &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+            &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+         
+         ! shear at T points
+         pshear_i(ji,jj) = SQRT( zdt2 + zds2 )
+
+         ! divergence at T points
+         pdivu_i(ji,jj) = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+            &             + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+            &             ) * r1_e1e2t(ji,jj)
+         
+         ! delta at T points
+         zfac            = SQRT( pdivu_i(ji,jj) * pdivu_i(ji,jj) + ( zdt2 + zds2 ) * z1_ecc2 ) ! delta  
+         rswitch         = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zfac ) ) ! 0 if delta=0
+         pdelta_i(ji,jj) = zfac + rn_creepl * rswitch ! delta+creepl
+
+      END_2D
+      CALL lbc_lnk_multi( 'icedyn_rhg_eap', pshear_i, 'T', 1.0_wp, pdivu_i, 'T', 1.0_wp, pdelta_i, 'T', 1.0_wp, &
+         &                                    zten_i, 'T', 1.0_wp, zs1    , 'T', 1.0_wp, zs2     , 'T', 1.0_wp, &
+         &                                      zs12, 'F', 1.0_wp )
+      
+      ! --- Store the stress tensor for the next time step --- !
+      pstress1_i (:,:) = zs1 (:,:)
+      pstress2_i (:,:) = zs2 (:,:)
+      pstress12_i(:,:) = zs12(:,:)
+      !
+
+      !------------------------------------------------------------------------------!
+      ! 5) diagnostics
+      !------------------------------------------------------------------------------!
+      ! --- ice-ocean, ice-atm. & ice-oceanbottom(landfast) stresses --- !
+      IF(  iom_use('utau_oi') .OR. iom_use('vtau_oi') .OR. iom_use('utau_ai') .OR. iom_use('vtau_ai') .OR. &
+         & iom_use('utau_bi') .OR. iom_use('vtau_bi') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', ztaux_oi, 'U', -1.0_wp, ztauy_oi, 'V', -1.0_wp, ztaux_ai, 'U', -1.0_wp, &
+            &                                  ztauy_ai, 'V', -1.0_wp, ztaux_bi, 'U', -1.0_wp, ztauy_bi, 'V', -1.0_wp )
+         !
+         CALL iom_put( 'utau_oi' , ztaux_oi * zmsk00 )
+         CALL iom_put( 'vtau_oi' , ztauy_oi * zmsk00 )
+         CALL iom_put( 'utau_ai' , ztaux_ai * zmsk00 )
+         CALL iom_put( 'vtau_ai' , ztauy_ai * zmsk00 )
+         CALL iom_put( 'utau_bi' , ztaux_bi * zmsk00 )
+         CALL iom_put( 'vtau_bi' , ztauy_bi * zmsk00 )
+      ENDIF
+       
+      ! --- divergence, shear and strength --- !
+      IF( iom_use('icediv') )   CALL iom_put( 'icediv' , pdivu_i  * zmsk00 )   ! divergence
+      IF( iom_use('iceshe') )   CALL iom_put( 'iceshe' , pshear_i * zmsk00 )   ! shear
+      IF( iom_use('icedlt') )   CALL iom_put( 'icedlt' , pdelta_i * zmsk00 )   ! delta
+      IF( iom_use('icestr') )   CALL iom_put( 'icestr' , strength * zmsk00 )   ! strength
+
+      ! --- Stress tensor invariants (SIMIP diags) --- !
+      IF( iom_use('normstr') .OR. iom_use('sheastr') ) THEN
+         !
+         ALLOCATE( zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )
+         !         
+         DO_2D( 1, 1, 1, 1 )
+         
+            ! Ice stresses
+            ! sigma1, sigma2, sigma12 are some useful recombination of the stresses (Hunke and Dukowicz MWR 2002, Bouillon et al., OM2013)
+            ! These are NOT stress tensor components, neither stress invariants, neither stress principal components
+            ! I know, this can be confusing...
+            zfac             =   strength(ji,jj) / ( pdelta_i(ji,jj) + rn_creepl ) 
+            zsig1            =   zfac * ( pdivu_i(ji,jj) - pdelta_i(ji,jj) )
+            zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+            zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            
+            ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008)
+            zsig_I (ji,jj)   =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+            zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+            
+         END_2D
+         !
+         ! Stress tensor invariants (normal and shear stress N/m) - SIMIP diags - definitions following Coon (1974) and Feltham (2008)
+         IF( iom_use('normstr') )   CALL iom_put( 'normstr', zsig_I (:,:) * zmsk00(:,:) ) ! Normal stress
+         IF( iom_use('sheastr') )   CALL iom_put( 'sheastr', zsig_II(:,:) * zmsk00(:,:) ) ! Maximum shear stress
+         
+         DEALLOCATE ( zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- Normalized stress tensor principal components --- !
+      ! This are used to plot the normalized yield curve, see Lemieux & Dupont, 2020
+      ! Recommendation 1 : we use ice strength, not replacement pressure
+      ! Recommendation 2 : need to use deformations at PREVIOUS iterate for viscosities
+      IF( iom_use('sig1_pnorm') .OR. iom_use('sig2_pnorm') ) THEN
+         !
+         ALLOCATE( zsig1_p(jpi,jpj) , zsig2_p(jpi,jpj) , zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )         
+         !         
+         DO_2D( 1, 1, 1, 1 )
+         
+            ! Ice stresses computed with **viscosities** (delta, p/delta) at **previous** iterates 
+            !                        and **deformations** at current iterates
+            !                        following Lemieux & Dupont (2020)
+            zfac             =   zp_delt(ji,jj)
+            zsig1            =   zfac * ( pdivu_i(ji,jj) - ( zdelta(ji,jj) + rn_creepl ) )
+            zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+            zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            
+            ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008), T-point
+            zsig_I(ji,jj)    =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+            zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+   
+            ! Normalized  principal stresses (used to display the ellipse)
+            z1_strength      =   1._wp / MAX( 1._wp, strength(ji,jj) )
+            zsig1_p(ji,jj)   =   ( zsig_I(ji,jj) + zsig_II(ji,jj) ) * z1_strength
+            zsig2_p(ji,jj)   =   ( zsig_I(ji,jj) - zsig_II(ji,jj) ) * z1_strength
+         END_2D
+         !
+         CALL iom_put( 'sig1_pnorm' , zsig1_p ) 
+         CALL iom_put( 'sig2_pnorm' , zsig2_p ) 
+      
+         DEALLOCATE( zsig1_p , zsig2_p , zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- yieldcurve --- !
+      IF( iom_use('yield11') .OR. iom_use('yield12') .OR. iom_use('yield22')) THEN
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zyield11, 'T', 1.0_wp, zyield22, 'T', 1.0_wp, zyield12, 'T', 1.0_wp )
+
+         CALL iom_put( 'yield11', zyield11 * zmsk00 )
+         CALL iom_put( 'yield22', zyield22 * zmsk00 )
+         CALL iom_put( 'yield12', zyield12 * zmsk00 )
+      ENDIF
+
+      ! --- anisotropy tensor --- !
+      IF( iom_use('aniso') ) THEN       
+         CALL lbc_lnk( 'icedyn_rhg_eap', paniso_11, 'T', 1.0_wp ) 
+         CALL iom_put( 'aniso' , paniso_11 * zmsk00 )
+      ENDIF
+      
+      ! --- SIMIP --- !
+      IF(  iom_use('dssh_dx') .OR. iom_use('dssh_dy') .OR. &
+         & iom_use('corstrx') .OR. iom_use('corstry') .OR. iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zspgU, 'U', -1.0_wp, zspgV, 'V', -1.0_wp, &
+            &                                  zCorU, 'U', -1.0_wp, zCorV, 'V', -1.0_wp, &
+            &                                    zfU, 'U', -1.0_wp,   zfV, 'V', -1.0_wp )
+
+         CALL iom_put( 'dssh_dx' , zspgU * zmsk00 )   ! Sea-surface tilt term in force balance (x)
+         CALL iom_put( 'dssh_dy' , zspgV * zmsk00 )   ! Sea-surface tilt term in force balance (y)
+         CALL iom_put( 'corstrx' , zCorU * zmsk00 )   ! Coriolis force term in force balance (x)
+         CALL iom_put( 'corstry' , zCorV * zmsk00 )   ! Coriolis force term in force balance (y)
+         CALL iom_put( 'intstrx' , zfU   * zmsk00 )   ! Internal force term in force balance (x)
+         CALL iom_put( 'intstry' , zfV   * zmsk00 )   ! Internal force term in force balance (y)
+      ENDIF
+
+      IF(  iom_use('xmtrpice') .OR. iom_use('ymtrpice') .OR. &
+         & iom_use('xmtrpsnw') .OR. iom_use('ymtrpsnw') .OR. iom_use('xatrp') .OR. iom_use('yatrp') ) THEN
+         !
+         ALLOCATE( zdiag_xmtrp_ice(jpi,jpj) , zdiag_ymtrp_ice(jpi,jpj) , &
+            &      zdiag_xmtrp_snw(jpi,jpj) , zdiag_ymtrp_snw(jpi,jpj) , zdiag_xatrp(jpi,jpj) , zdiag_yatrp(jpi,jpj) )
+         !
+         DO_2D( 0, 0, 0, 0 )
+            ! 2D ice mass, snow mass, area transport arrays (X, Y)
+            zfac_x = 0.5 * u_ice(ji,jj) * e2u(ji,jj) * zmsk00(ji,jj)
+            zfac_y = 0.5 * v_ice(ji,jj) * e1v(ji,jj) * zmsk00(ji,jj)
+
+            zdiag_xmtrp_ice(ji,jj) = rhoi * zfac_x * ( vt_i(ji+1,jj) + vt_i(ji,jj) ) ! ice mass transport, X-component
+            zdiag_ymtrp_ice(ji,jj) = rhoi * zfac_y * ( vt_i(ji,jj+1) + vt_i(ji,jj) ) !        ''           Y-   ''
+
+            zdiag_xmtrp_snw(ji,jj) = rhos * zfac_x * ( vt_s(ji+1,jj) + vt_s(ji,jj) ) ! snow mass transport, X-component
+            zdiag_ymtrp_snw(ji,jj) = rhos * zfac_y * ( vt_s(ji,jj+1) + vt_s(ji,jj) ) !          ''          Y-   ''
+
+            zdiag_xatrp(ji,jj)     = zfac_x * ( at_i(ji+1,jj) + at_i(ji,jj) )        ! area transport,      X-component
+            zdiag_yatrp(ji,jj)     = zfac_y * ( at_i(ji,jj+1) + at_i(ji,jj) )        !        ''            Y-   ''
+
+         END_2D
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zdiag_xmtrp_ice, 'U', -1.0_wp, zdiag_ymtrp_ice, 'V', -1.0_wp, &
+            &                                  zdiag_xmtrp_snw, 'U', -1.0_wp, zdiag_ymtrp_snw, 'V', -1.0_wp, &
+            &                                  zdiag_xatrp    , 'U', -1.0_wp, zdiag_yatrp    , 'V', -1.0_wp )
+
+         CALL iom_put( 'xmtrpice' , zdiag_xmtrp_ice )   ! X-component of sea-ice mass transport (kg/s)
+         CALL iom_put( 'ymtrpice' , zdiag_ymtrp_ice )   ! Y-component of sea-ice mass transport 
+         CALL iom_put( 'xmtrpsnw' , zdiag_xmtrp_snw )   ! X-component of snow mass transport (kg/s)
+         CALL iom_put( 'ymtrpsnw' , zdiag_ymtrp_snw )   ! Y-component of snow mass transport
+         CALL iom_put( 'xatrp'    , zdiag_xatrp     )   ! X-component of ice area transport
+         CALL iom_put( 'yatrp'    , zdiag_yatrp     )   ! Y-component of ice area transport
+
+         DEALLOCATE( zdiag_xmtrp_ice , zdiag_ymtrp_ice , &
+            &        zdiag_xmtrp_snw , zdiag_ymtrp_snw , zdiag_xatrp , zdiag_yatrp )
+
+      ENDIF
+      !
+      ! --- convergence tests --- !
+      IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2 ) THEN
+         IF( iom_use('uice_cvg') ) THEN
+            IF( ln_aEVP ) THEN   ! output: beta * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * zbeta(:,:) * umask(:,:,1) , &
+                  &                           ABS( v_ice(:,:) - zv_ice(:,:) ) * zbeta(:,:) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ELSE                 ! output: nn_nevp * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', REAL( nn_nevp ) * MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * umask(:,:,1) , &
+                  &                                             ABS( v_ice(:,:) - zv_ice(:,:) ) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ENDIF
+         ENDIF
+      ENDIF      
+      !
+      DEALLOCATE( zmsk00, zmsk15 )
+      !
+   END SUBROUTINE ice_dyn_rhg_eap
+
+   
+   SUBROUTINE rhg_cvg( kt, kiter, kitermax, pu, pv, pub, pvb )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE rhg_cvg  ***
+      !!                     
+      !! ** Purpose :   check convergence of oce rheology
+      !!
+      !! ** Method  :   create a file ice_cvg.nc containing the convergence of ice velocity
+      !!                during the sub timestepping of rheology so as:
+      !!                  uice_cvg = MAX( u(t+1) - u(t) , v(t+1) - v(t) )
+      !!                This routine is called every sub-iteration, so it is cpu expensive
+      !!
+      !! ** Note    :   for the first sub-iteration, uice_cvg is set to 0 (too large otherwise)   
+      !!----------------------------------------------------------------------
+      INTEGER ,                 INTENT(in) ::   kt, kiter, kitermax       ! ocean time-step index
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pu, pv, pub, pvb          ! now and before velocities
+      !!
+      INTEGER           ::   it, idtime, istatus
+      INTEGER           ::   ji, jj          ! dummy loop indices
+      REAL(wp)          ::   zresm           ! local real 
+      CHARACTER(len=20) ::   clname
+      REAL(wp), DIMENSION(jpi,jpj) ::   zres           ! check convergence
+      !!----------------------------------------------------------------------
+
+      ! create file
+      IF( kt == nit000 .AND. kiter == 1 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'rhg_cvg : ice rheology convergence control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !
+         IF( lwm ) THEN
+            clname = 'ice_cvg.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, ncvgid )
+            istatus = NF90_DEF_DIM( ncvgid, 'time'  , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( ncvgid, 'uice_cvg', NF90_DOUBLE   , (/ idtime /), nvarid )
+            istatus = NF90_ENDDEF(ncvgid)
+         ENDIF
+         !
+      ENDIF
+
+      ! time
+      it = ( kt - 1 ) * kitermax + kiter
+      
+      ! convergence
+      IF( kiter == 1 ) THEN ! remove the first iteration for calculations of convergence (always very large)
+         zresm = 0._wp
+      ELSE
+         DO_2D( 1, 1, 1, 1 )
+            zres(ji,jj) = MAX( ABS( pu(ji,jj) - pub(ji,jj) ) * umask(ji,jj,1), &
+               &               ABS( pv(ji,jj) - pvb(ji,jj) ) * vmask(ji,jj,1) ) * zmsk15(ji,jj)
+         END_2D
+         zresm = MAXVAL( zres )
+         CALL mpp_max( 'icedyn_rhg_evp', zresm )   ! max over the global domain
+      ENDIF
+
+      IF( lwm ) THEN
+         ! write variables
+         istatus = NF90_PUT_VAR( ncvgid, nvarid, (/zresm/), (/it/), (/1/) )
+         ! close file
+         IF( kt == nitend )   istatus = NF90_CLOSE(ncvgid)
+      ENDIF
+      
+   END SUBROUTINE rhg_cvg
+
+
+   SUBROUTINE update_stress_rdg( ksub, kndte, pdivu, ptension, pshear, pa11, pa12, &
+      &                          pstressp,  pstressm, pstress12, pstrength, palphar, palphas )
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE update_stress_rdg  ***
+      !!                     
+      !! ** Purpose :   Updates the stress depending on values of strain rate and structure
+      !!                tensor and for the last subcycle step it computes closing and sliding rate
+      !!---------------------------------------------------------------------
+      INTEGER,  INTENT(in   ) ::   ksub, kndte
+      REAL(wp), INTENT(in   ) ::   pstrength
+      REAL(wp), INTENT(in   ) ::   pdivu, ptension, pshear
+      REAL(wp), INTENT(in   ) ::   pa11, pa12
+      REAL(wp), INTENT(  out) ::   pstressp, pstressm, pstress12
+      REAL(wp), INTENT(  out) ::   palphar, palphas
+
+      INTEGER  ::   kx ,ky, ka
+
+      REAL(wp) ::   zstemp11r, zstemp12r, zstemp22r   
+      REAL(wp) ::   zstemp11s, zstemp12s, zstemp22s 
+      REAL(wp) ::   za22, zQd11Qd11, zQd11Qd12, zQd12Qd12 
+      REAL(wp) ::   zQ11Q11, zQ11Q12, zQ12Q12 
+      REAL(wp) ::   zdtemp11, zdtemp12, zdtemp22 
+      REAL(wp) ::   zrotstemp11r, zrotstemp12r, zrotstemp22r   
+      REAL(wp) ::   zrotstemp11s, zrotstemp12s, zrotstemp22s
+      REAL(wp) ::   zsig11, zsig12, zsig22 
+      REAL(wp) ::   zsgprm11, zsgprm12, zsgprm22 
+      REAL(wp) ::   zinvstressconviso 
+      REAL(wp) ::   zAngle_denom_gamma,  zAngle_denom_alpha 
+      REAL(wp) ::   zTany_1, zTany_2 
+      REAL(wp) ::   zx, zy, zdx, zdy, zda, zkxw, kyw, kaw
+      REAL(wp) ::   zinvdx, zinvdy, zinvda   
+      REAL(wp) ::   zdtemp1, zdtemp2, zatempprime, zinvsin
+
+      REAL(wp), PARAMETER ::   kfriction = 0.45_wp
+      !!---------------------------------------------------------------------
+      ! Factor to maintain the same stress as in EVP (see Section 3)
+      ! Can be set to 1 otherwise
+!      zinvstressconviso = 1._wp/(1._wp+kfriction*kfriction)
+      zinvstressconviso = 1._wp
+ 
+      zinvsin = 1._wp/sin(2._wp*pphi) * zinvstressconviso 
+      !now uses phi as set in higher code
+       
+      ! compute eigenvalues, eigenvectors and angles for structure tensor, strain
+      ! rates
+
+      ! 1) structure tensor
+      za22 = 1._wp-pa11
+      zQ11Q11 = 1._wp
+      zQ12Q12 = rsmall
+      zQ11Q12 = rsmall
+ 
+      ! gamma: angle between general coordiantes and principal axis of A 
+      ! here Tan2gamma = 2 a12 / (a11 - a22) 
+      IF((ABS(pa11 - za22) > rsmall).OR.(ABS(pa12) > rsmall)) THEN      
+         zAngle_denom_gamma = 1._wp/sqrt( ( pa11 - za22 )*( pa11 - za22) + &
+                              4._wp*pa12*pa12 )
+   
+         zQ11Q11 = 0.5_wp + ( pa11 - za22 )*0.5_wp*zAngle_denom_gamma   !Cos^2 
+         zQ12Q12 = 0.5_wp - ( pa11 - za22 )*0.5_wp*zAngle_denom_gamma   !Sin^2
+         zQ11Q12 = pa12*zAngle_denom_gamma                     !CosSin 
+      ENDIF
+ 
+      ! rotation Q*atemp*Q^T
+      zatempprime = zQ11Q11*pa11 + 2.0_wp*zQ11Q12*pa12 + zQ12Q12*za22 
+      
+      ! make first principal value the largest
+      zatempprime = max(zatempprime, 1.0_wp - zatempprime)
+ 
+      ! 2) strain rate
+      zdtemp11 = 0.5_wp*(pdivu + ptension)
+      zdtemp12 = pshear*0.5_wp
+      zdtemp22 = 0.5_wp*(pdivu - ptension)
+
+      ! here Tan2alpha = 2 dtemp12 / (dtemp11 - dtemp22) 
+
+      zQd11Qd11 = 1.0_wp
+      zQd12Qd12 = rsmall
+      zQd11Qd12 = rsmall
+
+      IF((ABS( zdtemp11 - zdtemp22) > rsmall).OR. (ABS(zdtemp12) > rsmall)) THEN
+
+         zAngle_denom_alpha = 1.0_wp/sqrt( ( zdtemp11 - zdtemp22 )* &
+                             ( zdtemp11 - zdtemp22 ) + 4.0_wp*zdtemp12*zdtemp12)
+
+         zQd11Qd11 = 0.5_wp + ( zdtemp11 - zdtemp22 )*0.5_wp*zAngle_denom_alpha !Cos^2 
+         zQd12Qd12 = 0.5_wp - ( zdtemp11 - zdtemp22 )*0.5_wp*zAngle_denom_alpha !Sin^2
+         zQd11Qd12 = zdtemp12*zAngle_denom_alpha !CosSin
+      ENDIF
+
+      zdtemp1 = zQd11Qd11*zdtemp11 + 2.0_wp*zQd11Qd12*zdtemp12 + zQd12Qd12*zdtemp22
+      zdtemp2 = zQd12Qd12*zdtemp11 - 2.0_wp*zQd11Qd12*zdtemp12 + zQd11Qd11*zdtemp22
+      ! In cos and sin values
+      zx = 0._wp
+      IF ((ABS(zdtemp1) > rsmall).OR.(ABS(zdtemp2) > rsmall)) THEN
+         zx = atan2(zdtemp2,zdtemp1)
+      ENDIF      
+               
+      ! to ensure the angle lies between pi/4 and 9 pi/4 
+      IF (zx < rpi*0.25_wp) zx = zx + rpi*2.0_wp
+      
+      ! y: angle between major principal axis of strain rate and structure
+      ! tensor
+      ! y = gamma - alpha 
+      ! Expressesed componently with
+      ! Tany = (Singamma*Cosgamma - Sinalpha*Cosgamma)/(Cos^2gamma - Sin^alpha)
+      
+      zTany_1 = zQ11Q12 - zQd11Qd12
+      zTany_2 = zQ11Q11 - zQd12Qd12
+      
+      zy = 0._wp
+      
+      IF ((ABS(zTany_1) > rsmall).OR.(ABS(zTany_2) > rsmall)) THEN
+         zy = atan2(zTany_1,zTany_2)
+      ENDIF
+      
+      ! to make sure y is between 0 and pi
+      IF (zy > rpi) zy = zy - rpi
+      IF (zy < 0)  zy = zy + rpi
+
+      ! 3) update anisotropic stress tensor 
+      zdx   = rpi/real(nx_yield-1,kind=wp)
+      zdy   = rpi/real(ny_yield-1,kind=wp)
+      zda   = 0.5_wp/real(na_yield-1,kind=wp)
+      zinvdx = 1._wp/zdx
+      zinvdy = 1._wp/zdy
+      zinvda = 1._wp/zda
+
+      ! % need 8 coords and 8 weights
+      ! % range in kx
+      kx  = int((zx-rpi*0.25_wp-rpi)*zinvdx) + 1
+      !!clem kx  = MAX( 1, MIN( nx_yield-1, INT((zx-rpi*0.25_wp-rpi)*zinvdx) + 1  ) )
+      zkxw = kx - (zx-rpi*0.25_wp-rpi)*zinvdx  
+      
+      ky  = int(zy*zinvdy) + 1
+      !!clem ky  = MAX( 1, MIN( ny_yield-1, INT(zy*zinvdy) + 1 ) )
+      kyw = ky - zy*zinvdy 
+      
+      ka  = int((zatempprime-0.5_wp)*zinvda) + 1
+      !!clem ka  = MAX( 1, MIN( na_yield-1, INT((zatempprime-0.5_wp)*zinvda) + 1 ) )
+      kaw = ka - (zatempprime-0.5_wp)*zinvda
+      
+      ! % Determine sigma_r(A1,Zeta,y) and sigma_s (see Section A1 of Tsamados 2013)
+!!$      zstemp11r =  zkxw  * kyw         * kaw         * s11r(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s11r(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s11r(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s11r(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s11r(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s11r(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s11r(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s11r(kx+1,ky+1,ka+1)
+!!$      zstemp12r =  zkxw  * kyw         * kaw         * s12r(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s12r(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s12r(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s12r(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s12r(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s12r(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s12r(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s12r(kx+1,ky+1,ka+1)
+!!$      zstemp22r =  zkxw  * kyw         * kaw         * s22r(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s22r(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s22r(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s22r(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s22r(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s22r(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s22r(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s22r(kx+1,ky+1,ka+1)
+!!$      
+!!$      zstemp11s =  zkxw  * kyw         * kaw         * s11s(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s11s(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s11s(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s11s(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s11s(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s11s(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s11s(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s11s(kx+1,ky+1,ka+1)
+!!$      zstemp12s =  zkxw  * kyw         * kaw         * s12s(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s12s(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s12s(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s12s(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s12s(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s12s(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s12s(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s12s(kx+1,ky+1,ka+1)
+!!$      zstemp22s =  zkxw  * kyw         * kaw         * s22s(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s22s(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s22s(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s22s(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s22s(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s22s(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s22s(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s22s(kx+1,ky+1,ka+1)
+
+      zstemp11r = s11r(kx,ky,ka)
+      zstemp12r = s12r(kx,ky,ka)
+      zstemp22r = s22r(kx,ky,ka)
+      zstemp11s = s11s(kx,ky,ka)
+      zstemp12s = s12s(kx,ky,ka)
+      zstemp22s = s22s(kx,ky,ka)
+      
+      
+      ! Calculate mean ice stress over a collection of floes (Equation 3 in
+      ! Tsamados 2013)
+
+      zsig11  = pstrength*(zstemp11r + kfriction*zstemp11s) * zinvsin
+      zsig12  = pstrength*(zstemp12r + kfriction*zstemp12s) * zinvsin
+      zsig22  = pstrength*(zstemp22r + kfriction*zstemp22s) * zinvsin
+
+      ! Back - rotation of the stress from principal axes into general coordinates
+
+      ! Update stress
+      zsgprm11 = zQ11Q11*zsig11 + zQ12Q12*zsig22 -      2._wp*zQ11Q12 *zsig12
+      zsgprm12 = zQ11Q12*zsig11 - zQ11Q12*zsig22 + (zQ11Q11 - zQ12Q12)*zsig12
+      zsgprm22 = zQ12Q12*zsig11 + zQ11Q11*zsig22 +      2._wp*zQ11Q12 *zsig12
+
+      pstressp  = zsgprm11 + zsgprm22
+      pstress12 = zsgprm12
+      pstressm  = zsgprm11 - zsgprm22
+
+      ! Compute ridging and sliding functions in general coordinates 
+      ! (Equation 11 in Tsamados 2013)
+      IF (ksub == kndte) THEN
+         zrotstemp11r = zQ11Q11*zstemp11r - 2._wp*zQ11Q12* zstemp12r &
+                      + zQ12Q12*zstemp22r
+         zrotstemp12r = zQ11Q11*zstemp12r +       zQ11Q12*(zstemp11r-zstemp22r) &
+                      - zQ12Q12*zstemp12r
+         zrotstemp22r = zQ12Q12*zstemp11r + 2._wp*zQ11Q12* zstemp12r & 
+                      + zQ11Q11*zstemp22r
+
+         zrotstemp11s = zQ11Q11*zstemp11s - 2._wp*zQ11Q12* zstemp12s &
+                      + zQ12Q12*zstemp22s
+         zrotstemp12s = zQ11Q11*zstemp12s +       zQ11Q12*(zstemp11s-zstemp22s) &
+                      - zQ12Q12*zstemp12s
+         zrotstemp22s = zQ12Q12*zstemp11s + 2._wp*zQ11Q12* zstemp12s & 
+                      + zQ11Q11*zstemp22s
+
+         palphar =  zrotstemp11r*zdtemp11 + 2._wp*zrotstemp12r*zdtemp12 &
+                  + zrotstemp22r*zdtemp22
+         palphas =  zrotstemp11s*zdtemp11 + 2._wp*zrotstemp12s*zdtemp12 &
+                  + zrotstemp22s*zdtemp22
+      ENDIF
+   END SUBROUTINE update_stress_rdg 
+
+!=======================================================================
+
+
+   SUBROUTINE calc_ffrac( pstressp, pstressm, pstress12, pa11, pa12, &
+      &                   pmresult11, pmresult12 )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE calc_ffrac  ***
+      !!                     
+      !! ** Purpose :   Computes term in evolution equation for structure tensor
+      !!                which determines the ice floe re-orientation due to fracture
+      !! ** Method :    Eq. 7: Ffrac = -kf(A-S) or = 0 depending on sigma_1 and sigma_2
+      !!---------------------------------------------------------------------
+      REAL (wp), INTENT(in)  ::   pstressp, pstressm, pstress12, pa11, pa12
+      REAL (wp), INTENT(out) ::   pmresult11, pmresult12
+
+      ! local variables
+
+      REAL (wp) ::   zsigma11, zsigma12, zsigma22  ! stress tensor elements
+      REAL (wp) ::   zAngle_denom        ! angle with principal component axis
+      REAL (wp) ::   zsigma_1, zsigma_2   ! principal components of stress
+      REAL (wp) ::   zQ11, zQ12, zQ11Q11, zQ11Q12, zQ12Q12
+
+!!$      REAL (wp), PARAMETER ::   kfrac = 0.0001_wp   ! rate of fracture formation 
+      REAL (wp), PARAMETER ::   kfrac = 1.e-3_wp   ! rate of fracture formation 
+      REAL (wp), PARAMETER ::   threshold = 0.3_wp  ! critical confinement ratio 
+      !!---------------------------------------------------------------
+      !
+      zsigma11 = 0.5_wp*(pstressp+pstressm) 
+      zsigma12 = pstress12 
+      zsigma22 = 0.5_wp*(pstressp-pstressm) 
+
+      ! Here's the change - no longer calculate gamma,
+      ! use trig formulation, angle signs are kept correct, don't worry
+   
+      ! rotate tensor to get into sigma principal axis
+   
+      ! here Tan2gamma = 2 sig12 / (sig11 - sig12) 
+      ! add rsmall to the denominator to stop 1/0 errors, makes very little 
+      ! error to the calculated angles < rsmall
+
+      zQ11Q11 = 0.1_wp
+      zQ12Q12 = rsmall
+      zQ11Q12 = rsmall
+
+      IF((ABS( zsigma11 - zsigma22) > rsmall).OR.(ABS(zsigma12) > rsmall)) THEN
+
+         zAngle_denom = 1.0_wp/sqrt( ( zsigma11 - zsigma22 )*( zsigma11 - &
+                       zsigma22 ) + 4.0_wp*zsigma12*zsigma12)
+
+         zQ11Q11 = 0.5_wp + ( zsigma11 - zsigma22 )*0.5_wp*zAngle_denom   !Cos^2 
+         zQ12Q12 = 0.5_wp - ( zsigma11 - zsigma22 )*0.5_wp*zAngle_denom   !Sin^2
+         zQ11Q12 = zsigma12*zAngle_denom                      !CosSin 
+      ENDIF
+
+      zsigma_1 = zQ11Q11*zsigma11 + 2.0_wp*zQ11Q12*zsigma12 + zQ12Q12*zsigma22 ! S(1,1)
+      zsigma_2 = zQ12Q12*zsigma11 - 2.0_wp*zQ11Q12*zsigma12 + zQ11Q11*zsigma22 ! S(2,2)
+
+      ! Pure divergence
+      IF ((zsigma_1 >= 0.0_wp).AND.(zsigma_2 >= 0.0_wp))  THEN
+         pmresult11 = 0.0_wp
+         pmresult12 = 0.0_wp
+
+      ! Unconfined compression: cracking of blocks not along the axial splitting
+      ! direction
+      ! which leads to the loss of their shape, so we again model it through diffusion
+      ELSEIF ((zsigma_1 >= 0.0_wp).AND.(zsigma_2 < 0.0_wp))  THEN
+         pmresult11 = - kfrac * (pa11 - zQ12Q12)
+         pmresult12 = - kfrac * (pa12 + zQ11Q12)
+
+      ! Shear faulting
+      ELSEIF (zsigma_2 == 0.0_wp) THEN
+         pmresult11 = 0.0_wp
+         pmresult12 = 0.0_wp
+      ELSEIF ((zsigma_1 <= 0.0_wp).AND.(zsigma_1/zsigma_2 <= threshold)) THEN
+         pmresult11 = - kfrac * (pa11 - zQ12Q12)
+         pmresult12 = - kfrac * (pa12 + zQ11Q12)
+
+      ! Horizontal spalling
+      ELSE 
+         pmresult11 = 0.0_wp
+         pmresult12 = 0.0_wp
+      ENDIF
+
+   END SUBROUTINE calc_ffrac
+
+
+   SUBROUTINE rhg_eap_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rhg_eap_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write RHG file in restart file
+      !!      
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER  ::   iter                      ! local integer
+      INTEGER  ::   id1, id2, id3, id4, id5   ! local integers
+      INTEGER  ::   ix, iy, ip, iz, n, ia     ! local integers
+    
+      INTEGER, PARAMETER            ::    nz = 100
+      
+      REAL(wp) ::   ainit, xinit, yinit, pinit, zinit
+      REAL(wp) ::   da, dx, dy, dp, dz, a1
+
+      !!clem
+      REAL(wp) ::   zw1, zw2, zfac, ztemp
+      REAL(wp) ::   idx, idy, idz
+
+      REAL(wp), PARAMETER           ::   eps6 = 1.0e-6_wp
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialize
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            id1 = iom_varid( numrir, 'stress1_i' , ldstop = .FALSE. )
+            id2 = iom_varid( numrir, 'stress2_i' , ldstop = .FALSE. )
+            id3 = iom_varid( numrir, 'stress12_i', ldstop = .FALSE. )
+            id4 = iom_varid( numrir, 'aniso_11'  , ldstop = .FALSE. )
+            id5 = iom_varid( numrir, 'aniso_12'  , ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2, id3, id4, id5 ) > 0 ) THEN      ! fields exist
+               CALL iom_get( numrir, jpdom_auto, 'stress1_i' , stress1_i , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'stress2_i' , stress2_i , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'stress12_i', stress12_i, cd_type = 'F' )
+               CALL iom_get( numrir, jpdom_auto, 'aniso_11'  , aniso_11  , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'aniso_12'  , aniso_12  , cd_type = 'T' )
+            ELSE                                     ! start rheology from rest
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) '   ==>>>   previous run without rheology, set stresses to 0'
+               stress1_i (:,:) = 0._wp
+               stress2_i (:,:) = 0._wp
+               stress12_i(:,:) = 0._wp
+               aniso_11  (:,:) = 0.5_wp
+               aniso_12  (:,:) = 0._wp
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>>   start from rest: set stresses to 0'
+            stress1_i (:,:) = 0._wp
+            stress2_i (:,:) = 0._wp
+            stress12_i(:,:) = 0._wp
+            aniso_11  (:,:) = 0.5_wp
+            aniso_12  (:,:) = 0._wp
+         ENDIF
+         !
+
+         da = 0.5_wp/real(na_yield-1,kind=wp)
+         ainit = 0.5_wp - da
+         dx = rpi/real(nx_yield-1,kind=wp)
+         xinit = rpi + 0.25_wp*rpi - dx
+         dz = rpi/real(nz,kind=wp)
+         zinit = -rpi*0.5_wp
+         dy = rpi/real(ny_yield-1,kind=wp)
+         yinit = -dy
+
+         s11r(:,:,:) = 0._wp
+         s12r(:,:,:) = 0._wp
+         s22r(:,:,:) = 0._wp
+         s11s(:,:,:) = 0._wp
+         s12s(:,:,:) = 0._wp
+         s22s(:,:,:) = 0._wp
+
+!!$         DO ia=1,na_yield
+!!$            DO ix=1,nx_yield
+!!$               DO iy=1,ny_yield
+!!$                  s11r(ix,iy,ia) = 0._wp
+!!$                  s12r(ix,iy,ia) = 0._wp
+!!$                  s22r(ix,iy,ia) = 0._wp
+!!$                  s11s(ix,iy,ia) = 0._wp
+!!$                  s12s(ix,iy,ia) = 0._wp
+!!$                  s22s(ix,iy,ia) = 0._wp
+!!$                  IF (ia <= na_yield-1) THEN
+!!$                     DO iz=1,nz
+!!$                        s11r(ix,iy,ia) = s11r(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s11kr(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s12r(ix,iy,ia) = s12r(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s12kr(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s22r(ix,iy,ia) = s22r(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s22kr(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi) 
+!!$                        s11s(ix,iy,ia) = s11s(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s11ks(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s12s(ix,iy,ia) = s12s(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s12ks(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s22s(ix,iy,ia) = s22s(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s22ks(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                     ENDDO
+!!$                     IF (abs(s11r(ix,iy,ia)) < eps6) s11r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12r(ix,iy,ia)) < eps6) s12r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22r(ix,iy,ia)) < eps6) s22r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s11s(ix,iy,ia)) < eps6) s11s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12s(ix,iy,ia)) < eps6) s12s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22s(ix,iy,ia)) < eps6) s22s(ix,iy,ia) = 0._wp
+!!$                  ELSE
+!!$                     s11r(ix,iy,ia) = 0.5_wp*s11kr(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s12r(ix,iy,ia) = 0.5_wp*s12kr(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s22r(ix,iy,ia) = 0.5_wp*s22kr(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s11s(ix,iy,ia) = 0.5_wp*s11ks(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s12s(ix,iy,ia) = 0.5_wp*s12ks(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s22s(ix,iy,ia) = 0.5_wp*s22ks(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     IF (abs(s11r(ix,iy,ia)) < eps6) s11r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12r(ix,iy,ia)) < eps6) s12r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22r(ix,iy,ia)) < eps6) s22r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s11s(ix,iy,ia)) < eps6) s11s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12s(ix,iy,ia)) < eps6) s12s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22s(ix,iy,ia)) < eps6) s22s(ix,iy,ia) = 0._wp
+!!$                  ENDIF
+!!$               ENDDO
+!!$            ENDDO
+!!$         ENDDO
+
+         !! faster but still very slow => to be improved         
+         zfac = dz/sin(2._wp*pphi)
+         DO ia = 1, na_yield-1
+            zw1 = w1(ainit+ia*da)
+            zw2 = w2(ainit+ia*da)
+            DO iz = 1, nz
+               idz = zinit+iz*dz
+               ztemp = zw1 * EXP(-zw2*(zinit+iz*dz)*(zinit+iz*dz))
+               DO iy = 1, ny_yield
+                  idy = yinit+iy*dy
+                  DO ix = 1, nx_yield
+                     idx = xinit+ix*dx
+                     s11r(ix,iy,ia) = s11r(ix,iy,ia) + ztemp * s11kr(idx,idy,idz)*zfac
+                     s12r(ix,iy,ia) = s12r(ix,iy,ia) + ztemp * s12kr(idx,idy,idz)*zfac
+                     s22r(ix,iy,ia) = s22r(ix,iy,ia) + ztemp * s22kr(idx,idy,idz)*zfac 
+                     s11s(ix,iy,ia) = s11s(ix,iy,ia) + ztemp * s11ks(idx,idy,idz)*zfac
+                     s12s(ix,iy,ia) = s12s(ix,iy,ia) + ztemp * s12ks(idx,idy,idz)*zfac
+                     s22s(ix,iy,ia) = s22s(ix,iy,ia) + ztemp * s22ks(idx,idy,idz)*zfac
+                  END DO
+               END DO
+            END DO
+         END DO
+
+         zfac = 1._wp/sin(2._wp*pphi)
+         ia = na_yield
+         DO iy = 1, ny_yield
+            idy = yinit+iy*dy
+            DO ix = 1, nx_yield
+               idx = xinit+ix*dx                  
+               s11r(ix,iy,ia) = 0.5_wp*s11kr(idx,idy,0._wp)*zfac
+               s12r(ix,iy,ia) = 0.5_wp*s12kr(idx,idy,0._wp)*zfac
+               s22r(ix,iy,ia) = 0.5_wp*s22kr(idx,idy,0._wp)*zfac
+               s11s(ix,iy,ia) = 0.5_wp*s11ks(idx,idy,0._wp)*zfac
+               s12s(ix,iy,ia) = 0.5_wp*s12ks(idx,idy,0._wp)*zfac
+               s22s(ix,iy,ia) = 0.5_wp*s22ks(idx,idy,0._wp)*zfac
+            ENDDO
+         ENDDO
+         WHERE (ABS(s11r(:,:,:)) < eps6) s11r(:,:,:) = 0._wp
+         WHERE (ABS(s12r(:,:,:)) < eps6) s12r(:,:,:) = 0._wp
+         WHERE (ABS(s22r(:,:,:)) < eps6) s22r(:,:,:) = 0._wp
+         WHERE (ABS(s11s(:,:,:)) < eps6) s11s(:,:,:) = 0._wp
+         WHERE (ABS(s12s(:,:,:)) < eps6) s12s(:,:,:) = 0._wp
+         WHERE (ABS(s22s(:,:,:)) < eps6) s22s(:,:,:) = 0._wp
+
+
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- rhg-rst ----'
+         iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         CALL iom_rstput( iter, nitrst, numriw, 'stress1_i' , stress1_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress2_i' , stress2_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress12_i', stress12_i )
+         CALL iom_rstput( iter, nitrst, numriw, 'aniso_11'  , aniso_11   )
+         CALL iom_rstput( iter, nitrst, numriw, 'aniso_12'  , aniso_12   )
+         !
+      ENDIF
+      !
+   END SUBROUTINE rhg_eap_rst
+
+
+   FUNCTION w1(pa)
+      !!-------------------------------------------------------------------
+      !! Function : w1 (see Gaussian function psi in Tsamados et al 2013)
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   pa
+      REAL(wp) ::   w1
+      !!-------------------------------------------------------------------
+   
+      w1 = -   223.87569446_wp &
+       &   +  2361.21986630_wp*pa &
+       &   - 10606.56079975_wp*pa*pa &
+       &   + 26315.50025642_wp*pa*pa*pa &
+       &   - 38948.30444297_wp*pa*pa*pa*pa &
+       &   + 34397.72407466_wp*pa*pa*pa*pa*pa &
+       &   - 16789.98003081_wp*pa*pa*pa*pa*pa*pa &
+       &   +  3495.82839237_wp*pa*pa*pa*pa*pa*pa*pa
+   
+   END FUNCTION w1
+
+
+   FUNCTION w2(pa)
+      !!-------------------------------------------------------------------
+      !! Function : w2 (see Gaussian function psi in Tsamados et al 2013)
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   pa
+      REAL(wp) ::   w2
+      !!-------------------------------------------------------------------
+   
+      w2 = -    6670.68911883_wp &
+       &   +   70222.33061536_wp*pa &
+       &   -  314871.71525448_wp*pa*pa &
+       &   +  779570.02793492_wp*pa*pa*pa &
+       &   - 1151098.82436864_wp*pa*pa*pa*pa &
+       &   + 1013896.59464498_wp*pa*pa*pa*pa*pa &
+       &   -  493379.44906738_wp*pa*pa*pa*pa*pa*pa &
+       &   +  102356.55151800_wp*pa*pa*pa*pa*pa*pa*pa
+   
+   END FUNCTION w2
+
+   FUNCTION s11kr(px,py,pz) 
+      !!-------------------------------------------------------------------
+      !! Function : s11kr
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+   
+      REAL(wp) ::   s11kr, zpih
+   
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+   
+      zpih = 0.5_wp*rpi
+   
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+   ! In expression of tensor d, with this formulatin d(x)=-d(x+pi)
+   ! Solution, when diagonalizing always check sgn(a11-a22) if > then keep x else
+   ! x=x-pi/2
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+   
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+   
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+   
+      s11kr = (- zHen1t2 * zn1t2i11 - zHen2t1 * zn2t1i11)
+
+   END FUNCTION s11kr
+
+   FUNCTION s12kr(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s12kr
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s12kr, zs12r0, zs21r0, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+   
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+   
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+   
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+   
+      zs12r0 = (- zHen1t2 * zn1t2i12 - zHen2t1 * zn2t1i12)
+      zs21r0 = (- zHen1t2 * zn1t2i21 - zHen2t1 * zn2t1i21)
+      s12kr=0.5_wp*(zs12r0+zs21r0)
+   
+   END FUNCTION s12kr
+
+   FUNCTION s22kr(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s22kr
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s22kr, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      s22kr = (- zHen1t2 * zn1t2i22 - zHen2t1 * zn2t1i22)
+
+   END FUNCTION s22kr
+
+   FUNCTION s11ks(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s11ks
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s11ks, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      s11ks = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i11 + zHen2t1 * zt2t1i11)
+
+   END FUNCTION s11ks
+
+   FUNCTION s12ks(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s12ks
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s12ks, zs12s0, zs21s0, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      zs12s0 = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i12 + zHen2t1 * zt2t1i12)
+      zs21s0 = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i21 + zHen2t1 * zt2t1i21)
+      s12ks=0.5_wp*(zs12s0+zs21s0)
+
+   END FUNCTION s12ks
+
+   FUNCTION s22ks(px,py,pz) 
+      !!-------------------------------------------------------------------
+      !! Function : s22ks
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s22ks, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      s22ks = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i22 + zHen2t1 * zt2t1i22)
+
+   END FUNCTION s22ks
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   USE par_kind
+   USE lib_mpp
+   CONTAINS
+   SUBROUTINE ice_dyn_rhg_eap( kt, Kmm, pstress1_i, pstress2_i, pstress12_i, pshear_i, pdivu_i, pdelta_i, paniso_11, paniso_12, prdg_conv )
+      INTEGER                 , INTENT(in   ) ::   kt                                    ! time step
+      INTEGER                 , INTENT(in   ) ::   Kmm                                   ! ocean time level index
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   pstress1_i, pstress2_i, pstress12_i   !
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   pshear_i  , pdivu_i   , pdelta_i      !
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   paniso_11 , paniso_12                 ! structure tensor components
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   prdg_conv                             ! for ridging
+      CALL ctl_stop('EAP rheology is currently dsabled due to issues with AGRIF preprocessing')
+   END SUBROUTINE ice_dyn_rhg_eap
+   SUBROUTINE rhg_eap_rst( cdrw, kt )
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+   END SUBROUTINE rhg_eap_rst
+#endif
+
+   !!==============================================================================
+END MODULE icedyn_rhg_eap
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_evp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_evp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_evp.F90	(revision 14055)
@@ -199,5 +199,5 @@
          zfmask(ji,jj) = tmask(ji,jj,1) * tmask(ji+1,jj,1) * tmask(ji,jj+1,1) * tmask(ji+1,jj+1,1)
       END_2D
-      CALL lbc_lnk( 'icedyn_rhg_evp', zfmask, 'F', 1._wp )
+      CALL lbc_lnk( 'icedyn_rhg_evp', zfmask, 'F', 1._wp)
 
       ! Lateral boundary conditions on velocity (modify zfmask)
@@ -326,11 +326,11 @@
             zvV = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
             ! ice-bottom stress at U points
-            zvCr = zaU(ji,jj) * rn_lf_depfra * hu(ji,jj,Kmm)
+            zvCr = zaU(ji,jj) * rn_lf_depfra * hu(ji,jj,Kmm) * ( 1._wp - icb_mask(ji,jj) ) ! if grounded icebergs are read: ocean depth = 0
             ztaux_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvU - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaU(ji,jj) ) )
             ! ice-bottom stress at V points
-            zvCr = zaV(ji,jj) * rn_lf_depfra * hv(ji,jj,Kmm)
+            zvCr = zaV(ji,jj) * rn_lf_depfra * hv(ji,jj,Kmm) * ( 1._wp - icb_mask(ji,jj) ) ! if grounded icebergs are read: ocean depth = 0
             ztauy_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvV - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaV(ji,jj) ) )
             ! ice_bottom stress at T points
-            zvCr = at_i(ji,jj) * rn_lf_depfra * ht(ji,jj)
+            zvCr = at_i(ji,jj) * rn_lf_depfra * ht(ji,jj) * ( 1._wp - icb_mask(ji,jj) )    ! if grounded icebergs are read: ocean depth = 0
             tau_icebfr(ji,jj) = - rn_lf_bfr * MAX( 0._wp, vt_i(ji,jj) - zvCr ) * EXP( -rn_crhg * ( 1._wp - at_i(ji,jj) ) )
          END_2D
@@ -1033,6 +1033,6 @@
          iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
          !
-         CALL iom_rstput( iter, nitrst, numriw, 'stress1_i' , stress1_i  )
-         CALL iom_rstput( iter, nitrst, numriw, 'stress2_i' , stress2_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress1_i' , stress1_i )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress2_i' , stress2_i )
          CALL iom_rstput( iter, nitrst, numriw, 'stress12_i', stress12_i )
          !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_vp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_vp.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icedyn_rhg_vp.F90	(revision 14055)
@@ -0,0 +1,1689 @@
+MODULE icedyn_rhg_vp
+   !!======================================================================
+   !!                     ***  MODULE  icedyn_rhg_vp  ***
+   !!   Sea-Ice dynamics : Viscous-plastic rheology with LSR technique
+   !!======================================================================
+   !!
+   !! History :   -   !  1997-20  (J. Zhang, M. Losch) Original code, implementation into mitGCM
+   !!            4.0  !  2020-09  (M. Vancoppenolle) Adaptation to SI3
+   !!
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_rhg_vp : computes ice velocities from VP rheolog with LSR solvery
+   !!----------------------------------------------------------------------
+   USE phycst         ! Physical constants
+   USE dom_oce        ! Ocean domain
+   USE sbc_oce , ONLY : ln_ice_embd, nn_fsbc, ssh_m
+   USE sbc_ice , ONLY : utau_ice, vtau_ice, snwice_mass, snwice_mass_b
+   USE ice            ! sea-ice: ice variables
+   USE icevar         ! ice_var_sshdyn
+   USE icedyn_rdgrft  ! sea-ice: ice strength
+   USE bdy_oce , ONLY : ln_bdy 
+   USE bdyice 
+#if defined key_agrif
+   USE agrif_ice_interp
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE prtctl         ! Print control
+
+   USE netcdf         ! NetCDF library for convergence test
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rhg_vp   ! called by icedyn_rhg.F90
+
+
+   LOGICAL  ::   lp_zebra_vp =.TRUE.      ! activate zebra (solve the linear system problem every odd j-band, then one every even one)
+   REAL(wp) ::   zrelaxu_vp=0.95     ! U-relaxation factor (MV: can probably be merged with V-factor once ok)
+   REAL(wp) ::   zrelaxv_vp=0.95     ! V-relaxation factor 
+   REAL(wp) ::   zuerr_max_vp=0.80   ! maximum velocity error, above which a forcing error is considered and solver is stopped
+   REAL(wp) ::   zuerr_min_vp=1.e-04   ! minimum velocity error, beyond which convergence is assumed
+
+   !! for convergence tests
+   INTEGER ::   ncvgid        ! netcdf file id
+   INTEGER ::   nvarid_ures
+   INTEGER ::   nvarid_vres
+   INTEGER ::   nvarid_velres
+   INTEGER ::   nvarid_udif
+   INTEGER ::   nvarid_vdif
+   INTEGER ::   nvarid_veldif
+   INTEGER ::   nvarid_mke
+   INTEGER ::   nvarid_ures_xy, nvarid_vres_xy
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zmsk00, zmsk15
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id: icedyn_rhg_vp.F90 13279 2020-07-09 10:39:43Z clem $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+   
+CONTAINS
+
+   SUBROUTINE ice_dyn_rhg_vp( kt, pshear_i, pdivu_i, pdelta_i )
+      !!-------------------------------------------------------------------
+      !!
+      !!                 ***  SUBROUTINE ice_dyn_rhg_vp  ***
+      !!                             VP-LSR-C-grid
+      !!
+      !! ** Purpose : determines sea ice drift from wind stress, ice-ocean
+      !!  stress and sea-surface slope. Internal forces assume viscous-plastic rheology (Hibler, 1979)
+      !! 
+      !! ** Method
+      !!  
+      !!  The resolution algorithm  follows from Zhang and Hibler (1997) and Losch (2010)
+      !!  with elements from Lemieux and Tremblay (2008) and Lemieux and Tremblay (2009)
+      !!  
+      !!  The components of the momentum equations are arranged following the ideas of Zhang and Hibler (1997)
+      !!
+      !!  f1(u) = g1(v)
+      !!  f2(v) = g2(v)
+      !!
+      !!  The right-hand side (RHS) is explicit
+      !!  The left-hand side (LHS) is implicit
+      !!  Coriolis is part of explicit terms, whereas ice-ocean drag is implicit
+      !!
+      !!  Two iteration levels (outer and inner loops) are used to solve the equations
+      !!
+      !!  The outer loop (OL, typically 10 iterations) is there to deal with the (strong) non-linearities in the equation
+      !!
+      !!  The inner loop (IL, typically 1500 iterations) is there to solve the linear problem with a line-successive-relaxation algorithm
+      !!
+      !!  The velocity used in the non-linear terms uses a "modified euler time step" (not sure its the correct term), 
+      !!! with uk = ( uk-1 + uk-2 ) / 2.
+      !!  
+      !!  * Spatial discretization 
+      !!
+      !!  Assumes a C-grid
+      !!
+      !!  The points in the C-grid look like this, my darling
+      !!
+      !!                              (ji,jj)
+      !!                                 |
+      !!                                 |
+      !!                      (ji-1,jj)  |  (ji,jj)
+      !!                             ---------   
+      !!                            |         |
+      !!                            | (ji,jj) |------(ji,jj)
+      !!                            |         |
+      !!                             ---------   
+      !!                     (ji-1,jj-1)     (ji,jj-1)
+      !!
+      !! ** Inputs  : - wind forcing (stress), oceanic currents
+      !!                ice total volume (vt_i) per unit area
+      !!                snow total volume (vt_s) per unit area
+      !!
+      !! ** Action  : 
+      !!             
+      !! ** Steps   :
+      !!            
+      !! ** Notes   : 
+      !!             
+      !! References : Zhang and Hibler, JGR 1997; Losch et al., OM 2010., Lemieux et al., 2008, 2009, ...  
+      !!             
+      !!             
+      !!-------------------------------------------------------------------
+      !!
+      INTEGER                 , INTENT(in   ) ::   kt                                    ! time step
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pshear_i  , pdivu_i   , pdelta_i      !
+      !!
+      LOGICAL ::   ll_u_iterate, ll_v_iterate   ! continue iteration or not
+      !
+      INTEGER ::   ji, ji2, jj, jj2, jn          ! dummy loop indices
+      INTEGER ::   jter, i_out, i_inn  ! 
+      INTEGER ::   ji_min, jj_min      !
+      INTEGER ::   nn_zebra_vp         ! number of zebra steps
+
+      INTEGER ::   nn_nvp              ! total number of VP iterations (n_out_vp*n_inn_vp)      
+      !
+      REAL(wp) ::   zrhoco                                              ! rho0 * rn_cio
+      REAL(wp) ::   ecc2, z1_ecc2                                       ! square of yield ellipse eccenticity
+      REAL(wp) ::   zglob_area                                          ! global ice area for diagnostics
+      REAL(wp) ::   zkt                                                 ! isotropic tensile strength for landfast ice
+      REAL(wp) ::   zm1, zm2, zm3, zmassU, zmassV                       ! ice/snow mass and volume
+      REAL(wp) ::   zdeltat, zds2, zdt, zdt2, zdiv, zdiv2               ! temporary scalars
+      REAL(wp) ::   zp_deltastar_f                                      ! 
+      REAL(wp) ::   zu_cV, zv_cU                                        ! 
+      REAL(wp) ::   zfac, zfac1, zfac2, zfac3
+      REAL(wp) ::   zt12U, zt11U, zt22U, zt21U, zt122U, zt121U
+      REAL(wp) ::   zt12V, zt11V, zt22V, zt21V, zt122V, zt121V
+      REAL(wp) ::   zAA3, zw, ztau, zuerr_max, zverr_max
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfmask                          ! mask at F points for the ice
+      REAL(wp), DIMENSION(jpi,jpj) ::   za_iU  , za_iV                      ! ice fraction on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmU_t, zmV_t                    ! Acceleration term contribution to RHS
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmassU_t, zmassV_t              ! Mass per unit area divided by time step
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdeltastar_t                    ! Delta* at T-points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zten_i                          ! Tension
+      REAL(wp), DIMENSION(jpi,jpj) ::   zp_deltastar_t                  ! P/delta* at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zzt, zet                        ! Viscosity pre-factors at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zef                             ! Viscosity pre-factor at F point
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmt                             ! Mass per unit area at t-point
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmf                             ! Coriolis factor (m*f) at t-point 
+      REAL(wp), DIMENSION(jpi,jpj) ::   v_oceU, u_oceV, v_iceU, u_iceV  ! ocean/ice u/v component on V/U points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_c, zv_c                      ! "current" ice velocity (m/s), average of previous two OL iterates
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_b, zv_b                      ! velocity at previous sub-iterate
+      REAL(wp), DIMENSION(jpi,jpj) ::   zuerr, zverr                    ! absolute U/Vvelocity difference between current and previous sub-iterates
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zds                             ! shear
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsshdyn                         ! array used for the calculation of ice surface slope:
+      !                                                                 !    ocean surface (ssh_m) if ice is not embedded
+      !                                                                 !    ice bottom surface if ice is embedded   
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCwU, zCwV                      ! ice-ocean drag pre-factor (rho*c*module(u))
+      REAL(wp), DIMENSION(jpi,jpj) ::   zspgU, zspgV                    ! surface pressure gradient at U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCorU, zCorV                    ! Coriolis stress array
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_ai, ztauy_ai              ! ice-atm. stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_oi_rhsu, ztauy_oi_rhsv    ! ice-ocean stress RHS contribution at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1_rhsu, zs2_rhsu, zs12_rhsu   ! internal stress contributions to RHSU
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1_rhsv, zs2_rhsv, zs12_rhsv   ! internal stress contributions to RHSV
+      REAL(wp), DIMENSION(jpi,jpj) ::   zf_rhsu, zf_rhsv                ! U- and V- components of internal force RHS contributions
+      REAL(wp), DIMENSION(jpi,jpj) ::   zrhsu, zrhsv                    ! U and V RHS 
+      REAL(wp), DIMENSION(jpi,jpj) ::   zAU, zBU, zCU, zDU, zEU         ! Linear system coefficients, U equation
+      REAL(wp), DIMENSION(jpi,jpj) ::   zAV, zBV, zCV, zDV, zEV         ! Linear system coefficients, V equation
+      REAL(wp), DIMENSION(jpi,jpj) ::   zFU, zFU_prime, zBU_prime       ! Rearranged linear system coefficients, U equation
+      REAL(wp), DIMENSION(jpi,jpj) ::   zFV, zFV_prime, zBV_prime       ! Rearranged linear system coefficients, V equation
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCU_prime, zCV_prime            ! Rearranged linear system coefficients, V equation
+!!!      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_bi, ztauy_bi              ! ice-OceanBottom stress at U-V points (landfast)
+!!!      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_base, ztauy_base          ! ice-bottom stress at U-V points (landfast)
+     !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk01x, zmsk01y                ! mask for lots of ice (1), little ice (0)
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk00x, zmsk00y                ! mask for ice presence (1), no ice (0)
+      !
+      REAL(wp), PARAMETER          ::   zepsi  = 1.0e-20_wp             ! tolerance parameter
+      REAL(wp), PARAMETER          ::   zmmin  = 1._wp                  ! ice mass (kg/m2)  below which ice velocity becomes very small
+      REAL(wp), PARAMETER          ::   zamin  = 0.001_wp               ! ice concentration below which ice velocity becomes very small
+      !! --- diags
+      REAL(wp) ::   zsig1, zsig2, zsig12, zdelta, z1_strength, zfac_x, zfac_y
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1, zs2, zs12, zs12f           ! stress tensor components
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zsig_I, zsig_II, zsig1_p, zsig2_p
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   ztaux_oi, ztauy_oi
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_ice, zdiag_ymtrp_ice ! X/Y-component of ice mass transport (kg/s, SIMIP)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_snw, zdiag_ymtrp_snw ! X/Y-component of snow mass transport (kg/s, SIMIP)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xatrp, zdiag_yatrp         ! X/Y-component of area transport (m2/s, SIMIP)
+
+
+      CALL ctl_stop( 'STOP', 'icedyn_rhg_vp: stop because vp rheology is an ongoing work and should not be used' )
+      
+      !!----------------------------------------------------------------------------------------------------------------------
+      ! DEBUG put all forcing terms to zero
+         ! air-ice drag
+         utau_ice(:,:) = 0._wp
+         vtau_ice(:,:) = 0._wp
+         ! coriolis
+         ff_t(:,:) = 0._wp
+         ! ice-ocean drag
+         rn_cio = 0._wp
+         ! ssh 
+         ! done line 330 !!! dont forget to act there
+      ! END DEBUG
+
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_rhg_vp: VP sea-ice rheology (LSR solver)'
+      IF( lwp )   WRITE(numout,*) '-- ice_dyn_rhg_vp: VP sea-ice rheology (LSR solver)'
+            
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Initialization
+      !
+      !------------------------------------------------------------------------------!
+      
+      ! for diagnostics and convergence tests
+      ALLOCATE( zmsk00(jpi,jpj), zmsk15(jpi,jpj) )
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zmsk00(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06  ) ) ! 1 if ice    , 0 if no ice
+            zmsk15(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.15_wp ) ) ! 1 if 15% ice, 0 if less
+         END DO
+      END DO
+      
+      IF ( lp_zebra_vp ) THEN; nn_zebra_vp = 2
+                         ELSE; nn_zebra_vp = 1; ENDIF 
+
+      nn_nvp = nn_vp_nout * nn_vp_ninn ! maximum number of iterations
+
+      IF( lwp )   WRITE(numout,*) ' lp_zebra_vp : ', lp_zebra_vp
+      IF( lwp )   WRITE(numout,*) ' nn_zebra_vp : ', nn_zebra_vp
+      IF( lwp )   WRITE(numout,*) ' nn_nvp      : ', nn_nvp
+      
+      zrhoco = rho0 * rn_cio 
+
+      ! ecc2: square of yield ellipse eccentricity
+      ecc2    = rn_ecc * rn_ecc
+      z1_ecc2 = 1._wp / ecc2
+               
+      ! Initialise convergence checks
+      IF( nn_rhg_chkcvg /= 0 ) THEN
+      
+         ! ice area for global mean kinetic energy
+         zglob_area = glob_sum( 'ice_rhg_vp', at_i(:,:) * e1e2t(:,:) ) ! global ice area (km2)
+         
+      ENDIF
+
+      ! Landfast param from Lemieux(2016): add isotropic tensile strength (following Konig Beatty and Holland, 2010)
+      ! MV: Not working yet...
+      IF( ln_landfast_L16 ) THEN   ;   zkt = rn_lf_tensile
+      ELSE                         ;   zkt = 0._wp
+      ENDIF
+
+      zs1_rhsu(:,:) = 0._wp; zs2_rhsu(:,:) = 0._wp; zs1_rhsv(:,:) = 0._wp; zs2_rhsv(:,:) = 0._wp
+      zAU(:,:) = 0._wp; zBU(:,:) = 0._wp; zCU(:,:) = 0._wp; zDU(:,:) = 0._wp; zEU(:,:) = 0._wp;
+      zAV(:,:) = 0._wp; zBV(:,:) = 0._wp; zCV(:,:) = 0._wp; zDV(:,:) = 0._wp; zEV(:,:) = 0._wp;
+      zrhsu(:,:) = 0._wp; zrhsv(:,:) = 0._wp
+      zf_rhsu(:,:) = 0._wp; zf_rhsv(:,:) = 0._wp
+
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Time-independent quantities
+      !
+      !------------------------------------------------------------------------------!
+      
+      CALL ice_strength ! strength at T points
+      
+      !------------------------------
+      ! -- F-mask       (code from EVP)
+      !------------------------------
+      ! MartinV: 
+      ! In EVP routine, zfmask is applied on shear at F-points, in order to enforce the lateral boundary condition (no-slip, ..., free-slip)
+      ! I am not sure the same recipe applies here
+      
+      ! - ocean/land mask
+      DO jj = 1, jpj - 1
+         DO ji = 1, jpi - 1
+            zfmask(ji,jj) = tmask(ji,jj,1) * tmask(ji+1,jj,1) * tmask(ji,jj+1,1) * tmask(ji+1,jj+1,1)
+         END DO
+      END DO
+
+      ! Lateral boundary conditions on velocity (modify zfmask)
+      ! Can be computed once for all, at first time step, for all rheologies
+      DO jj = 2, jpj - 1
+         DO ji = 2, jpi - 1   ! vector opt.
+            IF( zfmask(ji,jj) == 0._wp ) THEN
+               zfmask(ji,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(ji,jj,1), umask(ji,jj+1,1), &
+                  &                                          vmask(ji,jj,1), vmask(ji+1,jj,1) ) )
+            ENDIF
+         END DO
+      END DO
+      DO jj = 2, jpj - 1
+         IF( zfmask(1,jj) == 0._wp ) THEN
+            zfmask(1  ,jj) = rn_ishlat * MIN( 1._wp , MAX( vmask(2,jj,1), umask(1,jj+1,1), umask(1,jj,1) ) )
+         ENDIF
+         IF( zfmask(jpi,jj) == 0._wp ) THEN
+            zfmask(jpi,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(jpi,jj+1,1), vmask(jpi - 1,jj,1), umask(jpi,jj-1,1) ) )
+        ENDIF
+      END DO
+      DO ji = 2, jpi - 1
+         IF( zfmask(ji,1) == 0._wp ) THEN
+            zfmask(ji, 1 ) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,1,1), umask(ji,2,1), vmask(ji,1,1) ) )
+         ENDIF
+         IF( zfmask(ji,jpj) == 0._wp ) THEN
+            zfmask(ji,jpj) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,jpj,1), vmask(ji-1,jpj,1), umask(ji,jpj - 1,1) ) )
+         ENDIF
+      END DO
+      
+      CALL lbc_lnk( 'icedyn_rhg_vp', zfmask, 'F', 1._wp )
+      
+      !----------------------------------------------------------------------------------------------------------
+      ! -- Time-independent pre-factors for acceleration, ocean drag, coriolis, atmospheric drag, surface tilt
+      !----------------------------------------------------------------------------------------------------------
+      ! Compute all terms & factors independent of velocities, or only depending on velocities at previous time step      
+      
+      ! sea surface height
+      !    embedded sea ice: compute representative ice top surface
+      !    non-embedded sea ice: use ocean surface for slope calculation
+      zsshdyn(:,:) = ice_var_sshdyn( ssh_m, snwice_mass, snwice_mass_b)
+      zsshdyn(:,:) = 0._wp ! DEBUG CAREFUL !!!
+
+      zmt(:,:) = rhos * vt_s(:,:) + rhoi * vt_i(:,:)       ! Snow and ice mass at T-point
+      zmf(:,:) = zmt(:,:) * ff_t(:,:)                      ! Coriolis factor at T points (m*f)
+      
+      DO jj = 2, jpj - 1
+         DO ji = 2, jpi - 1
+
+            ! Ice fraction at U-V points
+            za_iU(ji,jj)    = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            za_iV(ji,jj)    = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+            ! Snow and ice mass at U-V points
+            zm1             = zmt(ji,jj)
+            zm2             = zmt(ji+1,jj)
+            zm3             = zmt(ji,jj+1)
+            
+            zmassU          = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm2 * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            zmassV          = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm3 * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+                          
+            ! Mass per unit area divided by time step
+            zmassU_t(ji,jj) = zmassU * r1_Dt_ice
+            zmassV_t(ji,jj) = zmassV * r1_Dt_ice
+
+            ! Acceleration term contribution to RHS (depends on velocity at previous time step)            
+            zmU_t(ji,jj)    = zmassU_t(ji,jj) * u_ice(ji,jj)
+            zmV_t(ji,jj)    = zmassV_t(ji,jj) * v_ice(ji,jj)
+            
+            ! Ocean currents at U-V points
+            v_oceU(ji,jj)   = 0.25_wp * ( v_oce(ji,jj) + v_oce(ji,jj-1) + v_oce(ji+1,jj) + v_oce(ji+1,jj-1) ) * umask(ji,jj,1)
+            u_oceV(ji,jj)   = 0.25_wp * ( u_oce(ji,jj) + u_oce(ji-1,jj) + u_oce(ji,jj+1) + u_oce(ji-1,jj+1) ) * vmask(ji,jj,1)
+            
+            ! Wind stress
+            ztaux_ai(ji,jj) = za_iU(ji,jj) * utau_ice(ji,jj)
+            ztauy_ai(ji,jj) = za_iV(ji,jj) * vtau_ice(ji,jj)
+
+            ! Force due to sea surface tilt(- m*g*GRAD(ssh))
+            zspgU(ji,jj)    = - zmassU * grav * ( zsshdyn(ji+1,jj) - zsshdyn(ji,jj) ) * r1_e1u(ji,jj)
+            zspgV(ji,jj)    = - zmassV * grav * ( zsshdyn(ji,jj+1) - zsshdyn(ji,jj) ) * r1_e2v(ji,jj)
+
+            ! Mask for ice presence (1) or absence (0)
+            zmsk00x(ji,jj)  = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassU ) )  ! 0 if no ice
+            zmsk00y(ji,jj)  = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassV ) )  ! 0 if no ice
+
+            ! Mask for lots of ice (1) or little ice (0)
+            IF ( zmassU <= zmmin .AND. za_iU(ji,jj) <= zamin ) THEN   ;   zmsk01x(ji,jj) = 0._wp
+            ELSE                                                      ;   zmsk01x(ji,jj) = 1._wp   ;   ENDIF
+            IF ( zmassV <= zmmin .AND. za_iV(ji,jj) <= zamin ) THEN   ;   zmsk01y(ji,jj) = 0._wp
+            ELSE                                                      ;   zmsk01y(ji,jj) = 1._wp   ;   ENDIF              
+
+! MV TEST DEBUG
+            IF ( ( zmt(ji,jj)   <= zmmin .OR. zmt(ji+1,jj)  <= zmmin )     .AND.  &
+               & ( at_i(ji,jj)  <= zamin .OR. at_i(ji+1,jj) <= zamin ) )    THEN   ;   zmsk01x(ji,jj) = 0._wp
+            ELSE                                                                   ;   zmsk01x(ji,jj) = 1._wp   ;   ENDIF
+
+            IF ( ( zmt(ji,jj)   <= zmmin .OR. zmt(ji,jj+1)  <= zmmin )     .AND.  &
+               & ( at_i(ji,jj)  <= zamin .OR. at_i(ji,jj+1) <= zamin ) )    THEN   ;   zmsk01y(ji,jj) = 0._wp
+            ELSE                                                                   ;   zmsk01y(ji,jj) = 1._wp   ;   ENDIF              
+! END MV TEST DEBUG
+
+         END DO
+      END DO   
+
+      CALL iom_put( 'zmsk00x'    , zmsk00x  )   ! MV DEBUG
+      CALL iom_put( 'zmsk00y'    , zmsk00y  )   ! MV DEBUG
+      CALL iom_put( 'zmsk01x'    , zmsk01x  )   ! MV DEBUG
+      CALL iom_put( 'zmsk01y'    , zmsk01y  )   ! MV DEBUG
+      CALL iom_put( 'ztaux_ai'   , ztaux_ai )   ! MV DEBUG
+      CALL iom_put( 'ztauy_ai'   , ztauy_ai )   ! MV DEBUG
+      CALL iom_put( 'zspgU'      , zspgU    )   ! MV DEBUG
+      CALL iom_put( 'zspgV'      , zspgV    )   ! MV DEBUG
+            
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Start outer loop
+      !
+      !------------------------------------------------------------------------------!
+      
+      zu_c(:,:) = u_ice(:,:)
+      zv_c(:,:) = v_ice(:,:)
+      
+      jter = 0
+
+      DO i_out = 1, nn_vp_nout
+
+         IF( lwp )   WRITE(numout,*) ' outer loop  i_out : ', i_out
+               
+         ! Velocities used in the non linear terms are the average of the past two iterates
+         ! u_it = 0.5 * ( u_{it-1} + u_{it-2})
+         ! Also used in Hibler and Ackley (1983); Zhang and Hibler (1997); Lemieux and Tremblay (2009)
+         zu_c(:,:) = 0.5_wp * ( u_ice(:,:) + zu_c(:,:) )
+         zv_c(:,:) = 0.5_wp * ( v_ice(:,:) + zv_c(:,:) )
+         
+         !------------------------------------------------------------------------------!
+         !
+         ! --- Right-hand side (RHS) of the linear problem
+         !
+         !------------------------------------------------------------------------------!
+         ! In the outer loop, one needs to update all RHS terms
+         ! with explicit velocity dependencies (viscosities, coriolis, ocean stress)
+         ! as a function of uc
+         !
+      
+         !------------------------------------------
+         ! -- Strain rates, viscosities and P/Delta
+         !------------------------------------------
+
+         ! --- divergence, tension & shear (Appendix B of Hunke & Dukowicz, 2002) --- !
+         DO jj = 1, jpj - 1         ! loops start at 1 since there is no boundary condition (lbc_lnk) at i=1 and j=1 for F points
+            DO ji = 1, jpi - 1
+
+               ! shear at F points
+               zds(ji,jj) = ( ( zu_c(ji,jj+1) * r1_e1u(ji,jj+1) - zu_c(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+                  &         + ( zv_c(ji+1,jj) * r1_e2v(ji+1,jj) - zv_c(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+                  &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+            END DO
+         END DO
+
+         CALL lbc_lnk( 'icedyn_rhg_vp', zds, 'F', 1. ) ! MV TEST could be un-necessary according to Gurvan
+         CALL iom_put( 'zds'        , zds      )   ! MV DEBUG
+
+         IF( lwp )   WRITE(numout,*) ' outer loop  1a i_out : ', i_out
+
+         !DO jj = 2, jpj - 1    ! loop to jpi,jpj to avoid making a communication for zs1,zs2,zs12
+         !   DO ji = 2, jpi - 1 ! 
+
+! MV DEBUG
+         DO jj = 2, jpj        ! loop to jpi,jpj to avoid making a communication for zs1,zs2,zs12
+            DO ji = 2, jpi     ! 
+! END MV DEBUG
+
+               ! shear**2 at T points (doc eq. A16)
+               zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+                  &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+                  &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+              
+               ! divergence at T points
+               zdiv  = ( e2u(ji,jj) * zu_c(ji,jj) - e2u(ji-1,jj) * zu_c(ji-1,jj)   &
+                  &    + e1v(ji,jj) * zv_c(ji,jj) - e1v(ji,jj-1) * zv_c(ji,jj-1)   &
+                  &    ) * r1_e1e2t(ji,jj)
+               zdiv2 = zdiv * zdiv
+               
+               ! tension at T points
+               zdt  = ( ( zu_c(ji,jj) * r1_e2u(ji,jj) - zu_c(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+                  &   - ( zv_c(ji,jj) * r1_e1v(ji,jj) - zv_c(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+                  &   ) * r1_e1e2t(ji,jj)
+               zdt2 = zdt * zdt
+               
+               ! delta at T points
+               zdeltat = SQRT( zdiv2 + ( zdt2 + zds2 ) * z1_ecc2 )  
+               
+               ! delta* at T points (following Lemieux and Dupont, GMD 2020)
+               zdeltastar_t(ji,jj) = zdeltat + rn_creepl
+              
+               ! P/delta at T-points
+               zp_deltastar_t(ji,jj) = strength(ji,jj) / zdeltastar_t(ji,jj)
+               
+               ! Temporary zzt and zet factors at T-points
+               zzt(ji,jj)     = zp_deltastar_t(ji,jj) * r1_e1e2t(ji,jj)
+               zet(ji,jj)     = zzt(ji,jj)     * z1_ecc2 
+                          
+            END DO
+         END DO
+         
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zp_deltastar_t , 'T', 1. , zzt , 'T', 1., zet, 'T', 1. )
+
+         CALL iom_put( 'zzt'        , zzt      )   ! MV DEBUG
+         CALL iom_put( 'zet'        , zet      )   ! MV DEBUG
+         CALL iom_put( 'zp_deltastar_t', zp_deltastar_t ) ! MV DEBUG
+
+         IF( lwp )   WRITE(numout,*) ' outer loop  1b i_out : ', i_out
+
+         DO jj = 1, jpj - 1
+            DO ji = 1, jpi - 1
+               
+               ! P/delta* at F points
+               zp_deltastar_f = 0.25_wp * ( zp_deltastar_t(ji,jj) + zp_deltastar_t(ji+1,jj) + zp_deltastar_t(ji,jj+1) + zp_deltastar_t(ji+1,jj+1) )
+               
+               ! Temporary zef factor at F-point
+               zef(ji,jj)      = zp_deltastar_f * r1_e1e2f(ji,jj) * z1_ecc2 * zfmask(ji,jj)
+
+            END DO
+         END DO
+         
+         CALL lbc_lnk( 'icedyn_rhg_vp', zef, 'F', 1. )
+         CALL iom_put( 'zef'           , zef            ) ! MV DEBUG
+         IF( lwp )   WRITE(numout,*) ' outer loop  1c i_out : ', i_out
+
+         !---------------------------------------------------
+         ! -- Ocean-ice drag and Coriolis RHS contributions
+         !---------------------------------------------------
+
+         DO jj = 2, jpj - 1
+             DO ji = 2, jpi - 1
+                
+                !--- ice u-velocity @V points, v-velocity @U points (for non-linear drag computation)
+                zu_cV            = 0.25_wp * ( zu_c(ji,jj) + zu_c(ji-1,jj) + zu_c(ji,jj+1) + zu_c(ji-1,jj+1) ) * vmask(ji,jj,1)
+                zv_cU            = 0.25_wp * ( zv_c(ji,jj) + zv_c(ji,jj-1) + zv_c(ji+1,jj) + zv_c(ji+1,jj-1) ) * umask(ji,jj,1)
+                
+                !--- non-linear drag coefficients (need to be updated at each outer loop, see Lemieux and Tremblay JGR09, p.3, beginning of Section 3)
+                zCwU(ji,jj)          = za_iU(ji,jj) * zrhoco * SQRT( ( zu_c (ji,jj) - u_oce (ji,jj) ) * ( zu_c (ji,jj) - u_oce (ji,jj) )  &
+                  &                                                + ( zv_cU - v_oceU(ji,jj) ) * ( zv_cU - v_oceU(ji,jj) ) )
+                zCwV(ji,jj)          = za_iV(ji,jj) * zrhoco * SQRT( ( zv_c (ji,jj) - v_oce (ji,jj) ) * ( zv_c (ji,jj) - v_oce (ji,jj) )  &
+                  &                                                + ( zu_cV - u_oceV(ji,jj) ) * ( zu_cV - u_oceV(ji,jj) ) )
+                 
+                !--- Ocean-ice drag contributions to RHS 
+                ztaux_oi_rhsu(ji,jj) = zCwU(ji,jj) * u_oce(ji,jj)
+                ztauy_oi_rhsv(ji,jj) = zCwV(ji,jj) * v_oce(ji,jj)
+                
+                ! --- U-component of Coriolis Force (energy conserving formulation)
+                ! Note Lemieux et al 2008 recommend to do that implicitly, but I don't really see how this could be done
+                zCorU(ji,jj)         =   0.25_wp * r1_e1u(ji,jj) *  &
+                           &             ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * zv_c(ji  ,jj) + e1v(ji  ,jj-1) * zv_c(ji  ,jj-1) )  &
+                           &             + zmf(ji+1,jj) * ( e1v(ji+1,jj) * zv_c(ji+1,jj) + e1v(ji+1,jj-1) * zv_c(ji+1,jj-1) ) )
+                           
+                ! --- V-component of Coriolis Force (energy conserving formulation)
+                zCorV(ji,jj)         = - 0.25_wp * r1_e2v(ji,jj) *  &
+                           &             ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * zu_c(ji,jj  ) + e2u(ji-1,jj  ) * zu_c(ji-1,jj  ) )  &
+                           &             + zmf(ji,jj+1) * ( e2u(ji,jj+1) * zu_c(ji,jj+1) + e2u(ji-1,jj+1) * zu_c(ji-1,jj+1) ) )
+         
+             END DO
+         END DO
+
+         IF( lwp )   WRITE(numout,*) ' outer loop  1d i_out : ', i_out
+         
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zCwU ,  'U', -1., zCwV, 'V', -1. )
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zCorU,  'U', -1., zCorV, 'V', -1. )
+
+         CALL iom_put( 'zCwU'          , zCwU           ) ! MV DEBUG
+         CALL iom_put( 'zCwV'          , zCwV           ) ! MV DEBUG
+         CALL iom_put( 'zCorU'         , zCorU          ) ! MV DEBUG
+         CALL iom_put( 'zCorV'         , zCorV          ) ! MV DEBUG
+
+         IF( lwp )   WRITE(numout,*) ' outer loop  1f i_out : ', i_out
+         
+         ! a priori, Coriolis and drag terms only affect diagonal or independent term of the linear system, 
+         ! so there is no need for lbclnk on drag and coriolis
+
+         !-------------------------------------
+         ! -- Internal stress RHS contribution
+         !-------------------------------------
+
+         ! --- Stress contributions at T-points         
+         DO jj = 2, jpj    ! loop to jpi,jpj to avoid making a communication for zs1,zs2,zs12
+            DO ji = 2, jpi ! 
+            
+               ! sig1 contribution to RHS of U-equation at T-points
+               zs1_rhsu(ji,jj) =   zzt(ji,jj) * ( e1v(ji,jj)    * zv_c(ji,jj) - e1v(ji,jj-1)    * zv_c(ji,jj-1) - 1.0_wp )
+                                            
+               ! sig2 contribution to RHS of U-equation at T-points            
+               zs2_rhsu(ji,jj) = - zet(ji,jj) * ( r1_e1v(ji,jj) * zv_c(ji,jj) - r1_e1v(ji,jj-1) * zv_c(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj) 
+
+               ! sig1 contribution to RHS of V-equation at T-points
+               zs1_rhsv(ji,jj) =   zzt(ji,jj) * ( e2u(ji,jj)    * zu_c(ji,jj) - e2u(ji-1,jj)    * zu_c(ji-1,jj) - 1.0_wp )
+
+               ! sig2 contribution to RHS of V-equation  at T-points
+               zs2_rhsv(ji,jj) =   zet(ji,jj) * ( r1_e2u(ji,jj) * zu_c(ji,jj) - r1_e2u(ji-1,jj) * zu_c(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)
+
+            END DO
+         END DO
+
+         CALL iom_put( 'zs1_rhsu'      , zs1_rhsu       ) ! MV DEBUG
+         CALL iom_put( 'zs2_rhsu'      , zs2_rhsu       ) ! MV DEBUG
+         CALL iom_put( 'zs1_rhsv'      , zs1_rhsv       ) ! MV DEBUG
+         CALL iom_put( 'zs2_rhsv'      , zs2_rhsv       ) ! MV DEBUG
+         
+         ! a priori, no lbclnk, because rhsu is only used in the inner domain
+         
+         ! --- Stress contributions at f-points         
+         ! MV NOTE: I applied zfmask on zds, by mimetism on EVP, but without deep understanding of what I was doing
+         ! My guess is that this is the way to enforce boundary conditions on strain rate tensor
+
+         IF( lwp )   WRITE(numout,*) ' outer loop 2 i_out : ', i_out
+
+         DO jj = 1, jpj - 1
+            DO ji = 1, jpi - 1
+               
+               ! sig12 contribution to RHS of U equation at F-points 
+               zs12_rhsu(ji,jj) = - zef(ji,jj)  * ( r1_e2v(ji+1,jj) * zv_c(ji+1,jj) - r1_e2v(ji,jj) * zv_c(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj) * zfmask(ji,jj)
+               
+               ! sig12 contribution to RHS of V equation at F-points
+               zs12_rhsv(ji,jj) =   zef(ji,jj)  * ( r1_e1u(ji,jj+1) * zu_c(ji,jj+1) - r1_e1u(ji,jj) * zu_c(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj) * zfmask(ji,jj)
+
+            END DO
+         END DO
+
+         CALL lbc_lnk( 'icedyn_rhg_vp', zs12_rhsu, 'F', 1. )
+         CALL lbc_lnk( 'icedyn_rhg_vp', zs12_rhsv, 'F', 1. )
+
+         CALL iom_put( 'zs12_rhsu'     , zs12_rhsu      ) ! MV DEBUG
+         CALL iom_put( 'zs12_rhsv'     , zs12_rhsv      ) ! MV DEBUG
+
+         ! a priori, no lbclnk, because rhsu are only used in the inner domain
+
+         ! --- Internal force contributions to RHS, taken as divergence of stresses (Appendix C of Hunke and Dukowicz, 2002)
+         ! OPT: merge with next loop and use intermediate scalars for zf_rhsu
+         
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1               
+               ! --- U component of internal force contribution to RHS at U points
+               zf_rhsu(ji,jj) = 0.5_wp * r1_e1e2u(ji,jj) * & 
+                              (    e2u(ji,jj)    * ( zs1_rhsu(ji+1,jj) - zs1_rhsu(ji,jj) )                                                                 &
+                  &      +         r1_e2u(ji,jj) * ( e2t(ji+1,jj) * e2t(ji+1,jj) * zs2_rhsu(ji+1,jj) - e2t(ji,jj)   * e2t(ji,jj)   * zs2_rhsu(ji,jj) )     &
+                  &      + 2._wp * r1_e1u(ji,jj) * ( e1f(ji,jj)   * e1f(ji,jj)   * zs12_rhsu(ji,jj)  - e1f(ji,jj-1) * e1f(ji,jj-1) * zs12_rhsu(ji,jj-1) ) )
+                  
+               ! --- V component of internal force contribution to RHS at V points
+               zf_rhsv(ji,jj) = 0.5_wp * r1_e1e2v(ji,jj) * &
+                  &           (    e1v(ji,jj)    * ( zs1_rhsv(ji,jj+1) - zs1_rhsv(ji,jj) )                                                                 &
+                  &      +         r1_e1v(ji,jj) * ( e1t(ji,jj+1) * e1t(ji,jj+1) * zs2_rhsv(ji,jj+1) - e1t(ji,jj) * e1t(ji,jj)     * zs2_rhsv(ji,jj) )     &
+                  &      + 2._wp * r1_e2v(ji,jj) * ( e2f(ji,jj)   * e2f(ji,jj)   * zs12_rhsv(ji,jj)  - e2f(ji-1,jj) * e2f(ji-1,jj) * zs12_rhsv(ji-1,jj) ) )
+                  
+            END DO
+         END DO
+
+         CALL iom_put( 'zf_rhsu'       , zf_rhsu        ) ! MV DEBUG
+         CALL iom_put( 'zf_rhsv'       , zf_rhsv        ) ! MV DEBUG
+         
+         !---------------------------
+         ! -- Sum RHS contributions
+         !---------------------------
+         !
+         ! OPT: could use intermediate scalars to reduce memory access
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+            
+               ! still miss ice ocean stress and acceleration contribution
+               zrhsu(ji,jj) = zmU_t(ji,jj) + ztaux_ai(ji,jj) + ztaux_oi_rhsu(ji,jj) + zspgU(ji,jj) + zCorU(ji,jj) + zf_rhsu(ji,jj)
+               zrhsv(ji,jj) = zmV_t(ji,jj) + ztauy_ai(ji,jj) + ztauy_oi_rhsv(ji,jj) + zspgV(ji,jj) + zCorV(ji,jj) + zf_rhsu(ji,jj)
+
+            END DO
+         END DO
+         
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zrhsu, 'U', -1., zrhsv, 'V',  -1.)
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zmU_t, 'U', -1., zmV_t, 'V',  -1.)
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', ztaux_oi_rhsu, 'U', -1., ztauy_oi_rhsv, 'V',  -1.)
+
+         CALL iom_put( 'zmU_t'         , zmU_t          ) ! MV DEBUG
+         CALL iom_put( 'zmV_t'         , zmV_t          ) ! MV DEBUG
+         CALL iom_put( 'ztaux_oi_rhsu' , ztaux_oi_rhsu  ) ! MV DEBUG
+         CALL iom_put( 'ztauy_oi_rhsv' , ztauy_oi_rhsv  ) ! MV DEBUG
+         CALL iom_put( 'zrhsu'         , zrhsu          ) ! MV DEBUG
+         CALL iom_put( 'zrhsv'         , zrhsv          ) ! MV DEBUG
+         
+         ! inner domain calculations -> no lbclnk
+
+         IF( lwp )   WRITE(numout,*) ' outer loop 4 i_out : ', i_out
+     
+         !---------------------------------------------------------------------------------------!
+         !
+         ! --- Linear system matrix
+         !
+         !---------------------------------------------------------------------------------------!
+      
+         ! Linear system matrix contains all implicit contributions 
+         ! 1) internal forces, 2) acceleration, 3) ice-ocean drag
+
+         ! The linear system equation is written as follows
+         ! AU * u_{i-1,j} + BU * u_{i,j}   + CU * u_{i+1,j}
+         !                = DU * u_{i,j-1} + EU * u_{i,j+1} + RHS 			(! my convention, not the same as ZH97 )         
+         
+         ! MV Note 1: martin losch applies boundary condition to BU in mitGCM - check whether it is necessary here ?
+         ! MV Note 2: "T" factor calculations can be optimized by putting things out of the loop 
+         !         only zzt and zet are iteration-dependent, other only depend on scale factors
+                  
+         DO ji = 2, jpi - 1 ! internal domain do loop
+            DO jj = 2, jpj - 1
+
+               !-------------------------------------
+               ! -- Internal forces LHS contribution
+               !-------------------------------------
+               !
+               ! --- U-component
+               !
+               ! "T" factors (intermediate results)
+               !
+               zfac       = 0.5_wp * r1_e1e2u(ji,jj)
+               zfac1      =         zfac * e2u(ji,jj)
+               zfac2      =         zfac * r1_e2u(ji,jj)
+               zfac3      = 2._wp * zfac * r1_e1u(ji,jj)
+
+               zt12U      = - zfac1 * zzt(ji+1,jj)
+               zt11U      =   zfac1 * zzt(ji,jj)
+         
+               zt22U      = - zfac2 * zet(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj)
+               zt21U      =   zfac2 * zet(ji,jj)   * e2t(ji,jj)   * e2t(ji,jj)   * e2t(ji,jj)   * e2t(ji,jj)
+         
+               zt122U     = - zfac3 * zef(ji,jj)   * e1f(ji,jj)   * e1f(ji,jj)   * e1f(ji,jj)   * e1f(ji,jj)
+               zt121U     =   zfac3 * zef(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1)
+               
+               !
+               ! Linear system coefficients
+               !
+               zAU(ji,jj) = - zt11U * e2u(ji-1,jj) - zt21U * r1_e2u(ji-1,jj)
+               zBU(ji,jj) = ( zt12U + zt11U ) * e2u(ji,jj) + ( zt22U + zt21U ) * r1_e2u(ji,jj) + ( zt122U + zt121U ) * r1_e1u(ji,jj)
+               zCU(ji,jj) = - zt12U * e2u(ji+1,jj) - zt22U * r1_e2u(ji+1,jj)
+         
+               zDU(ji,jj) =   zt121U * r1_e1u(ji,jj-1)
+               zEU(ji,jj) =   zt122U * r1_e1u(ji,jj+1)
+              
+               !
+               ! --- V-component
+               !
+               ! "T" factors (intermediate results)
+               !
+               zfac       = 0.5_wp * r1_e1e2v(ji,jj)
+               zfac1      =         zfac * e2v(ji,jj)
+               zfac2      =         zfac * r1_e1v(ji,jj)
+               zfac3      = 2._wp * zfac * r1_e2v(ji,jj)
+         
+               zt12V      = - zfac1 * zzt(ji,jj+1)
+               zt11V      =   zfac1 * zzt(ji,jj)
+         
+               zt22V      =   zfac2 * zet(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1)
+               zt21V      = - zfac2 * zet(ji,jj)   * e1t(ji,jj)   * e1t(ji,jj)   * e1t(ji,jj)   * e1t(ji,jj)
+         
+               zt122V     =   zfac3 * zef(ji,jj)   * e2f(ji,jj)   * e2f(ji,jj)   * e2f(ji,jj)   * e2f(ji,jj)
+               zt121V     = - zfac3 * zef(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj)
+         
+               !
+               ! Linear system coefficients
+               !
+               zAV(ji,jj) = - zt11V * e1v(ji,jj-1) + zt21V * r1_e1v(ji,jj-1)
+               zBV(ji,jj) =  ( zt12V + zt11V ) * e1v(ji,jj) - ( zt22V + zt21V ) * r1_e1v(ji,jj) - ( zt122V + zt121V ) * r1_e2v(ji,jj)
+               zCV(ji,jj) = - zt12V * e1v(ji,jj+1) + zt22V * r1_e1v(ji,jj+1)
+         
+               zDV(ji,jj) = - zt121V * r1_e2v(ji-1,jj) ! mistake is in the pdf notes not here
+               zEV(ji,jj) = - zt122V * r1_e2v(ji+1,jj)
+                  
+               !-----------------------------------------------------
+               ! -- Ocean-ice drag and acceleration LHS contribution
+               !-----------------------------------------------------
+               zBU(ji,jj) = zBU(ji,jj) + zCwU(ji,jj) + zmassU_t(ji,jj)
+               zBV(ji,jj) = ZBV(ji,jj) + zCwV(ji,jj) + zmassV_t(ji,jj)
+         
+            END DO
+         END DO
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zAU  , 'U', 1., zAV  , 'V',  1. )
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zBU  , 'U', 1., zBV  , 'V',  1. )
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zCU  , 'U', 1., zCV  , 'V',  1. )
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zDU  , 'U', 1., zDV  , 'V',  1. )
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zEU  , 'U', 1., zEV  , 'V',  1. )
+               
+         CALL iom_put( 'zAU'           , zAU            ) ! MV DEBUG
+         CALL iom_put( 'zBU'           , zBU            ) ! MV DEBUG
+         CALL iom_put( 'zCU'           , zCU            ) ! MV DEBUG
+         CALL iom_put( 'zDU'           , zDU            ) ! MV DEBUG
+         CALL iom_put( 'zEU'           , zEU            ) ! MV DEBUG
+         CALL iom_put( 'zAV'           , zAV            ) ! MV DEBUG
+         CALL iom_put( 'zBV'           , zBV            ) ! MV DEBUG
+         CALL iom_put( 'zCV'           , zCV            ) ! MV DEBUG
+         CALL iom_put( 'zDV'           , zDV            ) ! MV DEBUG
+         CALL iom_put( 'zEV'           , zEV            ) ! MV DEBUG
+
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Inner loop: solve linear system, check convergence
+      !
+      !------------------------------------------------------------------------------!
+               
+         ! Inner loop solves the linear problem .. requires 1500 iterations
+         ll_u_iterate = .TRUE.
+         ll_v_iterate = .TRUE.
+
+         DO i_inn = 1, nn_vp_ninn ! inner loop iterations
+
+            IF( lwp )   WRITE(numout,*) ' inner loop 1 i_inn : ', i_inn
+         
+            !--- mitgcm computes initial value of residual here...
+
+            jter             = jter + 1
+            ! l_full_nf_update = jter == nn_nvp   ! false: disable full North fold update (performances) for iter = 1 to nn_nevp-1
+
+            zu_b(:,:)      = u_ice(:,:) ! velocity at previous sub-iterate
+            zv_b(:,:)      = v_ice(:,:)
+
+!           zAU(:,:) = 0._wp; zBU(:,:) = 0._wp; zCU(:,:) = 0._wp; zDU(:,:) = 0._wp; zEU(:,:) = 0._wp
+!           zAV(:,:) = 0._wp; zBV(:,:) = 0._wp; zCV(:,:) = 0._wp; zDV(:,:) = 0._wp; zEV(:,:) = 0._wp
+
+            IF ( ll_u_iterate .OR. ll_v_iterate )   THEN
+
+                                           ! ---------------------------- !
+               IF ( ll_u_iterate ) THEN    ! --- Solve for u-velocity --- !
+                                           ! ---------------------------- !
+
+                  ! What follows could be subroutinized...
+      
+                  ! Thomas Algorithm  for tridiagonal solver
+                  ! A*u(i-1,j)+B*u(i,j)+C*u(i+1,j) = F
+
+                  zFU(:,:)       = 0._wp ; zFU_prime(:,:) = 0._wp ; zBU_prime(:,:) = 0._wp; zCU_prime(:,:) = 0._wp
+                  
+                  DO jn = 1, nn_zebra_vp ! "zebra" loop (! red-black-sor!!! )
+                  
+                     ! OPT: could be even better optimized with a true red-black SOR
+      
+                     IF ( jn == 1 ) THEN   ;   jj_min = 2 
+                     ELSE                  ;   jj_min = 3
+                     ENDIF
+
+                     IF ( lwp ) WRITE(numout,*) ' Into the U-zebra loop at step jn = ', jn, ', with jj_min = ', jj_min
+
+                     DO jj = jj_min, jpj - 1, nn_zebra_vp
+                     
+                        !------------------------
+                        ! Independent term (zFU)
+                        !------------------------
+                        DO ji = 2, jpi - 1    
+
+                           ! boundary condition substitution
+                           ! see Zhang and Hibler, 1997, Appendix B
+                           zAA3 = 0._wp
+                           IF ( ji == 2 )         zAA3 = zAA3 - zAU(ji,jj) * u_ice(ji-1,jj)
+                           IF ( ji == jpi - 1 )   zAA3 = zAA3 - zCU(ji,jj) * u_ice(ji+1,jj)
+
+                           ! right hand side
+                           zFU(ji,jj) = ( zrhsu(ji,jj) &                                      ! right-hand side terms
+                               &      +   zAA3         &                                      ! boundary condition translation
+                               &      +   zDU(ji,jj) * u_ice(ji,jj-1)   &                     ! internal force, j-1
+                               &      +   zEU(ji,jj) * u_ice(ji,jj+1) ) * umask(ji,jj,1)      ! internal force, j+1
+
+                        END DO
+
+                     END DO
+                     
+                     CALL lbc_lnk( 'icedyn_rhg_vp', zFU, 'U',  1. )
+                     
+                     !---------------
+                     ! Forward sweep
+                     !---------------   
+                     DO jj = jj_min, jpj - 1, nn_zebra_vp
+      
+                        DO ji = 3, jpi - 1
+
+                           zfac             = SIGN( 1._wp , zBU(ji-1,jj) ) * MAX( 0._wp , SIGN( 1._wp , ABS( zBU(ji-1,jj) ) - epsi20 ) )
+                           zw               = zfac * zAU(ji,jj) / MAX ( ABS( zBU(ji-1,jj) ) , epsi20 ) 
+                           zBU_prime(ji,jj) = zBU(ji,jj) - zw * zCU(ji-1,jj)
+                           zFU_prime(ji,jj) = zFU(ji,jj) - zw * zFU(ji-1,jj)
+
+                        END DO
+
+                     END DO
+
+                     CALL lbc_lnk_multi( 'icedyn_rhg_vp', zFU_prime, 'U',  1., zBU_prime, 'U', 1. )
+ 
+                     !-----------------------------
+                     ! Backward sweep & relaxation
+                     !-----------------------------
+
+                     DO jj = jj_min, jpj - 1, nn_zebra_vp
+                    
+                        ! --- Backward sweep 
+                        ! last row 
+                        zfac = SIGN( 1._wp , zBU_prime(jpi-1,jj) ) * MAX( 0._wp , SIGN( 1._wp , ABS( zBU_prime(jpi-1,jj) ) - epsi20 ) )
+                        u_ice(jpi-1,jj)    = zfac * zFU_prime(jpi-1,jj) / MAX( ABS ( zBU_prime(jpi-1,jj) ) , epsi20 ) & 
+                                           &            * umask(jpi-1,jj,1)
+                        DO ji = jpi-2 , 2, -1 ! all other rows    !  ---> original backward loop
+                           zfac = SIGN( 1._wp , zBU_prime(ji,jj) ) * MAX( 0._wp , SIGN( 1._wp , ABS( zBU_prime(ji,jj) ) - epsi20 ) )
+                           u_ice(ji,jj)    = zfac * ( zFU_prime(ji,jj) - zCU(ji,jj) * u_ice(ji+1,jj) ) * umask(ji,jj,1)   & 
+                                           &                  / MAX ( ABS ( zBU_prime(ji,jj) ) , epsi20 ) 
+                        END DO
+
+                        !--- Relaxation
+                        ! and velocity masking for little-ice and no-ice cases
+                        DO ji = 2, jpi - 1    
+                        
+                           u_ice(ji,jj) = zu_b(ji,jj) + zrelaxu_vp * ( u_ice(ji,jj) - zu_b(ji,jj) ) ! relaxation
+                           
+                           u_ice(ji,jj) =   zmsk00x(ji,jj)                                        &   ! masking
+                              &         * (           zmsk01x(ji,jj)   * u_ice(ji,jj)             &
+                              &           + ( 1._wp - zmsk01x(ji,jj) ) * u_oce(ji,jj) * 0.01_wp     ) * umask(ji,jj,1)
+                           
+                        END DO
+
+                     END DO ! jj
+                     
+                  END DO ! zebra loop
+
+               ENDIF !   ll_u_iterate
+
+               !                           ! ---------------------------- !
+               IF ( ll_v_iterate ) THEN    ! --- Solve for V-velocity --- !
+               !                           ! ---------------------------- !
+                                          
+                  ! MV OPT: what follows could be subroutinized...                  
+                  ! Thomas Algorithm  for tridiagonal solver
+                  ! A*v(i,j-1)+B*v(i,j)+C*v(i,j+1) = F
+                  ! It is intentional to have a ji then jj loop for V-velocity
+                  !!! ZH97 explain it is critical for convergence speed
+
+                  zFV(:,:)       = 0._wp ; zFV_prime(:,:) = 0._wp ; zBV_prime(:,:) = 0._wp; zCV_prime(:,:) = 0._wp
+
+                  DO jn = 1, nn_zebra_vp ! "zebra" loop
+      
+                     IF ( jn == 1 ) THEN   ;   ji_min = 2 
+                     ELSE                  ;   ji_min = 3
+                     ENDIF
+
+                     IF ( lwp ) WRITE(numout,*) ' Into the V-zebra loop at step jn = ', jn, ', with ji_min = ', ji_min
+         
+                     DO ji = ji_min, jpi - 1, nn_zebra_vp 
+                     
+                        !------------------------
+                        ! Independent term (zFV)
+                        !------------------------
+                        DO jj = 2, jpj - 1
+
+                           ! boundary condition substitution (check it is correctly applied !!!)
+                           ! see Zhang and Hibler, 1997, Appendix B
+                           zAA3 = 0._wp
+                           IF ( jj == 2 )       zAA3 = zAA3 - zAV(ji,jj) * v_ice(ji,jj-1)
+                           IF ( jj == jpj - 1 ) zAA3 = zAA3 - zCV(ji,jj) * v_ice(ji,jj+1)
+     
+                           ! right hand side
+                           zFV(ji,jj) = ( zrhsv(ji,jj) &                                   ! right-hand side terms
+                               &        + zAA3                                           & ! boundary condition translation
+                               &        + zDV(ji,jj) * v_ice(ji-1,jj)                    & ! internal force, j-1
+                               &        + zEV(ji,jj) * v_ice(ji+1,jj) ) * vmask(ji,jj,1)   ! internal force, j+1
+
+                        END DO
+                        
+                     END DO
+
+                     CALL lbc_lnk_multi( 'icedyn_rhg_vp', zFV, 'V',  1.)
+                     
+                     !---------------
+                     ! Forward sweep
+                     !---------------
+                     DO ji = ji_min, jpi - 1, nn_zebra_vp 
+                     
+                        DO jj = 3, jpj - 1
+
+                           zfac             = SIGN( 1._wp , zBV(ji,jj-1) ) * MAX( 0._wp , SIGN( 1._wp , ABS( zBV(ji,jj-1) ) - epsi20 ) )
+                           zw               = zfac * zAV(ji,jj) / MAX ( ABS( zBV(ji,jj-1) ) , epsi20 )
+                           zBV_prime(ji,jj) = zBV(ji,jj) - zw * zCV(ji,jj-1)
+                           zFV_prime(ji,jj) = zFV(ji,jj) - zw * zFV(ji,jj-1) 
+
+                        END DO
+
+                     END DO
+
+                     CALL lbc_lnk_multi( 'icedyn_rhg_vp', zFV_prime, 'V',  1., zBV_prime, 'V', 1. )
+                     
+                     !-----------------------------
+                     ! Backward sweep & relaxation
+                     !-----------------------------
+                     DO ji = ji_min, jpi - 1, nn_zebra_vp 
+                    
+                        ! --- Backward sweep 
+                        ! last row
+                        zfac = SIGN( 1._wp , zBV_prime(ji,jpj-1) ) * MAX( 0._wp , SIGN( 1._wp , ABS( zBV_prime(ji,jpj-1) ) - epsi20 ) )
+                        v_ice(ji,jpj-1)  = zfac * zFV_prime(ji,jpj-1) / MAX ( ABS(zBV_prime(ji,jpj-1) ) , epsi20 ) & 
+                                         &         * vmask(ji,jpj-1,1)  ! last row
+
+                        ! other rows
+                        DO jj = jpj-2, 2, -1 ! original back loop
+                           zfac = SIGN( 1._wp , zBV_prime(ji,jj) ) * MAX( 0._wp , SIGN( 1._wp , ABS( zBV_prime(ji,jj) ) - epsi20 ) )
+                           v_ice(ji,jj)   = zfac * ( zFV_prime(ji,jj) - zCV(ji,jj) * v_ice(ji,jj+1) ) * vmask(ji,jj,1) &
+                                          &  / MAX ( ABS( zBV_prime(ji,jj) ) , epsi20 )       
+                        END DO            
+                                                   
+                        ! --- Relaxation  & masking (should it be now or later)
+                        DO jj = 2, jpj - 1
+                        
+                            v_ice(ji,jj) = zv_b(ji,jj) + zrelaxv_vp * ( v_ice(ji,jj) - zv_b(ji,jj) )    ! relaxation
+                            
+                            v_ice(ji,jj) =   zmsk00y(ji,jj)                                        &      ! masking
+                              &         * (           zmsk01y(ji,jj)   * v_ice(ji,jj)              &
+                              &           + ( 1._wp - zmsk01y(ji,jj) ) * v_oce(ji,jj) * 0.01_wp    ) * vmask(ji,jj,1)
+
+                        END DO ! jj
+                        
+                     END DO ! ji
+                     
+                  END DO ! zebra loop
+                                    
+               ENDIF !   ll_v_iterate
+
+               CALL lbc_lnk_multi( 'icedyn_rhg_vp', u_ice, 'U', -1., v_ice, 'V', -1. )
+                              
+               !--------------------------------------------------------------------------------------
+               ! -- Check convergence based on maximum velocity difference, continue or stop the loop
+               !--------------------------------------------------------------------------------------
+
+               !------
+               ! on U
+               !------
+               ! MV OPT: if the number of iterations to convergence is really variable, and keep the convergence check
+               ! then we must optimize the use of the mpp_max, which is prohibitive                            
+               zuerr_max = 0._wp
+                               
+               IF ( ll_u_iterate .AND. MOD ( i_inn, nn_vp_chkcvg ) == 0 ) THEN
+
+                  ! - Maximum U-velocity difference               
+                  zuerr(:,:) = 0._wp
+                  DO jj = 2, jpj - 1
+                     DO ji = 2, jpi - 1
+                        zuerr(ji,jj) = ABS ( ( u_ice(ji,jj) - zu_b(ji,jj) ) ) * umask(ji,jj,1)
+                     END DO
+                  END DO
+                  zuerr_max = MAXVAL( zuerr )
+                  CALL mpp_max( 'icedyn_rhg_evp', zuerr_max )   ! max over the global domain - damned!
+                  
+                  ! - Stop if error is too large ("safeguard against bad forcing" of original Zhang routine)
+                  IF ( i_inn > 1 .AND. zuerr_max > zuerr_max_vp ) THEN
+                      IF ( lwp ) WRITE(numout,*) " VP rheology error was too large : ", zuerr_max, " in outer U-iteration ", i_out, " after ", i_inn, " iterations, we stopped "
+                      ll_u_iterate = .FALSE.
+                  ENDIF
+                  
+                  ! - Stop if error small enough
+                  IF ( zuerr_max < zuerr_min_vp ) THEN                                        
+                      IF ( lwp ) WRITE(numout,*) " VP rheology nicely done in outer U-iteration ", i_out, " after ", i_inn, " iterations, finished! "
+                      ll_u_iterate = .FALSE.
+                  ENDIF
+                                               
+               ENDIF ! ll_u_iterate
+
+               !------
+               ! on V
+               !------
+               zverr_max = 0._wp
+               
+               IF ( ll_v_iterate .AND. MOD ( i_inn, nn_vp_chkcvg ) == 0 ) THEN
+               
+                  ! - Maximum V-velocity difference
+                  zverr(:,:)   = 0._wp   
+                  DO jj = 2, jpj - 1
+                     DO ji = 2, jpi - 1
+                        zverr(ji,jj) = ABS ( ( v_ice(ji,jj) - zv_b(ji,jj) ) ) * vmask(ji,jj,1)
+                     END DO
+                  END DO
+                  
+                  zverr_max = MAXVAL( zverr )
+                  CALL mpp_max( 'icedyn_rhg_evp', zverr_max )   ! max over the global domain - damned!
+                  
+                  ! - Stop if error is too large ("safeguard against bad forcing" of original Zhang routine)
+                  IF ( i_inn > 1 .AND. zverr_max > zuerr_max_vp ) THEN
+                      IF ( lwp ) WRITE(numout,*) " VP rheology error was too large : ", zverr_max, " in outer V-iteration ", i_out, " after ", i_inn, " iterations, we stopped "
+                      ll_v_iterate = .FALSE.
+                  ENDIF
+                  
+                  ! - Stop if error small enough
+                  IF ( zverr_max < zuerr_min_vp ) THEN                                        
+                      IF ( lwp ) WRITE(numout,*) " VP rheology nicely done in outer V-iteration ", i_out, " after ", i_inn, " iterations, finished! "
+                      ll_v_iterate = .FALSE.
+                  ENDIF
+                  
+               ENDIF ! ll_v_iterate
+
+            ENDIF ! ---    end ll_u_iterate or ll_v_iterate
+               
+            !---------------------------------------------------------------------------------------
+            !
+            ! --- Calculate extra convergence diagnostics and save them
+            !
+            !---------------------------------------------------------------------------------------
+
+            IF( nn_rhg_chkcvg/=0 .AND. MOD ( i_inn - 1, nn_vp_chkcvg ) == 0 ) CALL rhg_cvg_vp( kt, jter, nn_nvp, u_ice, v_ice, zmt, zuerr_max, zverr_max, zglob_area, &
+                      &                         zrhsu, zAU, zBU, zCU, zDU, zEU, zrhsv, zAV, zBV, zCV, zDV, zEV )
+
+            IF ( lwp ) WRITE(numout,*) ' Done convergence tests '
+
+         END DO ! i_inn, end of inner loop
+
+      END DO ! End of outer loop (i_out) =============================================================================================
+
+      IF ( lwp ) WRITE(numout,*) ' We are out of outer loop '
+
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', zFU  , 'U',  1., zFV  , 'V',  1. )
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', zBU_prime  , 'U',  1., zBV_prime  , 'V',  1. )
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', zFU_prime  , 'U',  1., zFV_prime  , 'V',  1. )
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', zCU_prime  , 'U',  1., zCV_prime  , 'V',  1. )
+
+      CALL iom_put( 'zFU'           , zFU            ) ! MV DEBUG
+      CALL iom_put( 'zBU_prime'     , zBU_prime      ) ! MV DEBUG
+      CALL iom_put( 'zCU_prime'     , zCU_prime      ) ! MV DEBUG
+      CALL iom_put( 'zFU_prime'     , zFU_prime      ) ! MV DEBUG
+
+      CALL iom_put( 'zFV'           , zFV            ) ! MV DEBUG
+      CALL iom_put( 'zBV_prime'     , zBV_prime      ) ! MV DEBUG
+      CALL iom_put( 'zCV_prime'     , zCV_prime      ) ! MV DEBUG
+      CALL iom_put( 'zFV_prime'     , zFV_prime      ) ! MV DEBUG
+
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', u_ice, 'U', -1., v_ice, 'V', -1. )
+
+      IF ( lwp ) WRITE(numout,*) ' We are about to output uice_dbg '
+      IF( iom_use('uice_dbg' ) )   CALL iom_put( 'uice_dbg'   , u_ice    )                              ! ice velocity u after solver
+      IF( iom_use('vice_dbg' ) )   CALL iom_put( 'vice_dbg'   , v_ice    )                              ! ice velocity v after solver
+            
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Convergence diagnostics 
+      !
+      !------------------------------------------------------------------------------!
+
+      IF( nn_rhg_chkcvg /= 0 ) THEN
+          
+         IF( iom_use('uice_cvg')  ) THEN
+            CALL iom_put( 'uice_cvg', MAX( ABS( u_ice(:,:) - zu_b(:,:) ) * umask(:,:,1) , &                ! ice velocity difference at last iteration
+                  &                        ABS( v_ice(:,:) - zv_b(:,:) ) * vmask(:,:,1) ) * zmsk15(:,:) )
+         ENDIF   
+        
+      ENDIF
+
+      ! MV DEBUG test - replace ice velocity by ocean current to give the model the means to go ahead
+      DO jj = 2, jpj - 1
+         DO ji = 2, jpi - 1   
+
+             u_ice(ji,jj) =   zmsk00x(ji,jj)                               & 
+      &         * (           zmsk01x(ji,jj)   * u_oce(ji,jj) * 0.01_wp    &
+                  + ( 1._wp - zmsk01x(ji,jj) ) * u_oce(ji,jj) * 0.01_wp    )
+
+             v_ice(ji,jj) =   zmsk00y(ji,jj)                               & 
+      &         * (           zmsk01y(ji,jj)   * v_oce(ji,jj) * 0.01_wp    &
+                  + ( 1._wp - zmsk01y(ji,jj) ) * v_oce(ji,jj) * 0.01_wp    )
+
+         END DO
+      END DO
+
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', u_ice, 'U', -1., v_ice, 'V', -1. )
+
+      IF ( lwp ) WRITE(numout,*) ' Velocity replaced '
+
+      ! END DEBUG
+
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Recompute delta, shear and div (inputs for mechanical redistribution) 
+      !
+      !------------------------------------------------------------------------------!
+      !
+      ! MV OPT: subroutinize ?
+
+      DO jj = 1, jpj - 1
+         DO ji = 1, jpi - 1
+
+            ! shear at F points
+            zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+               &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+               &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+         END DO
+      END DO           
+      
+      DO jj = 2, jpj - 1
+         DO ji = 2, jpi - 1 ! 
+            
+            ! tension**2 at T points
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+            zdt2 = zdt * zdt
+            
+            zten_i(ji,jj) = zdt
+            
+            ! shear**2 at T points (doc eq. A16)
+            zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+            
+            ! shear at T points
+            pshear_i(ji,jj) = SQRT( zdt2 + zds2 )
+
+            ! divergence at T points
+            pdivu_i(ji,jj) = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &             + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &             ) * r1_e1e2t(ji,jj)
+            
+            ! delta at T points
+            zdelta         = SQRT( pdivu_i(ji,jj) * pdivu_i(ji,jj) + ( zdt2 + zds2 ) * z1_ecc2 )  
+            rswitch        = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zdelta ) ) ! 0 if delta=0
+            
+            !pdelta_i(ji,jj) = zdelta + rn_creepl * rswitch
+            pdelta_i(ji,jj) = zdelta + rn_creepl
+
+         END DO
+      END DO
+
+      IF ( lwp ) WRITE(numout,*) ' Deformation recalculated '
+      
+      CALL lbc_lnk_multi( 'icedyn_rhg_vp', pshear_i, 'T', 1., pdivu_i, 'T', 1., pdelta_i, 'T', 1. )
+      
+      !------------------------------------------------------------------------------!
+      !
+      ! --- Diagnostics
+      !
+      !------------------------------------------------------------------------------!
+      !
+      ! MV OPT: subroutinize ?
+      !
+      !----------------------------------
+      ! --- Recompute stresses if needed 
+      !----------------------------------
+      !
+      ! ---- Sea ice stresses at T-points
+      IF ( iom_use('normstr') .OR. iom_use('sheastr') .OR. iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+      
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+               zp_deltastar_t(ji,jj)   =   strength(ji,jj) / pdelta_i(ji,jj) 
+               zfac                    =   zp_deltastar_t(ji,jj) 
+               zs1(ji,jj)              =   zfac * ( pdivu_i(ji,jj) - pdelta_i(ji,jj) )
+               zs2(ji,jj)              =   zfac * z1_ecc2 * zten_i(ji,jj)
+               zs12(ji,jj)             =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            END DO
+         END DO
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zs1, 'T', 1., zs2, 'T', 1., zs12, 'T', 1. )
+      
+      ENDIF
+      
+      ! ---- s12 at F-points      
+      IF ( iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+
+         DO jj = 1, jpj - 1
+            DO ji = 1, jpi - 1
+            
+               ! P/delta* at F points
+               zp_deltastar_f = 0.25_wp * ( zp_deltastar_t(ji,jj) + zp_deltastar_t(ji+1,jj) + zp_deltastar_t(ji,jj+1) + zp_deltastar_t(ji+1,jj+1) )
+               
+               ! s12 at F-points 
+               zs12f(ji,jj) = zp_deltastar_f * z1_ecc2 * zds(ji,jj)
+               
+            END DO
+         END DO
+
+         CALL lbc_lnk( 'icedyn_rhg_vp', zs12f, 'F', 1. )
+         
+      ENDIF
+
+      IF ( lwp ) WRITE(numout,*) ' zs12f recalculated '
+
+      !
+      !-----------------------
+      ! --- Store diagnostics
+      !-----------------------
+      !
+      ! --- Ice-ocean, ice-atm. & ice-ocean bottom (landfast) stresses --- !
+      IF(  iom_use('utau_oi') .OR. iom_use('vtau_oi') .OR. iom_use('utau_ai') .OR. iom_use('vtau_ai') .OR. &
+         & iom_use('utau_bi') .OR. iom_use('vtau_bi') ) THEN
+
+         ALLOCATE( ztaux_oi(jpi,jpj) , ztauy_oi(jpi,jpj) )
+
+         !--- Recalculate oceanic stress at last inner iteration
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+
+                !--- ice u-velocity @V points, v-velocity @U points (for non-linear drag computation)
+                zu_cV            = 0.25_wp * ( u_ice(ji,jj) + u_ice(ji-1,jj) + u_ice(ji,jj+1) + u_ice(ji-1,jj+1) ) * vmask(ji,jj,1)
+                zv_cU            = 0.25_wp * ( v_ice(ji,jj) + v_ice(ji,jj-1) + v_ice(ji+1,jj) + v_ice(ji+1,jj-1) ) * umask(ji,jj,1)
+                
+                !--- non-linear drag coefficients (need to be updated at each outer loop, see Lemieux and Tremblay JGR09, p.3, beginning of Section 3)
+                zCwU(ji,jj)          = za_iU(ji,jj) * zrhoco * SQRT( ( u_ice(ji,jj) - u_oce (ji,jj) ) * ( u_ice(ji,jj) - u_oce (ji,jj) )  &
+                  &                                                + ( zv_cU - v_oceU(ji,jj) ) * ( zv_cU - v_oceU(ji,jj) ) )
+                zCwV(ji,jj)          = za_iV(ji,jj) * zrhoco * SQRT( ( v_ice(ji,jj) - v_oce (ji,jj) ) * ( v_ice(ji,jj) - v_oce (ji,jj) )  &
+                  &                                                + ( zu_cV - u_oceV(ji,jj) ) * ( zu_cV - u_oceV(ji,jj) ) )
+                 
+                !--- Ocean-ice stress
+                ztaux_oi(ji,jj) = zCwU(ji,jj) * ( u_oce(ji,jj) - u_ice(ji,jj) )
+                ztauy_oi(ji,jj) = zCwV(ji,jj) * ( v_oce(ji,jj) - v_ice(ji,jj) )
+                
+            END DO
+         END DO
+         
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', ztaux_oi, 'U', -1., ztauy_oi, 'V', -1., ztaux_ai, 'U', -1., ztauy_ai, 'V', -1. ) !, &
+!            &                                 ztaux_bi, 'U', -1., ztauy_bi, 'V', -1. )
+         !
+         CALL iom_put( 'utau_oi' , ztaux_oi * zmsk00 )
+         CALL iom_put( 'vtau_oi' , ztauy_oi * zmsk00 )
+         CALL iom_put( 'utau_ai' , ztaux_ai * zmsk00 )
+         CALL iom_put( 'vtau_ai' , ztauy_ai * zmsk00 )
+!        CALL iom_put( 'utau_bi' , ztaux_bi * zmsk00 )
+!        CALL iom_put( 'vtau_bi' , ztauy_bi * zmsk00 )
+
+         DEALLOCATE( ztaux_oi , ztauy_oi )
+
+      ENDIF
+       
+      ! --- Divergence, shear and strength --- !
+      IF( iom_use('icediv') )   CALL iom_put( 'icediv' , pdivu_i  * zmsk00 )   ! divergence
+      IF( iom_use('iceshe') )   CALL iom_put( 'iceshe' , pshear_i * zmsk00 )   ! shear
+      IF( iom_use('icedlt') )   CALL iom_put( 'icedlt' , pdelta_i * zmsk00 )   ! delta
+      IF( iom_use('icestr') )   CALL iom_put( 'icestr' , strength * zmsk00 )   ! strength
+
+      IF ( lwp ) WRITE(numout,*) 'Some terms recalculated '
+
+      ! --- Stress tensor invariants (SIMIP diags) --- !
+      IF( iom_use('normstr') .OR. iom_use('sheastr') ) THEN
+         !
+         ! Stress tensor invariants (normal and shear stress N/m) - SIMIP diags.
+         ! Definitions following Coon (1974) and Feltham (2008)
+         !
+         ! sigma1, sigma2, sigma12 are useful (Hunke and Dukowicz MWR 2002, Bouillon et al., OM2013)
+         ! however these are NOT stress tensor components, neither stress invariants, nor stress principal components
+         !
+         ALLOCATE( zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )
+         !         
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+               ! Stress invariants
+               zsig_I(ji,jj)    =   zs1(ji,jj) * 0.5_wp                                        ! 1st invariant, aka average normal stress aka negative pressure
+               zsig_II(ji,jj)   =   SQRT ( zs2(ji,jj) * zs2(ji,jj) * 0.25_wp + zs12(ji,jj) )  ! 2nd invariant, aka maximum shear stress               
+            END DO
+         END DO
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zsig_I, 'T', 1., zsig_II, 'T', 1.)
+         
+         IF( iom_use('normstr') )   CALL iom_put( 'normstr' ,   zsig_I(:,:)  * zmsk00(:,:) ) ! Normal stress
+         IF( iom_use('sheastr') )   CALL iom_put( 'sheastr' ,   zsig_II(:,:) * zmsk00(:,:) ) ! Maximum shear stress
+         
+         DEALLOCATE ( zsig_I, zsig_II )
+         
+      ENDIF
+
+      IF ( lwp ) WRITE(numout,*) 'SIMIP work done'
+
+      ! --- Normalized stress tensor principal components --- !
+      ! These are used to plot the normalized yield curve (Lemieux & Dupont, GMD 2020)
+      ! To plot the yield curve and evaluate physical convergence, they have two recommendations
+      ! Recommendation 1 : Use ice strength, not replacement pressure
+      ! Recommendation 2 : Need to use deformations at PREVIOUS iterate for viscosities (see p. 1765)
+      ! R2 means we need to recompute stresses
+
+      IF( iom_use('sig1_pnorm') .OR. iom_use('sig2_pnorm') ) THEN
+         !
+         ALLOCATE( zsig1_p(jpi,jpj) , zsig2_p(jpi,jpj) , zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )
+         !         
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+               ! Ice stresses computed with **viscosities** (delta, p/delta) at **previous** iterates 
+               !                        and **deformations** at current iterates
+               !                        following Lemieux & Dupont (2020)
+               zfac             =   zp_deltastar_t(ji,jj)
+               zsig1            =   zfac * ( pdivu_i(ji,jj) - zdeltastar_t(ji,jj) )
+               zsig1            = 0._wp !!! FUCKING DEBUG TEST !!!
+               zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+               zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+               
+               ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008), T-point
+               zsig_I(ji,jj)    =   zsig1 * 0.5_wp                              ! 1st invariant
+               zsig_II(ji,jj)   =   SQRT ( zsig2 * zsig2 * 0.25_wp + zsig12 )   ! 2nd invariant
+
+               ! Normalized  principal stresses (used to display the ellipse)
+               z1_strength      =   1._wp / MAX ( 1._wp , strength(ji,jj) )
+               zsig1_p(ji,jj)   =   ( zsig_I(ji,jj) + zsig_II(ji,jj) ) * z1_strength
+               zsig2_p(ji,jj)   =   ( zsig_I(ji,jj) - zsig_II(ji,jj) ) * z1_strength
+            END DO
+         END DO
+         IF ( lwp ) WRITE(numout,*) 'Some shitty stress work done'
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zsig1_p, 'T', 1., zsig2_p, 'T', 1.)
+         !      
+         IF ( lwp ) WRITE(numout,*) ' Beauaaaarflblbllll '
+         !
+         CALL iom_put( 'sig1_pnorm' , zsig1_p ) 
+         CALL iom_put( 'sig2_pnorm' , zsig2_p ) 
+
+         DEALLOCATE( zsig1_p , zsig2_p , zsig_I , zsig_II )
+
+         IF ( lwp ) WRITE(numout,*) ' So what ??? '
+         
+      ENDIF
+
+      ! --- SIMIP, terms of tendency for momentum equation  --- !
+      IF(  iom_use('dssh_dx') .OR. iom_use('dssh_dy') .OR. &
+         & iom_use('corstrx') .OR. iom_use('corstry') ) THEN
+
+         ! --- Recalculate Coriolis stress at last inner iteration
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+                ! --- U-component 
+                zCorU(ji,jj)         =   0.25_wp * r1_e1u(ji,jj) *  &
+                           &             ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                           &             + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+                zCorV(ji,jj)         = - 0.25_wp * r1_e2v(ji,jj) *  &
+                           &             ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                           &             + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+            END DO
+         END DO
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zspgU, 'U', -1., zspgV, 'V', -1., &
+            &                                 zCorU, 'U', -1., zCorV, 'V', -1. )
+         !
+         CALL iom_put( 'dssh_dx' , zspgU * zmsk00 )   ! Sea-surface tilt term in force balance (x)
+         CALL iom_put( 'dssh_dy' , zspgV * zmsk00 )   ! Sea-surface tilt term in force balance (y)
+         CALL iom_put( 'corstrx' , zCorU * zmsk00 )   ! Coriolis force term in force balance (x)
+         CALL iom_put( 'corstry' , zCorV * zmsk00 )   ! Coriolis force term in force balance (y)
+
+      ENDIF
+      
+      IF ( iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+
+         ! Recalculate internal forces (divergence of stress tensor) at last inner iteration
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+               zfU(ji,jj) = 0.5_wp * ( ( zs1(ji+1,jj) - zs1(ji,jj) ) * e2u(ji,jj)                                             &
+                  &                  + ( zs2(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) - zs2(ji,jj) * e2t(ji,jj) * e2t(ji,jj)    &
+                  &                    ) * r1_e2u(ji,jj)                                                                      &
+                  &                  + ( zs12f(ji,jj) * e1f(ji,jj) * e1f(ji,jj) - zs12f(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1)  &
+                  &                    ) * 2._wp * r1_e1u(ji,jj)                                                              &
+                  &                  ) * r1_e1e2u(ji,jj)
+               zfV(ji,jj) = 0.5_wp * ( ( zs1(ji,jj+1) - zs1(ji,jj) ) * e1v(ji,jj)                                             &
+                  &                  - ( zs2(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) - zs2(ji,jj) * e1t(ji,jj) * e1t(ji,jj)    &
+                  &                    ) * r1_e1v(ji,jj)                                                                      &
+                  &                  + ( zs12f(ji,jj) * e2f(ji,jj) * e2f(ji,jj) - zs12f(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj)  &
+                  &                    ) * 2._wp * r1_e2v(ji,jj)                                                              &
+                  &                  ) * r1_e1e2v(ji,jj)
+            END DO
+         END DO
+            
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zfU, 'U', -1., zfV, 'V', -1. )
+         
+         CALL iom_put( 'intstrx' , zfU   * zmsk00 )   ! Internal force term in force balance (x)
+         CALL iom_put( 'intstry' , zfV   * zmsk00 )   ! Internal force term in force balance (y)
+         
+      ENDIF
+
+      ! --- Ice & snow mass and ice area transports
+      IF(  iom_use('xmtrpice') .OR. iom_use('ymtrpice') .OR. &
+         & iom_use('xmtrpsnw') .OR. iom_use('ymtrpsnw') .OR. iom_use('xatrp') .OR. iom_use('yatrp') ) THEN
+         !
+         ALLOCATE( zdiag_xmtrp_ice(jpi,jpj) , zdiag_ymtrp_ice(jpi,jpj) , &
+            &      zdiag_xmtrp_snw(jpi,jpj) , zdiag_ymtrp_snw(jpi,jpj) , zdiag_xatrp(jpi,jpj) , zdiag_yatrp(jpi,jpj) )
+         !
+         DO jj = 2, jpj - 1
+            DO ji = 2, jpi - 1
+               ! 2D ice mass, snow mass, area transport arrays (X, Y)
+               zfac_x = 0.5 * u_ice(ji,jj) * e2u(ji,jj) * zmsk00(ji,jj)
+               zfac_y = 0.5 * v_ice(ji,jj) * e1v(ji,jj) * zmsk00(ji,jj)
+
+               zdiag_xmtrp_ice(ji,jj) = rhoi * zfac_x * ( vt_i(ji+1,jj) + vt_i(ji,jj) ) ! ice mass transport, X-component
+               zdiag_ymtrp_ice(ji,jj) = rhoi * zfac_y * ( vt_i(ji,jj+1) + vt_i(ji,jj) ) !        ''           Y-   ''
+
+               zdiag_xmtrp_snw(ji,jj) = rhos * zfac_x * ( vt_s(ji+1,jj) + vt_s(ji,jj) ) ! snow mass transport, X-component
+               zdiag_ymtrp_snw(ji,jj) = rhos * zfac_y * ( vt_s(ji,jj+1) + vt_s(ji,jj) ) !          ''          Y-   ''
+
+               zdiag_xatrp(ji,jj)     = zfac_x * ( at_i(ji+1,jj) + at_i(ji,jj) )        ! area transport,      X-component
+               zdiag_yatrp(ji,jj)     = zfac_y * ( at_i(ji,jj+1) + at_i(ji,jj) )        !        ''            Y-   ''
+
+            END DO
+         END DO
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_vp', zdiag_xmtrp_ice, 'U', -1., zdiag_ymtrp_ice, 'V', -1., &
+            &                                 zdiag_xmtrp_snw, 'U', -1., zdiag_ymtrp_snw, 'V', -1., &
+            &                                 zdiag_xatrp    , 'U', -1., zdiag_yatrp    , 'V', -1. )
+
+         CALL iom_put( 'xmtrpice' , zdiag_xmtrp_ice )   ! X-component of sea-ice mass transport (kg/s)
+         CALL iom_put( 'ymtrpice' , zdiag_ymtrp_ice )   ! Y-component of sea-ice mass transport 
+         CALL iom_put( 'xmtrpsnw' , zdiag_xmtrp_snw )   ! X-component of snow mass transport (kg/s)
+         CALL iom_put( 'ymtrpsnw' , zdiag_ymtrp_snw )   ! Y-component of snow mass transport
+         CALL iom_put( 'xatrp'    , zdiag_xatrp     )   ! X-component of ice area transport
+         CALL iom_put( 'yatrp'    , zdiag_yatrp     )   ! Y-component of ice area transport
+
+         DEALLOCATE( zdiag_xmtrp_ice , zdiag_ymtrp_ice , &
+            &        zdiag_xmtrp_snw , zdiag_ymtrp_snw , zdiag_xatrp , zdiag_yatrp )
+
+      ENDIF
+
+      DEALLOCATE( zmsk00, zmsk15 )
+
+   END SUBROUTINE ice_dyn_rhg_vp
+   
+   
+   
+   SUBROUTINE rhg_cvg_vp( kt, kiter, kitermax, pu, pv, pmt, puerr_max, pverr_max, pglob_area, &
+                  &       prhsu, pAU, pBU, pCU, pDU, pEU, prhsv, pAV, pBV, pCV, pDV, pEV )
+   
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE rhg_cvg_vp  ***
+      !!                     
+      !! ** Purpose :   check convergence of VP ice rheology
+      !!
+      !! ** Method  :   create a file ice_cvg.nc containing a few convergence diagnostics
+      !!                This routine is called every sub-iteration, so it is cpu expensive
+      !!
+      !!                Calculates / stores
+      !!                   - maximum absolute U-V difference (uice_cvg, u_dif, v_dif, m/s)
+      !!                   - residuals in U, V and UV-mean taken as square-root of area-weighted mean square residual (u_res, v_res, vel_res, N/m2)
+      !!                   - mean kinetic energy (mke_ice, J/m2)
+      !!
+      !! ** Note    :   for the first sub-iteration, uice_cvg is set to 0 (too large otherwise)   
+      !!----------------------------------------------------------------------
+      INTEGER ,                 INTENT(in) ::   kt, kiter, kitermax      ! ocean time-step index
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pu, pv, pmt              ! now velocity and mass per unit area 
+      REAL(wp),                 INTENT(in) ::   puerr_max, pverr_max     ! absolute mean velocity difference
+      REAL(wp),                 INTENT(in) ::   pglob_area               ! global ice area
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   prhsu, pAU, pBU, pCU, pDU, pEU ! linear system coefficients 
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   prhsv, pAV, pBV, pCV, pDV, pEV
+      !!
+      INTEGER           ::   it, idtime, istatus, ix_dim, iy_dim
+      INTEGER           ::   ji, jj          ! dummy loop indices
+      REAL(wp)          ::   zveldif, zu_res_mean, zv_res_mean, zvelres, zmke, zu, zv ! local scalars
+      REAL(wp)          ::   z1_pglob_area
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_res, zv_res, zvel2                         ! local arrays
+                                                                             
+      CHARACTER(len=20) ::   clname
+      !!----------------------------------------------------------------------
+
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'rhg_cvg_vp : ice rheology convergence control'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*) ' kiter    =  : ', kiter
+         WRITE(numout,*) ' kitermax =  : ', kitermax
+      ENDIF
+
+      ! create file
+      IF( kt == nit000 .AND. kiter == 1 ) THEN
+         !
+         IF( lwm ) THEN
+
+            clname = 'ice_cvg.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, ncvgid )
+
+            istatus = NF90_DEF_DIM( ncvgid, 'time'  , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_DIM( ncvgid, 'x'     , jpi, ix_dim )
+            istatus = NF90_DEF_DIM( ncvgid, 'y'     , jpj, iy_dim )
+
+            ! i suggest vel_dif instead
+            istatus = NF90_DEF_VAR( ncvgid, 'u_res'  , NF90_DOUBLE  , (/ idtime /), nvarid_ures )
+            istatus = NF90_DEF_VAR( ncvgid, 'v_res'  , NF90_DOUBLE  , (/ idtime /), nvarid_vres )
+            istatus = NF90_DEF_VAR( ncvgid, 'vel_res', NF90_DOUBLE  , (/ idtime /), nvarid_velres )
+            istatus = NF90_DEF_VAR( ncvgid, 'u_dif'  , NF90_DOUBLE  , (/ idtime /), nvarid_udif )
+            istatus = NF90_DEF_VAR( ncvgid, 'v_dif'  , NF90_DOUBLE  , (/ idtime /), nvarid_vdif )
+            istatus = NF90_DEF_VAR( ncvgid, 'vel_dif', NF90_DOUBLE  , (/ idtime /), nvarid_veldif )
+            istatus = NF90_DEF_VAR( ncvgid, 'mke_ice', NF90_DOUBLE  , (/ idtime /), nvarid_mke )
+
+            istatus = NF90_DEF_VAR( ncvgid, 'u_res_xy', NF90_DOUBLE, (/ ix_dim, iy_dim /), nvarid_ures_xy)
+            istatus = NF90_DEF_VAR( ncvgid, 'v_res_xy', NF90_DOUBLE, (/ ix_dim, iy_dim /), nvarid_vres_xy)
+
+            istatus = NF90_ENDDEF(ncvgid)
+
+         ENDIF
+         !
+      ENDIF
+
+      IF ( lwp ) WRITE(numout,*) ' File created '
+
+      ! --- Max absolute velocity difference with previous iterate (zveldif)
+      zveldif = MAX( puerr_max, pverr_max ) ! velocity difference with previous iterate, should nearly be equivalent to evp code 
+                                            ! if puerrmask and pverrmax are masked at 15% (TEST)
+
+      ! ---  Mean residual and kinetic energy
+      IF ( kiter == 1 ) THEN
+
+         zu_res_mean = 0._wp
+         zv_res_mean = 0._wp
+         zvelres     = 0._wp
+         zmke        = 0._wp
+
+      ELSE
+
+      ! -- Mean residual (N/m^2), zu_res_mean
+      ! Here we take the residual of the linear system (N/m^2), 
+      ! We define it as in mitgcm: square-root of area-weighted mean square residual
+      ! Local residual r = Ax - B expresses to which extent the momentum balance is verified 
+      ! i.e., how close we are to a solution
+
+      IF ( lwp ) WRITE(numout,*) ' TEST 1 ' 
+
+      z1_pglob_area = 1._wp / pglob_area
+
+      zu_res(:,:) = 0._wp; zv_res(:,:) = 0._wp
+
+      DO jj = 2, jpj - 1
+         DO ji = 2, jpi - 1                                      
+            zu_res(ji,jj)  = ( prhsu(ji,jj) + pDU(ji,jj) * pu(ji,jj-1) + pEU(ji,jj) * pu(ji,jj+1)               &
+               &             - pAU(ji,jj) * pu(ji-1,jj) - pBU(ji,jj) * pu(ji,jj) - pCU(ji,jj) * pu(ji+1,jj) )
+                           
+            zv_res(ji,jj)  = ( prhsv(ji,jj) + pDV(ji,jj) * pv(ji-1,jj) + pEV(ji,jj) * pv(ji+1,jj)               &
+               &             - pAV(ji,jj) * pv(ji,jj-1) - pBV(ji,jj) * pv(ji,jj) - pCV(ji,jj) * pv(ji,jj+1) )
+
+            zu_res(ji,jj)  = SQRT( zu_res(ji,jj) * zu_res(ji,jj) ) * umask(ji,jj,1) * e1e2u(ji,jj) * z1_pglob_area
+            zv_res(ji,jj)  = SQRT( zv_res(ji,jj) * zv_res(ji,jj) ) * vmask(ji,jj,1) * e1e2v(ji,jj) * z1_pglob_area
+
+         END DO
+      END DO                  
+
+      IF ( lwp ) WRITE(numout,*) ' TEST 2 ' 
+      zu_res_mean = glob_sum( 'ice_rhg_vp', zu_res(:,:) )
+      zv_res_mean = glob_sum( 'ice_rhg_vp', zv_res(:,:) )
+      IF ( lwp ) WRITE(numout,*) ' TEST 3 ' 
+      zvelres     = 0.5_wp * ( zu_res_mean + zv_res_mean )
+
+      IF ( lwp ) WRITE(numout,*) ' TEST 4 ' 
+                                          
+      ! -- Global mean kinetic energy per unit area (J/m2)
+      zvel2(:,:) = 0._wp
+      DO jj = 2, jpj - 1
+         DO ji = 2, jpi - 1                   
+            zu     = 0.5_wp * ( pu(ji-1,jj) + pu(ji,jj) ) ! u-vel at T-point
+            zv     = 0.5_wp * ( pv(ji,jj-1) + pv(ji,jj) )
+            zvel2(ji,jj)  = zu*zu + zv*zv              ! square of ice velocity at T-point  
+         END DO
+      END DO
+       
+      IF ( lwp ) WRITE(numout,*) ' TEST 5 ' 
+
+      zmke = 0.5_wp * glob_sum( 'ice_rhg_vp', pmt(:,:) * e1e2t(:,:) * zvel2(:,:) ) / pglob_area
+
+      IF ( lwp ) WRITE(numout,*) ' TEST 6 '
+
+      ENDIF ! kiter
+                  
+         !                                                ! ==================== !
+
+      ! time
+      it = ( kt - 1 ) * kitermax + kiter
+
+
+      IF( lwm ) THEN
+         ! write variables
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_ures, (/zu_res_mean/), (/it/), (/1/) ) ! U-residual of the linear system
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_vres, (/zv_res_mean/), (/it/), (/1/) ) ! V-residual of the linear system
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_velres, (/zvelres/), (/it/), (/1/) )   ! average of u- and v- residuals
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_udif, (/puerr_max/), (/it/), (/1/) )   ! max U velocity difference, inner iterations
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_vdif, (/pverr_max/), (/it/), (/1/) )   ! max V velocity difference, inner iterations
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_veldif, (/zveldif/), (/it/), (/1/) )   ! max U or V velocity diff between subiterations
+         istatus = NF90_PUT_VAR( ncvgid, nvarid_mke, (/zmke/), (/it/), (/1/) )         ! mean kinetic energy
+
+         !
+         IF ( kiter == kitermax ) THEN
+            WRITE(numout,*) ' Should plot the spatially dependent residual '
+            istatus = NF90_PUT_VAR( ncvgid, nvarid_ures_xy, (/zu_res/) )          ! U-residual, spatially dependent
+            istatus = NF90_PUT_VAR( ncvgid, nvarid_vres_xy, (/zv_res/) )          ! V-residual, spatially dependent
+         ENDIF
+
+         ! close file
+         IF( kt == nitend )   istatus = NF90_CLOSE( ncvgid )
+      ENDIF
+      
+   END SUBROUTINE rhg_cvg_vp
+   
+
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!==============================================================================
+END MODULE icedyn_rhg_vp
+
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceistate.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceistate.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceistate.F90	(revision 14055)
@@ -411,5 +411,5 @@
       ! 4) Snow-ice mass (case ice is fully embedded)
       !----------------------------------------------
-      snwice_mass  (:,:) = tmask(:,:,1) * SUM( rhos * v_s(:,:,:) + rhoi * v_i(:,:,:), dim=3  )   ! snow+ice mass
+      snwice_mass  (:,:) = tmask(:,:,1) * SUM( rhos * v_s + rhoi * v_i + rhow * ( v_ip + v_il ), dim=3  )   ! snow+ice mass
       snwice_mass_b(:,:) = snwice_mass(:,:)
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceitd.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceitd.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceitd.F90	(revision 14055)
@@ -29,4 +29,5 @@
    USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
    USE prtctl         ! Print control
+   USE timing         ! Timing
 
    IMPLICIT NONE
@@ -87,4 +88,5 @@
       REAL(wp), DIMENSION(jpij,0:jpl) ::   zhbnew          ! new boundaries of ice categories
       !!------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('iceitd_rem')
 
       IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_itd_rem: remapping ice thickness distribution' 
@@ -315,5 +317,5 @@
             IF ( a_i_1d(ji) > epsi10 .AND. h_i_1d(ji) < rn_himin ) THEN
                a_i_1d(ji) = a_i_1d(ji) * h_i_1d(ji) / rn_himin 
-               IF( ln_pnd_LEV )   a_ip_1d(ji) = a_ip_1d(ji) * h_i_1d(ji) / rn_himin
+               IF( ln_pnd_LEV .OR. ln_pnd_TOPO )   a_ip_1d(ji) = a_ip_1d(ji) * h_i_1d(ji) / rn_himin
                h_i_1d(ji) = rn_himin
             ENDIF
@@ -328,4 +330,5 @@
       IF( ln_icediachk )   CALL ice_cons_hsm(1, 'iceitd_rem', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
       IF( ln_icediachk )   CALL ice_cons2D  (1, 'iceitd_rem',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      IF( ln_timing    )   CALL timing_stop ('iceitd_rem')
       !
    END SUBROUTINE ice_itd_rem
@@ -486,15 +489,15 @@
                zaTsfn(ji,jl2)  = zaTsfn(ji,jl2) + ztrans
                !  
-               IF ( ln_pnd_LEV ) THEN
+               IF ( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
                   ztrans          = a_ip_2d(ji,jl1) * zworka(ji)     ! Pond fraction
                   a_ip_2d(ji,jl1) = a_ip_2d(ji,jl1) - ztrans
                   a_ip_2d(ji,jl2) = a_ip_2d(ji,jl2) + ztrans
                   !                                              
-                  ztrans          = v_ip_2d(ji,jl1) * zworka(ji)     ! Pond volume (also proportional to da/a)
+                  ztrans          = v_ip_2d(ji,jl1) * zworkv(ji)     ! Pond volume
                   v_ip_2d(ji,jl1) = v_ip_2d(ji,jl1) - ztrans
                   v_ip_2d(ji,jl2) = v_ip_2d(ji,jl2) + ztrans
                   !
                   IF ( ln_pnd_lids ) THEN                            ! Pond lid volume
-                     ztrans          = v_il_2d(ji,jl1) * zworka(ji)
+                     ztrans          = v_il_2d(ji,jl1) * zworkv(ji)
                      v_il_2d(ji,jl1) = v_il_2d(ji,jl1) - ztrans
                      v_il_2d(ji,jl2) = v_il_2d(ji,jl2) + ztrans
@@ -606,4 +609,5 @@
       REAL(wp), DIMENSION(jpij,jpl-1) ::   zdaice, zdvice   ! ice area and volume transferred
       !!------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('iceitd_reb')
       !
       IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_itd_reb: rebining ice thickness distribution' 
@@ -635,13 +639,10 @@
                jdonor(ji,jl)  = jl 
                ! how much of a_i you send in cat sup is somewhat arbitrary
-               !!clem: these do not work properly after a restart (I do not know why) => not sure it is still true
-               !!          zdaice(ji,jl)  = a_i_1d(ji) * ( h_i_1d(ji) - hi_max(jl) + epsi10 ) / h_i_1d(ji)  
-               !!          zdvice(ji,jl)  = v_i_1d(ji) - ( a_i_1d(ji) - zdaice(ji,jl) ) * ( hi_max(jl) - epsi10 )
-               !!clem: these do not work properly after a restart (I do not know why) => not sure it is still true
-               !!          zdaice(ji,jl)  = a_i_1d(ji)
-               !!          zdvice(ji,jl)  = v_i_1d(ji)
-               !!clem: these are from UCL and work ok
-               zdaice(ji,jl)  = a_i_1d(ji) * 0.5_wp
-               zdvice(ji,jl)  = v_i_1d(ji) - zdaice(ji,jl) * ( hi_max(jl) + hi_max(jl-1) ) * 0.5_wp
+               ! these are from CICE => transfer everything
+               !!zdaice(ji,jl)  = a_i_1d(ji)
+               !!zdvice(ji,jl)  = v_i_1d(ji)
+               ! these are from LLN => transfer only half of the category
+               zdaice(ji,jl)  =                       0.5_wp  * a_i_1d(ji)
+               zdvice(ji,jl)  = v_i_1d(ji) - (1._wp - 0.5_wp) * a_i_1d(ji) * hi_mean(jl)
             END DO
             !
@@ -686,4 +687,5 @@
       IF( ln_icediachk )   CALL ice_cons_hsm(1, 'iceitd_reb', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
       IF( ln_icediachk )   CALL ice_cons2D  (1, 'iceitd_reb',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      IF( ln_timing    )   CALL timing_stop ('iceitd_reb')
       !
    END SUBROUTINE ice_itd_reb
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icerst.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icerst.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icerst.F90	(revision 14055)
@@ -60,4 +60,5 @@
       CHARACTER(len=50)   ::   clname   ! ice output restart file name
       CHARACTER(len=256)  ::   clpath   ! full path to ice output restart file 
+      CHARACTER(LEN=52)   ::   clpname   ! ocean output restart file name including prefix for AGRIF
       !!----------------------------------------------------------------------
       !
@@ -89,5 +90,21 @@
             ENDIF
             !
-            CALL iom_open( TRIM(clpath)//TRIM(clname), numriw, ldwrt = .TRUE., kdlev = jpl, cdcomp = 'ICE' )
+            IF(.NOT.lwxios) THEN
+               CALL iom_open( TRIM(clpath)//TRIM(clname), numriw, ldwrt = .TRUE., kdlev = jpl, cdcomp = 'ICE' )
+            ELSE
+#if defined key_iomput
+               cw_icerst_cxt = "rstwi_"//TRIM(ADJUSTL(clkt))
+               IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+                  clpname = clname
+               ELSE
+                  clpname = TRIM(Agrif_CFixed())//"_"//clname
+               ENDIF
+               numriw = iom_xios_setid(TRIM(clpath)//TRIM(clpname))
+               CALL iom_init( cw_icerst_cxt, kdid = numriw, ld_closedef = .FALSE. )
+               CALL iom_swap( cxios_context )
+#else
+               CALL ctl_stop( 'Can not use XIOS in rst_opn' )
+#endif
+            ENDIF
             lrst_ice = .TRUE.
          ENDIF
@@ -122,5 +139,5 @@
          IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~'         
       ENDIF
-
+      
       ! Write in numriw (if iter == nitrst)
       ! ------------------ 
@@ -128,5 +145,6 @@
       CALL iom_rstput( iter, nitrst, numriw, 'nn_fsbc', REAL( nn_fsbc, wp ) )      ! time-step 
       CALL iom_rstput( iter, nitrst, numriw, 'kt_ice' , REAL( iter   , wp ) )      ! date
-      CALL iom_delay_rst( 'WRITE', 'ICE', numriw )   ! save only ice delayed global communication variables
+      
+      IF(.NOT.lwxios) CALL iom_delay_rst( 'WRITE', 'ICE', numriw )   ! save only ice delayed global communication variables
 
       ! Prognostic variables
@@ -159,5 +177,5 @@
       IF( ln_cpl ) THEN
          CALL iom_rstput( iter, nitrst, numriw, 'cnd_ice', cnd_ice )
-         CALL iom_rstput( iter, nitrst, numriw, 't1_ice' , t1_ice  )
+         CALL iom_rstput( iter, nitrst, numriw, 't1_ice' , t1_ice )
       ENDIF
       !
@@ -166,5 +184,11 @@
       ! ------------------
       IF( iter == nitrst ) THEN
-         CALL iom_close( numriw )
+         IF(.NOT.lwxios) THEN
+            CALL iom_close( numriw )
+         ELSE
+            CALL iom_context_finalize(      cw_icerst_cxt          )
+            iom_file(numriw)%nfid       = 0
+            numriw = 0
+         ENDIF
          lrst_ice = .FALSE.
       ENDIF
@@ -186,4 +210,5 @@
       CHARACTER(len=2)  ::   zchar, zchar1
       REAL(wp)          ::   zfice, ziter
+      CHARACTER(lc)     ::   clpname
       REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z3d   ! 3D workspace
       !!----------------------------------------------------------------------
@@ -205,5 +230,17 @@
       ENDIF
 
+      lxios_sini = .FALSE.
       CALL iom_open ( TRIM(cn_icerst_indir)//'/'//cn_icerst_in, numrir )
+
+      IF( lrxios) THEN
+          cr_icerst_cxt = 'si3_rst'
+          IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS for SI3'
+!         IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+!            clpname = cn_icerst_in
+!         ELSE
+!            clpname = TRIM(Agrif_CFixed())//"_"//cn_icerst_in   
+!         ENDIF
+          CALL iom_init( cr_icerst_cxt, kdid = numrir, ld_closedef = .TRUE. )
+      ENDIF
 
       ! test if v_i exists 
@@ -213,5 +250,4 @@
       IF( id0 > 0 ) THEN   ! == case of a normal restart == !
          !                 ! ------------------------------ !
-         
          ! Time info
          CALL iom_get( numrir, 'nn_fsbc', zfice )
@@ -293,6 +329,5 @@
          ENDIF
 
-         CALL iom_delay_rst( 'READ', 'ICE', numrir )   ! read only ice delayed global communication variables
-
+         IF(.NOT.lrxios) CALL iom_delay_rst( 'READ', 'ICE', numrir )   ! read only ice delayed global communication variables
          !                 ! ---------------------------------- !
       ELSE                 ! == case of a simplified restart == !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icesbc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icesbc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icesbc.F90	(revision 14055)
@@ -62,5 +62,5 @@
       !!-------------------------------------------------------------------
       !
-      IF( ln_timing )   CALL timing_start('ice_sbc')
+      IF( ln_timing )   CALL timing_start('icesbc')
       !
       IF( kt == nit000 .AND. lwp ) THEN
@@ -89,5 +89,5 @@
       ENDIF
       !
-      IF( ln_timing )   CALL timing_stop('ice_sbc')
+      IF( ln_timing )   CALL timing_stop('icesbc')
       !
    END SUBROUTINE ice_sbc_tau
@@ -122,5 +122,5 @@
       !!--------------------------------------------------------------------
       !
-      IF( ln_timing )   CALL timing_start('ice_sbc_flx')
+      IF( ln_timing )   CALL timing_start('icesbc')
 
       IF( kt == nit000 .AND. lwp ) THEN
@@ -176,5 +176,5 @@
       ENDIF
       !
-      IF( ln_timing )   CALL timing_stop('ice_sbc_flx')
+      IF( ln_timing )   CALL timing_stop('icesbc')
       !
    END SUBROUTINE ice_sbc_flx
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icestp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icestp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icestp.F90	(revision 14055)
@@ -121,5 +121,5 @@
       !!----------------------------------------------------------------------
       !
-      IF( ln_timing )   CALL timing_start('ice_stp')
+      IF( ln_timing )   CALL timing_start('icestp')
       !
       !                                      !-----------------------!
@@ -215,5 +215,5 @@
 !!gm   remark, the ocean-ice stress is not saved in ice diag call above .....  find a solution!!!
       !
-      IF( ln_timing )   CALL timing_stop('ice_stp')
+      IF( ln_timing )   CALL timing_stop('icestp')
       !
    END SUBROUTINE ice_stp
@@ -291,5 +291,8 @@
       tn_ice(:,:,:) = t_su(:,:,:)      ! initialisation of surface temp for coupled simu
       !
-      IF( ln_rstart )   CALL iom_close( numrir )  ! close input ice restart file
+      IF( ln_rstart )  THEN
+         CALL iom_close( numrir )  ! close input ice restart file
+         IF(lrxios) CALL iom_context_finalize(      cr_icerst_cxt         )
+      ENDIF
       !
    END SUBROUTINE ice_init
@@ -370,4 +373,6 @@
       v_i_b (:,:,:)   = v_i (:,:,:)     ! ice volume
       v_s_b (:,:,:)   = v_s (:,:,:)     ! snow volume
+      v_ip_b(:,:,:)   = v_ip(:,:,:)     ! pond volume
+      v_il_b(:,:,:)   = v_il(:,:,:)     ! pond lid volume
       sv_i_b(:,:,:)   = sv_i(:,:,:)     ! salt content
       e_s_b (:,:,:,:) = e_s (:,:,:,:)   ! snow thermal energy
@@ -429,4 +434,5 @@
          diag_heat(ji,jj) = 0._wp ;   diag_sice(ji,jj) = 0._wp
          diag_vice(ji,jj) = 0._wp ;   diag_vsnw(ji,jj) = 0._wp
+         diag_aice(ji,jj) = 0._wp ;   diag_vpnd(ji,jj) = 0._wp
 
          tau_icebfr (ji,jj) = 0._wp   ! landfast ice param only (clem: important to keep the init here)
@@ -454,4 +460,7 @@
             qcn_ice    (ji,jj,jl) = 0._wp   ! conductive flux (ln_cndflx=T & ln_cndemule=T)
             qtr_ice_bot(ji,jj,jl) = 0._wp   ! part of solar radiation transmitted through the ice needed at least for outputs
+            ! Melt pond surface melt diagnostics (mv - more efficient: grouped into one water volume flux)
+            dh_i_sum_2d(ji,jj,jl) = 0._wp
+            dh_s_mlt_2d(ji,jj,jl) = 0._wp
          END_2D
       ENDDO
@@ -482,4 +491,6 @@
          diag_vsnw(:,:) = diag_vsnw(:,:) &
             &             + SUM(     v_s (:,:,:)          - v_s_b (:,:,:)                  , dim=3 ) * r1_Dt_ice * rhos
+         diag_vpnd(:,:) = diag_vpnd(:,:) &
+            &             + SUM(     v_ip + v_il          - v_ip_b - v_il_b                , dim=3 ) * r1_Dt_ice * rhow
          !
          IF( kn == 2 )    CALL iom_put ( 'hfxdhc' , diag_heat )   ! output of heat trend
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd.F90	(revision 14055)
@@ -166,4 +166,12 @@
          qsb_ice_bot(ji,jj) = rswitch * MIN( qsb_ice_bot(ji,jj), - zqfr_neg * r1_Dt_ice / MAX( at_i(ji,jj), epsi10 ) )
 
+         ! If conditions are always supercooled (such as at the mouth of ice-shelves), then ice grows continuously
+         ! ==> stop ice formation by artificially setting up the turbulent fluxes to 0 when volume > 20m (arbitrary)
+         IF( ( t_bo(ji,jj) - ( sst_m(ji,jj) + rt0 ) ) > 0._wp .AND. vt_i(ji,jj) >= 20._wp ) THEN
+            zqfr               = 0._wp
+            zqfr_pos           = 0._wp
+            qsb_ice_bot(ji,jj) = 0._wp
+         ENDIF
+         !
          ! --- Energy Budget of the leads (qlead, J.m-2) --- !
          !     qlead is the energy received from the atm. in the leads.
@@ -239,5 +247,4 @@
             IF( ln_icedH ) THEN                                     ! --- Growing/Melting --- !
                               CALL ice_thd_dh                           ! Ice-Snow thickness   
-                              CALL ice_thd_pnd                          ! Melt ponds formation
                               CALL ice_thd_ent( e_i_1d(1:npti,:) )      ! Ice enthalpy remapping
             ENDIF
@@ -260,4 +267,7 @@
       IF( ln_icediachk )   CALL ice_cons2D  (1, 'icethd',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
       !                   
+      IF ( ln_pnd .AND. ln_icedH ) &
+         &                    CALL ice_thd_pnd                      ! --- Melt ponds 
+      !
       IF( jpl > 1  )          CALL ice_itd_rem( kt )                ! --- Transport ice between thickness categories --- !
       !
@@ -266,5 +276,5 @@
                               CALL ice_cor( kt , 2 )                ! --- Corrections --- !
       !
-      oa_i(:,:,:) = oa_i(:,:,:) + a_i(:,:,:) * rdt_ice              ! ice natural aging incrementation     
+      oa_i(:,:,:) = oa_i(:,:,:) + a_i(:,:,:) * rDt_ice              ! ice natural aging incrementation     
       !
       ! convergence tests
@@ -377,7 +387,4 @@
             CALL tab_2d_1d( npti, nptidx(1:npti), sz_i_1d(1:npti,jk), sz_i(:,:,jk,kl)  )
          END DO
-         CALL tab_2d_1d( npti, nptidx(1:npti), a_ip_1d     (1:npti), a_ip     (:,:,kl) )
-         CALL tab_2d_1d( npti, nptidx(1:npti), h_ip_1d     (1:npti), h_ip     (:,:,kl) )
-         CALL tab_2d_1d( npti, nptidx(1:npti), h_il_1d     (1:npti), h_il     (:,:,kl) )
          !
          CALL tab_2d_1d( npti, nptidx(1:npti), qprec_ice_1d  (1:npti), qprec_ice            )
@@ -409,5 +416,4 @@
          CALL tab_2d_1d( npti, nptidx(1:npti), wfx_spr_1d (1:npti), wfx_spr          )
          CALL tab_2d_1d( npti, nptidx(1:npti), wfx_lam_1d (1:npti), wfx_lam          )
-         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_pnd_1d (1:npti), wfx_pnd          )
          !
          CALL tab_2d_1d( npti, nptidx(1:npti), sfx_bog_1d (1:npti), sfx_bog          )
@@ -464,6 +470,4 @@
          v_s_1d (1:npti) = h_s_1d (1:npti) * a_i_1d (1:npti)
          sv_i_1d(1:npti) = s_i_1d (1:npti) * v_i_1d (1:npti)
-         v_ip_1d(1:npti) = h_ip_1d(1:npti) * a_ip_1d(1:npti)
-         v_il_1d(1:npti) = h_il_1d(1:npti) * a_ip_1d(1:npti)
          oa_i_1d(1:npti) = o_i_1d (1:npti) * a_i_1d (1:npti)
          
@@ -483,7 +487,4 @@
             CALL tab_1d_2d( npti, nptidx(1:npti), sz_i_1d(1:npti,jk), sz_i(:,:,jk,kl)  )
          END DO
-         CALL tab_1d_2d( npti, nptidx(1:npti), a_ip_1d     (1:npti), a_ip     (:,:,kl) )
-         CALL tab_1d_2d( npti, nptidx(1:npti), h_ip_1d     (1:npti), h_ip     (:,:,kl) )
-         CALL tab_1d_2d( npti, nptidx(1:npti), h_il_1d     (1:npti), h_il     (:,:,kl) )
          !
          CALL tab_1d_2d( npti, nptidx(1:npti), wfx_snw_sni_1d(1:npti), wfx_snw_sni )
@@ -501,5 +502,4 @@
          CALL tab_1d_2d( npti, nptidx(1:npti), wfx_spr_1d (1:npti), wfx_spr        )
          CALL tab_1d_2d( npti, nptidx(1:npti), wfx_lam_1d (1:npti), wfx_lam        )
-         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_pnd_1d (1:npti), wfx_pnd        )
          !
          CALL tab_1d_2d( npti, nptidx(1:npti), sfx_bog_1d (1:npti), sfx_bog        )
@@ -529,4 +529,7 @@
          CALL tab_1d_2d( npti, nptidx(1:npti), cnd_ice_1d(1:npti), cnd_ice(:,:,kl) )
          CALL tab_1d_2d( npti, nptidx(1:npti), t1_ice_1d (1:npti), t1_ice (:,:,kl) )
+         ! Melt ponds
+         CALL tab_1d_2d( npti, nptidx(1:npti), dh_i_sum  (1:npti) , dh_i_sum_2d(:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), dh_s_mlt  (1:npti) , dh_s_mlt_2d(:,:,kl) )
          ! SIMIP diagnostics         
          CALL tab_1d_2d( npti, nptidx(1:npti), t_si_1d       (1:npti), t_si       (:,:,kl) )
@@ -537,6 +540,4 @@
          CALL tab_1d_2d( npti, nptidx(1:npti), v_s_1d (1:npti), v_s (:,:,kl) )
          CALL tab_1d_2d( npti, nptidx(1:npti), sv_i_1d(1:npti), sv_i(:,:,kl) )
-         CALL tab_1d_2d( npti, nptidx(1:npti), v_ip_1d(1:npti), v_ip(:,:,kl) )
-         CALL tab_1d_2d( npti, nptidx(1:npti), v_il_1d(1:npti), v_il(:,:,kl) )
          CALL tab_1d_2d( npti, nptidx(1:npti), oa_i_1d(1:npti), oa_i(:,:,kl) )
          ! check convergence of heat diffusion scheme
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_dh.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_dh.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_dh.F90	(revision 14055)
@@ -55,4 +55,7 @@
       !!                - Snow ice formation
       !!
+      !! ** Note     :  h=max(0,h+dh) are often used to ensure positivity of h.
+      !!                very small negative values can occur otherwise (e.g. -1.e-20)
+      !!
       !! References : Bitz and Lipscomb, 1999, J. Geophys. Res.
       !!              Fichefet T. and M. Maqueda 1997, J. Geophys. Res., 102(C6), 12609-12646   
@@ -79,5 +82,4 @@
       REAL(wp) ::   zfmdt        ! exchange mass flux x time step (J/m2), >0 towards the ocean
 
-      REAL(wp), DIMENSION(jpij) ::   zqprec      ! energy of fallen snow                       (J.m-3)
       REAL(wp), DIMENSION(jpij) ::   zq_top      ! heat for surface ablation                   (J.m-2)
       REAL(wp), DIMENSION(jpij) ::   zq_bot      ! heat for bottom ablation                    (J.m-2)
@@ -85,15 +87,11 @@
       REAL(wp), DIMENSION(jpij) ::   zf_tt       ! Heat budget to determine melting or freezing(W.m-2)
       REAL(wp), DIMENSION(jpij) ::   zevap_rema  ! remaining mass flux from sublimation        (kg.m-2)
-
-      REAL(wp), DIMENSION(jpij) ::   zdh_s_mel   ! snow melt 
-      REAL(wp), DIMENSION(jpij) ::   zdh_s_pre   ! snow precipitation 
-      REAL(wp), DIMENSION(jpij) ::   zdh_s_sub   ! snow sublimation
-
-      REAL(wp), DIMENSION(jpij,nlay_s) ::   zh_s      ! snw layer thickness
-      REAL(wp), DIMENSION(jpij,nlay_i) ::   zh_i      ! ice layer thickness
-      REAL(wp), DIMENSION(jpij,nlay_i) ::   zdeltah
-      INTEGER , DIMENSION(jpij,nlay_i) ::   icount    ! number of layers vanished by melting 
-
+      REAL(wp), DIMENSION(jpij) ::   zdeltah     
       REAL(wp), DIMENSION(jpij) ::   zsnw        ! distribution of snow after wind blowing
+
+      INTEGER , DIMENSION(jpij,nlay_i)     ::   icount    ! number of layers vanishing by melting 
+      REAL(wp), DIMENSION(jpij,0:nlay_i+1) ::   zh_i      ! ice layer thickness (m)
+      REAL(wp), DIMENSION(jpij,0:nlay_s  ) ::   zh_s      ! snw layer thickness (m)
+      REAL(wp), DIMENSION(jpij,0:nlay_s  ) ::   ze_s      ! snw layer enthalpy (J.m-3)
 
       REAL(wp) ::   zswitch_sal
@@ -108,11 +106,23 @@
       END SELECT
 
-      ! initialize layer thicknesses and enthalpies
+      ! initialize ice layer thicknesses and enthalpies
+      eh_i_old(1:npti,0:nlay_i+1) = 0._wp
       h_i_old (1:npti,0:nlay_i+1) = 0._wp
-      eh_i_old(1:npti,0:nlay_i+1) = 0._wp
+      zh_i    (1:npti,0:nlay_i+1) = 0._wp
       DO jk = 1, nlay_i
          DO ji = 1, npti
+            eh_i_old(ji,jk) = h_i_1d(ji) * r1_nlay_i * e_i_1d(ji,jk)
             h_i_old (ji,jk) = h_i_1d(ji) * r1_nlay_i
-            eh_i_old(ji,jk) = e_i_1d(ji,jk) * h_i_old(ji,jk)
+            zh_i    (ji,jk) = h_i_1d(ji) * r1_nlay_i
+         END DO
+      END DO
+      !
+      ! initialize snw layer thicknesses and enthalpies
+      zh_s(1:npti,0) = 0._wp
+      ze_s(1:npti,0) = 0._wp
+      DO jk = 1, nlay_s
+         DO ji = 1, npti
+            zh_s(ji,jk) = h_s_1d(ji) * r1_nlay_s
+            ze_s(ji,jk) = e_s_1d(ji,jk)
          END DO
       END DO
@@ -141,18 +151,4 @@
          zf_tt(ji)         = qcn_ice_bot_1d(ji) + qsb_ice_bot_1d(ji) + fhld_1d(ji) + qtr_ice_bot_1d(ji) * frq_m_1d(ji) 
          zq_bot(ji)        = MAX( 0._wp, zf_tt(ji) * rDt_ice )
-      END DO
-
-      ! Ice and snow layer thicknesses
-      !-------------------------------
-      DO jk = 1, nlay_i
-         DO ji = 1, npti
-            zh_i(ji,jk) = h_i_1d(ji) * r1_nlay_i
-         END DO
-      END DO
-
-      DO jk = 1, nlay_s
-         DO ji = 1, npti
-            zh_s(ji,jk) = h_s_1d(ji) * r1_nlay_s
-         END DO
       END DO
 
@@ -167,12 +163,11 @@
          DO ji = 1, npti
             IF( t_s_1d(ji,jk) > rt0 ) THEN
-               hfx_res_1d    (ji) = hfx_res_1d    (ji) + e_s_1d(ji,jk) * zh_s(ji,jk) * a_i_1d(ji) * r1_Dt_ice   ! heat flux to the ocean [W.m-2], < 0
-               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) + rhos          * zh_s(ji,jk) * a_i_1d(ji) * r1_Dt_ice   ! mass flux
+               hfx_res_1d    (ji) = hfx_res_1d    (ji) - ze_s(ji,jk) * zh_s(ji,jk) * a_i_1d(ji) * r1_Dt_ice   ! heat flux to the ocean [W.m-2], < 0
+               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) + rhos        * zh_s(ji,jk) * a_i_1d(ji) * r1_Dt_ice   ! mass flux
                ! updates
-               dh_s_mlt(ji)    = dh_s_mlt(ji) - zh_s(ji,jk)
-               h_s_1d  (ji)    = h_s_1d(ji) - zh_s(ji,jk)
+               dh_s_mlt(ji)    =             dh_s_mlt(ji) - zh_s(ji,jk)
+               h_s_1d  (ji)    = MAX( 0._wp, h_s_1d  (ji) - zh_s(ji,jk) )
                zh_s    (ji,jk) = 0._wp
-               e_s_1d  (ji,jk) = 0._wp
-               t_s_1d  (ji,jk) = rt0
+               ze_s    (ji,jk) = 0._wp
             END IF
          END DO
@@ -181,69 +176,40 @@
       ! Snow precipitation
       !-------------------
-      CALL ice_var_snwblow( 1.0_wp - at_i_1d(1:npti), zsnw(1:npti) )   ! snow distribution over ice after wind blowing
-
-      zdeltah(1:npti,:) = 0._wp
+      CALL ice_var_snwblow( 1._wp - at_i_1d(1:npti), zsnw(1:npti) )   ! snow distribution over ice after wind blowing
+
       DO ji = 1, npti
          IF( sprecip_1d(ji) > 0._wp ) THEN
+            zh_s(ji,0) = zsnw(ji) * sprecip_1d(ji) * rDt_ice * r1_rhos / at_i_1d(ji)   ! thickness of precip
+            ze_s(ji,0) = MAX( 0._wp, - qprec_ice_1d(ji) )                              ! enthalpy of the precip (>0, J.m-3)
             !
-            ! --- precipitation ---
-            zdh_s_pre (ji) = zsnw(ji) * sprecip_1d(ji) * rDt_ice * r1_rhos / at_i_1d(ji)   ! thickness change
-            zqprec    (ji) = - qprec_ice_1d(ji)                                             ! enthalpy of the precip (>0, J.m-3)
+            hfx_spr_1d(ji) = hfx_spr_1d(ji) + ze_s(ji,0) * zh_s(ji,0) * a_i_1d(ji) * r1_Dt_ice   ! heat flux from snow precip (>0, W.m-2)
+            wfx_spr_1d(ji) = wfx_spr_1d(ji) - rhos       * zh_s(ji,0) * a_i_1d(ji) * r1_Dt_ice   ! mass flux, <0
             !
-            hfx_spr_1d(ji) = hfx_spr_1d(ji) + zdh_s_pre(ji) * a_i_1d(ji) * zqprec(ji)    * r1_Dt_ice   ! heat flux from snow precip (>0, W.m-2)
-            wfx_spr_1d(ji) = wfx_spr_1d(ji) - rhos          * a_i_1d(ji) * zdh_s_pre(ji) * r1_Dt_ice   ! mass flux, <0
-            
-            ! --- melt of falling snow ---
-            rswitch              = MAX( 0._wp , SIGN( 1._wp , zqprec(ji) - epsi20 ) )
-            zdeltah       (ji,1) = - rswitch * zq_top(ji) / MAX( zqprec(ji) , epsi20 )   ! thickness change
-            zdeltah       (ji,1) = MAX( - zdh_s_pre(ji), zdeltah(ji,1) )                 ! bound melting 
-            hfx_snw_1d    (ji)   = hfx_snw_1d    (ji) - zdeltah(ji,1) * a_i_1d(ji) * zqprec(ji)    * r1_Dt_ice   ! heat used to melt snow (W.m-2, >0)
-            wfx_snw_sum_1d(ji)   = wfx_snw_sum_1d(ji) - rhos          * a_i_1d(ji) * zdeltah(ji,1) * r1_Dt_ice   ! snow melting only = water into the ocean (then without snow precip), >0
-            
-            ! updates available heat + precipitations after melting
-            dh_s_mlt (ji) = dh_s_mlt(ji) + zdeltah(ji,1)
-            zq_top   (ji) = MAX( 0._wp , zq_top (ji) + zdeltah(ji,1) * zqprec(ji) )      
-            zdh_s_pre(ji) = zdh_s_pre(ji) + zdeltah(ji,1)
-            
             ! update thickness
-            h_s_1d(ji) = MAX( 0._wp , h_s_1d(ji) + zdh_s_pre(ji) )
-            !
-         ELSE
-            !
-            zdh_s_pre(ji) = 0._wp
-            zqprec   (ji) = 0._wp
-            !
+            h_s_1d(ji) = h_s_1d(ji) + zh_s(ji,0)
          ENDIF
-      END DO
-
-      ! recalculate snow layers
-      DO jk = 1, nlay_s
-         DO ji = 1, npti
-            zh_s(ji,jk) = h_s_1d(ji) * r1_nlay_s
-         END DO
       END DO
 
       ! Snow melting
       ! ------------
-      ! If heat still available (zq_top > 0), then melt more snow
-      zdeltah(1:npti,:) = 0._wp
-      zdh_s_mel(1:npti) = 0._wp
-      DO jk = 1, nlay_s
+      ! If heat still available (zq_top > 0)
+      ! then all snw precip has been melted and we need to melt more snow
+      DO jk = 0, nlay_s
          DO ji = 1, npti
             IF( zh_s(ji,jk) > 0._wp .AND. zq_top(ji) > 0._wp ) THEN
                !
-               rswitch          = MAX( 0._wp, SIGN( 1._wp, e_s_1d(ji,jk) - epsi20 ) )
-               zdeltah  (ji,jk) = - rswitch * zq_top(ji) / MAX( e_s_1d(ji,jk), epsi20 )   ! thickness change
-               zdeltah  (ji,jk) = MAX( zdeltah(ji,jk) , - zh_s(ji,jk) )                   ! bound melting
-               zdh_s_mel(ji)    = zdh_s_mel(ji) + zdeltah(ji,jk)
-               
-               hfx_snw_1d(ji)     = hfx_snw_1d(ji)     - zdeltah(ji,jk) * a_i_1d(ji) * e_s_1d (ji,jk) * r1_Dt_ice   ! heat used to melt snow(W.m-2, >0)
-               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) - rhos           * a_i_1d(ji) * zdeltah(ji,jk) * r1_Dt_ice   ! snow melting only = water into the ocean (then without snow precip)
+               rswitch = MAX( 0._wp , SIGN( 1._wp , ze_s(ji,jk) - epsi20 ) )
+               zdum    = - rswitch * zq_top(ji) / MAX( ze_s(ji,jk), epsi20 )   ! thickness change
+               zdum    = MAX( zdum , - zh_s(ji,jk) )                           ! bound melting
+               
+               hfx_snw_1d    (ji) = hfx_snw_1d    (ji) - ze_s(ji,jk) * zdum * a_i_1d(ji) * r1_Dt_ice   ! heat used to melt snow(W.m-2, >0)
+               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) - rhos        * zdum * a_i_1d(ji) * r1_Dt_ice   ! snow melting only = water into the ocean
                
                ! updates available heat + thickness
-               dh_s_mlt(ji)    = dh_s_mlt(ji) + zdeltah(ji,jk)
-               zq_top  (ji)    = MAX( 0._wp , zq_top(ji) + zdeltah(ji,jk) * e_s_1d(ji,jk) )
-               h_s_1d  (ji)    = MAX( 0._wp , h_s_1d(ji) + zdeltah(ji,jk) )
-               zh_s    (ji,jk) = MAX( 0._wp , zh_s(ji,jk) + zdeltah(ji,jk) )
+               dh_s_mlt(ji)    =              dh_s_mlt(ji)    + zdum
+               zq_top  (ji)    = MAX( 0._wp , zq_top  (ji)    + zdum * ze_s(ji,jk) )
+               h_s_1d  (ji)    = MAX( 0._wp , h_s_1d  (ji)    + zdum )
+               zh_s    (ji,jk) = MAX( 0._wp , zh_s    (ji,jk) + zdum )
+!!$               IF( zh_s(ji,jk) == 0._wp )   ze_s(ji,jk) = 0._wp
                !
             ENDIF
@@ -255,48 +221,31 @@
       ! qla_ice is always >=0 (upwards), heat goes to the atmosphere, therefore snow sublimates
       !    comment: not counted in mass/heat exchange in iceupdate.F90 since this is an exchange with atm. (not ocean)
-      zdeltah(1:npti,:) = 0._wp
+      zdeltah   (1:npti) = 0._wp ! total snow thickness that sublimates, < 0
+      zevap_rema(1:npti) = 0._wp
       DO ji = 1, npti
          IF( evap_ice_1d(ji) > 0._wp ) THEN
+            zdeltah   (ji) = MAX( - evap_ice_1d(ji) * r1_rhos * rDt_ice, - h_s_1d(ji) )   ! amount of snw that sublimates, < 0            
+            zevap_rema(ji) = MAX( 0._wp, evap_ice_1d(ji) * rDt_ice + zdeltah(ji) * rhos ) ! remaining evap in kg.m-2 (used for ice sublimation later on)
+         ENDIF
+      END DO
+      
+      DO jk = 0, nlay_s
+         DO ji = 1, npti
+            zdum = MAX( -zh_s(ji,jk), zdeltah(ji) ) ! snow layer thickness that sublimates, < 0
             !
-            zdh_s_sub (ji)   = MAX( - h_s_1d(ji) , - evap_ice_1d(ji) * r1_rhos * rDt_ice )
-            zevap_rema(ji)   = evap_ice_1d(ji) * rDt_ice + zdh_s_sub(ji) * rhos   ! remaining evap in kg.m-2 (used for ice melting later on)
-            zdeltah   (ji,1) = MAX( zdh_s_sub(ji), - zdh_s_pre(ji) )
-            
-            hfx_sub_1d    (ji) = hfx_sub_1d(ji) + &   ! Heat flux by sublimation [W.m-2], < 0 (sublimate snow that had fallen, then pre-existing snow)
-               &                 ( zdeltah(ji,1) * zqprec(ji) + ( zdh_s_sub(ji) - zdeltah(ji,1) ) * e_s_1d(ji,1) )  &
-               &                 * a_i_1d(ji) * r1_Dt_ice
-            wfx_snw_sub_1d(ji) = wfx_snw_sub_1d(ji) - rhos * a_i_1d(ji) * zdh_s_sub(ji) * r1_Dt_ice   ! Mass flux by sublimation
-            
-            ! new snow thickness
-            h_s_1d(ji)    =  MAX( 0._wp , h_s_1d(ji) + zdh_s_sub(ji) )
-            ! update precipitations after sublimation and correct sublimation
-            zdh_s_pre(ji) = zdh_s_pre(ji) + zdeltah(ji,1)
-            zdh_s_sub(ji) = zdh_s_sub(ji) - zdeltah(ji,1)
-            !
-         ELSE
-            !
-            zdh_s_sub (ji) = 0._wp
-            zevap_rema(ji) = 0._wp
-            !
-         ENDIF
-      END DO
-      
-      ! --- Update snow diags --- !
-      DO ji = 1, npti
-         dh_s_tot(ji) = zdh_s_mel(ji) + zdh_s_pre(ji) + zdh_s_sub(ji)
-      END DO
-
-      ! Update temperature, energy
-      !---------------------------
-      ! new temp and enthalpy of the snow (remaining snow precip + remaining pre-existing snow)
-      DO jk = 1, nlay_s
-         DO ji = 1,npti
-            rswitch       = MAX( 0._wp , SIGN( 1._wp, h_s_1d(ji) - epsi20 ) )
-            e_s_1d(ji,jk) = rswitch / MAX( h_s_1d(ji), epsi20 ) *            &
-              &             ( ( zdh_s_pre(ji)              ) * zqprec(ji) +  &
-              &               ( h_s_1d(ji) - zdh_s_pre(ji) ) * rhos * ( rcpi * ( rt0 - t_s_1d(ji,jk) ) + rLfus ) )
-         END DO
-      END DO
-      
+            hfx_sub_1d    (ji) = hfx_sub_1d    (ji) + ze_s(ji,jk) * zdum * a_i_1d(ji) * r1_Dt_ice  ! Heat flux of snw that sublimates [W.m-2], < 0
+            wfx_snw_sub_1d(ji) = wfx_snw_sub_1d(ji) - rhos        * zdum * a_i_1d(ji) * r1_Dt_ice  ! Mass flux by sublimation
+
+            ! update thickness
+            h_s_1d(ji)    = MAX( 0._wp , h_s_1d(ji)    + zdum )
+            zh_s  (ji,jk) = MAX( 0._wp , zh_s  (ji,jk) + zdum )
+!!$            IF( zh_s(ji,jk) == 0._wp )   ze_s(ji,jk) = 0._wp
+
+            ! update sublimation left
+            zdeltah(ji) = MIN( zdeltah(ji) - zdum, 0._wp )
+         END DO
+      END DO
+
+      !      
       !                       ! ============ !
       !                       !     Ice      !
@@ -305,5 +254,4 @@
       ! Surface ice melting 
       !--------------------
-      zdeltah(1:npti,:) = 0._wp ! important
       DO jk = 1, nlay_i
          DO ji = 1, npti
@@ -313,20 +261,17 @@
 
                zEi            = - e_i_1d(ji,jk) * r1_rhoi             ! Specific enthalpy of layer k [J/kg, <0]       
-               zdE            = 0._wp                                 ! Specific enthalpy difference (J/kg, <0)
-                                                                      ! set up at 0 since no energy is needed to melt water...(it is already melted)
-               zdeltah(ji,jk) = MIN( 0._wp , - zh_i(ji,jk) )          ! internal melting occurs when the internal temperature is above freezing     
-                                                                      ! this should normally not happen, but sometimes, heat diffusion leads to this
-               zfmdt          = - zdeltah(ji,jk) * rhoi               ! Mass flux x time step > 0
-                         
-               dh_i_itm(ji)   = dh_i_itm(ji) + zdeltah(ji,jk)         ! Cumulate internal melting
-               
-               zfmdt          = - rhoi * zdeltah(ji,jk)               ! Recompute mass flux [kg/m2, >0]
-
-               hfx_res_1d(ji) = hfx_res_1d(ji) + zfmdt * a_i_1d(ji) * zEi * r1_Dt_ice                           ! Heat flux to the ocean [W.m-2], <0
-               !                                                                                                  ice enthalpy zEi is "sent" to the ocean
-               sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_Dt_ice    ! Salt flux
-               !                                                                                                  using s_i_1d and not sz_i_1d(jk) is ok
-               wfx_res_1d(ji) = wfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_Dt_ice                 ! Mass flux
-
+               zdE            =   0._wp                               ! Specific enthalpy difference (J/kg, <0)
+               !                                                          set up at 0 since no energy is needed to melt water...(it is already melted)
+               zdum           = MIN( 0._wp , - zh_i(ji,jk) )          ! internal melting occurs when the internal temperature is above freezing     
+               !                                                          this should normally not happen, but sometimes, heat diffusion leads to this
+               zfmdt          = - zdum * rhoi                         ! Recompute mass flux [kg/m2, >0]
+               !
+               dh_i_itm(ji)   = dh_i_itm(ji) + zdum                   ! Cumulate internal melting
+               !
+               hfx_res_1d(ji) = hfx_res_1d(ji) + zEi  * zfmdt             * a_i_1d(ji) * r1_Dt_ice    ! Heat flux to the ocean [W.m-2], <0
+               !                                                                                          ice enthalpy zEi is "sent" to the ocean
+               wfx_res_1d(ji) = wfx_res_1d(ji) - rhoi * zdum              * a_i_1d(ji) * r1_Dt_ice    ! Mass flux
+               sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * zdum * s_i_1d(ji) * a_i_1d(ji) * r1_Dt_ice    ! Salt flux
+               !                                                                                          using s_i_1d and not sz_i_1d(jk) is ok
             ELSE                                        !-- Surface melting
                
@@ -337,60 +282,60 @@
                zfmdt          = - zq_top(ji) / zdE                    ! Mass flux to the ocean [kg/m2, >0]
                
-               zdeltah(ji,jk) = - zfmdt * r1_rhoi                     ! Melt of layer jk [m, <0]
-               
-               zdeltah(ji,jk) = MIN( 0._wp , MAX( zdeltah(ji,jk) , - zh_i(ji,jk) ) )    ! Melt of layer jk cannot exceed the layer thickness [m, <0]
-               
-               zq_top(ji)      = MAX( 0._wp , zq_top(ji) - zdeltah(ji,jk) * rhoi * zdE ) ! update available heat
-               
-               dh_i_sum(ji)   = dh_i_sum(ji) + zdeltah(ji,jk)         ! Cumulate surface melt
-               
-               zfmdt          = - rhoi * zdeltah(ji,jk)               ! Recompute mass flux [kg/m2, >0]
+               zdum           = - zfmdt * r1_rhoi                     ! Melt of layer jk [m, <0]
+               
+               zdum           = MIN( 0._wp , MAX( zdum , - zh_i(ji,jk) ) )    ! Melt of layer jk cannot exceed the layer thickness [m, <0]
+
+               zq_top(ji)     = MAX( 0._wp , zq_top(ji) - zdum * rhoi * zdE ) ! update available heat
+               
+               dh_i_sum(ji)   = dh_i_sum(ji) + zdum                   ! Cumulate surface melt
+               
+               zfmdt          = - rhoi * zdum                         ! Recompute mass flux [kg/m2, >0]
                
                zQm            = zfmdt * zEw                           ! Energy of the melt water sent to the ocean [J/m2, <0]
                
-               sfx_sum_1d(ji) = sfx_sum_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_Dt_ice    ! Salt flux >0
-               !                                                                                                  using s_i_1d and not sz_i_1d(jk) is ok)
-               hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_Dt_ice                           ! Heat flux [W.m-2], < 0
-               hfx_sum_1d(ji) = hfx_sum_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_Dt_ice                           ! Heat flux used in this process [W.m-2], > 0  
-               ! 
-               wfx_sum_1d(ji) = wfx_sum_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_Dt_ice                 ! Mass flux
-               
+               hfx_thd_1d(ji) = hfx_thd_1d(ji) + zEw  * zfmdt             * a_i_1d(ji) * r1_Dt_ice    ! Heat flux [W.m-2], < 0
+               hfx_sum_1d(ji) = hfx_sum_1d(ji) - zdE  * zfmdt             * a_i_1d(ji) * r1_Dt_ice    ! Heat flux used in this process [W.m-2], > 0  
+               wfx_sum_1d(ji) = wfx_sum_1d(ji) - rhoi * zdum              * a_i_1d(ji) * r1_Dt_ice    ! Mass flux
+               sfx_sum_1d(ji) = sfx_sum_1d(ji) - rhoi * zdum * s_i_1d(ji) * a_i_1d(ji) * r1_Dt_ice    ! Salt flux >0
+               !                                                                                          using s_i_1d and not sz_i_1d(jk) is ok) 
             END IF
-            
+            ! update thickness
+            zh_i(ji,jk) = MAX( 0._wp, zh_i(ji,jk) + zdum )
+            h_i_1d(ji)  = MAX( 0._wp, h_i_1d(ji)  + zdum )
+            !
+            ! update heat content (J.m-2) and layer thickness
+            eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdum * e_i_1d(ji,jk)
+            h_i_old (ji,jk) = h_i_old (ji,jk) + zdum
+            !
+            !
             ! Ice sublimation
             ! ---------------
-            zdum            = MAX( - ( zh_i(ji,jk) + zdeltah(ji,jk) ) , - zevap_rema(ji) * r1_rhoi )
-            zdeltah (ji,jk) = zdeltah (ji,jk) + zdum
-            dh_i_sub(ji)    = dh_i_sub(ji)    + zdum
-            
-            sfx_sub_1d(ji)     = sfx_sub_1d(ji) - rhoi * a_i_1d(ji) * zdum * s_i_1d(ji) * r1_Dt_ice  ! Salt flux >0
-            !                                                                                          clem: flux is sent to the ocean for simplicity
-            !                                                                                                but salt should remain in the ice except
-            !                                                                                                if all ice is melted. => must be corrected
-            hfx_sub_1d(ji)     = hfx_sub_1d(ji) + zdum * e_i_1d(ji,jk) * a_i_1d(ji) * r1_Dt_ice      ! Heat flux [W.m-2], < 0
-
-            wfx_ice_sub_1d(ji) = wfx_ice_sub_1d(ji) - rhoi * a_i_1d(ji) * zdum * r1_Dt_ice           ! Mass flux > 0
-
-            ! update remaining mass flux
-            zevap_rema(ji)  = zevap_rema(ji) + zdum * rhoi
-            
+            zdum               = MAX( - zh_i(ji,jk) , - zevap_rema(ji) * r1_rhoi )
+            !
+            hfx_sub_1d(ji)     = hfx_sub_1d(ji)     + e_i_1d(ji,jk) * zdum              * a_i_1d(ji) * r1_Dt_ice ! Heat flux [W.m-2], < 0
+            wfx_ice_sub_1d(ji) = wfx_ice_sub_1d(ji) - rhoi          * zdum              * a_i_1d(ji) * r1_Dt_ice ! Mass flux > 0
+            sfx_sub_1d(ji)     = sfx_sub_1d(ji)     - rhoi          * zdum * s_i_1d(ji) * a_i_1d(ji) * r1_Dt_ice ! Salt flux >0
+            !                                                                                                      clem: flux is sent to the ocean for simplicity
+            !                                                                                                            but salt should remain in the ice except
+            !                                                                                                            if all ice is melted. => must be corrected
+            ! update remaining mass flux and thickness
+            zevap_rema(ji) = zevap_rema(ji) + zdum * rhoi            
+            zh_i(ji,jk)    = MAX( 0._wp, zh_i(ji,jk) + zdum )
+            h_i_1d(ji)     = MAX( 0._wp, h_i_1d(ji)  + zdum )
+            dh_i_sub(ji)   = dh_i_sub(ji) + zdum
+
+            ! update heat content (J.m-2) and layer thickness
+            eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdum * e_i_1d(ji,jk)
+            h_i_old (ji,jk) = h_i_old (ji,jk) + zdum
+
             ! record which layers have disappeared (for bottom melting) 
             !    => icount=0 : no layer has vanished
             !    => icount=5 : 5 layers have vanished
-            rswitch       = MAX( 0._wp , SIGN( 1._wp , - ( zh_i(ji,jk) + zdeltah(ji,jk) ) ) ) 
+            rswitch       = MAX( 0._wp , SIGN( 1._wp , - zh_i(ji,jk) ) ) 
             icount(ji,jk) = NINT( rswitch )
-            zh_i(ji,jk)   = MAX( 0._wp , zh_i(ji,jk) + zdeltah(ji,jk) )
                         
-            ! update heat content (J.m-2) and layer thickness
-            eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdeltah(ji,jk) * e_i_1d(ji,jk)
-            h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
-         END DO
-      END DO
-      
-      ! update ice thickness
-      DO ji = 1, npti
-         h_i_1d(ji) =  MAX( 0._wp , h_i_1d(ji) + dh_i_sum(ji) + dh_i_itm(ji) + dh_i_sub(ji) )
-      END DO
-
+         END DO
+      END DO
+      
       ! remaining "potential" evap is sent to ocean
       DO ji = 1, npti
@@ -430,29 +375,31 @@
                   &          + zswi2  * 0.26 / ( 0.26 + 0.74 * EXP ( - 724300.0 * zgrr ) )  , 0.5 )
 
-               s_i_new(ji)   = zswitch_sal * zfracs * sss_1d(ji) + ( 1. - zswitch_sal ) * s_i_1d(ji)  ! New ice salinity
-
-               ztmelts       = - rTmlt * s_i_new(ji)                                                  ! New ice melting point (C)
-
-               zt_i_new      = zswitch_sal * t_bo_1d(ji) + ( 1. - zswitch_sal) * t_i_1d(ji, nlay_i)
-               
-               zEi           = rcpi * ( zt_i_new - (ztmelts+rt0) ) &                                  ! Specific enthalpy of forming ice (J/kg, <0)
-                  &            - rLfus * ( 1.0 - ztmelts / ( MIN( zt_i_new - rt0, -epsi10 ) ) ) + rcp  * ztmelts
-
-               zEw           = rcp  * ( t_bo_1d(ji) - rt0 )                                           ! Specific enthalpy of seawater (J/kg, < 0)
-
-               zdE           = zEi - zEw                                                              ! Specific enthalpy difference (J/kg, <0)
-
-               dh_i_bog(ji)  = rDt_ice * MAX( 0._wp , zf_tt(ji) / ( zdE * rhoi ) )
+               s_i_new(ji)    = zswitch_sal * zfracs * sss_1d(ji) + ( 1. - zswitch_sal ) * s_i_1d(ji)  ! New ice salinity
+
+               ztmelts        = - rTmlt * s_i_new(ji)                                                  ! New ice melting point (C)
+
+               zt_i_new       = zswitch_sal * t_bo_1d(ji) + ( 1. - zswitch_sal) * t_i_1d(ji, nlay_i)
+               
+               zEi            = rcpi * ( zt_i_new - (ztmelts+rt0) ) &                                  ! Specific enthalpy of forming ice (J/kg, <0)
+                  &             - rLfus * ( 1.0 - ztmelts / ( MIN( zt_i_new - rt0, -epsi10 ) ) ) + rcp * ztmelts
+
+               zEw            = rcp  * ( t_bo_1d(ji) - rt0 )                                           ! Specific enthalpy of seawater (J/kg, < 0)
+
+               zdE            = zEi - zEw                                                              ! Specific enthalpy difference (J/kg, <0)
+
+               dh_i_bog(ji)   = rDt_ice * MAX( 0._wp , zf_tt(ji) / ( zdE * rhoi ) )
                
             END DO
             ! Contribution to Energy and Salt Fluxes                                    
-            zfmdt          = - rhoi * dh_i_bog(ji)                                                   ! Mass flux x time step (kg/m2, < 0)
+            zfmdt = - rhoi * dh_i_bog(ji)                                                              ! Mass flux x time step (kg/m2, < 0)
             
-            hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_Dt_ice                           ! Heat flux to the ocean [W.m-2], >0
-            hfx_bog_1d(ji) = hfx_bog_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_Dt_ice                           ! Heat flux used in this process [W.m-2], <0
-            
-            sfx_bog_1d(ji) = sfx_bog_1d(ji) - rhoi * a_i_1d(ji) * dh_i_bog(ji) * s_i_new(ji) * r1_Dt_ice     ! Salt flux, <0
-
-            wfx_bog_1d(ji) = wfx_bog_1d(ji) - rhoi * a_i_1d(ji) * dh_i_bog(ji) * r1_Dt_ice                   ! Mass flux, <0
+            hfx_thd_1d(ji) = hfx_thd_1d(ji) + zEw  * zfmdt                      * a_i_1d(ji) * r1_Dt_ice   ! Heat flux to the ocean [W.m-2], >0
+            hfx_bog_1d(ji) = hfx_bog_1d(ji) - zdE  * zfmdt                      * a_i_1d(ji) * r1_Dt_ice   ! Heat flux used in this process [W.m-2], <0          
+            wfx_bog_1d(ji) = wfx_bog_1d(ji) - rhoi * dh_i_bog(ji)               * a_i_1d(ji) * r1_Dt_ice   ! Mass flux, <0
+            sfx_bog_1d(ji) = sfx_bog_1d(ji) - rhoi * dh_i_bog(ji) * s_i_new(ji) * a_i_1d(ji) * r1_Dt_ice   ! Salt flux, <0
+
+            ! update thickness
+            zh_i(ji,nlay_i+1) = zh_i(ji,nlay_i+1) + dh_i_bog(ji)
+            h_i_1d(ji)        = h_i_1d(ji)        + dh_i_bog(ji)
 
             ! update heat content (J.m-2) and layer thickness
@@ -466,5 +413,4 @@
       ! Ice Basal melt
       !---------------
-      zdeltah(1:npti,:) = 0._wp ! important
       DO jk = nlay_i, 1, -1
          DO ji = 1, npti
@@ -475,99 +421,104 @@
                IF( t_i_1d(ji,jk) >= (ztmelts+rt0) ) THEN   !-- Internal melting
 
-                  zEi               = - e_i_1d(ji,jk) * r1_rhoi     ! Specific enthalpy of melting ice (J/kg, <0)
-                  zdE               = 0._wp                         ! Specific enthalpy difference   (J/kg, <0)
-                                                                    !    set up at 0 since no energy is needed to melt water...(it is already melted)
-                  zdeltah   (ji,jk) = MIN( 0._wp , - zh_i(ji,jk) )  ! internal melting occurs when the internal temperature is above freezing     
-                                                                    ! this should normally not happen, but sometimes, heat diffusion leads to this
-
-                  dh_i_itm (ji)     = dh_i_itm(ji) + zdeltah(ji,jk)
-
-                  zfmdt             = - zdeltah(ji,jk) * rhoi      ! Mass flux x time step > 0
-
-                  hfx_res_1d(ji) = hfx_res_1d(ji) + zfmdt * a_i_1d(ji) * zEi * r1_Dt_ice                           ! Heat flux to the ocean [W.m-2], <0
-                  !                                                                                                  ice enthalpy zEi is "sent" to the ocean
-                  sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_Dt_ice    ! Salt flux
-                  !                                                                                                  using s_i_1d and not sz_i_1d(jk) is ok
-                  wfx_res_1d(ji) = wfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_Dt_ice                 ! Mass flux
-
-                  ! update heat content (J.m-2) and layer thickness
-                  eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdeltah(ji,jk) * e_i_1d(ji,jk)
-                  h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
-
+                  zEi            = - e_i_1d(ji,jk) * r1_rhoi     ! Specific enthalpy of melting ice (J/kg, <0)
+                  zdE            = 0._wp                         ! Specific enthalpy difference   (J/kg, <0)
+                  !                                                  set up at 0 since no energy is needed to melt water...(it is already melted)
+                  zdum           = MIN( 0._wp , - zh_i(ji,jk) )  ! internal melting occurs when the internal temperature is above freezing     
+                  !                                                  this should normally not happen, but sometimes, heat diffusion leads to this
+                  dh_i_itm (ji)  = dh_i_itm(ji) + zdum
+                  !
+                  zfmdt          = - zdum * rhoi                 ! Mass flux x time step > 0
+                  !
+                  hfx_res_1d(ji) = hfx_res_1d(ji) + zEi  * zfmdt             * a_i_1d(ji) * r1_Dt_ice   ! Heat flux to the ocean [W.m-2], <0
+                  !                                                                                         ice enthalpy zEi is "sent" to the ocean
+                  wfx_res_1d(ji) = wfx_res_1d(ji) - rhoi * zdum              * a_i_1d(ji) * r1_Dt_ice   ! Mass flux
+                  sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * zdum * s_i_1d(ji) * a_i_1d(ji) * r1_Dt_ice   ! Salt flux
+                  !                                                                                         using s_i_1d and not sz_i_1d(jk) is ok
                ELSE                                        !-- Basal melting
 
-                  zEi             = - e_i_1d(ji,jk) * r1_rhoi                                 ! Specific enthalpy of melting ice (J/kg, <0)
-                  zEw             = rcp * ztmelts                                             ! Specific enthalpy of meltwater (J/kg, <0)
-                  zdE             = zEi - zEw                                                 ! Specific enthalpy difference   (J/kg, <0)
-
-                  zfmdt           = - zq_bot(ji) / zdE                                        ! Mass flux x time step (kg/m2, >0)
-
-                  zdeltah(ji,jk)  = - zfmdt * r1_rhoi                                         ! Gross thickness change
-
-                  zdeltah(ji,jk)  = MIN( 0._wp , MAX( zdeltah(ji,jk), - zh_i(ji,jk) ) )       ! bound thickness change
+                  zEi            = - e_i_1d(ji,jk) * r1_rhoi                       ! Specific enthalpy of melting ice (J/kg, <0)
+                  zEw            = rcp * ztmelts                                   ! Specific enthalpy of meltwater (J/kg, <0)
+                  zdE            = zEi - zEw                                       ! Specific enthalpy difference   (J/kg, <0)
+
+                  zfmdt          = - zq_bot(ji) / zdE                              ! Mass flux x time step (kg/m2, >0)
+
+                  zdum           = - zfmdt * r1_rhoi                               ! Gross thickness change
+
+                  zdum           = MIN( 0._wp , MAX( zdum, - zh_i(ji,jk) ) )       ! bound thickness change
                   
-                  zq_bot(ji)      = MAX( 0._wp , zq_bot(ji) - zdeltah(ji,jk) * rhoi * zdE )   ! update available heat. MAX is necessary for roundup errors
-
-                  dh_i_bom(ji)    = dh_i_bom(ji) + zdeltah(ji,jk)                             ! Update basal melt
-
-                  zfmdt           = - zdeltah(ji,jk) * rhoi                                   ! Mass flux x time step > 0
-
-                  zQm             = zfmdt * zEw                                               ! Heat exchanged with ocean
-
-                  hfx_thd_1d(ji)  = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_Dt_ice                           ! Heat flux to the ocean [W.m-2], <0  
-                  hfx_bom_1d(ji)  = hfx_bom_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_Dt_ice                           ! Heat used in this process [W.m-2], >0  
-
-                  sfx_bom_1d(ji)  = sfx_bom_1d(ji) - rhoi *  a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_Dt_ice   ! Salt flux
-                  !                                                                                                   using s_i_1d and not sz_i_1d(jk) is ok
-                  
-                  wfx_bom_1d(ji)  = wfx_bom_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_Dt_ice                 ! Mass flux
-
-                  ! update heat content (J.m-2) and layer thickness
-                  eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdeltah(ji,jk) * e_i_1d(ji,jk)
-                  h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
+                  zq_bot(ji)     = MAX( 0._wp , zq_bot(ji) - zdum * rhoi * zdE )   ! update available heat. MAX is necessary for roundup errors
+
+                  dh_i_bom(ji)   = dh_i_bom(ji) + zdum                             ! Update basal melt
+
+                  zfmdt          = - zdum * rhoi                                   ! Mass flux x time step > 0
+
+                  zQm            = zfmdt * zEw                                     ! Heat exchanged with ocean
+
+                  hfx_thd_1d(ji) = hfx_thd_1d(ji) + zEw  * zfmdt             * a_i_1d(ji) * r1_Dt_ice   ! Heat flux to the ocean [W.m-2], <0  
+                  hfx_bom_1d(ji) = hfx_bom_1d(ji) - zdE  * zfmdt             * a_i_1d(ji) * r1_Dt_ice   ! Heat used in this process [W.m-2], >0
+                  wfx_bom_1d(ji) = wfx_bom_1d(ji) - rhoi * zdum              * a_i_1d(ji) * r1_Dt_ice   ! Mass flux
+                  sfx_bom_1d(ji) = sfx_bom_1d(ji) - rhoi * zdum * s_i_1d(ji) * a_i_1d(ji) * r1_Dt_ice   ! Salt flux
+                  !                                                                                         using s_i_1d and not sz_i_1d(jk) is ok
                ENDIF
-           
+               ! update thickness
+               zh_i(ji,jk) = MAX( 0._wp, zh_i(ji,jk) + zdum )
+               h_i_1d(ji)  = MAX( 0._wp, h_i_1d(ji)  + zdum )
+               !
+               ! update heat content (J.m-2) and layer thickness
+               eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdum * e_i_1d(ji,jk)
+               h_i_old (ji,jk) = h_i_old (ji,jk) + zdum
             ENDIF
          END DO
       END DO
 
-      ! Update temperature, energy
-      ! --------------------------
-      DO ji = 1, npti
-         h_i_1d(ji) = MAX( 0._wp , h_i_1d(ji) + dh_i_bog(ji) + dh_i_bom(ji) )
-      END DO  
-
-      ! If heat still available then melt more snow
-      !-------------------------------------------
-      zdeltah(1:npti,:) = 0._wp ! important
-      DO ji = 1, npti
-         zq_rema (ji)   = zq_top(ji) + zq_bot(ji) 
-         rswitch        = 1._wp - MAX( 0._wp, SIGN( 1._wp, - h_s_1d(ji) ) )   ! =1 if snow
-         rswitch        = rswitch * MAX( 0._wp, SIGN( 1._wp, e_s_1d(ji,1) - epsi20 ) )
-         zdeltah (ji,1) = - rswitch * zq_rema(ji) / MAX( e_s_1d(ji,1), epsi20 )
-         zdeltah (ji,1) = MIN( 0._wp , MAX( zdeltah(ji,1) , - h_s_1d(ji) ) ) ! bound melting
-         dh_s_tot(ji)   = dh_s_tot(ji) + zdeltah(ji,1)
-         h_s_1d  (ji)   = h_s_1d  (ji) + zdeltah(ji,1)
-        
-         zq_rema(ji)        = zq_rema(ji) + zdeltah(ji,1) * e_s_1d(ji,1)                               ! update available heat (J.m-2)
-         hfx_snw_1d(ji)     = hfx_snw_1d(ji) - zdeltah(ji,1) * a_i_1d(ji) * e_s_1d(ji,1) * r1_Dt_ice   ! Heat used to melt snow, W.m-2 (>0)
-         wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) - rhos * a_i_1d(ji) * zdeltah(ji,1) * r1_Dt_ice       ! Mass flux
-         dh_s_mlt(ji)       = dh_s_mlt(ji) + zdeltah(ji,1)
-         !    
-         ! Remaining heat flux (W.m-2) is sent to the ocean heat budget
-         !!hfx_res_1d(ji) = hfx_res_1d(ji) + ( zq_rema(ji) * a_i_1d(ji) ) * r1_Dt_ice
-
-         IF( ln_icectl .AND. zq_rema(ji) < 0. .AND. lwp ) WRITE(numout,*) 'ALERTE zq_rema <0 = ', zq_rema(ji)
-      END DO
-
-      !
+      ! Remove snow if ice has melted entirely
+      ! --------------------------------------
+      DO jk = 0, nlay_s
+         DO ji = 1,npti
+            IF( h_i_1d(ji) == 0._wp ) THEN
+               ! mass & energy loss to the ocean
+               hfx_res_1d(ji) = hfx_res_1d(ji) - ze_s(ji,jk) * zh_s(ji,jk) * a_i_1d(ji) * r1_Dt_ice  ! heat flux to the ocean [W.m-2], < 0
+               wfx_res_1d(ji) = wfx_res_1d(ji) + rhos        * zh_s(ji,jk) * a_i_1d(ji) * r1_Dt_ice  ! mass flux
+
+               ! update thickness and energy
+               h_s_1d(ji)    = 0._wp
+               ze_s  (ji,jk) = 0._wp
+               zh_s  (ji,jk) = 0._wp
+            ENDIF
+         END DO
+      END DO
+      
+      ! Snow load on ice
+      ! -----------------
+      ! When snow load exceeds Archimede's limit and sst is positive,
+      ! snow-ice formation (next bloc) can lead to negative ice enthalpy.
+      ! Therefore we consider here that this excess of snow falls into the ocean
+      zdeltah(1:npti) = h_s_1d(1:npti) + h_i_1d(1:npti) * (rhoi-rho0) * r1_rhos
+      DO jk = 0, nlay_s
+         DO ji = 1, npti
+            IF( zdeltah(ji) > 0._wp .AND. sst_1d(ji) > 0._wp ) THEN
+               ! snow layer thickness that falls into the ocean
+               zdum = MIN( zdeltah(ji) , zh_s(ji,jk) )
+               ! mass & energy loss to the ocean
+               hfx_res_1d(ji) = hfx_res_1d(ji) - ze_s(ji,jk) * zdum * a_i_1d(ji) * r1_Dt_ice  ! heat flux to the ocean [W.m-2], < 0
+               wfx_res_1d(ji) = wfx_res_1d(ji) + rhos        * zdum * a_i_1d(ji) * r1_Dt_ice  ! mass flux
+               ! update thickness and energy
+               h_s_1d(ji)    = MAX( 0._wp, h_s_1d(ji)  - zdum )
+               zh_s  (ji,jk) = MAX( 0._wp, zh_s(ji,jk) - zdum )
+               ! update snow thickness that still has to fall
+               zdeltah(ji)   = MAX( 0._wp, zdeltah(ji) - zdum )
+            ENDIF
+         END DO
+      END DO
+      
       ! Snow-Ice formation
       ! ------------------
-      ! When snow load excesses Archimede's limit, snow-ice interface goes down under sea-level, 
-      ! flooding of seawater transforms snow into ice dh_snowice is positive for the ice
+      ! When snow load exceeds Archimede's limit, snow-ice interface goes down under sea-level, 
+      ! flooding of seawater transforms snow into ice. Thickness that is transformed is dh_snowice (positive for the ice)
       z1_rho = 1._wp / ( rhos+rho0-rhoi )
+      zdeltah(1:npti) = 0._wp
       DO ji = 1, npti
          !
-         dh_snowice(ji) = MAX(  0._wp , ( rhos * h_s_1d(ji) + (rhoi-rho0) * h_i_1d(ji) ) * z1_rho )
+         dh_snowice(ji) = MAX( 0._wp , ( rhos * h_s_1d(ji) + (rhoi-rho0) * h_i_1d(ji) ) * z1_rho )
 
          h_i_1d(ji)    = h_i_1d(ji) + dh_snowice(ji)
@@ -579,56 +530,163 @@
          zQm            = zfmdt * zEw 
          
-         hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_Dt_ice ! Heat flux
-
-         sfx_sni_1d(ji) = sfx_sni_1d(ji) + sss_1d(ji) * a_i_1d(ji) * zfmdt * r1_Dt_ice ! Salt flux
+         hfx_thd_1d(ji) = hfx_thd_1d(ji) + zEw        * zfmdt * a_i_1d(ji) * r1_Dt_ice ! Heat flux
+         sfx_sni_1d(ji) = sfx_sni_1d(ji) + sss_1d(ji) * zfmdt * a_i_1d(ji) * r1_Dt_ice ! Salt flux
 
          ! Case constant salinity in time: virtual salt flux to keep salinity constant
          IF( nn_icesal /= 2 )  THEN
-            sfx_bri_1d(ji) = sfx_bri_1d(ji) - sss_1d (ji) * a_i_1d(ji) * zfmdt                  * r1_Dt_ice  & ! put back sss_m     into the ocean
-               &                            - s_i_1d(ji)  * a_i_1d(ji) * dh_snowice(ji) * rhoi * r1_Dt_ice     ! and get  rn_icesal from the ocean 
+            sfx_bri_1d(ji) = sfx_bri_1d(ji) - sss_1d(ji) * zfmdt                 * a_i_1d(ji) * r1_Dt_ice  &  ! put back sss_m     into the ocean
+               &                            - s_i_1d(ji) * dh_snowice(ji) * rhoi * a_i_1d(ji) * r1_Dt_ice     ! and get  rn_icesal from the ocean 
          ENDIF
 
          ! Mass flux: All snow is thrown in the ocean, and seawater is taken to replace the volume
-         wfx_sni_1d(ji)     = wfx_sni_1d(ji)     - a_i_1d(ji) * dh_snowice(ji) * rhoi * r1_Dt_ice
-         wfx_snw_sni_1d(ji) = wfx_snw_sni_1d(ji) + a_i_1d(ji) * dh_snowice(ji) * rhos * r1_Dt_ice
+         wfx_sni_1d    (ji) = wfx_sni_1d    (ji) - dh_snowice(ji) * rhoi * a_i_1d(ji) * r1_Dt_ice
+         wfx_snw_sni_1d(ji) = wfx_snw_sni_1d(ji) + dh_snowice(ji) * rhos * a_i_1d(ji) * r1_Dt_ice
+
+         ! update thickness
+         zh_i(ji,0)  = zh_i(ji,0) + dh_snowice(ji)
+         zdeltah(ji) =              dh_snowice(ji)
 
          ! update heat content (J.m-2) and layer thickness
-         eh_i_old(ji,0) = eh_i_old(ji,0) + dh_snowice(ji) * e_s_1d(ji,1) + zfmdt * zEw
          h_i_old (ji,0) = h_i_old (ji,0) + dh_snowice(ji)
-         
-      END DO
-
-      !
-      ! Update temperature, energy
-      ! --------------------------
-      DO ji = 1, npti
-         rswitch     = 1._wp - MAX( 0._wp , SIGN( 1._wp , - h_i_1d(ji) ) ) 
-         t_su_1d(ji) = rswitch * t_su_1d(ji) + ( 1._wp - rswitch ) * rt0
-      END DO
-
+         eh_i_old(ji,0) = eh_i_old(ji,0) + zfmdt * zEw           ! 1st part (sea water enthalpy)
+
+      END DO
+      !
+      DO jk = nlay_s, 0, -1   ! flooding of snow starts from the base
+         DO ji = 1, npti
+            zdum           = MIN( zdeltah(ji), zh_s(ji,jk) )     ! amount of snw that floods, > 0
+            zh_s(ji,jk)    = MAX( 0._wp, zh_s(ji,jk) - zdum )    ! remove some snow thickness
+            eh_i_old(ji,0) = eh_i_old(ji,0) + zdum * ze_s(ji,jk) ! 2nd part (snow enthalpy)
+            ! update dh_snowice
+            zdeltah(ji)    = MAX( 0._wp, zdeltah(ji) - zdum )
+         END DO
+      END DO
+      !
+      !
+!!$      ! --- Update snow diags --- !
+!!$      !!clem: this is wrong. dh_s_tot is not used anyway
+!!$      DO ji = 1, npti
+!!$         dh_s_tot(ji) = dh_s_tot(ji) + dh_s_mlt(ji) + zdeltah(ji) + zdh_s_sub(ji) - dh_snowice(ji)
+!!$      END DO
+      !
+      !
+      ! Remapping of snw enthalpy on a regular grid
+      !--------------------------------------------
+      CALL snw_ent( zh_s, ze_s, e_s_1d )
+      
+      ! recalculate t_s_1d from e_s_1d
       DO jk = 1, nlay_s
          DO ji = 1,npti
-            ! where there is no ice or no snow
-            rswitch = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, - h_s_1d(ji) ) ) ) * ( 1._wp - MAX( 0._wp, SIGN(1._wp, - h_i_1d(ji) ) ) )
-            ! mass & energy loss to the ocean
-            hfx_res_1d(ji) = hfx_res_1d(ji) + ( 1._wp - rswitch ) * &
-               &                              ( e_s_1d(ji,jk) * h_s_1d(ji) * r1_nlay_s * a_i_1d(ji) * r1_Dt_ice )  ! heat flux to the ocean [W.m-2], < 0
-            wfx_res_1d(ji) = wfx_res_1d(ji) + ( 1._wp - rswitch ) * &
-               &                              ( rhos          * h_s_1d(ji) * r1_nlay_s * a_i_1d(ji) * r1_Dt_ice )  ! mass flux
-            ! update energy (mass is updated in the next loop)
-            e_s_1d(ji,jk) = rswitch * e_s_1d(ji,jk)
-            ! recalculate t_s_1d from e_s_1d
-            t_s_1d(ji,jk) = rt0 + rswitch * ( - e_s_1d(ji,jk) * r1_rhos * r1_rcpi + rLfus * r1_rcpi )
-         END DO
-      END DO
+            IF( h_s_1d(ji) > 0._wp ) THEN
+               t_s_1d(ji,jk) = rt0 + ( - e_s_1d(ji,jk) * r1_rhos * r1_rcpi + rLfus * r1_rcpi )
+            ELSE
+               t_s_1d(ji,jk) = rt0
+            ENDIF
+         END DO
+      END DO
+
+      ! Note: remapping of ice enthalpy is done in icethd.F90
 
       ! --- ensure that a_i = 0 & h_s = 0 where h_i = 0 ---
       WHERE( h_i_1d(1:npti) == 0._wp )   
-         a_i_1d(1:npti) = 0._wp
-         h_s_1d(1:npti) = 0._wp
+         a_i_1d (1:npti) = 0._wp
+         h_s_1d (1:npti) = 0._wp
+         t_su_1d(1:npti) = rt0
       END WHERE
-      !
+      
    END SUBROUTINE ice_thd_dh
 
+   SUBROUTINE snw_ent( ph_old, pe_old, pe_new )
+      !!-------------------------------------------------------------------
+      !!               ***   ROUTINE snw_ent  ***
+      !!
+      !! ** Purpose :
+      !!           This routine computes new vertical grids in the snow, 
+      !!           and consistently redistributes temperatures. 
+      !!           Redistribution is made so as to ensure to energy conservation
+      !!
+      !!
+      !! ** Method  : linear conservative remapping
+      !!           
+      !! ** Steps : 1) cumulative integrals of old enthalpies/thicknesses
+      !!            2) linear remapping on the new layers
+      !!
+      !! ------------ cum0(0)                        ------------- cum1(0)
+      !!                                    NEW      -------------
+      !! ------------ cum0(1)               ==>      -------------
+      !!     ...                                     -------------
+      !! ------------                                -------------
+      !! ------------ cum0(nlay_s+1)                 ------------- cum1(nlay_s)
+      !!
+      !!
+      !! References : Bitz & Lipscomb, JGR 99; Vancoppenolle et al., GRL, 2005
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpij,0:nlay_s), INTENT(in   ) ::   ph_old             ! old thicknesses (m)
+      REAL(wp), DIMENSION(jpij,0:nlay_s), INTENT(in   ) ::   pe_old             ! old enthlapies (J.m-3)
+      REAL(wp), DIMENSION(jpij,1:nlay_s), INTENT(inout) ::   pe_new             ! new enthlapies (J.m-3, remapped)
+      !
+      INTEGER  :: ji         !  dummy loop indices
+      INTEGER  :: jk0, jk1   !  old/new layer indices
+      !
+      REAL(wp), DIMENSION(jpij,0:nlay_s+1) ::   zeh_cum0, zh_cum0   ! old cumulative enthlapies and layers interfaces
+      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zeh_cum1, zh_cum1   ! new cumulative enthlapies and layers interfaces
+      REAL(wp), DIMENSION(jpij)            ::   zhnew               ! new layers thicknesses
+      !!-------------------------------------------------------------------
+
+      !--------------------------------------------------------------------------
+      !  1) Cumulative integral of old enthalpy * thickness and layers interfaces
+      !--------------------------------------------------------------------------
+      zeh_cum0(1:npti,0) = 0._wp 
+      zh_cum0 (1:npti,0) = 0._wp
+      DO jk0 = 1, nlay_s+1
+         DO ji = 1, npti
+            zeh_cum0(ji,jk0) = zeh_cum0(ji,jk0-1) + pe_old(ji,jk0-1) * ph_old(ji,jk0-1)
+            zh_cum0 (ji,jk0) = zh_cum0 (ji,jk0-1) + ph_old(ji,jk0-1)
+         END DO
+      END DO
+
+      !------------------------------------
+      !  2) Interpolation on the new layers
+      !------------------------------------
+      ! new layer thickesses
+      DO ji = 1, npti
+         zhnew(ji) = SUM( ph_old(ji,0:nlay_s) ) * r1_nlay_s  
+      END DO
+
+      ! new layers interfaces
+      zh_cum1(1:npti,0) = 0._wp
+      DO jk1 = 1, nlay_s
+         DO ji = 1, npti
+            zh_cum1(ji,jk1) = zh_cum1(ji,jk1-1) + zhnew(ji)
+         END DO
+      END DO
+
+      zeh_cum1(1:npti,0:nlay_s) = 0._wp 
+      ! new cumulative q*h => linear interpolation
+      DO jk0 = 1, nlay_s+1
+         DO jk1 = 1, nlay_s-1
+            DO ji = 1, npti
+               IF( zh_cum1(ji,jk1) <= zh_cum0(ji,jk0) .AND. zh_cum1(ji,jk1) > zh_cum0(ji,jk0-1) ) THEN
+                  zeh_cum1(ji,jk1) = ( zeh_cum0(ji,jk0-1) * ( zh_cum0(ji,jk0) - zh_cum1(ji,jk1  ) ) +  &
+                     &                 zeh_cum0(ji,jk0  ) * ( zh_cum1(ji,jk1) - zh_cum0(ji,jk0-1) ) )  &
+                     &             / ( zh_cum0(ji,jk0) - zh_cum0(ji,jk0-1) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      ! to ensure that total heat content is strictly conserved, set:
+      zeh_cum1(1:npti,nlay_s) = zeh_cum0(1:npti,nlay_s+1) 
+
+      ! new enthalpies
+      DO jk1 = 1, nlay_s
+         DO ji = 1, npti
+            rswitch      = MAX( 0._wp , SIGN( 1._wp , zhnew(ji) - epsi20 ) ) 
+            pe_new(ji,jk1) = rswitch * ( zeh_cum1(ji,jk1) - zeh_cum1(ji,jk1-1) ) / MAX( zhnew(ji), epsi20 )
+         END DO
+      END DO
+      
+   END SUBROUTINE snw_ent
+
+   
 #else
    !!----------------------------------------------------------------------
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_pnd.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_pnd.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_pnd.F90	(revision 14055)
@@ -20,6 +20,8 @@
    USE ice1D          ! sea-ice: thermodynamics variables
    USE icetab         ! sea-ice: 1D <==> 2D transformation
+   USE sbc_ice        ! surface energy budget
    !
    USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
    USE lib_mpp        ! MPP library
    USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
@@ -34,8 +36,32 @@
    INTEGER ::              nice_pnd    ! choice of the type of pond scheme
    !                                   ! associated indices:
-   INTEGER, PARAMETER ::   np_pndNO  = 0   ! No pond scheme
-   INTEGER, PARAMETER ::   np_pndCST = 1   ! Constant ice pond scheme
-   INTEGER, PARAMETER ::   np_pndLEV = 2   ! Level ice pond scheme
-
+   INTEGER, PARAMETER ::   np_pndNO   = 0   ! No pond scheme
+   INTEGER, PARAMETER ::   np_pndCST  = 1   ! Constant ice pond scheme
+   INTEGER, PARAMETER ::   np_pndLEV  = 2   ! Level ice pond scheme
+   INTEGER, PARAMETER ::   np_pndTOPO = 3   ! Level ice pond scheme
+
+   !-------------------------------------------------------------------------- 
+   ! Diagnostics for pond volume per area
+   !
+   ! dV/dt = mlt + drn + lid + rnf
+   ! mlt   = input from surface melting
+   ! drn   = drainage through brine network
+   ! lid   = lid growth & melt
+   ! rnf   = runoff (water directly removed out of surface melting + overflow)
+   !
+   ! In topo mode, the pond water lost because it is in the snow is not included in the budget
+   ! In level mode, all terms are incorporated
+   !
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   diag_dvpn_mlt       ! meltwater pond volume input      [kg/m2/s]
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   diag_dvpn_drn       ! pond volume lost by drainage     [-]
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   diag_dvpn_lid       ! exchange with lid / refreezing   [-]
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   diag_dvpn_rnf       ! meltwater pond lost to runoff    [-]      
+   REAL(wp), ALLOCATABLE, DIMENSION(:)   ::   diag_dvpn_mlt_1d    ! meltwater pond volume input      [-]
+   REAL(wp), ALLOCATABLE, DIMENSION(:)   ::   diag_dvpn_drn_1d    ! pond volume lost by drainage     [-]
+   REAL(wp), ALLOCATABLE, DIMENSION(:)   ::   diag_dvpn_lid_1d    ! exchange with lid / refreezing   [-]
+   REAL(wp), ALLOCATABLE, DIMENSION(:)   ::   diag_dvpn_rnf_1d    ! meltwater pond lost to runoff    [-]
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
    !!----------------------------------------------------------------------
    !! NEMO/ICE 4.0 , NEMO Consortium (2018)
@@ -46,19 +72,81 @@
 
    SUBROUTINE ice_thd_pnd
+
       !!-------------------------------------------------------------------
       !!               ***  ROUTINE ice_thd_pnd   ***
       !!               
       !! ** Purpose :   change melt pond fraction and thickness
-      !!                
+      !!
+      !! ** Note    : Melt ponds affect only radiative transfer for now
+      !!              No heat, no salt.
+      !!              The current diagnostics lacks a contribution from drainage
       !!-------------------------------------------------------------------
+      INTEGER ::   ji, jj, jl        ! loop indices
+      !!-------------------------------------------------------------------
+      
+      ALLOCATE( diag_dvpn_mlt(jpi,jpj), diag_dvpn_lid(jpi,jpj), diag_dvpn_drn(jpi,jpj), diag_dvpn_rnf(jpi,jpj) )
+      ALLOCATE( diag_dvpn_mlt_1d(jpij), diag_dvpn_lid_1d(jpij), diag_dvpn_drn_1d(jpij), diag_dvpn_rnf_1d(jpij) )
       !
-      SELECT CASE ( nice_pnd )
+      diag_dvpn_mlt (:,:) = 0._wp   ;   diag_dvpn_drn (:,:) = 0._wp
+      diag_dvpn_lid (:,:) = 0._wp   ;   diag_dvpn_rnf (:,:) = 0._wp
+      diag_dvpn_mlt_1d(:) = 0._wp   ;   diag_dvpn_drn_1d(:) = 0._wp
+      diag_dvpn_lid_1d(:) = 0._wp   ;   diag_dvpn_rnf_1d(:) = 0._wp
+
+      !-------------------------------------
+      !  Remove ponds where ice has vanished
+      !-------------------------------------
+      at_i(:,:) = SUM( a_i, dim=3 )
       !
-      CASE (np_pndCST)   ;   CALL pnd_CST    !==  Constant melt ponds  ==!
-         !
-      CASE (np_pndLEV)   ;   CALL pnd_LEV    !==  Level ice melt ponds  ==!
-         !
-      END SELECT
+      DO jl = 1, jpl
+         DO_2D( 1, 1, 1, 1 )
+            IF( v_i(ji,jj,jl) < epsi10 .OR. at_i(ji,jj) < epsi10 ) THEN
+               wfx_pnd  (ji,jj)    = wfx_pnd(ji,jj) + ( v_ip(ji,jj,jl) + v_il(ji,jj,jl) ) * rhow * r1_Dt_ice
+               a_ip     (ji,jj,jl) = 0._wp
+               v_ip     (ji,jj,jl) = 0._wp
+               v_il     (ji,jj,jl) = 0._wp
+               h_ip     (ji,jj,jl) = 0._wp
+               h_il     (ji,jj,jl) = 0._wp
+               a_ip_frac(ji,jj,jl) = 0._wp
+            ENDIF
+         END_2D
+      END DO
+      
+      !------------------------------
+      !  Identify grid cells with ice
+      !------------------------------
+      npti = 0   ;   nptidx(:) = 0
+      DO_2D( 1, 1, 1, 1 )
+         IF( at_i(ji,jj) >= epsi10 ) THEN
+            npti = npti + 1
+            nptidx( npti ) = (jj - 1) * jpi + ji
+         ENDIF
+      END_2D
+
+      !------------------------------------
+      !  Select melt pond scheme to be used
+      !------------------------------------
+      IF( npti > 0 ) THEN
+         SELECT CASE ( nice_pnd )
+            !
+         CASE (np_pndCST)   ;   CALL pnd_CST                              !==  Constant melt ponds  ==!
+            !
+         CASE (np_pndLEV)   ;   CALL pnd_LEV                              !==  Level ice melt ponds  ==!
+            !
+         CASE (np_pndTOPO)  ;   CALL pnd_TOPO                             !==  Topographic melt ponds  ==!
+            !
+         END SELECT
+      ENDIF
+
+      !------------------------------------
+      !  Diagnostics
+      !------------------------------------
+      CALL iom_put( 'dvpn_mlt', diag_dvpn_mlt ) ! input from melting
+      CALL iom_put( 'dvpn_lid', diag_dvpn_lid ) ! exchanges with lid
+      CALL iom_put( 'dvpn_drn', diag_dvpn_drn ) ! vertical drainage
+      CALL iom_put( 'dvpn_rnf', diag_dvpn_rnf ) ! runoff + overflow
       !
+      DEALLOCATE( diag_dvpn_mlt   , diag_dvpn_lid   , diag_dvpn_drn   , diag_dvpn_rnf    )
+      DEALLOCATE( diag_dvpn_mlt_1d, diag_dvpn_lid_1d, diag_dvpn_drn_1d, diag_dvpn_rnf_1d )
+      
    END SUBROUTINE ice_thd_pnd 
 
@@ -80,18 +168,45 @@
       !! ** References : Bush, G.W., and Trump, D.J. (2017)
       !!-------------------------------------------------------------------
-      INTEGER  ::   ji        ! loop indices
+      INTEGER  ::   ji, jl    ! loop indices
+      REAL(wp) ::   zdv_pnd   ! Amount of water going into the ponds & lids
       !!-------------------------------------------------------------------
-      DO ji = 1, npti
-         !
-         IF( a_i_1d(ji) > 0._wp .AND. t_su_1d(ji) >= rt0 ) THEN
-            h_ip_1d(ji)      = rn_hpnd    
-            a_ip_1d(ji)      = rn_apnd * a_i_1d(ji)
-            h_il_1d(ji)      = 0._wp    ! no pond lids whatsoever
-         ELSE
-            h_ip_1d(ji)      = 0._wp    
-            a_ip_1d(ji)      = 0._wp
-            h_il_1d(ji)      = 0._wp
-         ENDIF
-         !
+      DO jl = 1, jpl
+         
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d    (1:npti), a_i    (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_su_1d   (1:npti), t_su   (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_ip_1d   (1:npti), a_ip   (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_ip_1d   (1:npti), h_ip   (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_il_1d   (1:npti), h_il   (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_pnd_1d(1:npti), wfx_pnd(:,:)    )
+
+         DO ji = 1, npti
+            !
+            zdv_pnd = ( h_ip_1d(ji) + h_il_1d(ji) ) * a_ip_1d(ji)
+            !
+            IF( a_i_1d(ji) >= 0.01_wp .AND. t_su_1d(ji) >= rt0 ) THEN
+               h_ip_1d(ji)      = rn_hpnd    
+               a_ip_1d(ji)      = rn_apnd * a_i_1d(ji)
+               h_il_1d(ji)      = 0._wp    ! no pond lids whatsoever
+            ELSE
+               h_ip_1d(ji)      = 0._wp    
+               a_ip_1d(ji)      = 0._wp
+               h_il_1d(ji)      = 0._wp
+            ENDIF
+            !
+            v_ip_1d(ji) = h_ip_1d(ji) * a_ip_1d(ji)
+            v_il_1d(ji) = h_il_1d(ji) * a_ip_1d(ji)
+            !
+            zdv_pnd = ( h_ip_1d(ji) + h_il_1d(ji) ) * a_ip_1d(ji) - zdv_pnd
+            wfx_pnd_1d(ji) = wfx_pnd_1d(ji) - zdv_pnd * rhow * r1_Dt_ice
+            !
+         END DO
+
+         CALL tab_1d_2d( npti, nptidx(1:npti), a_ip_1d   (1:npti), a_ip   (:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_ip_1d   (1:npti), h_ip   (:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_il_1d   (1:npti), h_il   (:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_ip_1d   (1:npti), v_ip   (:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_il_1d   (1:npti), v_il   (:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_pnd_1d(1:npti), wfx_pnd(:,:)    )
+
       END DO
       !
@@ -132,9 +247,10 @@
       !!                    if no lids:   Vp = Vp * exp(0.01*MAX(Tp-Tsu,0)/Tp)                      --- from Holland et al 2012 ---
       !!
-      !!              - Flushing:         w = -perm/visc * rho_oce * grav * Hp / Hi                 --- from Flocco et al 2007 ---
-      !!                                     perm = permability of sea-ice
+      !!              - Flushing:         w = -perm/visc * rho_oce * grav * Hp / Hi * flush         --- from Flocco et al 2007 ---
+      !!                                     perm = permability of sea-ice                              + correction from Hunke et al 2012 (flush)
       !!                                     visc = water viscosity
       !!                                     Hp   = height of top of the pond above sea-level
       !!                                     Hi   = ice thickness thru which there is flushing
+      !!                                     flush= correction otherwise flushing is excessive
       !!
       !!              - Corrections:      remove melt ponds when lid thickness is 10 times the pond thickness
@@ -143,12 +259,13 @@
       !!                                  a_ip/a_i = a_ip_frac = h_ip / zaspect
       !!
-      !! ** Tunable parameters : ln_pnd_lids, rn_apnd_max, rn_apnd_min
+      !! ** Tunable parameters : rn_apnd_max, rn_apnd_min, rn_pnd_flush
       !! 
-      !! ** Note       :   mostly stolen from CICE
+      !! ** Note       :   Mostly stolen from CICE but not only. These are between level-ice ponds and CESM ponds. 
       !!
       !! ** References :   Flocco and Feltham (JGR, 2007)
       !!                   Flocco et al       (JGR, 2010)
       !!                   Holland et al      (J. Clim, 2012)
-      !!-------------------------------------------------------------------
+      !!                   Hunke et al        (OM 2012)
+      !!-------------------------------------------------------------------  
       REAL(wp), DIMENSION(nlay_i) ::   ztmp           ! temporary array
       !!
@@ -157,147 +274,1064 @@
       REAL(wp), PARAMETER ::   zvisc   =  1.79e-3_wp  ! water viscosity
       !!
-      REAL(wp) ::   zfr_mlt, zdv_mlt                  ! fraction and volume of available meltwater retained for melt ponding
+      REAL(wp) ::   zfr_mlt, zdv_mlt, zdv_avail       ! fraction and volume of available meltwater retained for melt ponding
       REAL(wp) ::   zdv_frz, zdv_flush                ! Amount of melt pond that freezes, flushes
+      REAL(wp) ::   zdv_pnd                           ! Amount of water going into the ponds & lids
       REAL(wp) ::   zhp                               ! heigh of top of pond lid wrt ssh
       REAL(wp) ::   zv_ip_max                         ! max pond volume allowed
       REAL(wp) ::   zdT                               ! zTp-t_su
-      REAL(wp) ::   zsbr                              ! Brine salinity
+      REAL(wp) ::   zsbr, ztmelts                     ! Brine salinity
       REAL(wp) ::   zperm                             ! permeability of sea ice
       REAL(wp) ::   zfac, zdum                        ! temporary arrays
       REAL(wp) ::   z1_rhow, z1_aspect, z1_Tp         ! inverse
       !!
-      INTEGER  ::   ji, jk                            ! loop indices
+      INTEGER  ::   ji, jk, jl                        ! loop indices
       !!-------------------------------------------------------------------
       z1_rhow   = 1._wp / rhow 
       z1_aspect = 1._wp / zaspect
       z1_Tp     = 1._wp / zTp 
-
-      DO ji = 1, npti
-         !                                                            !----------------------------------------------------!
-         IF( h_i_1d(ji) < rn_himin .OR. a_i_1d(ji) < epsi10 ) THEN    ! Case ice thickness < rn_himin or tiny ice fraction !
-            !                                                         !----------------------------------------------------!
-            !--- Remove ponds on thin ice or tiny ice fractions
-            a_ip_1d(ji)      = 0._wp
-            h_ip_1d(ji)      = 0._wp
-            h_il_1d(ji)      = 0._wp
-            !                                                         !--------------------------------!
-         ELSE                                                         ! Case ice thickness >= rn_himin !
-            !                                                         !--------------------------------!
-            v_ip_1d(ji) = h_ip_1d(ji) * a_ip_1d(ji)   ! retrieve volume from thickness
+      
+      CALL tab_2d_1d( npti, nptidx(1:npti), at_i_1d          (1:npti), at_i          )
+      CALL tab_2d_1d( npti, nptidx(1:npti), wfx_pnd_1d       (1:npti), wfx_pnd       )
+      
+      CALL tab_2d_1d( npti, nptidx(1:npti), diag_dvpn_mlt_1d (1:npti), diag_dvpn_mlt )
+      CALL tab_2d_1d( npti, nptidx(1:npti), diag_dvpn_drn_1d (1:npti), diag_dvpn_drn )
+      CALL tab_2d_1d( npti, nptidx(1:npti), diag_dvpn_lid_1d (1:npti), diag_dvpn_lid )
+      CALL tab_2d_1d( npti, nptidx(1:npti), diag_dvpn_rnf_1d (1:npti), diag_dvpn_rnf )
+
+      DO jl = 1, jpl
+
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d  (1:npti), a_i (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_i_1d  (1:npti), h_i (:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_su_1d (1:npti), t_su(:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_ip_1d (1:npti), a_ip(:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_ip_1d (1:npti), h_ip(:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_il_1d (1:npti), h_il(:,:,jl) )
+
+         CALL tab_2d_1d( npti, nptidx(1:npti), dh_i_sum(1:npti), dh_i_sum_2d(:,:,jl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), dh_s_mlt(1:npti), dh_s_mlt_2d(:,:,jl) )
+
+         DO jk = 1, nlay_i
+            CALL tab_2d_1d( npti, nptidx(1:npti), sz_i_1d(1:npti,jk), sz_i(:,:,jk,jl) )
+            CALL tab_2d_1d( npti, nptidx(1:npti), t_i_1d (1:npti,jk), t_i (:,:,jk,jl) )
+         END DO
+         
+         !-----------------------
+         ! Melt pond calculations
+         !-----------------------
+         DO ji = 1, npti
+            !
+            zdv_pnd = ( h_ip_1d(ji) + h_il_1d(ji) ) * a_ip_1d(ji)
+            !                                                            !----------------------------------------------------!
+            IF( h_i_1d(ji) < rn_himin .OR. a_i_1d(ji) < 0.01_wp ) THEN   ! Case ice thickness < rn_himin or tiny ice fraction !
+               !                                                         !----------------------------------------------------!
+               !--- Remove ponds on thin ice or tiny ice fractions
+               a_ip_1d(ji) = 0._wp
+               h_ip_1d(ji) = 0._wp
+               h_il_1d(ji) = 0._wp
+               !                                                         !--------------------------------!
+            ELSE                                                         ! Case ice thickness >= rn_himin !
+               !                                                         !--------------------------------!
+               v_ip_1d(ji) = h_ip_1d(ji) * a_ip_1d(ji)   ! retrieve volume from thickness
+               v_il_1d(ji) = h_il_1d(ji) * a_ip_1d(ji)
+               !
+               !------------------!
+               ! case ice melting !
+               !------------------!
+               !
+               !--- available meltwater for melt ponding (zdv_avail) ---!
+               zdv_avail = -( dh_i_sum(ji)*rhoi + dh_s_mlt(ji)*rhos ) * z1_rhow * a_i_1d(ji) ! > 0
+               zfr_mlt   = rn_apnd_min + ( rn_apnd_max - rn_apnd_min ) * at_i_1d(ji) !  = ( 1 - r ) = fraction of melt water that is not flushed
+               zdv_mlt   = MAX( 0._wp, zfr_mlt * zdv_avail ) ! max for roundoff errors? 
+               !
+               !--- overflow ---!
+               !
+               ! area driven overflow
+               !    If pond area exceeds zfr_mlt * a_i_1d(ji) then reduce the pond volume
+               !       a_ip_max = zfr_mlt * a_i
+               !       => from zaspect = h_ip / (a_ip / a_i), set v_ip_max as: 
+               zv_ip_max = zfr_mlt**2 * a_i_1d(ji) * zaspect
+               zdv_mlt   = MAX( 0._wp, MIN( zdv_mlt, zv_ip_max - v_ip_1d(ji) ) )
+
+               ! depth driven overflow
+               !    If pond depth exceeds half the ice thickness then reduce the pond volume
+               !       h_ip_max = 0.5 * h_i
+               !       => from zaspect = h_ip / (a_ip / a_i), set v_ip_max as: 
+               zv_ip_max = z1_aspect * a_i_1d(ji) * 0.25 * h_i_1d(ji) * h_i_1d(ji)
+               zdv_mlt   = MAX( 0._wp, MIN( zdv_mlt, zv_ip_max - v_ip_1d(ji) ) )
+
+               !--- Pond growing ---!
+               v_ip_1d(ji) = v_ip_1d(ji) + zdv_mlt
+               !
+               !--- Lid melting ---!
+               IF( ln_pnd_lids )   v_il_1d(ji) = MAX( 0._wp, v_il_1d(ji) - zdv_mlt ) ! must be bounded by 0
+               !
+               !-------------------!
+               ! case ice freezing ! i.e. t_su_1d(ji) < (zTp+rt0)
+               !-------------------!
+               !
+               zdT = MAX( zTp+rt0 - t_su_1d(ji), 0._wp )
+               !
+               !--- Pond contraction (due to refreezing) ---!
+               IF( ln_pnd_lids ) THEN
+                  !
+                  !--- Lid growing and subsequent pond shrinking ---! 
+                  zdv_frz = - 0.5_wp * MAX( 0._wp, -v_il_1d(ji) + & ! Flocco 2010 (eq. 5) solved implicitly as aH**2 + bH + c = 0
+                     &                    SQRT( v_il_1d(ji)**2 + a_ip_1d(ji)**2 * 4._wp * rcnd_i * zdT * rDt_ice / (rLfus * rhow) ) ) ! max for roundoff errors
+
+                  ! Lid growing
+                  v_il_1d(ji) = MAX( 0._wp, v_il_1d(ji) - zdv_frz )
+
+                  ! Pond shrinking
+                  v_ip_1d(ji) = MAX( 0._wp, v_ip_1d(ji) + zdv_frz )
+
+               ELSE
+                  zdv_frz = v_ip_1d(ji) * ( EXP( 0.01_wp * zdT * z1_Tp ) - 1._wp )  ! Holland 2012 (eq. 6) 
+                  ! Pond shrinking
+                  v_ip_1d(ji) = MAX( 0._wp, v_ip_1d(ji) + zdv_frz )
+               ENDIF
+               !
+               !--- Set new pond area and depth ---! assuming linear relation between h_ip and a_ip_frac
+               ! v_ip     = h_ip * a_ip
+               ! a_ip/a_i = a_ip_frac = h_ip / zaspect (cf Holland 2012, fitting SHEBA so that knowing v_ip we can distribute it to a_ip and h_ip)
+               a_ip_1d(ji) = MIN( a_i_1d(ji), SQRT( v_ip_1d(ji) * z1_aspect * a_i_1d(ji) ) ) ! make sure a_ip < a_i
+               h_ip_1d(ji) = zaspect * a_ip_1d(ji) / a_i_1d(ji)
+               !
+
+               !------------------------------------------------!            
+               ! Pond drainage through brine network (flushing) !
+               !------------------------------------------------!
+               ! height of top of the pond above sea-level
+               zhp = ( h_i_1d(ji) * ( rho0 - rhoi ) + h_ip_1d(ji) * ( rho0 - rhow * a_ip_1d(ji) / a_i_1d(ji) ) ) * r1_rho0
+
+               ! Calculate the permeability of the ice (Assur 1958, see Flocco 2010)
+               DO jk = 1, nlay_i
+                  ! MV Assur is inconsistent with SI3
+                  !!zsbr = - 1.2_wp                                  &
+                  !!   &   - 21.8_wp    * ( t_i_1d(ji,jk) - rt0 )    &
+                  !!   &   - 0.919_wp   * ( t_i_1d(ji,jk) - rt0 )**2 &
+                  !!   &   - 0.0178_wp  * ( t_i_1d(ji,jk) - rt0 )**3
+                  !!ztmp(jk) = sz_i_1d(ji,jk) / zsbr
+                  ! MV linear expression more consistent & simpler: zsbr = - ( t_i_1d(ji,jk) - rt0 ) / rTmlt
+                  ztmelts  = -rTmlt * sz_i_1d(ji,jk)
+                  ztmp(jk) = ztmelts / MIN( ztmelts, t_i_1d(ji,jk) - rt0 )
+               END DO
+               zperm = MAX( 0._wp, 3.e-08_wp * MINVAL(ztmp)**3 )
+
+               ! Do the drainage using Darcy's law
+               zdv_flush   = -zperm * rho0 * grav * zhp * rDt_ice / (zvisc * h_i_1d(ji)) * a_ip_1d(ji) * rn_pnd_flush ! zflush comes from Hunke et al. (2012)
+               zdv_flush   = MAX( zdv_flush, -v_ip_1d(ji) ) ! < 0 
+               v_ip_1d(ji) = v_ip_1d(ji) + zdv_flush
+
+               !--- Set new pond area and depth ---! assuming linear relation between h_ip and a_ip_frac
+               a_ip_1d(ji) = MIN( a_i_1d(ji), SQRT( v_ip_1d(ji) * z1_aspect * a_i_1d(ji) ) ) ! make sure a_ip < a_i
+               h_ip_1d(ji) = zaspect * a_ip_1d(ji) / a_i_1d(ji)
+
+               !--- Corrections and lid thickness ---!
+               IF( ln_pnd_lids ) THEN
+                  !--- retrieve lid thickness from volume ---!
+                  IF( a_ip_1d(ji) > 0.01_wp ) THEN   ;   h_il_1d(ji) = v_il_1d(ji) / a_ip_1d(ji)
+                  ELSE                               ;   h_il_1d(ji) = 0._wp
+                  ENDIF
+                  !--- remove ponds if lids are much larger than ponds ---!
+                  IF ( h_il_1d(ji) > h_ip_1d(ji) * 10._wp ) THEN
+                     a_ip_1d(ji) = 0._wp
+                     h_ip_1d(ji) = 0._wp
+                     h_il_1d(ji) = 0._wp
+                  ENDIF
+               ENDIF
+
+               ! diagnostics: dvpnd = mlt+rnf+lid+drn
+               diag_dvpn_mlt_1d(ji) = diag_dvpn_mlt_1d(ji) + rhow *   zdv_avail             * r1_Dt_ice   ! > 0, surface melt input
+               diag_dvpn_rnf_1d(ji) = diag_dvpn_rnf_1d(ji) + rhow * ( zdv_mlt - zdv_avail ) * r1_Dt_ice   ! < 0, runoff
+               diag_dvpn_lid_1d(ji) = diag_dvpn_lid_1d(ji) + rhow *   zdv_frz               * r1_Dt_ice   ! < 0, shrinking
+               diag_dvpn_drn_1d(ji) = diag_dvpn_drn_1d(ji) + rhow *   zdv_flush             * r1_Dt_ice   ! < 0, drainage
+               !
+            ENDIF
+            !
+            v_ip_1d(ji) = h_ip_1d(ji) * a_ip_1d(ji)
             v_il_1d(ji) = h_il_1d(ji) * a_ip_1d(ji)
             !
-            !------------------!
-            ! case ice melting !
-            !------------------!
+            zdv_pnd = ( h_ip_1d(ji) + h_il_1d(ji) ) * a_ip_1d(ji) - zdv_pnd
+            wfx_pnd_1d(ji) = wfx_pnd_1d(ji) - zdv_pnd * rhow * r1_Dt_ice
             !
-            !--- available meltwater for melt ponding ---!
-            zdum    = -( dh_i_sum(ji)*rhoi + dh_s_mlt(ji)*rhos ) * z1_rhow * a_i_1d(ji)
-            zfr_mlt = rn_apnd_min + ( rn_apnd_max - rn_apnd_min ) * at_i_1d(ji) !  = ( 1 - r ) = fraction of melt water that is not flushed
-            zdv_mlt = MAX( 0._wp, zfr_mlt * zdum ) ! max for roundoff errors? 
-            !
-            !--- overflow ---!
-            ! If pond area exceeds zfr_mlt * a_i_1d(ji) then reduce the pond volume
-            !    a_ip_max = zfr_mlt * a_i
-            !    => from zaspect = h_ip / (a_ip / a_i), set v_ip_max as: 
-            zv_ip_max = zfr_mlt**2 * a_i_1d(ji) * zaspect
-            zdv_mlt = MAX( 0._wp, MIN( zdv_mlt, zv_ip_max - v_ip_1d(ji) ) )
-
-            ! If pond depth exceeds half the ice thickness then reduce the pond volume
-            !    h_ip_max = 0.5 * h_i
-            !    => from zaspect = h_ip / (a_ip / a_i), set v_ip_max as: 
-            zv_ip_max = z1_aspect * a_i_1d(ji) * 0.25 * h_i_1d(ji) * h_i_1d(ji)
-            zdv_mlt = MAX( 0._wp, MIN( zdv_mlt, zv_ip_max - v_ip_1d(ji) ) )
-            
-            !--- Pond growing ---!
-            v_ip_1d(ji) = v_ip_1d(ji) + zdv_mlt
-            !
-            !--- Lid melting ---!
-            IF( ln_pnd_lids )   v_il_1d(ji) = MAX( 0._wp, v_il_1d(ji) - zdv_mlt ) ! must be bounded by 0
-            !
-            !--- mass flux ---!
-            IF( zdv_mlt > 0._wp ) THEN
-               zfac = zdv_mlt * rhow * r1_Dt_ice                        ! melt pond mass flux < 0 [kg.m-2.s-1]
-               wfx_pnd_1d(ji) = wfx_pnd_1d(ji) - zfac
-               !
-               zdum = zfac / ( wfx_snw_sum_1d(ji) + wfx_sum_1d(ji) )    ! adjust ice/snow melting flux > 0 to balance melt pond flux
-               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) * (1._wp + zdum)
-               wfx_sum_1d(ji)     = wfx_sum_1d(ji)     * (1._wp + zdum)
-            ENDIF
-
-            !-------------------!
-            ! case ice freezing ! i.e. t_su_1d(ji) < (zTp+rt0)
-            !-------------------!
-            !
-            zdT = MAX( zTp+rt0 - t_su_1d(ji), 0._wp )
-            !
-            !--- Pond contraction (due to refreezing) ---!
-            IF( ln_pnd_lids ) THEN
-               !
-               !--- Lid growing and subsequent pond shrinking ---! 
-               zdv_frz = 0.5_wp * MAX( 0._wp, -v_il_1d(ji) + & ! Flocco 2010 (eq. 5) solved implicitly as aH**2 + bH + c = 0
-                  &                    SQRT( v_il_1d(ji)**2 + a_ip_1d(ji)**2 * 4._wp * rcnd_i * zdT * rdt_ice / (rLfus * rhow) ) ) ! max for roundoff errors
-               
-               ! Lid growing
-               v_il_1d(ji) = MAX( 0._wp, v_il_1d(ji) + zdv_frz )
-               
-               ! Pond shrinking
-               v_ip_1d(ji) = MAX( 0._wp, v_ip_1d(ji) - zdv_frz )
-
-            ELSE
-               ! Pond shrinking
-               v_ip_1d(ji) = v_ip_1d(ji) * EXP( 0.01_wp * zdT * z1_Tp ) ! Holland 2012 (eq. 6)
-            ENDIF
-            !
-            !--- Set new pond area and depth ---! assuming linear relation between h_ip and a_ip_frac
-            ! v_ip     = h_ip * a_ip
-            ! a_ip/a_i = a_ip_frac = h_ip / zaspect (cf Holland 2012, fitting SHEBA so that knowing v_ip we can distribute it to a_ip and h_ip)
-            a_ip_1d(ji)      = MIN( a_i_1d(ji), SQRT( v_ip_1d(ji) * z1_aspect * a_i_1d(ji) ) ) ! make sure a_ip < a_i
-            h_ip_1d(ji)      = zaspect * a_ip_1d(ji) / a_i_1d(ji)
-
-            !---------------!            
-            ! Pond flushing !
-            !---------------!
-            ! height of top of the pond above sea-level
-            zhp = ( h_i_1d(ji) * ( rho0 - rhoi ) + h_ip_1d(ji) * ( rho0 - rhow * a_ip_1d(ji) / a_i_1d(ji) ) ) * r1_rho0
-            
-            ! Calculate the permeability of the ice (Assur 1958, see Flocco 2010)
-            DO jk = 1, nlay_i
-               zsbr = - 1.2_wp                                  &
-                  &   - 21.8_wp    * ( t_i_1d(ji,jk) - rt0 )    &
-                  &   - 0.919_wp   * ( t_i_1d(ji,jk) - rt0 )**2 &
-                  &   - 0.0178_wp  * ( t_i_1d(ji,jk) - rt0 )**3
-               ztmp(jk) = sz_i_1d(ji,jk) / zsbr
-            END DO
-            zperm = MAX( 0._wp, 3.e-08_wp * MINVAL(ztmp)**3 )
-            
-            ! Do the drainage using Darcy's law
-            zdv_flush   = -zperm * rho0 * grav * zhp * rdt_ice / (zvisc * h_i_1d(ji)) * a_ip_1d(ji)
-            zdv_flush   = MAX( zdv_flush, -v_ip_1d(ji) )
-            v_ip_1d(ji) = v_ip_1d(ji) + zdv_flush
-            
-            !--- Set new pond area and depth ---! assuming linear relation between h_ip and a_ip_frac
-            a_ip_1d(ji)      = MIN( a_i_1d(ji), SQRT( v_ip_1d(ji) * z1_aspect * a_i_1d(ji) ) ) ! make sure a_ip < a_i
-            h_ip_1d(ji)      = zaspect * a_ip_1d(ji) / a_i_1d(ji)
-
-            !--- Corrections and lid thickness ---!
-            IF( ln_pnd_lids ) THEN
-               !--- retrieve lid thickness from volume ---!
-               IF( a_ip_1d(ji) > epsi10 ) THEN   ;   h_il_1d(ji) = v_il_1d(ji) / a_ip_1d(ji)
-               ELSE                              ;   h_il_1d(ji) = 0._wp
-               ENDIF
-               !--- remove ponds if lids are much larger than ponds ---!
-               IF ( h_il_1d(ji) > h_ip_1d(ji) * 10._wp ) THEN
-                  a_ip_1d(ji)      = 0._wp
-                  h_ip_1d(ji)      = 0._wp
-                  h_il_1d(ji)      = 0._wp
-               ENDIF
-            ENDIF
-            !
-         ENDIF
-         
+         END DO
+
+         !--------------------------------------------------------------------
+         ! Retrieve 2D arrays
+         !--------------------------------------------------------------------
+         CALL tab_1d_2d( npti, nptidx(1:npti), a_ip_1d(1:npti), a_ip(:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_ip_1d(1:npti), h_ip(:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_il_1d(1:npti), h_il(:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_ip_1d(1:npti), v_ip(:,:,jl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_il_1d(1:npti), v_il(:,:,jl) )
+         !
       END DO
       !
+      CALL tab_1d_2d( npti, nptidx(1:npti), wfx_pnd_1d(1:npti), wfx_pnd )
+      !
+      CALL tab_1d_2d( npti, nptidx(1:npti), diag_dvpn_mlt_1d (1:npti), diag_dvpn_mlt        )
+      CALL tab_1d_2d( npti, nptidx(1:npti), diag_dvpn_drn_1d (1:npti), diag_dvpn_drn        )
+      CALL tab_1d_2d( npti, nptidx(1:npti), diag_dvpn_lid_1d (1:npti), diag_dvpn_lid        )
+      CALL tab_1d_2d( npti, nptidx(1:npti), diag_dvpn_rnf_1d (1:npti), diag_dvpn_rnf        )
+      !
    END SUBROUTINE pnd_LEV
 
+
+
+   SUBROUTINE pnd_TOPO    
+                                         
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE pnd_TOPO  ***
+      !!
+      !! ** Purpose :   Compute melt pond evolution based on the ice
+      !!                topography inferred from the ice thickness distribution
+      !!
+      !! ** Method  :   This code is initially based on Flocco and Feltham
+      !!                (2007) and Flocco et al. (2010). 
+      !!
+      !!                - Calculate available pond water base on surface meltwater
+      !!                - Redistribute water as a function of topography, drain water
+      !!                - Exchange water with the lid
+      !!
+      !! ** Tunable parameters :
+      !!
+      !! ** Note :
+      !!
+      !! ** References
+      !!
+      !!    Flocco, D. and D. L. Feltham, 2007.  A continuum model of melt pond
+      !!    evolution on Arctic sea ice.  J. Geophys. Res. 112, C08016, doi:
+      !!    10.1029/2006JC003836.
+      !!
+      !!    Flocco, D., D. L. Feltham and A. K. Turner, 2010.  Incorporation of
+      !!    a physically based melt pond scheme into the sea ice component of a
+      !!    climate model.  J. Geophys. Res. 115, C08012,
+      !!    doi: 10.1029/2009JC005568.
+      !!
+      !!-------------------------------------------------------------------
+      REAL(wp), PARAMETER :: &   ! shared parameters for topographic melt ponds
+         zTd     = 0.15_wp       , & ! temperature difference for freeze-up (C)
+         zvp_min = 1.e-4_wp          ! minimum pond volume (m)
+
+
+      ! local variables
+      REAL(wp) :: &
+         zdHui,   &      ! change in thickness of ice lid (m)
+         zomega,  &      ! conduction
+         zdTice,  &      ! temperature difference across ice lid (C)
+         zdvice,  &      ! change in ice volume (m)
+         zTavg,   &      ! mean surface temperature across categories (C)
+         zfsurf,  &      ! net heat flux, excluding conduction and transmitted radiation (W/m2)
+         zTp,     &      ! pond freezing temperature (C)
+         zrhoi_L, &      ! volumetric latent heat of sea ice (J/m^3)
+         zfr_mlt, &      ! fraction and volume of available meltwater retained for melt ponding
+         z1_rhow, &      ! inverse water density
+         zv_pnd  , &     ! volume of meltwater contributing to ponds
+         zv_mlt          ! total amount of meltwater produced
+
+      REAL(wp), DIMENSION(jpi,jpj) ::   zvolp, &     !! total melt pond water available before redistribution and drainage
+                                        zvolp_res    !! remaining melt pond water available after drainage
+                                        
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z1_a_i
+
+      INTEGER  ::   ji, jj, jk, jl                    ! loop indices
+
+      INTEGER  ::   i_test
+
+      ! Note
+      ! equivalent for CICE translation
+      ! a_ip      -> apond
+      ! a_ip_frac -> apnd
+
+      CALL ctl_stop( 'STOP', 'icethd_pnd : topographic melt ponds are still an ongoing work' )
+      
+      !---------------------------------------------------------------
+      ! Initialise
+      !---------------------------------------------------------------
+
+      ! Parameters & constants (move to parameters)
+      zrhoi_L   = rhoi * rLfus      ! volumetric latent heat (J/m^3)
+      zTp       = rt0 - 0.15_wp          ! pond freezing point, slightly below 0C (ponds are bid saline)
+      z1_rhow   = 1._wp / rhow 
+
+      ! Set required ice variables (hard-coded here for now)
+!      zfpond(:,:) = 0._wp          ! contributing freshwater flux (?) 
+      
+      at_i (:,:) = SUM( a_i (:,:,:), dim=3 ) ! ice fraction
+      vt_i (:,:) = SUM( v_i (:,:,:), dim=3 ) ! volume per grid area
+      vt_ip(:,:) = SUM( v_ip(:,:,:), dim=3 ) ! pond volume per grid area
+      vt_il(:,:) = SUM( v_il(:,:,:), dim=3 ) ! lid volume per grid area
+      
+      ! thickness
+      WHERE( a_i(:,:,:) > epsi20 )   ;   z1_a_i(:,:,:) = 1._wp / a_i(:,:,:)
+      ELSEWHERE                      ;   z1_a_i(:,:,:) = 0._wp
+      END WHERE
+      h_i(:,:,:) = v_i (:,:,:) * z1_a_i(:,:,:)
+      
+      !---------------------------------------------------------------
+      ! Change 2D to 1D
+      !---------------------------------------------------------------
+      ! MV 
+      ! a less computing-intensive version would have 2D-1D passage here
+      ! use what we have in iceitd.F90 (incremental remapping)
+
+      !--------------------------------------------------------------
+      ! Collect total available pond water volume
+      !--------------------------------------------------------------
+      ! Assuming that meltwater (+rain in principle) runsoff the surface
+      ! Holland et al (2012) suggest that the fraction of runoff decreases with total ice fraction
+      ! I cite her words, they are very talkative
+      ! "grid cells with very little ice cover (and hence more open water area) 
+      ! have a higher runoff fraction to rep- resent the greater proximity of ice to open water."
+      ! "This results in the same runoff fraction r for each ice category within a grid cell"
+      
+      zvolp(:,:) = 0._wp
+
+      DO jl = 1, jpl
+         DO_2D( 1, 1, 1, 1 )
+                 
+               IF ( a_i(ji,jj,jl) > epsi10 ) THEN
+            
+                  !--- Available and contributing meltwater for melt ponding ---!
+                  zv_mlt  = - ( dh_i_sum_2d(ji,jj,jl) * rhoi + dh_s_mlt_2d(ji,jj,jl) * rhos ) &        ! available volume of surface melt water per grid area
+                     &    * z1_rhow * a_i(ji,jj,jl)
+                      ! MV -> could move this directly in ice_thd_dh and get an array (ji,jj,jl) for surface melt water volume per grid area
+                  zfr_mlt = rn_apnd_min + ( rn_apnd_max - rn_apnd_min ) * at_i(ji,jj)                  ! fraction of surface meltwater going to ponds
+                  zv_pnd  = zfr_mlt * zv_mlt                                                           ! contributing meltwater volume for category jl
+
+                  diag_dvpn_mlt(ji,jj) = diag_dvpn_mlt(ji,jj) + zv_mlt * r1_Dt_ice                     ! diags
+                  diag_dvpn_rnf(ji,jj) = diag_dvpn_rnf(ji,jj) + ( 1. - zfr_mlt ) * zv_mlt * r1_Dt_ice   
+
+                  !--- Create possible new ponds
+                  ! if pond does not exist, create new pond over full ice area
+                  !IF ( a_ip_frac(ji,jj,jl) < epsi10 ) THEN
+                  IF ( a_ip(ji,jj,jl) < epsi10 ) THEN
+                     a_ip(ji,jj,jl)       = a_i(ji,jj,jl)
+                     a_ip_frac(ji,jj,jl)  = 1.0_wp    ! pond fraction of sea ice (apnd for CICE)
+                  ENDIF
+                  
+                  !--- Deepen existing ponds with no change in pond fraction, before redistribution and drainage
+                  v_ip(ji,jj,jl) = v_ip(ji,jj,jl) +  zv_pnd                                            ! use pond water to increase thickness
+                  h_ip(ji,jj,jl) = v_ip(ji,jj,jl) / a_ip(ji,jj,jl)
+                  
+                  !--- Total available pond water volume (pre-existing + newly produced)j
+                  zvolp(ji,jj)   = zvolp(ji,jj)   + v_ip(ji,jj,jl) 
+!                 zfpond(ji,jj) = zfpond(ji,jj) + zpond * a_ip_frac(ji,jj,jl) ! useless for now
+                   
+               ENDIF ! a_i
+
+         END_2D
+      END DO ! ji
+                  
+      !--------------------------------------------------------------
+      ! Redistribute and drain water from ponds
+      !--------------------------------------------------------------   
+      CALL ice_thd_pnd_area( zvolp, zvolp_res )
+                                   
+      !--------------------------------------------------------------
+      ! Melt pond lid growth and melt
+      !--------------------------------------------------------------   
+      
+      IF( ln_pnd_lids ) THEN
+
+         DO_2D( 1, 1, 1, 1 )
+
+            IF ( at_i(ji,jj) > 0.01 .AND. hm_i(ji,jj) > rn_himin .AND. vt_ip(ji,jj) > zvp_min * at_i(ji,jj) ) THEN
+                  
+               !--------------------------
+               ! Pond lid growth and melt
+               !--------------------------
+               ! Mean surface temperature
+               zTavg = 0._wp
+               DO jl = 1, jpl
+                  zTavg = zTavg + t_su(ji,jj,jl)*a_i(ji,jj,jl)
+               END DO
+               zTavg = zTavg / a_i(ji,jj,jl) !!! could get a division by zero here
+         
+               DO jl = 1, jpl-1
+            
+                  IF ( v_il(ji,jj,jl) > epsi10 ) THEN
+               
+                     !----------------------------------------------------------------
+                     ! Lid melting: floating upper ice layer melts in whole or part
+                     !----------------------------------------------------------------
+                     ! Use Tsfc for each category
+                     IF ( t_su(ji,jj,jl) > zTp ) THEN
+
+                        zdvice = MIN( dh_i_sum_2d(ji,jj,jl)*a_ip(ji,jj,jl), v_il(ji,jj,jl) )
+                        
+                        IF ( zdvice > epsi10 ) THEN
+                        
+                           v_il (ji,jj,jl) = v_il (ji,jj,jl)   - zdvice
+                           v_ip(ji,jj,jl)  = v_ip(ji,jj,jl)    + zdvice ! MV: not sure i understand dh_i_sum seems counted twice - 
+                                                                        ! as it is already counted in surface melt
+!                          zvolp(ji,jj)     = zvolp(ji,jj)     + zdvice ! pointless to calculate total volume (done in icevar)
+!                          zfpond(ji,jj)    = fpond(ji,jj)     + zdvice ! pointless to follow fw budget (ponds have no fw)
+                     
+                           IF ( v_il(ji,jj,jl) < epsi10 .AND. v_ip(ji,jj,jl) > epsi10) THEN
+                           ! ice lid melted and category is pond covered
+                              v_ip(ji,jj,jl)  = v_ip(ji,jj,jl)  + v_il(ji,jj,jl) 
+!                             zfpond(ji,jj)    = zfpond (ji,jj)    + v_il(ji,jj,jl) 
+                              v_il(ji,jj,jl)   = 0._wp
+                           ENDIF
+                           h_ip(ji,jj,jl) = v_ip(ji,jj,jl) / a_ip(ji,jj,jl) !!! could get a division by zero here
+                           
+                           diag_dvpn_lid(ji,jj) = diag_dvpn_lid(ji,jj) + zdvice   ! diag
+                           
+                        ENDIF
+                        
+                     !----------------------------------------------------------------
+                     ! Freeze pre-existing lid 
+                     !----------------------------------------------------------------
+
+                     ELSE IF ( v_ip(ji,jj,jl) > epsi10 ) THEN ! Tsfcn(i,j,n) <= Tp
+
+                        ! differential growth of base of surface floating ice layer
+                        zdTice = MAX( - t_su(ji,jj,jl) - zTd , 0._wp ) ! > 0   
+                        zomega = rcnd_i * zdTice / zrhoi_L
+                        zdHui  = SQRT( 2._wp * zomega * rDt_ice + ( v_il(ji,jj,jl) / a_i(ji,jj,jl) )**2 ) &
+                               - v_il(ji,jj,jl) / a_i(ji,jj,jl)
+                        zdvice = min( zdHui*a_ip(ji,jj,jl) , v_ip(ji,jj,jl) )
+                  
+                        IF ( zdvice > epsi10 ) THEN
+                           v_il (ji,jj,jl)  = v_il(ji,jj,jl)   + zdvice
+                           v_ip(ji,jj,jl)   = v_ip(ji,jj,jl)   - zdvice
+!                          zvolp(ji,jj)    = zvolp(ji,jj)     - zdvice
+!                          zfpond(ji,jj)   = zfpond(ji,jj)    - zdvice
+                           h_ip(ji,jj,jl)   = v_ip(ji,jj,jl) / a_ip(ji,jj,jl)
+                           
+                           diag_dvpn_lid(ji,jj) = diag_dvpn_lid(ji,jj) - zdvice    ! diag
+                           
+                        ENDIF
+                  
+                     ENDIF ! Tsfcn(i,j,n)
+
+                  !----------------------------------------------------------------
+                  ! Freeze new lids
+                  !----------------------------------------------------------------
+                  !  upper ice layer begins to form
+                  ! note: albedo does not change
+
+                  ELSE ! v_il < epsi10
+                    
+                     ! thickness of newly formed ice
+                     ! the surface temperature of a meltpond is the same as that
+                     ! of the ice underneath (0C), and the thermodynamic surface 
+                     ! flux is the same
+                     
+                     !!! we need net surface energy flux, excluding conduction
+                     !!! fsurf is summed over categories in CICE
+                     !!! we have the category-dependent flux, let us use it ?
+                     zfsurf = qns_ice(ji,jj,jl) + qsr_ice(ji,jj,jl)                     
+                     zdHui  = MAX ( -zfsurf * rDt_ice/zrhoi_L , 0._wp )
+                     zdvice = MIN ( zdHui * a_ip(ji,jj,jl) , v_ip(ji,jj,jl) )
+                     IF ( zdvice > epsi10 ) THEN
+                        v_il (ji,jj,jl)  = v_il(ji,jj,jl)   + zdvice
+                        v_ip(ji,jj,jl)   = v_ip(ji,jj,jl)   - zdvice
+                        
+                        diag_dvpn_lid(ji,jj) = diag_dvpn_lid(ji,jj) - zdvice      ! diag
+!                       zvolp(ji,jj)     = zvolp(ji,jj)     - zdvice
+!                       zfpond(ji,jj)    = zfpond(ji,jj)    - zdvice
+                        h_ip(ji,jj,jl)   = v_ip(ji,jj,jl) / a_ip(ji,jj,jl) ! MV - in principle, this is useless as h_ip is computed in icevar
+                     ENDIF
+               
+                  ENDIF  ! v_il
+            
+               END DO ! jl
+
+            ELSE  ! remove ponds on thin ice
+
+               v_ip(ji,jj,:) = 0._wp
+               v_il(ji,jj,:) = 0._wp
+!              zfpond(ji,jj) = zfpond(ji,jj)- zvolp(ji,jj)
+!		            zvolp(ji,jj)    = 0._wp         
+
+            ENDIF
+
+         END_2D
+
+      ENDIF ! ln_pnd_lids
+
+      !---------------------------------------------------------------
+      ! Clean-up variables (probably duplicates what icevar would do)
+      !---------------------------------------------------------------
+      ! MV comment
+      ! In the ideal world, the lines above should update only v_ip, a_ip, v_il
+      ! icevar should recompute all other variables (if needed at all)
+
+      DO jl = 1, jpl
+
+         DO_2D( 1, 1, 1, 1 )
+
+!              ! zap lids on small ponds
+!              IF ( a_i(ji,jj,jl) > epsi10 .AND. v_ip(ji,jj,jl) < epsi10 &
+!                                          .AND. v_il(ji,jj,jl) > epsi10) THEN
+!                 v_il(ji,jj,jl) = 0._wp ! probably uselesss now since we get zap_small
+!              ENDIF
+      
+               ! recalculate equivalent pond variables
+               IF ( a_ip(ji,jj,jl) > epsi10) THEN
+                  h_ip(ji,jj,jl)      = v_ip(ji,jj,jl) / a_i(ji,jj,jl)
+                  a_ip_frac(ji,jj,jl) = a_ip(ji,jj,jl) / a_i(ji,jj,jl) ! MV in principle, useless as computed in icevar
+                  h_il(ji,jj,jl) = v_il(ji,jj,jl) / a_ip(ji,jj,jl) ! MV in principle, useless as computed in icevar
+               ENDIF
+!                 h_ip(ji,jj,jl)      = 0._wp ! MV in principle, useless as computed in icevar
+!                 h_il(ji,jj,jl)      = 0._wp ! MV in principle, useless as omputed in icevar
+!              ENDIF
+               
+         END_2D
+
+      END DO   ! jl
+
+
+   END SUBROUTINE pnd_TOPO
+
+   
+   SUBROUTINE ice_thd_pnd_area( zvolp , zdvolp )
+
+       !!-------------------------------------------------------------------
+       !!                ***  ROUTINE ice_thd_pnd_area ***
+       !!
+       !! ** Purpose : Given the total volume of available pond water, 
+       !!              redistribute and drain water
+       !!
+       !! ** Method
+       !!
+       !-----------|
+       !           |
+       !           |-----------|
+       !___________|___________|______________________________________sea-level
+       !           |           |
+       !           |           |---^--------|
+       !           |           |   |        |
+       !           |           |   |        |-----------|              |-------
+       !           |           |   | alfan  |           |              |
+       !           |           |   |        |           |--------------|
+       !           |           |   |        |           |              |
+       !---------------------------v-------------------------------------------
+       !           |           |   ^        |           |              |
+       !           |           |   |        |           |--------------|
+       !           |           |   | betan  |           |              |
+       !           |           |   |        |-----------|              |-------
+       !           |           |   |        |
+       !           |           |---v------- |
+       !           |           |
+       !           |-----------|
+       !           |
+       !-----------|
+       !
+       !!
+       !!------------------------------------------------------------------
+       
+       REAL (wp), DIMENSION(jpi,jpj), INTENT(INOUT) :: &
+          zvolp,                                       &  ! total available pond water
+          zdvolp                                          ! remaining meltwater after redistribution
+
+       INTEGER ::  &
+          ns,      &
+          m_index, &
+          permflag
+
+       REAL (wp), DIMENSION(jpl) :: &
+          hicen, &
+          hsnon, &
+          asnon, &
+          alfan, &
+          betan, &
+          cum_max_vol, &
+          reduced_aicen
+
+       REAL (wp), DIMENSION(0:jpl) :: &
+          cum_max_vol_tmp
+
+       REAL (wp) :: &
+          hpond, &
+          drain, &
+          floe_weight, &
+          pressure_head, &
+          hsl_rel, &
+          deltah, &
+          perm, &
+          msno
+
+       REAL (wp), parameter :: &
+          viscosity = 1.79e-3_wp     ! kinematic water viscosity in kg/m/s
+
+      REAL(wp), PARAMETER :: &   ! shared parameters for topographic melt ponds
+         zvp_min = 1.e-4_wp          ! minimum pond volume (m)
+
+      INTEGER  ::   ji, jj, jk, jl                    ! loop indices
+
+       a_ip(:,:,:) = 0._wp
+       h_ip(:,:,:) = 0._wp
+ 
+       DO_2D( 1, 1, 1, 1 )
+ 
+             IF ( at_i(ji,jj) > 0.01 .AND. hm_i(ji,jj) > rn_himin .AND. zvolp(ji,jj) > zvp_min * at_i(ji,jj) ) THEN
+ 
+        !-------------------------------------------------------------------
+        ! initialize
+        !-------------------------------------------------------------------
+ 
+        DO jl = 1, jpl
+ 
+           !----------------------------------------
+           ! compute the effective snow fraction
+           !----------------------------------------
+ 
+           IF (a_i(ji,jj,jl) < epsi10)  THEN
+              hicen(jl) =  0._wp
+              hsnon(jl) =  0._wp
+              reduced_aicen(jl) = 0._wp
+              asnon(jl) = 0._wp         !js: in CICE 5.1.2: make sense as the compiler may not initiate the variables
+           ELSE
+              hicen(jl) = v_i(ji,jj,jl) / a_i(ji,jj,jl)
+              hsnon(jl) = v_s(ji,jj,jl) / a_i(ji,jj,jl)
+              reduced_aicen(jl) = 1._wp ! n=jpl
+ 
+              !js: initial code in NEMO_DEV
+              !IF (n < jpl) reduced_aicen(jl) = aicen(jl) &
+              !                     * (-0.024_wp*hicen(jl) + 0.832_wp)
+ 
+              !js: from CICE 5.1.2: this limit reduced_aicen to 0.2 when hicen is too large
+              IF (jl < jpl) reduced_aicen(jl) = a_i(ji,jj,jl) & 
+                                   * max(0.2_wp,(-0.024_wp*hicen(jl) + 0.832_wp))
+ 
+              asnon(jl) = reduced_aicen(jl)  ! effective snow fraction (empirical)
+              ! MV should check whether this makes sense to have the same effective snow fraction in here
+              ! OLI: it probably doesn't
+           END IF
+ 
+  ! This choice for alfa and beta ignores hydrostatic equilibium of categories.
+  ! Hydrostatic equilibium of the entire ITD is accounted for below, assuming
+  ! a surface topography implied by alfa=0.6 and beta=0.4, and rigidity across all
+  ! categories.  alfa and beta partition the ITD - they are areas not thicknesses!
+  ! Multiplying by hicen, alfan and betan (below) are thus volumes per unit area.
+  ! Here, alfa = 60% of the ice area (and since hice is constant in a category,
+  ! alfan = 60% of the ice volume) in each category lies above the reference line,
+  ! and 40% below. Note: p6 is an arbitrary choice, but alfa+beta=1 is required.
+ 
+  ! MV:
+  ! Note that this choice is not in the original FF07 paper and has been adopted in CICE
+  ! No reason why is explained in the doc, but I guess there is a reason. I'll try to investigate, maybe
+ 
+  ! Where does that choice come from ? => OLI : Coz' Chuck Norris said so...
+ 
+           alfan(jl) = 0.6 * hicen(jl)
+           betan(jl) = 0.4 * hicen(jl)
+ 
+           cum_max_vol(jl)     = 0._wp
+           cum_max_vol_tmp(jl) = 0._wp
+ 
+        END DO ! jpl
+ 
+        cum_max_vol_tmp(0) = 0._wp
+        drain = 0._wp
+        zdvolp(ji,jj) = 0._wp
+ 
+        !----------------------------------------------------------
+        ! Drain overflow water, update pond fraction and volume
+        !----------------------------------------------------------
+ 
+        !--------------------------------------------------------------------------
+        ! the maximum amount of water that can be contained up to each ice category
+        !--------------------------------------------------------------------------
+        ! If melt ponds are too deep to be sustainable given the ITD (OVERFLOW)
+        ! Then the excess volume cum_max_vol(jl) drains out of the system
+        ! It should be added to wfx_pnd_out
+ 
+        DO jl = 1, jpl-1 ! last category can not hold any volume
+ 
+           IF (alfan(jl+1) >= alfan(jl) .AND. alfan(jl+1) > 0._wp ) THEN
+ 
+              ! total volume in level including snow
+              cum_max_vol_tmp(jl) = cum_max_vol_tmp(jl-1) + &
+                 (alfan(jl+1) - alfan(jl)) * sum(reduced_aicen(1:jl))
+ 
+              ! subtract snow solid volumes from lower categories in current level
+              DO ns = 1, jl
+                 cum_max_vol_tmp(jl) = cum_max_vol_tmp(jl) &
+                    - rhos/rhow * &     ! free air fraction that can be filled by water
+                      asnon(ns)  * &    ! effective areal fraction of snow in that category
+                      max(min(hsnon(ns)+alfan(ns)-alfan(jl), alfan(jl+1)-alfan(jl)), 0._wp)
+              END DO
+ 
+           ELSE ! assume higher categories unoccupied
+              cum_max_vol_tmp(jl) = cum_max_vol_tmp(jl-1)
+           END IF
+           !IF (cum_max_vol_tmp(jl) < z0) THEN
+           !   CALL abort_ice('negative melt pond volume')
+           !END IF
+        END DO
+        cum_max_vol_tmp(jpl) = cum_max_vol_tmp(jpl-1)  ! last category holds no volume
+        cum_max_vol  (1:jpl) = cum_max_vol_tmp(1:jpl)
+ 
+        !----------------------------------------------------------------
+        ! is there more meltwater than can be held in the floe?
+        !----------------------------------------------------------------
+        IF (zvolp(ji,jj) >= cum_max_vol(jpl)) THEN
+           drain = zvolp(ji,jj) - cum_max_vol(jpl) + epsi10
+           zvolp(ji,jj) = zvolp(ji,jj) - drain ! update meltwater volume available
+ 
+           diag_dvpn_rnf(ji,jj) = - drain      ! diag - overflow counted in the runoff part (arbitrary choice)
+           
+           zdvolp(ji,jj) = drain         ! this is the drained water
+           IF (zvolp(ji,jj) < epsi10) THEN
+              zdvolp(ji,jj) = zdvolp(ji,jj) + zvolp(ji,jj)
+              zvolp(ji,jj) = 0._wp
+           END IF
+        END IF
+ 
+        ! height and area corresponding to the remaining volume
+        ! routine leaves zvolp unchanged
+        CALL ice_thd_pnd_depth(reduced_aicen, asnon, hsnon, alfan, zvolp(ji,jj), cum_max_vol, hpond, m_index)
+ 
+        DO jl = 1, m_index
+           !h_ip(jl) = hpond - alfan(jl) + alfan(1) ! here oui choulde update
+           !                                         !  volume instead, no ?
+           h_ip(ji,jj,jl) = max((hpond - alfan(jl) + alfan(1)), 0._wp)      !js: from CICE 5.1.2
+           a_ip(ji,jj,jl) = reduced_aicen(jl)
+           ! in practise, pond fraction depends on the empirical snow fraction
+           ! so in turn on ice thickness
+        END DO
+        !zapond = sum(a_ip(1:m_index))     !js: from CICE 5.1.2; not in Icepack1.1.0-6-gac6195d
+ 
+        !------------------------------------------------------------------------
+        ! Drainage through brine network (permeability)
+        !------------------------------------------------------------------------
+        !!! drainage due to ice permeability - Darcy's law
+ 
+        ! sea water level
+        msno = 0._wp 
+        DO jl = 1 , jpl
+          msno = msno + v_s(ji,jj,jl) * rhos
+        END DO
+        floe_weight = ( msno + rhoi*vt_i(ji,jj) + rho0*zvolp(ji,jj) ) / at_i(ji,jj)
+        hsl_rel = floe_weight / rho0 &
+                - ( ( sum(betan(:)*a_i(ji,jj,:)) / at_i(ji,jj) ) + alfan(1) )
+ 
+        deltah = hpond - hsl_rel
+        pressure_head = grav * rho0 * max(deltah, 0._wp)
+ 
+        ! drain if ice is permeable
+        permflag = 0
+ 
+        IF (pressure_head > 0._wp) THEN
+           DO jl = 1, jpl-1
+              IF ( hicen(jl) /= 0._wp ) THEN
+ 
+              !IF (hicen(jl) > 0._wp) THEN           !js: from CICE 5.1.2
+ 
+                 perm = 0._wp ! MV ugly dummy patch
+                 CALL ice_thd_pnd_perm(t_i(ji,jj,:,jl),  sz_i(ji,jj,:,jl), perm) ! bof 
+                 IF (perm > 0._wp) permflag = 1
+ 
+                 drain = perm*a_ip(ji,jj,jl)*pressure_head*rDt_ice / &
+                                          (viscosity*hicen(jl))
+                 zdvolp(ji,jj) = zdvolp(ji,jj) + min(drain, zvolp(ji,jj))
+                 zvolp(ji,jj) = max(zvolp(ji,jj) - drain, 0._wp)
+ 
+                 diag_dvpn_drn(ji,jj) = - drain ! diag (could be better coded)
+                 
+                 IF (zvolp(ji,jj) < epsi10) THEN
+                    zdvolp(ji,jj) = zdvolp(ji,jj) + zvolp(ji,jj)
+                    zvolp(ji,jj) = 0._wp
+                 END IF
+             END IF
+          END DO
+ 
+           ! adjust melt pond dimensions
+           IF (permflag > 0) THEN
+              ! recompute pond depth
+             CALL ice_thd_pnd_depth(reduced_aicen, asnon, hsnon, alfan, zvolp(ji,jj), cum_max_vol, hpond, m_index)
+              DO jl = 1, m_index
+                 h_ip(ji,jj,jl) = hpond - alfan(jl) + alfan(1)
+                 a_ip(ji,jj,jl) = reduced_aicen(jl)
+              END DO
+              !zapond = sum(a_ip(1:m_index))       !js: from CICE 5.1.2; not in Icepack1.1.0-6-gac6195d
+           END IF
+        END IF ! pressure_head
+ 
+        !-------------------------------
+        ! remove water from the snow
+        !-------------------------------
+        !------------------------------------------------------------------------
+        ! total melt pond volume in category does not include snow volume
+        ! snow in melt ponds is not melted
+        !------------------------------------------------------------------------
+        
+        ! MV here, it seems that we remove some meltwater from the ponds, but I can't really tell
+        ! how much, so I did not diagnose it
+        ! so if there is a problem here, nobody is going to see it...
+        
+ 
+        ! Calculate pond volume for lower categories
+        DO jl = 1,m_index-1
+           v_ip(ji,jj,jl) = a_ip(ji,jj,jl) * h_ip(ji,jj,jl) & ! what is not in the snow
+                          - (rhos/rhow) * asnon(jl) * min(hsnon(jl), h_ip(ji,jj,jl))
+        END DO
+ 
+        ! Calculate pond volume for highest category = remaining pond volume
+ 
+        ! The following is completely unclear to Martin at least
+        ! Could we redefine properly and recode in a more readable way ?
+ 
+        ! m_index = last category with melt pond
+ 
+        IF (m_index == 1) v_ip(ji,jj,m_index) = zvolp(ji,jj) ! volume of mw in 1st category is the total volume of melt water
+ 
+        IF (m_index > 1) THEN
+          IF (zvolp(ji,jj) > sum( v_ip(ji,jj,1:m_index-1))) THEN
+             v_ip(ji,jj,m_index) = zvolp(ji,jj) - sum(v_ip(ji,jj,1:m_index-1))
+          ELSE
+             v_ip(ji,jj,m_index) = 0._wp 
+             h_ip(ji,jj,m_index) = 0._wp
+             a_ip(ji,jj,m_index) = 0._wp
+             ! If remaining pond volume is negative reduce pond volume of
+             ! lower category
+             IF ( zvolp(ji,jj) + epsi10 < SUM(v_ip(ji,jj,1:m_index-1))) &
+              v_ip(ji,jj,m_index-1) = v_ip(ji,jj,m_index-1) - sum(v_ip(ji,jj,1:m_index-1)) + zvolp(ji,jj)
+          END IF
+        END IF
+ 
+        DO jl = 1,m_index
+           IF (a_ip(ji,jj,jl) > epsi10) THEN
+               h_ip(ji,jj,jl) = v_ip(ji,jj,jl) / a_ip(ji,jj,jl)
+           ELSE
+              zdvolp(ji,jj) = zdvolp(ji,jj) + v_ip(ji,jj,jl)
+              h_ip(ji,jj,jl) = 0._wp 
+              v_ip(ji,jj,jl)  = 0._wp
+              a_ip(ji,jj,jl) = 0._wp
+           END IF
+        END DO
+        DO jl = m_index+1, jpl
+           h_ip(ji,jj,jl) = 0._wp 
+           a_ip(ji,jj,jl) = 0._wp 
+           v_ip(ji,jj,jl) = 0._wp 
+        END DO
+        
+           ENDIF
+
+     END_2D
+
+    END SUBROUTINE ice_thd_pnd_area
+
+
+    SUBROUTINE ice_thd_pnd_depth(aicen, asnon, hsnon, alfan, zvolp, cum_max_vol, hpond, m_index)
+       !!-------------------------------------------------------------------
+       !!                ***  ROUTINE ice_thd_pnd_depth  ***
+       !!
+       !! ** Purpose :   Compute melt pond depth
+       !!-------------------------------------------------------------------
+
+       REAL (wp), DIMENSION(jpl), INTENT(IN) :: &
+          aicen, &
+          asnon, &
+          hsnon, &
+          alfan, &
+          cum_max_vol
+
+       REAL (wp), INTENT(IN) :: &
+          zvolp
+
+       REAL (wp), INTENT(OUT) :: &
+          hpond
+
+       INTEGER, INTENT(OUT) :: &
+          m_index
+
+       INTEGER :: n, ns
+
+       REAL (wp), DIMENSION(0:jpl+1) :: &
+          hitl, &
+          aicetl
+
+       REAL (wp) :: &
+          rem_vol, &
+          area, &
+          vol, &
+          tmp, &
+          z0   = 0.0_wp
+
+       !----------------------------------------------------------------
+       ! hpond is zero if zvolp is zero - have we fully drained?
+       !----------------------------------------------------------------
+
+       IF (zvolp < epsi10) THEN
+        hpond = z0
+        m_index = 0
+       ELSE
+
+        !----------------------------------------------------------------
+        ! Calculate the category where water fills up to
+        !----------------------------------------------------------------
+
+        !----------|
+        !          |
+        !          |
+        !          |----------|                                     -- --
+        !__________|__________|_________________________________________ ^
+        !          |          |             rem_vol     ^                | Semi-filled
+        !          |          |----------|-- -- -- - ---|-- ---- -- -- --v layer
+        !          |          |          |              |
+        !          |          |          |              |hpond
+        !          |          |          |----------|   |     |-------
+        !          |          |          |          |   |     |
+        !          |          |          |          |---v-----|
+        !          |          | m_index  |          |         |
+        !-------------------------------------------------------------
+
+        m_index = 0  ! 1:m_index categories have water in them
+        DO n = 1, jpl
+           IF (zvolp <= cum_max_vol(n)) THEN
+              m_index = n
+              IF (n == 1) THEN
+                 rem_vol = zvolp
+              ELSE
+                 rem_vol = zvolp - cum_max_vol(n-1)
+              END IF
+              exit ! to break out of the loop
+           END IF
+        END DO
+        m_index = min(jpl-1, m_index)
+
+        !----------------------------------------------------------------
+        ! semi-filled layer may have m_index different snow in it
+        !----------------------------------------------------------------
+
+        !-----------------------------------------------------------  ^
+        !                                                             |  alfan(m_index+1)
+        !                                                             |
+        !hitl(3)-->                             |----------|          |
+        !hitl(2)-->                |------------| * * * * *|          |
+        !hitl(1)-->     |----------|* * * * * * |* * * * * |          |
+        !hitl(0)-->-------------------------------------------------  |  ^
+        !                various snow from lower categories          |  |alfa(m_index)
+
+        ! hitl - heights of the snow layers from thinner and current categories
+        ! aicetl - area of each snow depth in this layer
+
+        hitl(:) = z0
+        aicetl(:) = z0
+        DO n = 1, m_index
+           hitl(n)   = max(min(hsnon(n) + alfan(n) - alfan(m_index), &
+                                  alfan(m_index+1) - alfan(m_index)), z0)
+           aicetl(n) = asnon(n)
+
+           aicetl(0) = aicetl(0) + (aicen(n) - asnon(n))
+        END DO
+
+        hitl(m_index+1) = alfan(m_index+1) - alfan(m_index)
+        aicetl(m_index+1) = z0
+
+        !----------------------------------------------------------------
+        ! reorder array according to hitl
+        ! snow heights not necessarily in height order
+        !----------------------------------------------------------------
+
+        DO ns = 1, m_index+1
+           DO n = 0, m_index - ns + 1
+              IF (hitl(n) > hitl(n+1)) THEN ! swap order
+                 tmp = hitl(n)
+                 hitl(n) = hitl(n+1)
+                 hitl(n+1) = tmp
+                 tmp = aicetl(n)
+                 aicetl(n) = aicetl(n+1)
+                 aicetl(n+1) = tmp
+              END IF
+           END DO
+        END DO
+
+        !----------------------------------------------------------------
+        ! divide semi-filled layer into set of sublayers each vertically homogenous
+        !----------------------------------------------------------------
+
+        !hitl(3)----------------------------------------------------------------
+        !                                                       | * * * * * * * *
+        !                                                       |* * * * * * * * *
+        !hitl(2)----------------------------------------------------------------
+        !                                    | * * * * * * * *  | * * * * * * * *
+        !                                    |* * * * * * * * * |* * * * * * * * *
+        !hitl(1)----------------------------------------------------------------
+        !                 | * * * * * * * *  | * * * * * * * *  | * * * * * * * *
+        !                 |* * * * * * * * * |* * * * * * * * * |* * * * * * * * *
+        !hitl(0)----------------------------------------------------------------
+        !    aicetl(0)         aicetl(1)           aicetl(2)          aicetl(3)
+
+        ! move up over layers incrementing volume
+        DO n = 1, m_index+1
+
+           area = sum(aicetl(:)) - &                 ! total area of sub-layer
+                (rhos/rho0) * sum(aicetl(n:jpl+1)) ! area of sub-layer occupied by snow
+
+           vol = (hitl(n) - hitl(n-1)) * area      ! thickness of sub-layer times area
+
+           IF (vol >= rem_vol) THEN  ! have reached the sub-layer with the depth within
+              hpond = rem_vol / area + hitl(n-1) + alfan(m_index) - alfan(1)
+
+              exit
+           ELSE  ! still in sub-layer below the sub-layer with the depth
+              rem_vol = rem_vol - vol
+           END IF
+
+        END DO
+
+       END IF
+
+    END SUBROUTINE ice_thd_pnd_depth
+
+
+    SUBROUTINE ice_thd_pnd_perm(ticen, salin, perm)
+       !!-------------------------------------------------------------------
+       !!                ***  ROUTINE ice_thd_pnd_perm ***
+       !!
+       !! ** Purpose :   Determine the liquid fraction of brine in the ice
+       !!                and its permeability
+       !!-------------------------------------------------------------------
+
+       REAL (wp), DIMENSION(nlay_i), INTENT(IN) :: &
+          ticen,  &     ! internal ice temperature (K)
+          salin         ! salinity (ppt)     !js: ppt according to cice
+
+       REAL (wp), INTENT(OUT) :: &
+          perm      ! permeability
+
+       REAL (wp) ::   &
+          Sbr       ! brine salinity
+
+       REAL (wp), DIMENSION(nlay_i) ::   &
+          Tin, &    ! ice temperature
+          phi       ! liquid fraction
+
+       INTEGER :: k
+
+       !-----------------------------------------------------------------
+       ! Compute ice temperatures from enthalpies using quadratic formula
+       !-----------------------------------------------------------------
+
+       DO k = 1,nlay_i
+          Tin(k) = ticen(k) - rt0   !js: from K to degC
+       END DO
+
+       !-----------------------------------------------------------------
+       ! brine salinity and liquid fraction
+       !-----------------------------------------------------------------
+
+       DO k = 1, nlay_i
+       
+          Sbr    = - Tin(k) / rTmlt ! Consistent expression with SI3 (linear liquidus)
+          ! Best expression to date is that one (Vancoppenolle et al JGR 2019)
+          ! Sbr  = - 18.7 * Tin(k) - 0.519 * Tin(k)**2 - 0.00535 * Tin(k) **3
+          phi(k) = salin(k) / Sbr
+          
+       END DO
+
+       !-----------------------------------------------------------------
+       ! permeability
+       !-----------------------------------------------------------------
+
+       perm = 3.0e-08_wp * (minval(phi))**3 ! Golden et al. (2007)
+
+   END SUBROUTINE ice_thd_pnd_perm
 
    SUBROUTINE ice_thd_pnd_init 
@@ -315,6 +1349,7 @@
       INTEGER  ::   ios, ioptio   ! Local integer
       !!
-      NAMELIST/namthd_pnd/  ln_pnd, ln_pnd_LEV , rn_apnd_min, rn_apnd_max, &
+      NAMELIST/namthd_pnd/  ln_pnd, ln_pnd_LEV , rn_apnd_min, rn_apnd_max, rn_pnd_flush, &
          &                          ln_pnd_CST , rn_apnd, rn_hpnd,         &
+         &                          ln_pnd_TOPO,                           &
          &                          ln_pnd_lids, ln_pnd_alb
       !!-------------------------------------------------------------------
@@ -332,7 +1367,9 @@
          WRITE(numout,*) '   Namelist namicethd_pnd:'
          WRITE(numout,*) '      Melt ponds activated or not                                 ln_pnd       = ', ln_pnd
+         WRITE(numout,*) '         Topographic melt pond scheme                             ln_pnd_TOPO  = ', ln_pnd_TOPO
          WRITE(numout,*) '         Level ice melt pond scheme                               ln_pnd_LEV   = ', ln_pnd_LEV
          WRITE(numout,*) '            Minimum ice fraction that contributes to melt ponds   rn_apnd_min  = ', rn_apnd_min
          WRITE(numout,*) '            Maximum ice fraction that contributes to melt ponds   rn_apnd_max  = ', rn_apnd_max
+         WRITE(numout,*) '            Pond flushing efficiency                              rn_pnd_flush = ', rn_pnd_flush
          WRITE(numout,*) '         Constant ice melt pond scheme                            ln_pnd_CST   = ', ln_pnd_CST
          WRITE(numout,*) '            Prescribed pond fraction                              rn_apnd      = ', rn_apnd
@@ -347,6 +1384,7 @@
       IF( ln_pnd_CST  ) THEN   ;   ioptio = ioptio + 1   ;   nice_pnd = np_pndCST    ;   ENDIF
       IF( ln_pnd_LEV  ) THEN   ;   ioptio = ioptio + 1   ;   nice_pnd = np_pndLEV    ;   ENDIF
+      IF( ln_pnd_TOPO ) THEN   ;   ioptio = ioptio + 1   ;   nice_pnd = np_pndTOPO   ;   ENDIF
       IF( ioptio /= 1 )   &
-         & CALL ctl_stop( 'ice_thd_pnd_init: choose either none (ln_pnd=F) or only one pond scheme (ln_pnd_LEV or ln_pnd_CST)' )
+         & CALL ctl_stop( 'ice_thd_pnd_init: choose either none (ln_pnd=F) or only one pond scheme (ln_pnd_LEV, ln_pnd_CST or ln_pnd_TOPO)' )
       !
       SELECT CASE( nice_pnd )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_zdf_bl99.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_zdf_bl99.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icethd_zdf_bl99.F90	(revision 14055)
@@ -109,29 +109,29 @@
       REAL(wp), DIMENSION(jpij) ::   zdqns_ice_b  ! derivative of the surface flux function
       !
-      REAL(wp), DIMENSION(jpij       )     ::   ztsuold     ! Old surface temperature in the ice
-      REAL(wp), DIMENSION(jpij,nlay_i)     ::   ztiold      ! Old temperature in the ice
-      REAL(wp), DIMENSION(jpij,nlay_s)     ::   ztsold      ! Old temperature in the snow
-      REAL(wp), DIMENSION(jpij,nlay_i)     ::   ztib        ! Temporary temperature in the ice to check the convergence
-      REAL(wp), DIMENSION(jpij,nlay_s)     ::   ztsb        ! Temporary temperature in the snow to check the convergence
-      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   ztcond_i    ! Ice thermal conductivity
-      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   ztcond_i_cp ! copy
-      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zradtr_i    ! Radiation transmitted through the ice
-      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zradab_i    ! Radiation absorbed in the ice
-      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zkappa_i    ! Kappa factor in the ice
-      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zeta_i      ! Eta factor in the ice
-      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zradtr_s    ! Radiation transmited through the snow
-      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zradab_s    ! Radiation absorbed in the snow
-      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zkappa_s    ! Kappa factor in the snow
-      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zeta_s      ! Eta factor in the snow
-      REAL(wp), DIMENSION(jpij)            ::   zkappa_comb ! Combined snow and ice surface conductivity
-      REAL(wp), DIMENSION(jpij,nlay_i+3)   ::   zindterm    ! 'Ind'ependent term
-      REAL(wp), DIMENSION(jpij,nlay_i+3)   ::   zindtbis    ! Temporary 'ind'ependent term
-      REAL(wp), DIMENSION(jpij,nlay_i+3)   ::   zdiagbis    ! Temporary 'dia'gonal term
-      REAL(wp), DIMENSION(jpij,nlay_i+3,3) ::   ztrid       ! Tridiagonal system terms
-      REAL(wp), DIMENSION(jpij)            ::   zq_ini      ! diag errors on heat
-      REAL(wp), DIMENSION(jpij)            ::   zghe        ! G(he), th. conduct enhancement factor, mono-cat
-      REAL(wp), DIMENSION(jpij)            ::   za_s_fra    ! ice fraction covered by snow 
-      REAL(wp), DIMENSION(jpij)            ::   isnow       ! snow presence (1) or not (0) 
-      REAL(wp), DIMENSION(jpij)            ::   isnow_comb  ! snow presence for met-office 
+      REAL(wp), DIMENSION(jpij       )   ::   ztsuold     ! Old surface temperature in the ice
+      REAL(wp), DIMENSION(jpij,nlay_i)   ::   ztiold      ! Old temperature in the ice
+      REAL(wp), DIMENSION(jpij,nlay_s)   ::   ztsold      ! Old temperature in the snow
+      REAL(wp), DIMENSION(jpij,nlay_i)   ::   ztib        ! Temporary temperature in the ice to check the convergence
+      REAL(wp), DIMENSION(jpij,nlay_s)   ::   ztsb        ! Temporary temperature in the snow to check the convergence
+      REAL(wp), DIMENSION(jpij,0:nlay_i) ::   ztcond_i    ! Ice thermal conductivity
+      REAL(wp), DIMENSION(jpij,0:nlay_i) ::   ztcond_i_cp ! copy
+      REAL(wp), DIMENSION(jpij,0:nlay_i) ::   zradtr_i    ! Radiation transmitted through the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_i) ::   zradab_i    ! Radiation absorbed in the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_i) ::   zkappa_i    ! Kappa factor in the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_i) ::   zeta_i      ! Eta factor in the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_s) ::   zradtr_s    ! Radiation transmited through the snow
+      REAL(wp), DIMENSION(jpij,0:nlay_s) ::   zradab_s    ! Radiation absorbed in the snow
+      REAL(wp), DIMENSION(jpij,0:nlay_s) ::   zkappa_s    ! Kappa factor in the snow
+      REAL(wp), DIMENSION(jpij,0:nlay_s) ::   zeta_s      ! Eta factor in the snow
+      REAL(wp), DIMENSION(jpij)          ::   zkappa_comb ! Combined snow and ice surface conductivity
+      REAL(wp), DIMENSION(jpij)          ::   zq_ini      ! diag errors on heat
+      REAL(wp), DIMENSION(jpij)          ::   zghe        ! G(he), th. conduct enhancement factor, mono-cat
+      REAL(wp), DIMENSION(jpij)          ::   za_s_fra    ! ice fraction covered by snow 
+      REAL(wp), DIMENSION(jpij)          ::   isnow       ! snow presence (1) or not (0) 
+      REAL(wp), DIMENSION(jpij)          ::   isnow_comb  ! snow presence for met-office 
+      REAL(wp), DIMENSION(jpij,nlay_i+nlay_s+1)   ::   zindterm    ! 'Ind'ependent term
+      REAL(wp), DIMENSION(jpij,nlay_i+nlay_s+1)   ::   zindtbis    ! Temporary 'ind'ependent term
+      REAL(wp), DIMENSION(jpij,nlay_i+nlay_s+1)   ::   zdiagbis    ! Temporary 'dia'gonal term
+      REAL(wp), DIMENSION(jpij,nlay_i+nlay_s+1,3) ::   ztrid       ! Tridiagonal system terms
       !
       ! Mono-category
@@ -533,14 +533,24 @@
             ! Solve the tridiagonal system with Gauss elimination method.
             ! Thomas algorithm, from Computational fluid Dynamics, J.D. ANDERSON, McGraw-Hill 1984
-            jm_maxt = 0
-            jm_mint = nlay_i+5
-            DO ji = 1, npti
-               jm_mint = MIN(jm_min(ji),jm_mint)
-               jm_maxt = MAX(jm_max(ji),jm_maxt)
-            END DO
-
-            DO jk = jm_mint+1, jm_maxt
-               DO ji = 1, npti
-                  jm = MIN(MAX(jm_min(ji)+1,jk),jm_max(ji))
+!!$            jm_maxt = 0
+!!$            jm_mint = nlay_i+5
+!!$            DO ji = 1, npti
+!!$               jm_mint = MIN(jm_min(ji),jm_mint)
+!!$               jm_maxt = MAX(jm_max(ji),jm_maxt)
+!!$            END DO
+!!$            !!clem SNWLAY => check why LIM1D does not get this loop. Is nlay_i+5 correct?
+!!$            
+!!$            DO jk = jm_mint+1, jm_maxt
+!!$               DO ji = 1, npti
+!!$                  jm = MIN(MAX(jm_min(ji)+1,jk),jm_max(ji))
+!!$                  zdiagbis(ji,jm) = ztrid   (ji,jm,2) - ztrid(ji,jm,1) * ztrid   (ji,jm-1,3) / zdiagbis(ji,jm-1)
+!!$                  zindtbis(ji,jm) = zindterm(ji,jm  ) - ztrid(ji,jm,1) * zindtbis(ji,jm-1  ) / zdiagbis(ji,jm-1)
+!!$               END DO
+!!$            END DO
+            ! clem: maybe one should find a way to reverse this loop for mpi performance
+            DO ji = 1, npti
+               jm_mint = jm_min(ji)
+               jm_maxt = jm_max(ji)
+               DO jm = jm_mint+1, jm_maxt
                   zdiagbis(ji,jm) = ztrid   (ji,jm,2) - ztrid(ji,jm,1) * ztrid   (ji,jm-1,3) / zdiagbis(ji,jm-1)
                   zindtbis(ji,jm) = zindterm(ji,jm  ) - ztrid(ji,jm,1) * zindtbis(ji,jm-1  ) / zdiagbis(ji,jm-1)
@@ -564,21 +574,30 @@
             END DO
 
+            ! snow temperatures      
             DO ji = 1, npti
                ! Variables used after iterations
                ! Value must be frozen after convergence for MPP independance reason
-               IF ( .NOT. l_T_converged(ji) ) THEN
-                  ! snow temperatures      
-                  IF( h_s_1d(ji) > 0._wp ) THEN
-                     t_s_1d(ji,nlay_s) = ( zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) * t_i_1d(ji,1) ) / zdiagbis(ji,nlay_s+1)
-                  ENDIF
-                  ! surface temperature
+               IF ( .NOT. l_T_converged(ji) .AND. h_s_1d(ji) > 0._wp ) &
+                  &   t_s_1d(ji,nlay_s) = ( zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) * t_i_1d(ji,1) ) / zdiagbis(ji,nlay_s+1)
+            END DO
+            !!clem SNWLAY
+            DO jm = nlay_s, 2, -1
+               DO ji = 1, npti
+                  jk = jm - 1
+                  IF ( .NOT. l_T_converged(ji) .AND. h_s_1d(ji) > 0._wp ) &
+                     &   t_s_1d(ji,jk) = ( zindtbis(ji,jm) - ztrid(ji,jm,3) * t_s_1d(ji,jk+1) ) / zdiagbis(ji,jm)
+               END DO
+            END DO
+            
+            ! surface temperature
+            DO ji = 1, npti
+               IF( .NOT. l_T_converged(ji) ) THEN
                   ztsub(ji) = t_su_1d(ji)
                   IF( t_su_1d(ji) < rt0 ) THEN
-                     t_su_1d(ji) = (  zindtbis(ji,jm_min(ji)) - ztrid(ji,jm_min(ji),3) *  &
-                        &           ( isnow(ji) * t_s_1d(ji,1) + ( 1._wp - isnow(ji) ) *  t_i_1d(ji,1) ) ) / zdiagbis(ji,jm_min(ji))
+                     t_su_1d(ji) = ( zindtbis(ji,jm_min(ji)) - ztrid(ji,jm_min(ji),3) *  &
+                        &          ( isnow(ji) * t_s_1d(ji,1) + ( 1._wp - isnow(ji) ) * t_i_1d(ji,1) ) ) / zdiagbis(ji,jm_min(ji))
                   ENDIF
                ENDIF
             END DO
-            !clem: in order to have several layers of snow, there is a missing loop here for t_s_1d(1:nlay_s-1)
             !
             !--------------------------------------------------------------
@@ -727,19 +746,28 @@
             ! Solve the tridiagonal system with Gauss elimination method.
             ! Thomas algorithm, from Computational fluid Dynamics, J.D. ANDERSON, McGraw-Hill 1984
-            jm_maxt = 0
-            jm_mint = nlay_i+5
-            DO ji = 1, npti
-               jm_mint = MIN(jm_min(ji),jm_mint)
-               jm_maxt = MAX(jm_max(ji),jm_maxt)
-            END DO
-            
-            DO jk = jm_mint+1, jm_maxt
-               DO ji = 1, npti
-                  jm = MIN(MAX(jm_min(ji)+1,jk),jm_max(ji))
+!!$            jm_maxt = 0
+!!$            jm_mint = nlay_i+5
+!!$            DO ji = 1, npti
+!!$               jm_mint = MIN(jm_min(ji),jm_mint)
+!!$               jm_maxt = MAX(jm_max(ji),jm_maxt)
+!!$            END DO
+!!$            
+!!$            DO jk = jm_mint+1, jm_maxt
+!!$               DO ji = 1, npti
+!!$                  jm = MIN(MAX(jm_min(ji)+1,jk),jm_max(ji))
+!!$                  zdiagbis(ji,jm) = ztrid   (ji,jm,2) - ztrid(ji,jm,1) * ztrid   (ji,jm-1,3) / zdiagbis(ji,jm-1)
+!!$                  zindtbis(ji,jm) = zindterm(ji,jm)   - ztrid(ji,jm,1) * zindtbis(ji,jm-1)   / zdiagbis(ji,jm-1)
+!!$               END DO
+!!$            END DO
+            ! clem: maybe one should find a way to reverse this loop for mpi performance
+            DO ji = 1, npti
+               jm_mint = jm_min(ji)
+               jm_maxt = jm_max(ji)
+               DO jm = jm_mint+1, jm_maxt
                   zdiagbis(ji,jm) = ztrid   (ji,jm,2) - ztrid(ji,jm,1) * ztrid   (ji,jm-1,3) / zdiagbis(ji,jm-1)
-                  zindtbis(ji,jm) = zindterm(ji,jm)   - ztrid(ji,jm,1) * zindtbis(ji,jm-1)   / zdiagbis(ji,jm-1)
+                  zindtbis(ji,jm) = zindterm(ji,jm  ) - ztrid(ji,jm,1) * zindtbis(ji,jm-1  ) / zdiagbis(ji,jm-1)
                END DO
             END DO
-            
+
             ! ice temperatures
             DO ji = 1, npti
@@ -761,13 +789,17 @@
             ! snow temperatures      
             DO ji = 1, npti
-               ! Variable used after iterations
+               ! Variables used after iterations
                ! Value must be frozen after convergence for MPP independance reason
-               IF ( .NOT. l_T_converged(ji) ) THEN
-                  IF( h_s_1d(ji) > 0._wp ) THEN
-                     t_s_1d(ji,nlay_s) = ( zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) * t_i_1d(ji,1) ) / zdiagbis(ji,nlay_s+1)
-                  ENDIF
-               ENDIF
-            END DO
-            !clem: in order to have several layers of snow, there is a missing loop here for t_s_1d(1:nlay_s-1)
+               IF ( .NOT. l_T_converged(ji) .AND. h_s_1d(ji) > 0._wp ) &
+                  &   t_s_1d(ji,nlay_s) = ( zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) * t_i_1d(ji,1) ) / zdiagbis(ji,nlay_s+1)
+            END DO
+            !!clem SNWLAY
+            DO jm = nlay_s, 2, -1
+               DO ji = 1, npti
+                  jk = jm - 1
+                  IF ( .NOT. l_T_converged(ji) .AND. h_s_1d(ji) > 0._wp ) &
+                     &   t_s_1d(ji,jk) = ( zindtbis(ji,jm) - ztrid(ji,jm,3) * t_s_1d(ji,jk+1) ) / zdiagbis(ji,jm)
+               END DO
+            END DO
             !
             !--------------------------------------------------------------
@@ -923,6 +955,6 @@
          !--- Snow-ice interfacial temperature (diagnostic SIMIP)
          IF( h_s_1d(ji) >= zhs_ssl ) THEN
-            t_si_1d(ji) = (   rn_cnd_s       * h_i_1d(ji) * r1_nlay_i * t_s_1d(ji,1)   &
-               &            + ztcond_i(ji,1) * h_s_1d(ji) * r1_nlay_s * t_i_1d(ji,1) ) &
+            t_si_1d(ji) = (   rn_cnd_s       * h_i_1d(ji) * r1_nlay_i * t_s_1d(ji,nlay_s)   &
+               &            + ztcond_i(ji,1) * h_s_1d(ji) * r1_nlay_s * t_i_1d(ji,1)      ) &
                &          / ( rn_cnd_s       * h_i_1d(ji) * r1_nlay_i &
                &            + ztcond_i(ji,1) * h_s_1d(ji) * r1_nlay_s )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceupdate.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceupdate.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/iceupdate.F90	(revision 14055)
@@ -94,5 +94,5 @@
       REAL(wp), DIMENSION(jpi,jpj) ::   z2d                  ! 2D workspace
       !!---------------------------------------------------------------------
-      IF( ln_timing )   CALL timing_start('ice_update')
+      IF( ln_timing )   CALL timing_start('iceupdate')
 
       IF( kt == nit000 .AND. lwp ) THEN
@@ -154,5 +154,5 @@
          ! ice-ocean  mass flux
          wfx_ice(ji,jj) = wfx_bog(ji,jj) + wfx_bom(ji,jj) + wfx_sum(ji,jj) + wfx_sni(ji,jj)   &
-            &           + wfx_opw(ji,jj) + wfx_dyn(ji,jj) + wfx_res(ji,jj) + wfx_lam(ji,jj) + wfx_pnd(ji,jj)
+            &           + wfx_opw(ji,jj) + wfx_dyn(ji,jj) + wfx_res(ji,jj) + wfx_lam(ji,jj)
          
          ! snw-ocean mass flux
@@ -160,6 +160,6 @@
          
          ! total mass flux at the ocean/ice interface
-         fmmflx(ji,jj) =                - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_err_sub(ji,jj)   ! ice-ocean mass flux saved at least for biogeochemical model
-         emp   (ji,jj) = emp_oce(ji,jj) - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_err_sub(ji,jj)   ! atm-ocean + ice-ocean mass flux
+         fmmflx(ji,jj) =                - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_pnd(ji,jj) - wfx_err_sub(ji,jj)   ! ice-ocean mass flux saved at least for biogeochemical model
+         emp   (ji,jj) = emp_oce(ji,jj) - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_pnd(ji,jj) - wfx_err_sub(ji,jj)   ! atm-ocean + ice-ocean mass flux
 
          ! Salt flux at the ocean surface      
@@ -172,5 +172,5 @@
          snwice_mass_b(ji,jj) = snwice_mass(ji,jj)       ! save mass from the previous ice time step
          !                                               ! new mass per unit area
-         snwice_mass  (ji,jj) = tmask(ji,jj,1) * ( rhos * vt_s(ji,jj) + rhoi * vt_i(ji,jj)  ) 
+         snwice_mass  (ji,jj) = tmask(ji,jj,1) * ( rhos * vt_s(ji,jj) + rhoi * vt_i(ji,jj) + rhow * (vt_ip(ji,jj) + vt_il(ji,jj)) ) 
          !                                               ! time evolution of snow+ice mass
          snwice_fmass (ji,jj) = ( snwice_mass(ji,jj) - snwice_mass_b(ji,jj) ) * r1_Dt_ice
@@ -286,5 +286,5 @@
       IF( ln_icectl         )   CALL ice_prt       (kt, iiceprt, jiceprt, 3, 'Final state ice_update') ! prints
       IF( sn_cfctl%l_prtctl )   CALL ice_prt3D     ('iceupdate')                                       ! prints
-      IF( ln_timing         )   CALL timing_stop   ('ice_update')                                      ! timing
+      IF( ln_timing         )   CALL timing_stop   ('iceupdate')                                       ! timing
       !
    END SUBROUTINE ice_update_flx
@@ -324,5 +324,5 @@
       REAL(wp) ::   zflagi                          !   -      -
       !!---------------------------------------------------------------------
-      IF( ln_timing )   CALL timing_start('ice_update_tau')
+      IF( ln_timing )   CALL timing_start('ice_update')
 
       IF( kt == nit000 .AND. lwp ) THEN
@@ -376,5 +376,5 @@
       CALL lbc_lnk_multi( 'iceupdate', utau, 'U', -1.0_wp, vtau, 'V', -1.0_wp )   ! lateral boundary condition
       !
-      IF( ln_timing )   CALL timing_stop('ice_update_tau')
+      IF( ln_timing )   CALL timing_stop('ice_update')
       !  
    END SUBROUTINE ice_update_tau
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icevar.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icevar.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icevar.F90	(revision 14055)
@@ -236,5 +236,5 @@
       z1_zhmax =  1._wp / hi_max(jpl)               
       WHERE( h_i(:,:,jpl) > zhmax )   ! bound h_i by hi_max (i.e. 99 m) with associated update of ice area
-         h_i  (:,:,jpl) = zhmax
+         h_i   (:,:,jpl) = zhmax
          a_i   (:,:,jpl) = v_i(:,:,jpl) * z1_zhmax 
          z1_a_i(:,:,jpl) = zhmax * z1_v_i(:,:,jpl)
@@ -252,5 +252,5 @@
       ELSEWHERE( h_il(:,:,:) >= zhl_max )  ;   a_ip_eff(:,:,:) = 0._wp                  ! lid is very thick. Cover all the pond up with ice and snow
       ELSEWHERE                            ;   a_ip_eff(:,:,:) = a_ip_frac(:,:,:) * &   ! lid is in between. Expose part of the pond
-         &                                                       ( h_il(:,:,:) - zhl_min ) / ( zhl_max - zhl_min )
+         &                                                       ( zhl_max - h_il(:,:,:) ) / ( zhl_max - zhl_min )
       END WHERE
       !
@@ -534,7 +534,8 @@
          DO_2D( 1, 1, 1, 1 )
             ! update exchanges with ocean
-            sfx_res(ji,jj)  = sfx_res(ji,jj) + (1._wp - zswitch(ji,jj) ) * sv_i(ji,jj,jl)   * rhoi * r1_Dt_ice
-            wfx_res(ji,jj)  = wfx_res(ji,jj) + (1._wp - zswitch(ji,jj) ) * v_i (ji,jj,jl)   * rhoi * r1_Dt_ice
-            wfx_res(ji,jj)  = wfx_res(ji,jj) + (1._wp - zswitch(ji,jj) ) * v_s (ji,jj,jl)   * rhos * r1_Dt_ice
+            sfx_res(ji,jj)  = sfx_res(ji,jj) + ( 1._wp - zswitch(ji,jj) ) * sv_i(ji,jj,jl)   * rhoi * r1_Dt_ice
+            wfx_res(ji,jj)  = wfx_res(ji,jj) + ( 1._wp - zswitch(ji,jj) ) * v_i (ji,jj,jl)   * rhoi * r1_Dt_ice
+            wfx_res(ji,jj)  = wfx_res(ji,jj) + ( 1._wp - zswitch(ji,jj) ) * v_s (ji,jj,jl)   * rhos * r1_Dt_ice
+            wfx_pnd(ji,jj)  = wfx_pnd(ji,jj) + ( 1._wp - zswitch(ji,jj) ) * ( v_ip(ji,jj,jl)+v_il(ji,jj,jl) ) * rhow * r1_Dt_ice
             !
             a_i  (ji,jj,jl) = a_i (ji,jj,jl) * zswitch(ji,jj)
@@ -551,4 +552,6 @@
             v_ip (ji,jj,jl) = v_ip (ji,jj,jl) * zswitch(ji,jj)
             v_il (ji,jj,jl) = v_il (ji,jj,jl) * zswitch(ji,jj)
+            h_ip (ji,jj,jl) = h_ip (ji,jj,jl) * zswitch(ji,jj)
+            h_il (ji,jj,jl) = h_il (ji,jj,jl) * zswitch(ji,jj)
             !
          END_2D
@@ -635,4 +638,12 @@
                psv_i  (ji,jj,jl) = 0._wp
             ENDIF
+            IF( pv_ip(ji,jj,jl) < 0._wp .OR. pv_il(ji,jj,jl) < 0._wp .OR. pa_ip(ji,jj,jl) <= 0._wp ) THEN
+               wfx_pnd(ji,jj)    = wfx_pnd(ji,jj) + pv_il(ji,jj,jl) * rhow * z1_dt
+               pv_il  (ji,jj,jl) = 0._wp
+            ENDIF
+            IF( pv_ip(ji,jj,jl) < 0._wp .OR. pa_ip(ji,jj,jl) <= 0._wp ) THEN
+               wfx_pnd(ji,jj)    = wfx_pnd(ji,jj) + pv_ip(ji,jj,jl) * rhow * z1_dt
+               pv_ip  (ji,jj,jl) = 0._wp
+            ENDIF
          END_2D
          !
@@ -643,6 +654,4 @@
       WHERE( pa_i  (:,:,:) < 0._wp )   pa_i  (:,:,:) = 0._wp
       WHERE( pa_ip (:,:,:) < 0._wp )   pa_ip (:,:,:) = 0._wp
-      WHERE( pv_ip (:,:,:) < 0._wp )   pv_ip (:,:,:) = 0._wp ! in theory one should change wfx_pnd(-) and wfx_sum(+)
-      WHERE( pv_il (:,:,:) < 0._wp )   pv_il (:,:,:) = 0._wp !    but it does not change conservation, so keep it this way is ok
       !
    END SUBROUTINE ice_var_zapneg
@@ -675,5 +684,5 @@
       WHERE( pe_i (1:npti,:,:) < 0._wp )   pe_i (1:npti,:,:) = 0._wp   !  e_i must be >= 0
       WHERE( pe_s (1:npti,:,:) < 0._wp )   pe_s (1:npti,:,:) = 0._wp   !  e_s must be >= 0
-      IF( ln_pnd_LEV ) THEN
+      IF( ln_pnd_LEV .OR. ln_pnd_TOPO ) THEN
          WHERE( pa_ip(1:npti,:) < 0._wp )    pa_ip(1:npti,:)   = 0._wp   ! a_ip must be >= 0
          WHERE( pv_ip(1:npti,:) < 0._wp )    pv_ip(1:npti,:)   = 0._wp   ! v_ip must be >= 0
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icewri.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icewri.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/ICE/icewri.F90	(revision 14055)
@@ -160,7 +160,8 @@
       IF( iom_use('icebrv_cat'  ) )   CALL iom_put( 'icebrv_cat'  ,   bv_i * 100.  * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! brine volume
       IF( iom_use('iceapnd_cat' ) )   CALL iom_put( 'iceapnd_cat' ,   a_ip         * zmsk00l                                   ) ! melt pond frac for categories
+      IF( iom_use('icevpnd_cat' ) )   CALL iom_put( 'icevpnd_cat' ,   v_ip         * zmsk00l                                   ) ! melt pond volume for categories
       IF( iom_use('icehpnd_cat' ) )   CALL iom_put( 'icehpnd_cat' ,   h_ip         * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! melt pond thickness for categories
       IF( iom_use('icehlid_cat' ) )   CALL iom_put( 'icehlid_cat' ,   h_il         * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! melt pond lid thickness for categories
-      IF( iom_use('iceafpnd_cat') )   CALL iom_put( 'iceafpnd_cat',   a_ip_frac    * zmsk00l                                   ) ! melt pond frac for categories
+      IF( iom_use('iceafpnd_cat') )   CALL iom_put( 'iceafpnd_cat',   a_ip_frac    * zmsk00l                                   ) ! melt pond frac per ice area for categories
       IF( iom_use('iceaepnd_cat') )   CALL iom_put( 'iceaepnd_cat',   a_ip_eff     * zmsk00l                                   ) ! melt pond effective frac for categories
       IF( iom_use('icealb_cat'  ) )   CALL iom_put( 'icealb_cat'  ,   alb_ice      * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! ice albedo for categories
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ASM/asminc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ASM/asminc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ASM/asminc.F90	(revision 14055)
@@ -26,4 +26,5 @@
    USE par_oce         ! Ocean space and time domain variables
    USE dom_oce         ! Ocean space and time domain
+   USE domain, ONLY : dom_tile
    USE domvvl          ! domain: variable volume level
    USE ldfdyn          ! lateral diffusion: eddy viscosity coefficients
@@ -518,14 +519,16 @@
       !
       INTEGER  :: ji, jj, jk
-      INTEGER  :: it
+      INTEGER  :: it, itile
       REAL(wp) :: zincwgt  ! IAU weight for current time step
-      REAL (wp), DIMENSION(jpi,jpj,jpk) :: fzptnz ! 3d freezing point values
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) :: fzptnz ! 3d freezing point values
       !!----------------------------------------------------------------------
       !
       ! freezing point calculation taken from oc_fz_pt (but calculated for all depths) 
       ! used to prevent the applied increments taking the temperature below the local freezing point 
-      DO jk = 1, jpkm1
-        CALL eos_fzp( pts(:,:,jk,jp_sal,Kmm), fzptnz(:,:,jk), gdept(:,:,jk,Kmm) )
-      END DO
+      IF( ln_temnofreeze ) THEN
+         DO jk = 1, jpkm1
+           CALL eos_fzp( pts(:,:,jk,jp_sal,Kmm), fzptnz(:,:,jk), gdept(:,:,jk,Kmm) )
+         END DO
+      ENDIF
          !
          !                             !--------------------------------------
@@ -538,8 +541,10 @@
             zincwgt = wgtiau(it) / rn_Dt   ! IAU weight for the current time step
             !
-            IF(lwp) THEN
-               WRITE(numout,*) 
-               WRITE(numout,*) 'tra_asm_inc : Tracer IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
-               WRITE(numout,*) '~~~~~~~~~~~~'
+            IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+               IF(lwp) THEN
+                  WRITE(numout,*)
+                  WRITE(numout,*) 'tra_asm_inc : Tracer IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
+                  WRITE(numout,*) '~~~~~~~~~~~~'
+               ENDIF
             ENDIF
             !
@@ -548,20 +553,24 @@
                IF (ln_temnofreeze) THEN
                   ! Do not apply negative increments if the temperature will fall below freezing
-                  WHERE(t_bkginc(:,:,jk) > 0.0_wp .OR. &
-                     &   pts(:,:,jk,jp_tem,Kmm) + pts(:,:,jk,jp_tem,Krhs) + t_bkginc(:,:,jk) * wgtiau(it) > fzptnz(:,:,jk) ) 
-                     pts(:,:,jk,jp_tem,Krhs) = pts(:,:,jk,jp_tem,Krhs) + t_bkginc(:,:,jk) * zincwgt  
+                  WHERE(t_bkginc(A2D(0),jk) > 0.0_wp .OR. &
+                     &   pts(A2D(0),jk,jp_tem,Kmm) + pts(A2D(0),jk,jp_tem,Krhs) + t_bkginc(A2D(0),jk) * wgtiau(it) > fzptnz(:,:,jk) )
+                     pts(A2D(0),jk,jp_tem,Krhs) = pts(A2D(0),jk,jp_tem,Krhs) + t_bkginc(A2D(0),jk) * zincwgt
                   END WHERE
                ELSE
-                  pts(:,:,jk,jp_tem,Krhs) = pts(:,:,jk,jp_tem,Krhs) + t_bkginc(:,:,jk) * zincwgt  
+                  DO_2D( 0, 0, 0, 0 )
+                     pts(ji,jj,jk,jp_tem,Krhs) = pts(ji,jj,jk,jp_tem,Krhs) + t_bkginc(ji,jj,jk) * zincwgt
+                  END_2D
                ENDIF
                IF (ln_salfix) THEN
                   ! Do not apply negative increments if the salinity will fall below a specified
                   ! minimum value salfixmin
-                  WHERE(s_bkginc(:,:,jk) > 0.0_wp .OR. &
-                     &   pts(:,:,jk,jp_sal,Kmm) + pts(:,:,jk,jp_sal,Krhs) + s_bkginc(:,:,jk) * wgtiau(it) > salfixmin ) 
-                     pts(:,:,jk,jp_sal,Krhs) = pts(:,:,jk,jp_sal,Krhs) + s_bkginc(:,:,jk) * zincwgt
+                  WHERE(s_bkginc(A2D(0),jk) > 0.0_wp .OR. &
+                     &   pts(A2D(0),jk,jp_sal,Kmm) + pts(A2D(0),jk,jp_sal,Krhs) + s_bkginc(A2D(0),jk) * wgtiau(it) > salfixmin )
+                     pts(A2D(0),jk,jp_sal,Krhs) = pts(A2D(0),jk,jp_sal,Krhs) + s_bkginc(A2D(0),jk) * zincwgt
                   END WHERE
                ELSE
-                  pts(:,:,jk,jp_sal,Krhs) = pts(:,:,jk,jp_sal,Krhs) + s_bkginc(:,:,jk) * zincwgt
+                  DO_2D( 0, 0, 0, 0 )
+                     pts(ji,jj,jk,jp_sal,Krhs) = pts(ji,jj,jk,jp_sal,Krhs) + s_bkginc(ji,jj,jk) * zincwgt
+                  END_2D
                ENDIF
             END DO
@@ -569,7 +578,9 @@
          ENDIF
          !
-         IF ( kt == nitiaufin_r + 1  ) THEN   ! For bias crcn to work
-            DEALLOCATE( t_bkginc )
-            DEALLOCATE( s_bkginc )
+         IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+            IF ( kt == nitiaufin_r + 1  ) THEN   ! For bias crcn to work
+               DEALLOCATE( t_bkginc )
+               DEALLOCATE( s_bkginc )
+            ENDIF
          ENDIF
          !                             !--------------------------------------
@@ -584,21 +595,27 @@
             IF (ln_temnofreeze) THEN
                ! Do not apply negative increments if the temperature will fall below freezing
-               WHERE( t_bkginc(:,:,:) > 0.0_wp .OR. pts(:,:,:,jp_tem,Kmm) + t_bkginc(:,:,:) > fzptnz(:,:,:) ) 
-                  pts(:,:,:,jp_tem,Kmm) = t_bkg(:,:,:) + t_bkginc(:,:,:)   
+               WHERE( t_bkginc(A2D(0),:) > 0.0_wp .OR. pts(A2D(0),:,jp_tem,Kmm) + t_bkginc(A2D(0),:) > fzptnz(:,:,:) )
+                  pts(A2D(0),:,jp_tem,Kmm) = t_bkg(A2D(0),:) + t_bkginc(A2D(0),:)
                END WHERE
             ELSE
-               pts(:,:,:,jp_tem,Kmm) = t_bkg(:,:,:) + t_bkginc(:,:,:)   
+               DO_3D( 0, 0, 0, 0, 1, jpk )
+                  pts(ji,jj,jk,jp_tem,Kmm) = t_bkg(ji,jj,jk) + t_bkginc(ji,jj,jk)
+               END_3D
             ENDIF
             IF (ln_salfix) THEN
                ! Do not apply negative increments if the salinity will fall below a specified
                ! minimum value salfixmin
-               WHERE( s_bkginc(:,:,:) > 0.0_wp .OR. pts(:,:,:,jp_sal,Kmm) + s_bkginc(:,:,:) > salfixmin ) 
-                  pts(:,:,:,jp_sal,Kmm) = s_bkg(:,:,:) + s_bkginc(:,:,:)   
+               WHERE( s_bkginc(A2D(0),:) > 0.0_wp .OR. pts(A2D(0),:,jp_sal,Kmm) + s_bkginc(A2D(0),:) > salfixmin )
+                  pts(A2D(0),:,jp_sal,Kmm) = s_bkg(A2D(0),:) + s_bkginc(A2D(0),:)
                END WHERE
             ELSE
-               pts(:,:,:,jp_sal,Kmm) = s_bkg(:,:,:) + s_bkginc(:,:,:)   
-            ENDIF
-
-            pts(:,:,:,:,Kbb) = pts(:,:,:,:,Kmm)                 ! Update before fields
+               DO_3D( 0, 0, 0, 0, 1, jpk )
+                  pts(ji,jj,jk,jp_sal,Kmm) = s_bkg(ji,jj,jk) + s_bkginc(ji,jj,jk)
+               END_3D
+            ENDIF
+
+            DO_3D( 0, 0, 0, 0, 1, jpk )
+               pts(ji,jj,jk,:,Kbb) = pts(ji,jj,jk,:,Kmm)             ! Update before fields
+            END_3D
 
             CALL eos( pts(:,:,:,:,Kbb), rhd, rhop, gdept_0(:,:,:) )  ! Before potential and in situ densities
@@ -607,15 +624,26 @@
 !!gm
 
-            IF( ln_zps .AND. .NOT. lk_c1d .AND. .NOT. ln_isfcav)           &
-               &  CALL zps_hde    ( kt, Kmm, jpts, pts(:,:,:,:,Kbb), gtsu, gtsv,        &  ! Partial steps: before horizontal gradient
-               &                              rhd, gru , grv               )  ! of t, s, rd at the last ocean level
-            IF( ln_zps .AND. .NOT. lk_c1d .AND.       ln_isfcav)                       &
-               &  CALL zps_hde_isf( nit000, Kmm, jpts, pts(:,:,:,:,Kbb), gtsu, gtsv, gtui, gtvi,    &  ! Partial steps for top cell (ISF)
-               &                                  rhd, gru , grv , grui, grvi          )  ! of t, s, rd at the last ocean level
-
-            DEALLOCATE( t_bkginc )
-            DEALLOCATE( s_bkginc )
-            DEALLOCATE( t_bkg    )
-            DEALLOCATE( s_bkg    )
+            ! TEMP: [tiling] This change not necessary after extra haloes development (lbc_lnk removed from zps_hde*)
+            IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only for the full domain
+               itile = ntile
+               IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )            ! Use full domain
+
+               IF( ln_zps .AND. .NOT. lk_c1d .AND. .NOT. ln_isfcav)           &
+                  &  CALL zps_hde    ( kt, Kmm, jpts, pts(:,:,:,:,Kbb), gtsu, gtsv,        &  ! Partial steps: before horizontal gradient
+                  &                              rhd, gru , grv               )  ! of t, s, rd at the last ocean level
+               IF( ln_zps .AND. .NOT. lk_c1d .AND.       ln_isfcav)                       &
+                  &  CALL zps_hde_isf( nit000, Kmm, jpts, pts(:,:,:,:,Kbb), gtsu, gtsv, gtui, gtvi,    &  ! Partial steps for top cell (ISF)
+                  &                                  rhd, gru , grv , grui, grvi          )  ! of t, s, rd at the last ocean level
+
+               IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = itile )            ! Revert to tile domain
+            ENDIF
+
+            IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+               DEALLOCATE( t_bkginc )
+               DEALLOCATE( s_bkginc )
+               DEALLOCATE( t_bkg    )
+               DEALLOCATE( s_bkg    )
+            ENDIF
+         !
          ENDIF
          !  
@@ -829,8 +857,9 @@
       INTEGER, INTENT(in), OPTIONAL ::   kindic   ! flag for disabling the deallocation
       !
+      INTEGER  ::   ji, jj
       INTEGER  ::   it
       REAL(wp) ::   zincwgt   ! IAU weight for current time step
 #if defined key_si3
-      REAL(wp), DIMENSION(jpi,jpj) ::   zofrld, zohicif, zseaicendg, zhicifinc
+      REAL(wp), DIMENSION(A2D(nn_hls)) ::   zofrld, zohicif, zseaicendg, zhicifinc
       REAL(wp) ::   zhicifmin = 0.5_wp      ! ice minimum depth in metres
 #endif
@@ -847,8 +876,10 @@
             ! note this is not a tendency so should not be divided by rn_Dt (as with the tracer and other increments)
             !
-            IF(lwp) THEN
-               WRITE(numout,*) 
-               WRITE(numout,*) 'seaice_asm_inc : sea ice conc IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
-               WRITE(numout,*) '~~~~~~~~~~~~'
+            IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+               IF(lwp) THEN
+                  WRITE(numout,*)
+                  WRITE(numout,*) 'seaice_asm_inc : sea ice conc IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
+                  WRITE(numout,*) '~~~~~~~~~~~~'
+               ENDIF
             ENDIF
             !
@@ -856,16 +887,18 @@
             !
 #if defined key_si3
-            zofrld (:,:) = 1._wp - at_i(:,:)
-            zohicif(:,:) = hm_i(:,:)
-            !
-            at_i  (:,:) = 1. - MIN( MAX( 1.-at_i  (:,:) - seaice_bkginc(:,:) * zincwgt, 0.0_wp), 1.0_wp)
-            at_i_b(:,:) = 1. - MIN( MAX( 1.-at_i_b(:,:) - seaice_bkginc(:,:) * zincwgt, 0.0_wp), 1.0_wp)
-            fr_i(:,:) = at_i(:,:)        ! adjust ice fraction
-            !
-            zseaicendg(:,:) = zofrld(:,:) - (1. - at_i(:,:))   ! find out actual sea ice nudge applied
+            DO_2D( 0, 0, 0, 0 )
+               zofrld (ji,jj) = 1._wp - at_i(ji,jj)
+               zohicif(ji,jj) = hm_i(ji,jj)
+               !
+               at_i  (ji,jj) = 1. - MIN( MAX( 1.-at_i  (ji,jj) - seaice_bkginc(ji,jj) * zincwgt, 0.0_wp), 1.0_wp)
+               at_i_b(ji,jj) = 1. - MIN( MAX( 1.-at_i_b(ji,jj) - seaice_bkginc(ji,jj) * zincwgt, 0.0_wp), 1.0_wp)
+               fr_i(ji,jj) = at_i(ji,jj)        ! adjust ice fraction
+               !
+               zseaicendg(ji,jj) = zofrld(ji,jj) - (1. - at_i(ji,jj))   ! find out actual sea ice nudge applied
+            END_2D
             !
             ! Nudge sea ice depth to bring it up to a required minimum depth
-            WHERE( zseaicendg(:,:) > 0.0_wp .AND. hm_i(:,:) < zhicifmin ) 
-               zhicifinc(:,:) = (zhicifmin - hm_i(:,:)) * zincwgt    
+            WHERE( zseaicendg(:,:) > 0.0_wp .AND. hm_i(A2D(0)) < zhicifmin )
+               zhicifinc(:,:) = (zhicifmin - hm_i(A2D(0))) * zincwgt
             ELSEWHERE
                zhicifinc(:,:) = 0.0_wp
@@ -873,5 +906,7 @@
             !
             ! nudge ice depth
-            hm_i (:,:) = hm_i (:,:) + zhicifinc(:,:)
+            DO_2D( 0, 0, 0, 0 )
+               hm_i (ji,jj) = hm_i (ji,jj) + zhicifinc(ji,jj)
+            END_2D
             !
             ! seaice salinity balancing (to add)
@@ -880,9 +915,13 @@
 #if defined key_cice && defined key_asminc
             ! Sea-ice : CICE case. Pass ice increment tendency into CICE
-            ndaice_da(:,:) = seaice_bkginc(:,:) * zincwgt / rn_Dt
-#endif
-            !
-            IF ( kt == nitiaufin_r ) THEN
-               DEALLOCATE( seaice_bkginc )
+            DO_2D( 0, 0, 0, 0 )
+               ndaice_da(ji,jj) = seaice_bkginc(ji,jj) * zincwgt / rn_Dt
+            END_2D
+#endif
+            !
+            IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+               IF ( kt == nitiaufin_r ) THEN
+                  DEALLOCATE( seaice_bkginc )
+               ENDIF
             ENDIF
             !
@@ -890,5 +929,7 @@
             !
 #if defined key_cice && defined key_asminc
-            ndaice_da(:,:) = 0._wp        ! Sea-ice : CICE case. Zero ice increment tendency into CICE
+            DO_2D( 0, 0, 0, 0 )
+               ndaice_da(ji,jj) = 0._wp        ! Sea-ice : CICE case. Zero ice increment tendency into CICE
+            END_2D
 #endif
             !
@@ -905,17 +946,19 @@
             !
 #if defined key_si3
-            zofrld (:,:) = 1._wp - at_i(:,:)
-            zohicif(:,:) = hm_i(:,:)
-            ! 
-            ! Initialize the now fields the background + increment
-            at_i(:,:) = 1. - MIN( MAX( 1.-at_i(:,:) - seaice_bkginc(:,:), 0.0_wp), 1.0_wp)
-            at_i_b(:,:) = at_i(:,:) 
-            fr_i(:,:) = at_i(:,:)        ! adjust ice fraction
-            !
-            zseaicendg(:,:) = zofrld(:,:) - (1. - at_i(:,:))   ! find out actual sea ice nudge applied
+            DO_2D( 0, 0, 0, 0 )
+               zofrld (ji,jj) = 1._wp - at_i(ji,jj)
+               zohicif(ji,jj) = hm_i(ji,jj)
+               !
+               ! Initialize the now fields the background + increment
+               at_i(ji,jj) = 1. - MIN( MAX( 1.-at_i(ji,jj) - seaice_bkginc(ji,jj), 0.0_wp), 1.0_wp)
+               at_i_b(ji,jj) = at_i(ji,jj)
+               fr_i(ji,jj) = at_i(ji,jj)        ! adjust ice fraction
+               !
+               zseaicendg(ji,jj) = zofrld(ji,jj) - (1. - at_i(ji,jj))   ! find out actual sea ice nudge applied
+            END_2D
             !
             ! Nudge sea ice depth to bring it up to a required minimum depth
-            WHERE( zseaicendg(:,:) > 0.0_wp .AND. hm_i(:,:) < zhicifmin ) 
-               zhicifinc(:,:) = zhicifmin - hm_i(:,:)
+            WHERE( zseaicendg(:,:) > 0.0_wp .AND. hm_i(A2D(0)) < zhicifmin )
+               zhicifinc(:,:) = zhicifmin - hm_i(A2D(0))
             ELSEWHERE
                zhicifinc(:,:) = 0.0_wp
@@ -923,5 +966,7 @@
             !
             ! nudge ice depth
-            hm_i (:,:) = hm_i (:,:) + zhicifinc(:,:)
+            DO_2D( 0, 0, 0, 0 )
+               hm_i(ji,jj) = hm_i (ji,jj) + zhicifinc(ji,jj)
+            END_2D
             !
             ! seaice salinity balancing (to add)
@@ -930,14 +975,20 @@
 #if defined key_cice && defined key_asminc
             ! Sea-ice : CICE case. Pass ice increment tendency into CICE
-           ndaice_da(:,:) = seaice_bkginc(:,:) / rn_Dt
-#endif
-            IF ( .NOT. PRESENT(kindic) ) THEN
-               DEALLOCATE( seaice_bkginc )
-            END IF
+            DO_2D( 0, 0, 0, 0 )
+               ndaice_da(ji,jj) = seaice_bkginc(ji,jj) / rn_Dt
+            END_2D
+#endif
+            IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+               IF ( .NOT. PRESENT(kindic) ) THEN
+                  DEALLOCATE( seaice_bkginc )
+               END IF
+            ENDIF
             !
          ELSE
             !
 #if defined key_cice && defined key_asminc
-            ndaice_da(:,:) = 0._wp     ! Sea-ice : CICE case. Zero ice increment tendency into CICE
+            DO_2D( 0, 0, 0, 0 )
+               ndaice_da(ji,jj) = 0._wp     ! Sea-ice : CICE case. Zero ice increment tendency into CICE
+            END_2D
 #endif
             !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/BDY/bdytra.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/BDY/bdytra.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/BDY/bdytra.F90	(revision 14055)
@@ -13,5 +13,5 @@
    !!----------------------------------------------------------------------
    USE oce            ! ocean dynamics and tracers variables
-   USE dom_oce        ! ocean space and time domain variables 
+   USE dom_oce        ! ocean space and time domain variables
    USE bdy_oce        ! ocean open boundary conditions
    USE bdylib         ! for orlanski library routines
@@ -157,4 +157,5 @@
       INTEGER  ::   ib_bdy         ! Loop index
       !!----------------------------------------------------------------------
+      IF( ntile /= 0 .AND. ntile /= 1 ) RETURN                        ! Do only for the full domain
       !
       IF( ln_timing )   CALL timing_start('bdy_tra_dmp')
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/C1D/step_c1d.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/C1D/step_c1d.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/C1D/step_c1d.F90	(revision 14055)
@@ -104,4 +104,5 @@
       IF( ln_tradmp )   CALL tra_dmp( kstp, Nbb, Nnn, ts, Nrhs  )  ! internal damping trends- tracers
       IF(.NOT.ln_linssh)CALL tra_adv( kstp, Nbb, Nnn, ts, Nrhs  )  ! horizontal & vertical advection
+      IF( ln_zdfmfc  )  CALL tra_mfc( kstp, Nbb     , ts, Nrhs  )  ! Mass Flux Convection
       IF( ln_zdfosm  )  CALL tra_osm( kstp, Nnn     , ts, Nrhs  )  ! OSMOSIS non-local tracer fluxes
                         CALL tra_zdf( kstp, Nbb, Nnn, Nrhs, ts, Naa   )         ! vertical mixing
@@ -122,4 +123,7 @@
                         CALL dyn_atf    ( kstp, Nbb, Nnn, Naa , uu, vv, e3t, e3u, e3v )  ! time filtering of "now" fields
       IF(.NOT.ln_linssh)CALL ssh_atf    ( kstp, Nbb, Nnn, Naa , ssh )                    ! time filtering of "now" sea surface height
+      IF( kstp == nit000 .AND. ln_linssh) THEN 
+         ssh(:,:,Naa) = ssh(:,:,Nnn)  ! init ssh after in ln_linssh case 
+      ENDIF
       !
       ! Swap time levels
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diaar5.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diaar5.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diaar5.F90	(revision 14055)
@@ -34,4 +34,5 @@
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:  ) ::   thick0       ! ocean thickness (interior domain)
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sn0          ! initial salinity
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   hstr_adv, hstr_ldf
 
    LOGICAL  :: l_ar5
@@ -54,5 +55,6 @@
       !!----------------------------------------------------------------------
       !
-      ALLOCATE( thick0(jpi,jpj) , sn0(jpi,jpj,jpk) , STAT=dia_ar5_alloc )
+      ALLOCATE( thick0(jpi,jpj) , sn0(jpi,jpj,jpk) , &
+         &      hstr_adv(jpi,jpj,jpts,2), hstr_ldf(jpi,jpj,jpts,2), STAT=dia_ar5_alloc )
       !
       CALL mpp_sum ( 'diaar5', dia_ar5_alloc )
@@ -304,6 +306,6 @@
    END SUBROUTINE dia_ar5
 
-
-   SUBROUTINE dia_ar5_hst( ktra, cptr, puflx, pvflx ) 
+   ! TEMP: [tiling] These changes not necessary if using XIOS (subdomain support, will not output haloes)
+   SUBROUTINE dia_ar5_hst( ktra, cptr, puflx, pvflx )
       !!----------------------------------------------------------------------
       !!                    ***  ROUTINE dia_ar5_htr ***
@@ -314,39 +316,47 @@
       INTEGER                         , INTENT(in )  :: ktra  ! tracer index
       CHARACTER(len=3)                , INTENT(in)   :: cptr  ! transport type  'adv'/'ldf'
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: puflx  ! u-flux of advection/diffusion
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: pvflx  ! v-flux of advection/diffusion
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk)    , INTENT(in)   :: puflx  ! u-flux of advection/diffusion
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk)    , INTENT(in)   :: pvflx  ! v-flux of advection/diffusion
       !
       INTEGER    ::  ji, jj, jk
-      REAL(wp), DIMENSION(jpi,jpj)  :: z2d
-
+
+      IF( cptr /= 'adv' .AND. cptr /= 'ldf' ) RETURN
+      IF( ktra /= jp_tem .AND. ktra /= jp_sal ) RETURN
+
+      IF( cptr == 'adv' ) THEN
+         DO_2D( 0, 0, 0, 0 )
+            hstr_adv(ji,jj,ktra,1) = puflx(ji,jj,1)
+            hstr_adv(ji,jj,ktra,2) = pvflx(ji,jj,1)
+         END_2D
+         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+            hstr_adv(ji,jj,ktra,1) = hstr_adv(ji,jj,ktra,1) + puflx(ji,jj,jk)
+            hstr_adv(ji,jj,ktra,2) = hstr_adv(ji,jj,ktra,2) + pvflx(ji,jj,jk)
+         END_3D
+      ELSE IF( cptr == 'ldf' ) THEN
+         DO_2D( 0, 0, 0, 0 )
+            hstr_ldf(ji,jj,ktra,1) = puflx(ji,jj,1)
+            hstr_ldf(ji,jj,ktra,2) = pvflx(ji,jj,1)
+         END_2D
+         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+            hstr_ldf(ji,jj,ktra,1) = hstr_ldf(ji,jj,ktra,1) + puflx(ji,jj,jk)
+            hstr_ldf(ji,jj,ktra,2) = hstr_ldf(ji,jj,ktra,2) + pvflx(ji,jj,jk)
+         END_3D
+      ENDIF
+
+      IF( ntile == 0 .OR. ntile == nijtile ) THEN
+         IF( cptr == 'adv' ) THEN
+            IF( ktra == jp_tem ) CALL iom_put( 'uadv_heattr' , rho0_rcp * hstr_adv(:,:,ktra,1) )  ! advective heat transport in i-direction
+            IF( ktra == jp_sal ) CALL iom_put( 'uadv_salttr' , rho0     * hstr_adv(:,:,ktra,1) )  ! advective salt transport in i-direction
+            IF( ktra == jp_tem ) CALL iom_put( 'vadv_heattr' , rho0_rcp * hstr_adv(:,:,ktra,2) )  ! advective heat transport in j-direction
+            IF( ktra == jp_sal ) CALL iom_put( 'vadv_salttr' , rho0     * hstr_adv(:,:,ktra,2) )  ! advective salt transport in j-direction
+         ENDIF
+         IF( cptr == 'ldf' ) THEN
+            IF( ktra == jp_tem ) CALL iom_put( 'udiff_heattr' , rho0_rcp * hstr_ldf(:,:,ktra,1) ) ! diffusive heat transport in i-direction
+            IF( ktra == jp_sal ) CALL iom_put( 'udiff_salttr' , rho0     * hstr_ldf(:,:,ktra,1) ) ! diffusive salt transport in i-direction
+            IF( ktra == jp_tem ) CALL iom_put( 'vdiff_heattr' , rho0_rcp * hstr_ldf(:,:,ktra,2) ) ! diffusive heat transport in j-direction
+            IF( ktra == jp_sal ) CALL iom_put( 'vdiff_salttr' , rho0     * hstr_ldf(:,:,ktra,2) ) ! diffusive salt transport in j-direction
+         ENDIF
+      ENDIF
     
-      z2d(:,:) = puflx(:,:,1) 
-      DO_3D( 0, 0, 0, 0, 1, jpkm1 )
-         z2d(ji,jj) = z2d(ji,jj) + puflx(ji,jj,jk) 
-      END_3D
-       CALL lbc_lnk( 'diaar5', z2d, 'U', -1.0_wp )
-       IF( cptr == 'adv' ) THEN
-          IF( ktra == jp_tem ) CALL iom_put( 'uadv_heattr' , rho0_rcp * z2d )  ! advective heat transport in i-direction
-          IF( ktra == jp_sal ) CALL iom_put( 'uadv_salttr' , rho0     * z2d )  ! advective salt transport in i-direction
-       ENDIF
-       IF( cptr == 'ldf' ) THEN
-          IF( ktra == jp_tem ) CALL iom_put( 'udiff_heattr' , rho0_rcp * z2d ) ! diffusive heat transport in i-direction
-          IF( ktra == jp_sal ) CALL iom_put( 'udiff_salttr' , rho0     * z2d ) ! diffusive salt transport in i-direction
-       ENDIF
-       !
-       z2d(:,:) = pvflx(:,:,1) 
-       DO_3D( 0, 0, 0, 0, 1, jpkm1 )
-          z2d(ji,jj) = z2d(ji,jj) + pvflx(ji,jj,jk) 
-       END_3D
-       CALL lbc_lnk( 'diaar5', z2d, 'V', -1.0_wp )
-       IF( cptr == 'adv' ) THEN
-          IF( ktra == jp_tem ) CALL iom_put( 'vadv_heattr' , rho0_rcp * z2d )  ! advective heat transport in j-direction
-          IF( ktra == jp_sal ) CALL iom_put( 'vadv_salttr' , rho0     * z2d )  ! advective salt transport in j-direction
-       ENDIF
-       IF( cptr == 'ldf' ) THEN
-          IF( ktra == jp_tem ) CALL iom_put( 'vdiff_heattr' , rho0_rcp * z2d ) ! diffusive heat transport in j-direction
-          IF( ktra == jp_sal ) CALL iom_put( 'vdiff_salttr' , rho0     * z2d ) ! diffusive salt transport in j-direction
-       ENDIF
-          
    END SUBROUTINE dia_ar5_hst
 
@@ -371,4 +381,8 @@
          &  iom_use( 'masstot' ) .OR. iom_use( 'temptot'   )  .OR. iom_use( 'saltot' ) .OR.  &    
          &  iom_use( 'botpres' ) .OR. iom_use( 'sshthster' )  .OR. iom_use( 'sshsteric' ) .OR. &
+         &  iom_use( 'uadv_heattr' ) .OR. iom_use( 'udiff_heattr' ) .OR. &
+         &  iom_use( 'uadv_salttr' ) .OR. iom_use( 'udiff_salttr' ) .OR. &
+         &  iom_use( 'vadv_heattr' ) .OR. iom_use( 'vdiff_heattr' ) .OR. &
+         &  iom_use( 'vadv_salttr' ) .OR. iom_use( 'vdiff_salttr' ) .OR. &
          &  iom_use( 'rhop' )  ) L_ar5 = .TRUE.
   
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diahsb.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diahsb.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diahsb.F90	(revision 14055)
@@ -267,20 +267,20 @@
             IF(lwp) WRITE(numout,*) '   dia_hsb_rst : read hsb restart at it= ', kt,' date= ', ndastp
             IF(lwp) WRITE(numout,*)
-            CALL iom_get( numror, 'frc_v', frc_v, ldxios = lrxios )
-            CALL iom_get( numror, 'frc_t', frc_t, ldxios = lrxios )
-            CALL iom_get( numror, 'frc_s', frc_s, ldxios = lrxios )
+            CALL iom_get( numror, 'frc_v', frc_v )
+            CALL iom_get( numror, 'frc_t', frc_t )
+            CALL iom_get( numror, 'frc_s', frc_s )
             IF( ln_linssh ) THEN
-               CALL iom_get( numror, 'frc_wn_t', frc_wn_t, ldxios = lrxios )
-               CALL iom_get( numror, 'frc_wn_s', frc_wn_s, ldxios = lrxios )
+               CALL iom_get( numror, 'frc_wn_t', frc_wn_t )
+               CALL iom_get( numror, 'frc_wn_s', frc_wn_s )
             ENDIF
-            CALL iom_get( numror, jpdom_auto, 'surf_ini'  , surf_ini  , ldxios = lrxios ) ! ice sheet coupling
-            CALL iom_get( numror, jpdom_auto, 'ssh_ini'   , ssh_ini   , ldxios = lrxios )
-            CALL iom_get( numror, jpdom_auto, 'e3t_ini'   , e3t_ini   , ldxios = lrxios )
-            CALL iom_get( numror, jpdom_auto, 'tmask_ini' , tmask_ini , ldxios = lrxios )
-            CALL iom_get( numror, jpdom_auto, 'hc_loc_ini', hc_loc_ini, ldxios = lrxios )
-            CALL iom_get( numror, jpdom_auto, 'sc_loc_ini', sc_loc_ini, ldxios = lrxios )
+            CALL iom_get( numror, jpdom_auto, 'surf_ini'  , surf_ini   ) ! ice sheet coupling
+            CALL iom_get( numror, jpdom_auto, 'ssh_ini'   , ssh_ini    )
+            CALL iom_get( numror, jpdom_auto, 'e3t_ini'   , e3t_ini    )
+            CALL iom_get( numror, jpdom_auto, 'tmask_ini' , tmask_ini  )
+            CALL iom_get( numror, jpdom_auto, 'hc_loc_ini', hc_loc_ini )
+            CALL iom_get( numror, jpdom_auto, 'sc_loc_ini', sc_loc_ini )
             IF( ln_linssh ) THEN
-               CALL iom_get( numror, jpdom_auto, 'ssh_hc_loc_ini', ssh_hc_loc_ini, ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'ssh_sc_loc_ini', ssh_sc_loc_ini, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'ssh_hc_loc_ini', ssh_hc_loc_ini )
+               CALL iom_get( numror, jpdom_auto, 'ssh_sc_loc_ini', ssh_sc_loc_ini )
             ENDIF
          ELSE
@@ -323,23 +323,21 @@
          IF(lwp) WRITE(numout,*)
          !
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'frc_v', frc_v, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'frc_t', frc_t, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'frc_s', frc_s, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'frc_v', frc_v )
+         CALL iom_rstput( kt, nitrst, numrow, 'frc_t', frc_t )
+         CALL iom_rstput( kt, nitrst, numrow, 'frc_s', frc_s )
          IF( ln_linssh ) THEN
-            CALL iom_rstput( kt, nitrst, numrow, 'frc_wn_t', frc_wn_t, ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'frc_wn_s', frc_wn_s, ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'frc_wn_t', frc_wn_t )
+            CALL iom_rstput( kt, nitrst, numrow, 'frc_wn_s', frc_wn_s )
          ENDIF
-         CALL iom_rstput( kt, nitrst, numrow, 'surf_ini'  , surf_ini  , ldxios = lwxios )      ! ice sheet coupling
-         CALL iom_rstput( kt, nitrst, numrow, 'ssh_ini'   , ssh_ini   , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_ini'   , e3t_ini   , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'tmask_ini' , tmask_ini , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'hc_loc_ini', hc_loc_ini, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'sc_loc_ini', sc_loc_ini, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'surf_ini'  , surf_ini   )      ! ice sheet coupling
+         CALL iom_rstput( kt, nitrst, numrow, 'ssh_ini'   , ssh_ini    )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_ini'   , e3t_ini    )
+         CALL iom_rstput( kt, nitrst, numrow, 'tmask_ini' , tmask_ini  )
+         CALL iom_rstput( kt, nitrst, numrow, 'hc_loc_ini', hc_loc_ini )
+         CALL iom_rstput( kt, nitrst, numrow, 'sc_loc_ini', sc_loc_ini )
          IF( ln_linssh ) THEN
-            CALL iom_rstput( kt, nitrst, numrow, 'ssh_hc_loc_ini', ssh_hc_loc_ini, ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'ssh_sc_loc_ini', ssh_sc_loc_ini, ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'ssh_hc_loc_ini', ssh_hc_loc_ini )
+            CALL iom_rstput( kt, nitrst, numrow, 'ssh_sc_loc_ini', ssh_sc_loc_ini )
          ENDIF
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
          !
       ENDIF
@@ -385,21 +383,4 @@
       IF( .NOT. ln_diahsb )   RETURN
 
-      IF(lwxios) THEN
-! define variables in restart file when writing with XIOS
-        CALL iom_set_rstw_var_active('frc_v')
-        CALL iom_set_rstw_var_active('frc_t')
-        CALL iom_set_rstw_var_active('frc_s')
-        CALL iom_set_rstw_var_active('surf_ini')
-        CALL iom_set_rstw_var_active('ssh_ini')
-        CALL iom_set_rstw_var_active('e3t_ini')
-        CALL iom_set_rstw_var_active('hc_loc_ini')
-        CALL iom_set_rstw_var_active('sc_loc_ini')
-        IF( ln_linssh ) THEN
-           CALL iom_set_rstw_var_active('ssh_hc_loc_ini')
-           CALL iom_set_rstw_var_active('ssh_sc_loc_ini')
-           CALL iom_set_rstw_var_active('frc_wn_t')
-           CALL iom_set_rstw_var_active('frc_wn_s')
-        ENDIF
-      ENDIF
       ! ------------------- !
       ! 1 - Allocate memory !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diaptr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diaptr.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diaptr.F90	(revision 14055)
@@ -22,4 +22,5 @@
    USE oce              ! ocean dynamics and active tracers
    USE dom_oce          ! ocean space and time domain
+   USE domain, ONLY : dom_tile
    USE phycst           ! physical constants
    !
@@ -32,4 +33,8 @@
    PRIVATE
 
+   INTERFACE ptr_sum
+      MODULE PROCEDURE ptr_sum_3d, ptr_sum_2d
+   END INTERFACE
+
    INTERFACE ptr_sj
       MODULE PROCEDURE ptr_sj_3d, ptr_sj_2d
@@ -39,8 +44,11 @@
    PUBLIC   dia_ptr_hst    ! called from tra_ldf/tra_adv routines
 
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hstr_adv, hstr_ldf, hstr_eiv   !: Heat/Salt TRansports(adv, diff, Bolus.)
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hstr_ove, hstr_btr, hstr_vtr   !: heat Salt TRansports(overturn, baro, merional)
-
-   LOGICAL, PUBLIC ::   l_diaptr       !: tracers  trend flag
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   hstr_adv, hstr_ldf, hstr_eiv   !: Heat/Salt TRansports(adv, diff, Bolus.)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   hstr_ove, hstr_btr, hstr_vtr   !: heat Salt TRansports(overturn, baro, merional)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   pvtr_int, pzon_int             !: Other zonal integrals
+
+   LOGICAL, PUBLIC    ::   l_diaptr       !: tracers  trend flag
+   INTEGER, PARAMETER ::   jp_msk = 3
+   INTEGER, PARAMETER ::   jp_vtr = 4
 
    REAL(wp) ::   rc_sv    = 1.e-6_wp   ! conversion from m3/s to Sverdrup
@@ -51,9 +59,6 @@
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: btmsk34 ! mask out Southern Ocean (=0 south of 34°S)
 
-   REAL(wp), TARGET, ALLOCATABLE, SAVE, DIMENSION(:)   :: p_fval1d
-   REAL(wp), TARGET, ALLOCATABLE, SAVE, DIMENSION(:,:) :: p_fval2d
-
    LOGICAL ::   ll_init = .TRUE.        !: tracers  trend flag
-   
+
    !! * Substitutions
 #  include "do_loop_substitute.h90"
@@ -72,12 +77,40 @@
       INTEGER                         , INTENT(in)           ::   kt     ! ocean time-step index     
       INTEGER                         , INTENT(in)           ::   Kmm    ! time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::   pvtr   ! j-effective transport
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk)    , INTENT(in), OPTIONAL ::   pvtr   ! j-effective transport
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dia_ptr')
+
+      IF( kt == nit000 .AND. ll_init )   CALL dia_ptr_init    ! -> will define l_diaptr and nbasin
+      !
+      IF( l_diaptr ) THEN
+         ! Calculate zonal integrals
+         IF( PRESENT( pvtr ) ) THEN
+            CALL dia_ptr_zint( Kmm, pvtr )
+         ELSE
+            CALL dia_ptr_zint( Kmm )
+         ENDIF
+
+         ! Calculate diagnostics only when zonal integrals have finished
+         IF( ntile == 0 .OR. ntile == nijtile ) CALL dia_ptr_iom(kt, Kmm, pvtr)
+      ENDIF
+
+      IF( ln_timing )   CALL timing_stop('dia_ptr')
+      !
+   END SUBROUTINE dia_ptr
+
+
+   SUBROUTINE dia_ptr_iom( kt, Kmm, pvtr )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_ptr_iom  ***
+      !!----------------------------------------------------------------------
+      !! ** Purpose : Calculate diagnostics and send to XIOS
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in)           ::   kt     ! ocean time-step index
+      INTEGER                         , INTENT(in)           ::   Kmm    ! time level index
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk)    , INTENT(in), OPTIONAL ::   pvtr   ! j-effective transport
       !
       INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp) ::   zsfc,zvfc               ! local scalar
       REAL(wp), DIMENSION(jpi,jpj)     ::  z2d   ! 2D workspace
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zmask   ! 3D workspace
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  z3d    ! 3D workspace
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts) ::  zts   ! 3D workspace
       REAL(wp), DIMENSION(jpj)      ::  zvsum, ztsum, zssum   ! 1D workspace
       !
@@ -90,112 +123,292 @@
       !!----------------------------------------------------------------------
       !
-      IF( ln_timing )   CALL timing_start('dia_ptr')
-
-      IF( kt == nit000 .AND. ll_init )   CALL dia_ptr_init   ! -> will define l_diaptr and nbasin
-      !
-      IF( .NOT. l_diaptr ) THEN
-         IF( ln_timing ) CALL timing_stop('dia_ptr')
-         RETURN
-      ENDIF
-      !
       ALLOCATE( z3dtr(jpi,jpj,nbasin) )
-      !
+
       IF( PRESENT( pvtr ) ) THEN
          IF( iom_use( 'zomsf' ) ) THEN    ! effective MSF
             ALLOCATE( z4d1(jpi,jpj,jpk,nbasin) )
+            !
             DO jn = 1, nbasin                                    ! by sub-basins
-               z4d1(1,:,:,jn) =  ptr_sjk( pvtr(:,:,:), btmsk34(:,:,jn) )  ! zonal cumulative effective transport excluding closed seas
-               DO jk = jpkm1, 1, -1 
+               z4d1(1,:,:,jn) =  pvtr_int(:,:,jp_vtr,jn)                  ! zonal cumulative effective transport excluding closed seas
+               DO jk = jpkm1, 1, -1
                   z4d1(1,:,jk,jn) = z4d1(1,:,jk+1,jn) - z4d1(1,:,jk,jn)    ! effective j-Stream-Function (MSF)
                END DO
-               DO ji = 1, jpi
+               DO ji = 2, jpi
                   z4d1(ji,:,:,jn) = z4d1(1,:,:,jn)
                ENDDO
             END DO
             CALL iom_put( 'zomsf', z4d1 * rc_sv )
+            !
             DEALLOCATE( z4d1 )
          ENDIF
+         IF( iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) ) THEN
+            ALLOCATE( sjk(jpj,jpk,nbasin), r1_sjk(jpj,jpk,nbasin), v_msf(jpj,jpk,nbasin),   &
+               &      zt_jk(jpj,jpk,nbasin), zs_jk(jpj,jpk,nbasin) )
+            !
+            DO jn = 1, nbasin
+               sjk(:,:,jn) = pvtr_int(:,:,jp_msk,jn)
+               r1_sjk(:,:,jn) = 0._wp
+               WHERE( sjk(:,:,jn) /= 0._wp )   r1_sjk(:,:,jn) = 1._wp / sjk(:,:,jn)
+               ! i-mean T and S, j-Stream-Function, basin
+               zt_jk(:,:,jn) = pvtr_int(:,:,jp_tem,jn) * r1_sjk(:,:,jn)
+               zs_jk(:,:,jn) = pvtr_int(:,:,jp_sal,jn) * r1_sjk(:,:,jn)
+               v_msf(:,:,jn) = pvtr_int(:,:,jp_vtr,jn)
+               hstr_ove(:,jp_tem,jn) = SUM( v_msf(:,:,jn)*zt_jk(:,:,jn), 2 )
+               hstr_ove(:,jp_sal,jn) = SUM( v_msf(:,:,jn)*zs_jk(:,:,jn), 2 )
+               !
+            ENDDO
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_ove(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtove', z3dtr )
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_ove(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstove', z3dtr )
+            !
+            DEALLOCATE( sjk, r1_sjk, v_msf, zt_jk, zs_jk )
+         ENDIF
+
+         IF( iom_use( 'sopstbtr' ) .OR. iom_use( 'sophtbtr' ) ) THEN
+            ! Calculate barotropic heat and salt transport here 
+            ALLOCATE( sjk(jpj,1,nbasin), r1_sjk(jpj,1,nbasin) )
+            !
+            DO jn = 1, nbasin
+               sjk(:,1,jn) = SUM( pvtr_int(:,:,jp_msk,jn), 2 )
+               r1_sjk(:,1,jn) = 0._wp
+               WHERE( sjk(:,1,jn) /= 0._wp )   r1_sjk(:,1,jn) = 1._wp / sjk(:,1,jn)
+               !
+               zvsum(:) =    SUM( pvtr_int(:,:,jp_vtr,jn), 2 )
+               ztsum(:) =    SUM( pvtr_int(:,:,jp_tem,jn), 2 )
+               zssum(:) =    SUM( pvtr_int(:,:,jp_sal,jn), 2 )
+               hstr_btr(:,jp_tem,jn) = zvsum(:) * ztsum(:) * r1_sjk(:,1,jn)
+               hstr_btr(:,jp_sal,jn) = zvsum(:) * zssum(:) * r1_sjk(:,1,jn)
+               !
+            ENDDO
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_btr(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtbtr', z3dtr )
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_btr(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstbtr', z3dtr )
+            !
+            DEALLOCATE( sjk, r1_sjk )
+         ENDIF
+         !
+         hstr_ove(:,:,:) = 0._wp       ! Zero before next timestep
+         hstr_btr(:,:,:) = 0._wp
+         pvtr_int(:,:,:,:) = 0._wp
+      ELSE
+         IF( iom_use( 'zotem' ) .OR. iom_use( 'zosal' ) .OR. iom_use( 'zosrf' )  ) THEN    ! i-mean i-k-surface
+            ALLOCATE( z4d1(jpi,jpj,jpk,nbasin), z4d2(jpi,jpj,jpk,nbasin) )
+            !
+            DO jn = 1, nbasin
+               z4d1(1,:,:,jn) = pzon_int(:,:,jp_msk,jn)
+               DO ji = 2, jpi
+                  z4d1(ji,:,:,jn) = z4d1(1,:,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'zosrf', z4d1 )
+            !
+            DO jn = 1, nbasin
+               z4d2(1,:,:,jn) = pzon_int(:,:,jp_tem,jn) / MAX( z4d1(1,:,:,jn), 10.e-15 )
+               DO ji = 2, jpi
+                  z4d2(ji,:,:,jn) = z4d2(1,:,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'zotem', z4d2 )
+            !
+            DO jn = 1, nbasin
+               z4d2(1,:,:,jn) = pzon_int(:,:,jp_sal,jn) / MAX( z4d1(1,:,:,jn), 10.e-15 )
+               DO ji = 2, jpi
+                  z4d2(ji,:,:,jn) = z4d2(1,:,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'zosal', z4d2 )
+            !
+            DEALLOCATE( z4d1, z4d2 )
+         ENDIF
+         !
+         !                                ! Advective and diffusive heat and salt transport
+         IF( iom_use( 'sophtadv' ) .OR. iom_use( 'sopstadv' ) ) THEN  
+            ! 
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_adv(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtadv', z3dtr )
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_adv(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstadv', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) THEN  
+            ! 
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_ldf(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtldf', z3dtr )
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_ldf(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstldf', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'sophteiv' ) .OR. iom_use( 'sopsteiv' ) ) THEN  
+            ! 
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_eiv(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophteiv', z3dtr )
+            DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_eiv(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopsteiv', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'sopstvtr' ) .OR. iom_use( 'sophtvtr' ) ) THEN
+             DO jn = 1, nbasin
+                z3dtr(1,:,jn) = hstr_vtr(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+                DO ji = 2, jpi
+                   z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+                ENDDO
+             ENDDO
+             CALL iom_put( 'sophtvtr', z3dtr )
+             DO jn = 1, nbasin
+               z3dtr(1,:,jn) = hstr_vtr(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 2, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstvtr', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'uocetr_vsum_cumul' ) ) THEN
+            IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )         ! Use full domain
+            CALL iom_get_var(  'uocetr_vsum_op', z2d ) ! get uocetr_vsum_op from xml
+            z2d(:,:) = ptr_ci_2d( z2d(:,:) )  
+            CALL iom_put( 'uocetr_vsum_cumul', z2d )
+            IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = nijtile )   ! Revert to tile domain
+         ENDIF
+         !
+         hstr_adv(:,:,:) = 0._wp       ! Zero before next timestep
+         hstr_ldf(:,:,:) = 0._wp
+         hstr_eiv(:,:,:) = 0._wp
+         hstr_vtr(:,:,:) = 0._wp
+         pzon_int(:,:,:,:) = 0._wp
+      ENDIF
+      !
+      DEALLOCATE( z3dtr )
+      !
+   END SUBROUTINE dia_ptr_iom
+
+
+   SUBROUTINE dia_ptr_zint( Kmm, pvtr )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ptr_zint ***
+      !!----------------------------------------------------------------------
+      !! ** Purpose : i and i-k sum operations on arrays
+      !!
+      !! ** Method  : - Call ptr_sjk (i sum) or ptr_sj (i-k sum) to perform the sum operation
+      !!              - Call ptr_sum to add this result to the sum over tiles
+      !!
+      !! ** Action  : pvtr_int - terms for volume streamfunction, heat/salt transport barotropic/overturning terms
+      !!              pzon_int - terms for i mean temperature/salinity
+      !!----------------------------------------------------------------------
+      INTEGER                     , INTENT(in)           :: Kmm          ! time level index
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(in), OPTIONAL :: pvtr         ! j-effective transport
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE            :: zmask        ! 3D workspace
+      REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE          :: zts          ! 4D workspace
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE            :: sjk, v_msf   ! Zonal sum: i-k surface area, j-effective transport
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE            :: zt_jk, zs_jk ! Zonal sum: i-k surface area * (T, S)
+      REAL(wp)                                           :: zsfc, zvfc   ! i-k surface area
+      INTEGER  ::   ji, jj, jk, jn                                       ! dummy loop indices
+      !!----------------------------------------------------------------------
+
+      IF( PRESENT( pvtr ) ) THEN
+         ! i sum of effective j transport excluding closed seas
+         IF( iom_use( 'zomsf' ) .OR. iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) ) THEN
+            ALLOCATE( v_msf(A1Dj(nn_hls),jpk,nbasin) )
+
+            DO jn = 1, nbasin
+               v_msf(:,:,jn) = ptr_sjk( pvtr(:,:,:), btmsk34(:,:,jn) )
+            ENDDO
+
+            CALL ptr_sum( pvtr_int(:,:,jp_vtr,:), v_msf(:,:,:) )
+
+            DEALLOCATE( v_msf )
+         ENDIF
+
+         ! i sum of j surface area, j surface area - temperature/salinity product on V grid
          IF(  iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) .OR.   &
             & iom_use( 'sopstbtr' ) .OR. iom_use( 'sophtbtr' ) ) THEN
-            ! define fields multiplied by scalar
+            ALLOCATE( zmask(A2D(nn_hls),jpk), zts(A2D(nn_hls),jpk,jpts), &
+               &      sjk(A1Dj(nn_hls),jpk,nbasin), &
+               &      zt_jk(A1Dj(nn_hls),jpk,nbasin), zs_jk(A1Dj(nn_hls),jpk,nbasin) )
+
             zmask(:,:,:) = 0._wp
             zts(:,:,:,:) = 0._wp
+
             DO_3D( 1, 0, 1, 1, 1, jpkm1 )
                zvfc = e1v(ji,jj) * e3v(ji,jj,jk,Kmm)
                zmask(ji,jj,jk)      = vmask(ji,jj,jk)      * zvfc
-               zts(ji,jj,jk,jp_tem) = (ts(ji,jj,jk,jp_tem,Kmm)+ts(ji,jj+1,jk,jp_tem,Kmm)) * 0.5 * zvfc  !Tracers averaged onto V grid
+               zts(ji,jj,jk,jp_tem) = (ts(ji,jj,jk,jp_tem,Kmm)+ts(ji,jj+1,jk,jp_tem,Kmm)) * 0.5 * zvfc !Tracers averaged onto V grid
                zts(ji,jj,jk,jp_sal) = (ts(ji,jj,jk,jp_sal,Kmm)+ts(ji,jj+1,jk,jp_sal,Kmm)) * 0.5 * zvfc
             END_3D
-         ENDIF
-         IF( iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) ) THEN
-            DO jn = 1, nbasin
-               ALLOCATE( sjk(jpj,jpk,nbasin), r1_sjk(jpj,jpk,nbasin), v_msf(jpj,jpk,nbasin),   &
-                  &                          zt_jk(jpj,jpk,nbasin), zs_jk(jpj,jpk,nbasin) )
-               sjk(:,:,jn) = ptr_sjk( zmask(:,:,:), btmsk(:,:,jn) )
-               r1_sjk(:,:,jn) = 0._wp
-               WHERE( sjk(:,:,jn) /= 0._wp )   r1_sjk(:,:,jn) = 1._wp / sjk(:,:,jn)
-               ! i-mean T and S, j-Stream-Function, basin
-               zt_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) ) * r1_sjk(:,:,jn)
-               zs_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) ) * r1_sjk(:,:,jn)
-               v_msf(:,:,jn) = ptr_sjk( pvtr(:,:,:), btmsk34(:,:,jn) ) 
-               hstr_ove(:,jp_tem,jn) = SUM( v_msf(:,:,jn)*zt_jk(:,:,jn), 2 )
-               hstr_ove(:,jp_sal,jn) = SUM( v_msf(:,:,jn)*zs_jk(:,:,jn), 2 )
-               DEALLOCATE( sjk, r1_sjk, v_msf, zt_jk, zs_jk )
-               !
-            ENDDO
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_ove(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sophtove', z3dtr )
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_ove(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sopstove', z3dtr )
-         ENDIF
-
-         IF( iom_use( 'sopstbtr' ) .OR. iom_use( 'sophtbtr' ) ) THEN
-            ! Calculate barotropic heat and salt transport here 
-            DO jn = 1, nbasin
-               ALLOCATE( sjk(jpj,1,nbasin), r1_sjk(jpj,1,nbasin) )
-               sjk(:,1,jn) = ptr_sj( zmask(:,:,:), btmsk(:,:,jn) )
-               r1_sjk(:,1,jn) = 0._wp
-               WHERE( sjk(:,1,jn) /= 0._wp )   r1_sjk(:,1,jn) = 1._wp / sjk(:,1,jn)
-               !
-               zvsum(:) = ptr_sj( pvtr(:,:,:), btmsk34(:,:,jn) )
-               ztsum(:) = ptr_sj( zts(:,:,:,jp_tem), btmsk(:,:,jn) )
-               zssum(:) = ptr_sj( zts(:,:,:,jp_sal), btmsk(:,:,jn) )
-               hstr_btr(:,jp_tem,jn) = zvsum(:) * ztsum(:) * r1_sjk(:,1,jn)
-               hstr_btr(:,jp_sal,jn) = zvsum(:) * zssum(:) * r1_sjk(:,1,jn)
-               DEALLOCATE( sjk, r1_sjk )
-               !
-            ENDDO
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_btr(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sophtbtr', z3dtr )
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_btr(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sopstbtr', z3dtr )
-         ENDIF 
-         !
+
+            DO jn = 1, nbasin
+               sjk(:,:,jn)   = ptr_sjk( zmask(:,:,:)     , btmsk(:,:,jn) )
+               zt_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) )
+               zs_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) )
+            ENDDO
+
+            CALL ptr_sum( pvtr_int(:,:,jp_msk,:), sjk(:,:,:)   )
+            CALL ptr_sum( pvtr_int(:,:,jp_tem,:), zt_jk(:,:,:) )
+            CALL ptr_sum( pvtr_int(:,:,jp_sal,:), zs_jk(:,:,:) )
+
+            DEALLOCATE( zmask, zts, sjk, zt_jk, zs_jk )
+         ENDIF
       ELSE
-         !
-         zmask(:,:,:) = 0._wp
-         zts(:,:,:,:) = 0._wp
-         IF( iom_use( 'zotem' ) .OR. iom_use( 'zosal' ) .OR. iom_use( 'zosrf' )  ) THEN    ! i-mean i-k-surface 
-            ALLOCATE( z4d1(jpi,jpj,jpk,nbasin), z4d2(jpi,jpj,jpk,nbasin) )
+         ! i sum of j surface area - temperature/salinity product on T grid
+         IF( iom_use( 'zotem' ) .OR. iom_use( 'zosal' ) .OR. iom_use( 'zosrf' )  ) THEN
+            ALLOCATE( zmask(A2D(nn_hls),jpk), zts(A2D(nn_hls),jpk,jpts), &
+               &      sjk(A1Dj(nn_hls),jpk,nbasin), &
+               &      zt_jk(A1Dj(nn_hls),jpk,nbasin), zs_jk(A1Dj(nn_hls),jpk,nbasin) )
+
+            zmask(:,:,:) = 0._wp
+            zts(:,:,:,:) = 0._wp
+
             DO_3D( 1, 1, 1, 1, 1, jpkm1 )
                zsfc = e1t(ji,jj) * e3t(ji,jj,jk,Kmm)
@@ -204,92 +417,24 @@
                zts(ji,jj,jk,jp_sal) = ts(ji,jj,jk,jp_sal,Kmm) * zsfc
             END_3D
-            !
-            DO jn = 1, nbasin
-               zmask(1,:,:) = ptr_sjk( zmask(:,:,:), btmsk(:,:,jn) )
-               DO ji = 1, jpi
-                  zmask(ji,:,:) = zmask(1,:,:)
-               ENDDO
-               z4d1(:,:,:,jn) = zmask(:,:,:)
-            ENDDO
-            CALL iom_put( 'zosrf', z4d1 )
-            !
-            DO jn = 1, nbasin
-               z4d2(1,:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) ) &
-                  &            / MAX( z4d1(1,:,:,jn), 10.e-15 )
-               DO ji = 1, jpi
-                  z4d2(ji,:,:,jn) = z4d2(1,:,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'zotem', z4d2 )
-            !
-            DO jn = 1, nbasin
-               z4d2(1,:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) ) &
-                  &            / MAX( z4d1(1,:,:,jn), 10.e-15 )
-               DO ji = 1, jpi
-                  z4d2(ji,:,:,jn) = z4d2(1,:,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'zosal', z4d2 )
-            DEALLOCATE( z4d1, z4d2 )
-            !
-         ENDIF
-         !
-         !                                ! Advective and diffusive heat and salt transport
-         IF( iom_use( 'sophtadv' ) .OR. iom_use( 'sopstadv' ) ) THEN  
-            ! 
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_adv(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sophtadv', z3dtr )
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_adv(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sopstadv', z3dtr )
-         ENDIF
-         !
-         IF( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) THEN  
-            ! 
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_ldf(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sophtldf', z3dtr )
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_ldf(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sopstldf', z3dtr )
-         ENDIF
-         !
-         IF( iom_use( 'sophteiv' ) .OR. iom_use( 'sopsteiv' ) ) THEN  
-            ! 
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_eiv(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sophteiv', z3dtr )
-            DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_eiv(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sopsteiv', z3dtr )
-         ENDIF
-         !
+
+            DO jn = 1, nbasin
+               sjk(:,:,jn)   = ptr_sjk( zmask(:,:,:)     , btmsk(:,:,jn) )
+               zt_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) )
+               zs_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) )
+            ENDDO
+
+            CALL ptr_sum( pzon_int(:,:,jp_msk,:), sjk(:,:,:)   )
+            CALL ptr_sum( pzon_int(:,:,jp_tem,:), zt_jk(:,:,:) )
+            CALL ptr_sum( pzon_int(:,:,jp_sal,:), zs_jk(:,:,:) )
+
+            DEALLOCATE( zmask, zts, sjk, zt_jk, zs_jk )
+         ENDIF
+
+         ! i-k sum of j surface area - temperature/salinity product on V grid
          IF( iom_use( 'sopstvtr' ) .OR. iom_use( 'sophtvtr' ) ) THEN
+            ALLOCATE( zts(A2D(nn_hls),jpk,jpts) )
+
             zts(:,:,:,:) = 0._wp
+
             DO_3D( 1, 0, 1, 1, 1, jpkm1 )
                zvfc = e1v(ji,jj) * e3v(ji,jj,jk,Kmm)
@@ -297,35 +442,12 @@
                zts(ji,jj,jk,jp_sal) = (ts(ji,jj,jk,jp_sal,Kmm)+ts(ji,jj+1,jk,jp_sal,Kmm)) * 0.5 * zvfc
             END_3D
-             CALL dia_ptr_hst( jp_tem, 'vtr', zts(:,:,:,jp_tem) )
-             CALL dia_ptr_hst( jp_sal, 'vtr', zts(:,:,:,jp_sal) )
-             DO jn = 1, nbasin
-                z3dtr(1,:,jn) = hstr_vtr(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
-                DO ji = 1, jpi
-                   z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-                ENDDO
-             ENDDO
-             CALL iom_put( 'sophtvtr', z3dtr )
-             DO jn = 1, nbasin
-               z3dtr(1,:,jn) = hstr_vtr(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
-               DO ji = 1, jpi
-                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
-               ENDDO
-            ENDDO
-            CALL iom_put( 'sopstvtr', z3dtr )
-         ENDIF
-         !
-         IF( iom_use( 'uocetr_vsum_cumul' ) ) THEN
-            CALL iom_get_var(  'uocetr_vsum_op', z2d ) ! get uocetr_vsum_op from xml
-            z2d(:,:) = ptr_ci_2d( z2d(:,:) )  
-            CALL iom_put( 'uocetr_vsum_cumul', z2d )
-         ENDIF
-         !
+
+            CALL dia_ptr_hst( jp_tem, 'vtr', zts(:,:,:,jp_tem) )
+            CALL dia_ptr_hst( jp_sal, 'vtr', zts(:,:,:,jp_sal) )
+
+            DEALLOCATE( zts )
+         ENDIF
       ENDIF
-      !
-      DEALLOCATE( z3dtr )
-      !
-      IF( ln_timing )   CALL timing_stop('dia_ptr')
-      !
-   END SUBROUTINE dia_ptr
+   END SUBROUTINE dia_ptr_zint
 
 
@@ -340,5 +462,5 @@
       REAL(wp), DIMENSION(jpi,jpj) :: zmsk
       !!----------------------------------------------------------------------
-      
+
       ! l_diaptr is defined with iom_use
       !   --> dia_ptr_init must be done after the call to iom_init
@@ -347,8 +469,8 @@
          &       iom_use( 'zosrf'    ) .OR. iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) .OR.  &
          &       iom_use( 'sopstbtr' ) .OR. iom_use( 'sophtbtr' ) .OR. iom_use( 'sophtadv' ) .OR.  &
-         &       iom_use( 'sopstadv' ) .OR. iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) .OR.  & 
+         &       iom_use( 'sopstadv' ) .OR. iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) .OR.  &
          &       iom_use( 'sophteiv' ) .OR. iom_use( 'sopsteiv' ) .OR. iom_use( 'sopstvtr' ) .OR.  &
-         &       iom_use( 'sophtvtr' ) .OR. iom_use( 'uocetr_vsum_cumul' ) 
- 
+         &       iom_use( 'sophtvtr' ) .OR. iom_use( 'uocetr_vsum_cumul' )
+      
       IF(lwp) THEN                     ! Control print
          WRITE(numout,*)
@@ -398,4 +520,6 @@
          hstr_btr(:,:,:) = 0._wp           !
          hstr_vtr(:,:,:) = 0._wp           !
+         pvtr_int(:,:,:,:) = 0._wp
+         pzon_int(:,:,:,:) = 0._wp
          !
          ll_init = .FALSE.
@@ -415,61 +539,101 @@
       INTEGER                         , INTENT(in )  :: ktra  ! tracer index
       CHARACTER(len=3)                , INTENT(in)   :: cptr  ! transport type  'adv'/'ldf'/'eiv'
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: pvflx   ! 3D input array of advection/diffusion
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk)    , INTENT(in)   :: pvflx ! 3D input array of advection/diffusion
+      REAL(wp), DIMENSION(A1Dj(nn_hls),nbasin)                 :: zsj   !
       INTEGER                                        :: jn    !
 
+      DO jn = 1, nbasin
+         zsj(:,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
+      ENDDO
       !
       IF( cptr == 'adv' ) THEN
-         IF( ktra == jp_tem )  THEN
-             DO jn = 1, nbasin
-                hstr_adv(:,jp_tem,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
-         IF( ktra == jp_sal )  THEN
-             DO jn = 1, nbasin
-                hstr_adv(:,jp_sal,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
+         IF( ktra == jp_tem )  CALL ptr_sum( hstr_adv(:,jp_tem,:), zsj(:,:) )
+         IF( ktra == jp_sal )  CALL ptr_sum( hstr_adv(:,jp_sal,:), zsj(:,:) )
+      ELSE IF( cptr == 'ldf' ) THEN
+         IF( ktra == jp_tem )  CALL ptr_sum( hstr_ldf(:,jp_tem,:), zsj(:,:) )
+         IF( ktra == jp_sal )  CALL ptr_sum( hstr_ldf(:,jp_sal,:), zsj(:,:) )
+      ELSE IF( cptr == 'eiv' ) THEN
+         IF( ktra == jp_tem )  CALL ptr_sum( hstr_eiv(:,jp_tem,:), zsj(:,:) )
+         IF( ktra == jp_sal )  CALL ptr_sum( hstr_eiv(:,jp_sal,:), zsj(:,:) )
+      ELSE IF( cptr == 'vtr' ) THEN
+         IF( ktra == jp_tem )  CALL ptr_sum( hstr_vtr(:,jp_tem,:), zsj(:,:) )
+         IF( ktra == jp_sal )  CALL ptr_sum( hstr_vtr(:,jp_sal,:), zsj(:,:) )
       ENDIF
       !
-      IF( cptr == 'ldf' ) THEN
-         IF( ktra == jp_tem )  THEN
-             DO jn = 1, nbasin
-                hstr_ldf(:,jp_tem,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
-         IF( ktra == jp_sal )  THEN
-             DO jn = 1, nbasin
-                hstr_ldf(:,jp_sal,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
+   END SUBROUTINE dia_ptr_hst
+
+
+   SUBROUTINE ptr_sum_2d( phstr, pva )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ptr_sum_2d ***
+      !!----------------------------------------------------------------------
+      !! ** Purpose : Add two 2D arrays with (j,nbasin) dimensions
+      !!
+      !! ** Method  : - phstr = phstr + pva
+      !!              - Call mpp_sum if the final tile
+      !!
+      !! ** Action  : phstr
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpj,nbasin) , INTENT(inout)         ::  phstr  !
+      REAL(wp), DIMENSION(A1Dj(nn_hls),nbasin), INTENT(in)            ::  pva    !
+      INTEGER                                               ::  jj
+#if defined key_mpp_mpi
+      INTEGER, DIMENSION(1)           ::  ish1d
+      INTEGER, DIMENSION(2)           ::  ish2d
+      REAL(wp), DIMENSION(jpj*nbasin) ::  zwork
+#endif
+
+      DO jj = ntsj, ntej
+         phstr(jj,:) = phstr(jj,:)  + pva(jj,:)
+      END DO
+
+#if defined key_mpp_mpi
+      IF( ntile == 0 .OR. ntile == nijtile ) THEN
+         ish1d(1) = jpj*nbasin
+         ish2d(1) = jpj ; ish2d(2) = nbasin
+         zwork(:) = RESHAPE( phstr(:,:), ish1d )
+         CALL mpp_sum( 'diaptr', zwork, ish1d(1), ncomm_znl )
+         phstr(:,:) = RESHAPE( zwork, ish2d )
       ENDIF
-      !
-      IF( cptr == 'eiv' ) THEN
-         IF( ktra == jp_tem )  THEN
-             DO jn = 1, nbasin
-                hstr_eiv(:,jp_tem,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
-         IF( ktra == jp_sal )  THEN
-             DO jn = 1, nbasin
-                hstr_eiv(:,jp_sal,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
+#endif
+   END SUBROUTINE ptr_sum_2d
+
+
+   SUBROUTINE ptr_sum_3d( phstr, pva )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ptr_sum_3d ***
+      !!----------------------------------------------------------------------
+      !! ** Purpose : Add two 3D arrays with (j,k,nbasin) dimensions
+      !!
+      !! ** Method  : - phstr = phstr + pva
+      !!              - Call mpp_sum if the final tile
+      !!
+      !! ** Action  : phstr
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpj,jpk,nbasin) , INTENT(inout)     ::  phstr  !
+      REAL(wp), DIMENSION(A1Dj(nn_hls),jpk,nbasin), INTENT(in)        ::  pva    !
+      INTEGER                                               ::  jj, jk
+#if defined key_mpp_mpi
+      INTEGER, DIMENSION(1)              ::  ish1d
+      INTEGER, DIMENSION(3)              ::  ish3d
+      REAL(wp), DIMENSION(jpj*jpk*nbasin)  ::  zwork
+#endif
+
+      DO jk = 1, jpk
+         DO jj = ntsj, ntej
+            phstr(jj,jk,:) = phstr(jj,jk,:)  + pva(jj,jk,:)
+         END DO
+      END DO
+
+#if defined key_mpp_mpi
+      IF( ntile == 0 .OR. ntile == nijtile ) THEN
+         ish1d(1) = jpj*jpk*nbasin
+         ish3d(1) = jpj ; ish3d(2) = jpk ; ish3d(3) = nbasin
+         zwork(:) = RESHAPE( phstr(:,:,:), ish1d )
+         CALL mpp_sum( 'diaptr', zwork, ish1d(1), ncomm_znl )
+         phstr(:,:,:) = RESHAPE( zwork, ish3d )
       ENDIF
-      !
-      IF( cptr == 'vtr' ) THEN
-         IF( ktra == jp_tem )  THEN
-             DO jn = 1, nbasin
-                hstr_vtr(:,jp_tem,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
-         IF( ktra == jp_sal )  THEN
-             DO jn = 1, nbasin
-                hstr_vtr(:,jp_sal,jn) = ptr_sj( pvflx(:,:,:), btmsk(:,:,jn) )
-             ENDDO
-         ENDIF
-      ENDIF
-      !
-   END SUBROUTINE dia_ptr_hst
+#endif
+   END SUBROUTINE ptr_sum_3d
 
 
@@ -479,5 +643,5 @@
       !!----------------------------------------------------------------------
       INTEGER               ::   dia_ptr_alloc   ! return value
-      INTEGER, DIMENSION(3) ::   ierr
+      INTEGER, DIMENSION(2) ::   ierr
       !!----------------------------------------------------------------------
       ierr(:) = 0
@@ -491,5 +655,6 @@
             &      hstr_ldf(jpj,jpts,nbasin), hstr_vtr(jpj,jpts,nbasin), STAT=ierr(1)  )
             !
-         ALLOCATE( p_fval1d(jpj), p_fval2d(jpj,jpk), Stat=ierr(2))
+         ALLOCATE( pvtr_int(jpj,jpk,jpts+2,nbasin), &
+            &      pzon_int(jpj,jpk,jpts+1,nbasin), STAT=ierr(2) )
          !
          dia_ptr_alloc = MAXVAL( ierr )
@@ -511,23 +676,15 @@
       !! ** Action  : - p_fval: i-k-mean poleward flux of pvflx
       !!----------------------------------------------------------------------
-      REAL(wp), INTENT(in), DIMENSION(jpi,jpj,jpk)  ::   pvflx  ! mask flux array at V-point
-      REAL(wp), INTENT(in), DIMENSION(jpi,jpj)      ::   pmsk   ! Optional 2D basin mask
+      REAL(wp), INTENT(in), DIMENSION(A2D(nn_hls),jpk)  ::   pvflx  ! mask flux array at V-point
+      REAL(wp), INTENT(in), DIMENSION(jpi,jpj)  ::   pmsk   ! Optional 2D basin mask
       !
       INTEGER                  ::   ji, jj, jk   ! dummy loop arguments
-      INTEGER                  ::   ijpj         ! ???
-      REAL(wp), POINTER, DIMENSION(:) :: p_fval  ! function value
+      REAL(wp), DIMENSION(A1Dj(nn_hls)) :: p_fval  ! function value
       !!--------------------------------------------------------------------
       !
-      p_fval => p_fval1d
-
-      ijpj = jpj
       p_fval(:) = 0._wp
       DO_3D( 0, 0, 0, 0, 1, jpkm1 )
          p_fval(jj) = p_fval(jj) + pvflx(ji,jj,jk) * pmsk(ji,jj) * tmask_i(ji,jj)
       END_3D
-#if defined key_mpp_mpi
-      CALL mpp_sum( 'diaptr', p_fval, ijpj, ncomm_znl)
-#endif
-      !
    END FUNCTION ptr_sj_3d
 
@@ -544,23 +701,15 @@
       !! ** Action  : - p_fval: i-k-mean poleward flux of pvflx
       !!----------------------------------------------------------------------
-      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj) ::   pvflx  ! mask flux array at V-point
+      REAL(wp) , INTENT(in), DIMENSION(A2D(nn_hls))     ::   pvflx  ! mask flux array at V-point
       REAL(wp) , INTENT(in), DIMENSION(jpi,jpj) ::   pmsk   ! Optional 2D basin mask
       !
       INTEGER                  ::   ji,jj       ! dummy loop arguments
-      INTEGER                  ::   ijpj        ! ???
-      REAL(wp), POINTER, DIMENSION(:) :: p_fval ! function value
+      REAL(wp), DIMENSION(A1Dj(nn_hls)) :: p_fval ! function value
       !!--------------------------------------------------------------------
-      ! 
-      p_fval => p_fval1d
-
-      ijpj = jpj
+      !
       p_fval(:) = 0._wp
       DO_2D( 0, 0, 0, 0 )
          p_fval(jj) = p_fval(jj) + pvflx(ji,jj) * pmsk(ji,jj) * tmask_i(ji,jj)
       END_2D
-#if defined key_mpp_mpi
-      CALL mpp_sum( 'diaptr', p_fval, ijpj, ncomm_znl )
-#endif
-      ! 
    END FUNCTION ptr_sj_2d
 
@@ -588,5 +737,4 @@
             p_fval(ji,jj) = p_fval(ji,jj-1) + pva(ji,jj) * tmask_i(ji,jj)
          END_2D
-         CALL lbc_lnk( 'diaptr', p_fval, 'U', -1.0_wp )
       END DO
       ! 
@@ -607,19 +755,11 @@
       !!
       IMPLICIT none
-      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj,jpk) ::   pta    ! mask flux array at V-point
-      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj)     ::   pmsk   ! Optional 2D basin mask
+      REAL(wp) , INTENT(in), DIMENSION(A2D(nn_hls),jpk) ::   pta    ! mask flux array at V-point
+      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj) ::   pmsk   ! Optional 2D basin mask
       !!
       INTEGER                           :: ji, jj, jk ! dummy loop arguments
-      REAL(wp), POINTER, DIMENSION(:,:) :: p_fval     ! return function value
-#if defined key_mpp_mpi
-      INTEGER, DIMENSION(1) ::   ish
-      INTEGER, DIMENSION(2) ::   ish2
-      INTEGER               ::   ijpjjpk
-      REAL(wp), DIMENSION(jpj*jpk) ::   zwork    ! mask flux array at V-point
-#endif
+      REAL(wp), DIMENSION(A1Dj(nn_hls),jpk) :: p_fval     ! return function value
       !!--------------------------------------------------------------------
       !
-      p_fval => p_fval2d
-
       p_fval(:,:) = 0._wp
       !
@@ -627,13 +767,4 @@
          p_fval(jj,jk) = p_fval(jj,jk) + pta(ji,jj,jk) * pmsk(ji,jj) * tmask_i(ji,jj)
       END_3D
-      !
-#if defined key_mpp_mpi
-      ijpjjpk = jpj*jpk
-      ish(1) = ijpjjpk  ;   ish2(1) = jpj   ;   ish2(2) = jpk
-      zwork(1:ijpjjpk) = RESHAPE( p_fval, ish )
-      CALL mpp_sum( 'diaptr', zwork, ijpjjpk, ncomm_znl )
-      p_fval(:,:) = RESHAPE( zwork, ish2 )
-#endif
-      !
    END FUNCTION ptr_sjk
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diawri.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diawri.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DIA/diawri.F90	(revision 14055)
@@ -46,4 +46,5 @@
    USE zdfdrg         ! ocean vertical physics: top/bottom friction
    USE zdfmxl         ! mixed layer
+   USE zdfosm         ! mixed layer
    !
    USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
@@ -1083,4 +1084,17 @@
          CALL iom_rstput ( 0, 0, inum, "qz1_abl",  tq_abl(:,:,2,nt_a,2) )   ! now first level humidity
       ENDIF
+      IF( ln_zdfosm ) THEN
+         CALL iom_rstput( 0, 0, inum, 'hbl', hbl*tmask(:,:,1)  )      ! now boundary-layer depth
+         CALL iom_rstput( 0, 0, inum, 'hml', hml*tmask(:,:,1)  )      ! now mixed-layer depth
+         CALL iom_rstput( 0, 0, inum, 'avt_k', avt_k*wmask     )      ! w-level diffusion
+         CALL iom_rstput( 0, 0, inum, 'avm_k', avm_k*wmask     )      ! now w-level viscosity
+         CALL iom_rstput( 0, 0, inum, 'ghamt', ghamt*wmask     )      ! non-local t forcing
+         CALL iom_rstput( 0, 0, inum, 'ghams', ghams*wmask     )      ! non-local s forcing
+         CALL iom_rstput( 0, 0, inum, 'ghamu', ghamu*umask     )      ! non-local u forcing
+         CALL iom_rstput( 0, 0, inum, 'ghamv', ghamv*vmask     )      ! non-local v forcing
+         IF( ln_osm_mle ) THEN
+            CALL iom_rstput( 0, 0, inum, 'hmle', hmle*tmask(:,:,1)  ) ! now transition-layer depth
+         END IF
+      ENDIF
       !
       CALL iom_close( inum )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/daymod.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/daymod.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/daymod.F90	(revision 14055)
@@ -149,12 +149,4 @@
       CALL day( nit000 )
       !
-      IF( lwxios ) THEN
-! define variables in restart file when writing with XIOS
-          CALL iom_set_rstw_var_active('kt')
-          CALL iom_set_rstw_var_active('ndastp')
-          CALL iom_set_rstw_var_active('adatrj')
-          CALL iom_set_rstw_var_active('ntime')
-      ENDIF
-
    END SUBROUTINE day_init
 
@@ -324,8 +316,7 @@
 
       IF( TRIM(cdrw) == 'READ' ) THEN
-
          IF( iom_varid( numror, 'kt', ldstop = .FALSE. ) > 0 ) THEN
             ! Get Calendar informations
-            CALL iom_get( numror, 'kt', zkt, ldxios = lrxios )   ! last time-step of previous run
+            CALL iom_get( numror, 'kt', zkt )   ! last time-step of previous run
             IF(lwp) THEN
                WRITE(numout,*) ' *** Info read in restart : '
@@ -346,8 +337,8 @@
             IF ( nrstdt == 2 ) THEN
                ! read the parameters corresponding to nit000 - 1 (last time step of previous run)
-               CALL iom_get( numror, 'ndastp', zndastp, ldxios = lrxios )
+               CALL iom_get( numror, 'ndastp', zndastp )
                ndastp = NINT( zndastp )
-               CALL iom_get( numror, 'adatrj', adatrj , ldxios = lrxios )
-	       CALL iom_get( numror, 'ntime' , ktime  , ldxios = lrxios )
+               CALL iom_get( numror, 'adatrj', adatrj  )
+	       CALL iom_get( numror, 'ntime' , ktime   )
                nn_time0 = NINT(ktime)
                ! calculate start time in hours and minutes
@@ -410,11 +401,9 @@
          ENDIF
          ! calendar control
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'kt'     , REAL( kt    , wp)  , ldxios = lwxios )   ! time-step
-         CALL iom_rstput( kt, nitrst, numrow, 'ndastp' , REAL( ndastp, wp)  , ldxios = lwxios )   ! date
-         CALL iom_rstput( kt, nitrst, numrow, 'adatrj' , adatrj             , ldxios = lwxios            )   ! number of elapsed days since
+         CALL iom_rstput( kt, nitrst, numrow, 'kt'     , REAL( kt    , wp)   )   ! time-step
+         CALL iom_rstput( kt, nitrst, numrow, 'ndastp' , REAL( ndastp, wp)   )   ! date
+         CALL iom_rstput( kt, nitrst, numrow, 'adatrj' , adatrj              )   ! number of elapsed days since
          !                                                                                                   ! the begining of the run [s]
-         CALL iom_rstput( kt, nitrst, numrow, 'ntime'  , REAL( nn_time0, wp), ldxios = lwxios ) ! time
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'ntime'  , REAL( nn_time0, wp) ) ! time
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/dom_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/dom_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/dom_oce.F90	(revision 14055)
@@ -74,4 +74,14 @@
    LOGICAL, PUBLIC ::   l_Iperio, l_Jperio   !   should we explicitely take care I/J periodicity 
 
+   ! Tiling namelist
+   LOGICAL, PUBLIC ::   ln_tile
+   INTEGER         ::   nn_ltile_i, nn_ltile_j
+
+   ! Domain tiling (all tiles)
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ntsi_a       !: start of internal part of tile domain
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ntsj_a       !
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ntei_a       !: end of internal part of tile domain
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ntej_a       !
+
    !                             !: domain MPP decomposition parameters
    INTEGER             , PUBLIC ::   nimpp, njmpp     !: i- & j-indexes for mpp-subdomain left bottom
@@ -87,4 +97,8 @@
    INTEGER, PUBLIC ::   noea, nowe        !: index of the local neighboring processors in
    INTEGER, PUBLIC ::   noso, nono        !: east, west, south and north directions
+   INTEGER, PUBLIC ::   nones, nonws        !: north-east, north-west directions for sending 
+   INTEGER, PUBLIC ::   noses, nosws        !: south-east, south-west directions for sending
+   INTEGER, PUBLIC ::   noner, nonwr        !: north-east, north-west directions for receiving
+   INTEGER, PUBLIC ::   noser, noswr        !: south-east, south-west directions for receiving
    INTEGER, PUBLIC ::   nidom             !: ???
 
@@ -296,9 +310,9 @@
       ALLOCATE( e3t(jpi,jpj,jpk,jpt) , e3u (jpi,jpj,jpk,jpt) , e3v (jpi,jpj,jpk,jpt) , e3f(jpi,jpj,jpk) ,      &
          &      e3w(jpi,jpj,jpk,jpt) , e3uw(jpi,jpj,jpk,jpt) , e3vw(jpi,jpj,jpk,jpt)                    ,  STAT=ierr(ii) )
-#endif  
+#endif
          !
       ii = ii+1
       ALLOCATE( r3t  (jpi,jpj,jpt)   , r3u  (jpi,jpj,jpt)    , r3v  (jpi,jpj,jpt)    , r3f  (jpi,jpj) ,  &
-         &      r3t_f(jpi,jpj)       , r3u_f(jpi,jpj)        , r3v_f(jpi,jpj)                         ,  STAT=ierr(ii) )       
+         &      r3t_f(jpi,jpj)       , r3u_f(jpi,jpj)        , r3v_f(jpi,jpj)                         ,  STAT=ierr(ii) )
          !
       ii = ii+1
@@ -317,5 +331,5 @@
          !
       ii = ii+1
-      ALLOCATE( risfdep(jpi,jpj) , bathy(jpi,jpj) , STAT=ierr(ii)  ) 
+      ALLOCATE( risfdep(jpi,jpj) , bathy(jpi,jpj) , STAT=ierr(ii)  )
          !
       ii = ii+1
@@ -323,5 +337,5 @@
          !
       ii = ii+1
-      ALLOCATE( tmask_i(jpi,jpj) , tmask_h(jpi,jpj) ,                        & 
+      ALLOCATE( tmask_i(jpi,jpj) , tmask_h(jpi,jpj) ,                        &
          &      ssmask (jpi,jpj) , ssumask(jpi,jpj) , ssvmask(jpi,jpj) , ssfmask(jpi,jpj) ,     &
          &      mbkt   (jpi,jpj) , mbku   (jpi,jpj) , mbkv   (jpi,jpj) ,                    STAT=ierr(ii) )
@@ -331,5 +345,5 @@
          !
       ii = ii+1
-      ALLOCATE( tmask(jpi,jpj,jpk) , umask(jpi,jpj,jpk) ,     & 
+      ALLOCATE( tmask(jpi,jpj,jpk) , umask(jpi,jpj,jpk) ,     &
          &      vmask(jpi,jpj,jpk) , fmask(jpi,jpj,jpk) , STAT=ierr(ii) )
          !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domain.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domain.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domain.F90	(revision 14055)
@@ -45,4 +45,5 @@
    USE closea , ONLY : dom_clo ! closed seas
    !
+   USE prtctl         ! Print control (prt_ctl_info routine)
    USE in_out_manager ! I/O manager
    USE iom            ! I/O library
@@ -55,4 +56,5 @@
    PUBLIC   dom_init     ! called by nemogcm.F90
    PUBLIC   domain_cfg   ! called by nemogcm.F90
+   PUBLIC   dom_tile     ! called by step.F90
 
    !!-------------------------------------------------------------------------
@@ -63,5 +65,5 @@
 CONTAINS
 
-   SUBROUTINE dom_init( Kbb, Kmm, Kaa, cdstr )
+   SUBROUTINE dom_init( Kbb, Kmm, Kaa )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE dom_init  ***
@@ -79,5 +81,4 @@
       !!----------------------------------------------------------------------
       INTEGER          , INTENT(in) :: Kbb, Kmm, Kaa          ! ocean time level indices
-      CHARACTER (len=*), INTENT(in) :: cdstr                  ! model: NEMO or SAS. Determines core restart variables
       !
       INTEGER ::   ji, jj, jk, jt   ! dummy loop indices
@@ -120,22 +121,13 @@
          WRITE(numout,*)     '         cn_cfg = ', TRIM( cn_cfg ), '   nn_cfg = ', nn_cfg
       ENDIF
+      nn_wxios = 0
+      ln_xios_read = .FALSE.
       !
       !           !==  Reference coordinate system  ==!
       !
-      CALL dom_glo                     ! global domain versus local domain
-      CALL dom_nam                     ! read namelist ( namrun, namdom )
-      !
-      IF( lwxios ) THEN
-!define names for restart write and set core output (restart.F90)
-         CALL iom_set_rst_vars(rst_wfields)
-         CALL iom_set_rstw_core(cdstr)
-      ENDIF
-!reset namelist for SAS
-      IF(cdstr == 'SAS') THEN
-         IF(lrxios) THEN
-               IF(lwp) write(numout,*) 'Disable reading restart file using XIOS for SAS'
-               lrxios = .FALSE.
-         ENDIF
-      ENDIF
+      CALL dom_glo                            ! global domain versus local domain
+      CALL dom_nam                            ! read namelist ( namrun, namdom )
+      CALL dom_tile( ntsi, ntsj, ntei, ntej ) ! Tile domain
+
       !
       CALL dom_hgr                      ! Horizontal mesh
@@ -285,4 +277,87 @@
 
 
+   SUBROUTINE dom_tile( ktsi, ktsj, ktei, ktej, ktile )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_tile  ***
+      !!
+      !! ** Purpose :   Set tile domain variables
+      !!
+      !! ** Action  : - ktsi, ktsj     : start of internal part of domain
+      !!              - ktei, ktej     : end of internal part of domain
+      !!              - ntile          : current tile number
+      !!              - nijtile        : total number of tiles
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(out) :: ktsi, ktsj, ktei, ktej      ! Tile domain indices
+      INTEGER, INTENT(in), OPTIONAL :: ktile              ! Tile number
+      INTEGER ::   jt                                     ! dummy loop argument
+      INTEGER ::   iitile, ijtile                         ! Local integers
+      CHARACTER (len=11) ::   charout
+      !!----------------------------------------------------------------------
+      IF( PRESENT(ktile) .AND. ln_tile ) THEN
+         ntile = ktile                 ! Set domain indices for tile
+         ktsi = ntsi_a(ktile)
+         ktsj = ntsj_a(ktile)
+         ktei = ntei_a(ktile)
+         ktej = ntej_a(ktile)
+
+         IF(sn_cfctl%l_prtctl) THEN
+            WRITE(charout, FMT="('ntile =', I4)") ktile
+            CALL prt_ctl_info( charout )
+         ENDIF
+      ELSE
+         ntile = 0                     ! Initialise to full domain
+         nijtile = 1
+         ktsi = Nis0
+         ktsj = Njs0
+         ktei = Nie0
+         ktej = Nje0
+
+         IF( ln_tile ) THEN            ! Calculate tile domain indices
+            iitile = Ni_0 / nn_ltile_i       ! Number of tiles
+            ijtile = Nj_0 / nn_ltile_j
+            IF( MOD( Ni_0, nn_ltile_i ) /= 0 ) iitile = iitile + 1
+            IF( MOD( Nj_0, nn_ltile_j ) /= 0 ) ijtile = ijtile + 1
+
+            nijtile = iitile * ijtile
+            ALLOCATE( ntsi_a(0:nijtile), ntsj_a(0:nijtile), ntei_a(0:nijtile), ntej_a(0:nijtile) )
+
+            ntsi_a(0) = ktsi                 ! Full domain
+            ntsj_a(0) = ktsj
+            ntei_a(0) = ktei
+            ntej_a(0) = ktej
+
+            DO jt = 1, nijtile               ! Tile domains
+               ntsi_a(jt) = Nis0 + nn_ltile_i * MOD(jt - 1, iitile)
+               ntsj_a(jt) = Njs0 + nn_ltile_j * ((jt - 1) / iitile)
+               ntei_a(jt) = MIN(ntsi_a(jt) + nn_ltile_i - 1, Nie0)
+               ntej_a(jt) = MIN(ntsj_a(jt) + nn_ltile_j - 1, Nje0)
+            ENDDO
+         ENDIF
+
+         IF(lwp) THEN                  ! control print
+            WRITE(numout,*)
+            WRITE(numout,*) 'dom_tile : Domain tiling decomposition'
+            WRITE(numout,*) '~~~~~~~~'
+            IF( ln_tile ) THEN
+               WRITE(numout,*) iitile, 'tiles in i'
+               WRITE(numout,*) '    Starting indices'
+               WRITE(numout,*) '        ', (ntsi_a(jt), jt=1, iitile)
+               WRITE(numout,*) '    Ending indices'
+               WRITE(numout,*) '        ', (ntei_a(jt), jt=1, iitile)
+               WRITE(numout,*) ijtile, 'tiles in j'
+               WRITE(numout,*) '    Starting indices'
+               WRITE(numout,*) '        ', (ntsj_a(jt), jt=1, nijtile, iitile)
+               WRITE(numout,*) '    Ending indices'
+               WRITE(numout,*) '        ', (ntej_a(jt), jt=1, nijtile, iitile)
+            ELSE
+               WRITE(numout,*) 'No domain tiling'
+               WRITE(numout,*) '    i indices =', ktsi, ':', ktei
+               WRITE(numout,*) '    j indices =', ktsj, ':', ktej
+            ENDIF
+         ENDIF
+      ENDIF
+   END SUBROUTINE dom_tile
+
+
    SUBROUTINE dom_nam
       !!----------------------------------------------------------------------
@@ -293,4 +368,5 @@
       !! ** input   : - namrun namelist
       !!              - namdom namelist
+      !!              - namtile namelist
       !!              - namnc4 namelist   ! "key_netcdf4" only
       !!----------------------------------------------------------------------
@@ -305,4 +381,5 @@
          &             ln_cfmeta, ln_xios_read, nn_wxios
       NAMELIST/namdom/ ln_linssh, rn_Dt, rn_atfp, ln_crs, ln_meshmask
+      NAMELIST/namtile/ ln_tile, nn_ltile_i, nn_ltile_j
 #if defined key_netcdf4
       NAMELIST/namnc4/ nn_nchunks_i, nn_nchunks_j, nn_nchunks_k, ln_nc4zip
@@ -443,4 +520,24 @@
       r1_Dt = 1._wp / rDt
 
+      READ  ( numnam_ref, namtile, IOSTAT = ios, ERR = 905 )
+905   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtile in reference namelist' )
+      READ  ( numnam_cfg, namtile, IOSTAT = ios, ERR = 906 )
+906   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtile in configuration namelist' )
+      IF(lwm) WRITE( numond, namtile )
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)    '   Namelist : namtile   ---   Domain tiling decomposition'
+         WRITE(numout,*)    '      Tiling (T) or not (F)                ln_tile    = ', ln_tile
+         WRITE(numout,*)    '      Length of tile in i                  nn_ltile_i = ', nn_ltile_i
+         WRITE(numout,*)    '      Length of tile in j                  nn_ltile_j = ', nn_ltile_j
+         WRITE(numout,*)
+         IF( ln_tile ) THEN
+            WRITE(numout,*) '      The domain will be decomposed into tiles of size', nn_ltile_i, 'x', nn_ltile_j
+         ELSE
+            WRITE(numout,*) '      Domain tiling will NOT be used'
+         ENDIF
+      ENDIF
+
       IF( TRIM(Agrif_CFixed()) == '0' ) THEN
          lrxios = ln_xios_read.AND.ln_rstart
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domqco.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domqco.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domqco.F90	(revision 14055)
@@ -91,9 +91,4 @@
       !
       CALL dom_qco_zgr(Kbb, Kmm, Kaa) ! interpolation scale factor, depth and water column
-      !
-      ! IF(lwxios) THEN   ! define variables in restart file when writing with XIOS
-      !    CALL iom_set_rstw_var_active('e3t_b')
-      !    CALL iom_set_rstw_var_active('e3t_n')
-      ! ENDIF
       !
    END SUBROUTINE dom_qco_init
@@ -217,6 +212,6 @@
             !
             IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
-               CALL iom_get( numror, jpdom_auto, 'sshb'   , ssh(:,:,Kbb), ldxios = lrxios    )
-               CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm), ldxios = lrxios    )
+               CALL iom_get( numror, jpdom_auto, 'sshb'   , ssh(:,:,Kbb)    )
+               CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm)    )
                ! needed to restart if land processor not computed
                IF(lwp) write(numout,*) 'qe_rst_read : ssh(:,:,Kbb) and ssh(:,:,Kmm) found in restart files'
@@ -232,5 +227,5 @@
                IF(lwp) write(numout,*) 'sshn set equal to sshb.'
                IF(lwp) write(numout,*) 'neuler is forced to 0'
-               CALL iom_get( numror, jpdom_auto, 'sshb', ssh(:,:,Kbb), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'sshb', ssh(:,:,Kbb) )
                ssh(:,:,Kmm) = ssh(:,:,Kbb)
                l_1st_euler = .TRUE.
@@ -239,5 +234,5 @@
                IF(lwp) write(numout,*) 'sshb set equal to sshn.'
                IF(lwp) write(numout,*) 'neuler is forced to 0'
-               CALL iom_get( numror, jpdom_auto, 'sshn', ssh(:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'sshn', ssh(:,:,Kmm) )
                ssh(:,:,Kbb) = ssh(:,:,Kmm)
                l_1st_euler = .TRUE.
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domutl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domutl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domutl.F90	(revision 14055)
@@ -21,6 +21,11 @@
    PRIVATE
 
+   INTERFACE is_tile
+      MODULE PROCEDURE is_tile_2d, is_tile_3d, is_tile_4d
+   END INTERFACE is_tile
+
    PUBLIC dom_ngb    ! routine called in iom.F90 module
    PUBLIC dom_uniq   ! Called by dommsk and domwri
+   PUBLIC is_tile
 
    !!----------------------------------------------------------------------
@@ -109,5 +114,44 @@
       !
    END SUBROUTINE dom_uniq
-   
+
+
+   FUNCTION is_tile_2d( pt )
+      !!
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pt
+      INTEGER :: is_tile_2d
+      !!
+      IF( ln_tile .AND. (SIZE(pt, 1) < jpi .OR. SIZE(pt, 2) < jpj) ) THEN
+         is_tile_2d = 1
+      ELSE
+         is_tile_2d = 0
+      ENDIF
+   END FUNCTION is_tile_2d
+
+
+   FUNCTION is_tile_3d( pt )
+      !!
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   pt
+      INTEGER :: is_tile_3d
+      !!
+      IF( ln_tile .AND. (SIZE(pt, 1) < jpi .OR. SIZE(pt, 2) < jpj) ) THEN
+         is_tile_3d = 1
+      ELSE
+         is_tile_3d = 0
+      ENDIF
+   END FUNCTION is_tile_3d
+
+
+   FUNCTION is_tile_4d( pt )
+      !!
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in) ::   pt
+      INTEGER :: is_tile_4d
+      !!
+      IF( ln_tile .AND. (SIZE(pt, 1) < jpi .OR. SIZE(pt, 2) < jpj) ) THEN
+         is_tile_4d = 1
+      ELSE
+         is_tile_4d = 0
+      ENDIF
+   END FUNCTION is_tile_4d
+
    !!======================================================================
 END MODULE domutl
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domvvl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domvvl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/domvvl.F90	(revision 14055)
@@ -287,22 +287,4 @@
       ENDIF
       !
-      IF(lwxios) THEN
-! define variables in restart file when writing with XIOS
-         CALL iom_set_rstw_var_active('e3t_b')
-         CALL iom_set_rstw_var_active('e3t_n')
-         !                                           ! ----------------------- !
-         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
-            !                                        ! ----------------------- !
-            CALL iom_set_rstw_var_active('tilde_e3t_b')
-            CALL iom_set_rstw_var_active('tilde_e3t_n')
-         END IF
-         !                                           ! -------------!    
-         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
-            !                                        ! ------------ !
-            CALL iom_set_rstw_var_active('hdiv_lf')
-         ENDIF
-         !
-      ENDIF
-      !
    END SUBROUTINE dom_vvl_zgr
 
@@ -815,5 +797,5 @@
 #endif
                CALL rst_read_open                  !  open the restart file if necessary
-               CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm), ldxios = lrxios    )
+               CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm)   )
                !
                id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
@@ -830,6 +812,6 @@
             !
             IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb) )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm) )
                ! needed to restart if land processor not computed 
                IF(lwp) write(numout,*) 'dom_vvl_rst : e3t(:,:,:,Kbb) and e3t(:,:,:,Kmm) found in restart files'
@@ -845,5 +827,5 @@
                IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb) )
                e3t(:,:,:,Kmm) = e3t(:,:,:,Kbb)
                l_1st_euler = .true.
@@ -852,5 +834,5 @@
                IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm) )
                e3t(:,:,:,Kbb) = e3t(:,:,:,Kmm)
                l_1st_euler = .true.
@@ -877,6 +859,6 @@
                !                          ! ----------------------- !
                IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:) )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:) )
                ELSE                            ! one at least array is missing
                   tilde_e3t_b(:,:,:) = 0.0_wp
@@ -887,5 +869,5 @@
                   !                       ! ------------ !
                   IF( id5 > 0 ) THEN  ! required array exists
-                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:) )
                   ELSE                ! array is missing
                      hdiv_lf(:,:,:) = 0.0_wp
@@ -975,23 +957,21 @@
          !                                   ! ===================
          IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
          !                                           ! --------- !
          !                                           ! all cases !
          !                                           ! --------- !
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb) )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm) )
          !                                           ! ----------------------- !
          IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
             !                                        ! ----------------------- !
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:))
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:))
          END IF
          !                                           ! -------------!    
          IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
             !                                        ! ------------ !
-            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:))
          ENDIF
          !
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/dtatsd.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/dtatsd.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DOM/dtatsd.F90	(revision 14055)
@@ -18,4 +18,5 @@
    USE phycst          ! physical constants
    USE dom_oce         ! ocean space and time domain
+   USE domain, ONLY : dom_tile
    USE fldread         ! read input fields
    !
@@ -135,56 +136,67 @@
       !! ** Action  :   ptsd   T-S data on medl mesh and interpolated at time-step kt
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   ) ::   kt     ! ocean time-step
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   ptsd   ! T & S data
+      INTEGER                          , INTENT(in   ) ::   kt     ! ocean time-step
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk,jpts), INTENT(  out) ::   ptsd   ! T & S data
       !
       INTEGER ::   ji, jj, jk, jl, jkk   ! dummy loop indicies
       INTEGER ::   ik, il0, il1, ii0, ii1, ij0, ij1   ! local integers
+      INTEGER ::   itile
       REAL(wp)::   zl, zi                             ! local scalars
       REAL(wp), DIMENSION(jpk) ::  ztp, zsp   ! 1D workspace
       !!----------------------------------------------------------------------
       !
-      CALL fld_read( kt, 1, sf_tsd )      !==   read T & S data at kt time step   ==!
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                                         ! Do only for the full domain
+         itile = ntile
+         IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )            ! Use full domain
+            CALL fld_read( kt, 1, sf_tsd )   !==   read T & S data at kt time step   ==!
       !
       !
 !!gm  This should be removed from the code   ===>>>>  T & S files has to be changed
-      !
-      !                                   !==   ORCA_R2 configuration and T & S damping   ==! 
-      IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN
-         IF( nn_cfg == 2 .AND. ln_tsd_dmp ) THEN    ! some hand made alterations
-            !
-            ij0 = 101 + nn_hls       ;   ij1 = 109 + nn_hls                       ! Reduced T & S in the Alboran Sea
-            ii0 = 141 + nn_hls - 1   ;   ii1 = 155 + nn_hls - 1
-            DO jj = mj0(ij0), mj1(ij1)
-               DO ji = mi0(ii0), mi1(ii1)
-                  sf_tsd(jp_tem)%fnow(ji,jj,13:13) = sf_tsd(jp_tem)%fnow(ji,jj,13:13) - 0.20_wp
-                  sf_tsd(jp_tem)%fnow(ji,jj,14:15) = sf_tsd(jp_tem)%fnow(ji,jj,14:15) - 0.35_wp
-                  sf_tsd(jp_tem)%fnow(ji,jj,16:25) = sf_tsd(jp_tem)%fnow(ji,jj,16:25) - 0.40_wp
-                  !
-                  sf_tsd(jp_sal)%fnow(ji,jj,13:13) = sf_tsd(jp_sal)%fnow(ji,jj,13:13) - 0.15_wp
-                  sf_tsd(jp_sal)%fnow(ji,jj,14:15) = sf_tsd(jp_sal)%fnow(ji,jj,14:15) - 0.25_wp
-                  sf_tsd(jp_sal)%fnow(ji,jj,16:17) = sf_tsd(jp_sal)%fnow(ji,jj,16:17) - 0.30_wp
-                  sf_tsd(jp_sal)%fnow(ji,jj,18:25) = sf_tsd(jp_sal)%fnow(ji,jj,18:25) - 0.35_wp
+         !
+         !                                   !==   ORCA_R2 configuration and T & S damping   ==!
+         IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN
+            IF( nn_cfg == 2 .AND. ln_tsd_dmp ) THEN    ! some hand made alterations
+               !
+               ij0 = 101 + nn_hls       ;   ij1 = 109 + nn_hls                       ! Reduced T & S in the Alboran Sea
+               ii0 = 141 + nn_hls - 1   ;   ii1 = 155 + nn_hls - 1
+               DO jj = mj0(ij0), mj1(ij1)
+                  DO ji = mi0(ii0), mi1(ii1)
+                     sf_tsd(jp_tem)%fnow(ji,jj,13:13) = sf_tsd(jp_tem)%fnow(ji,jj,13:13) - 0.20_wp
+                     sf_tsd(jp_tem)%fnow(ji,jj,14:15) = sf_tsd(jp_tem)%fnow(ji,jj,14:15) - 0.35_wp
+                     sf_tsd(jp_tem)%fnow(ji,jj,16:25) = sf_tsd(jp_tem)%fnow(ji,jj,16:25) - 0.40_wp
+                     !
+                     sf_tsd(jp_sal)%fnow(ji,jj,13:13) = sf_tsd(jp_sal)%fnow(ji,jj,13:13) - 0.15_wp
+                     sf_tsd(jp_sal)%fnow(ji,jj,14:15) = sf_tsd(jp_sal)%fnow(ji,jj,14:15) - 0.25_wp
+                     sf_tsd(jp_sal)%fnow(ji,jj,16:17) = sf_tsd(jp_sal)%fnow(ji,jj,16:17) - 0.30_wp
+                     sf_tsd(jp_sal)%fnow(ji,jj,18:25) = sf_tsd(jp_sal)%fnow(ji,jj,18:25) - 0.35_wp
+                  END DO
                END DO
-            END DO
-            ij0 =  87 + nn_hls       ;   ij1 =  96 + nn_hls                       ! Reduced temperature in Red Sea
-            ii0 = 148 + nn_hls - 1   ;   ii1 = 160 + nn_hls - 1
-            sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ,  4:10 ) = 7.0_wp
-            sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 11:13 ) = 6.5_wp
-            sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 14:20 ) = 6.0_wp
-         ENDIF
-      ENDIF
+               ij0 =  87 + nn_hls       ;   ij1 =  96 + nn_hls                       ! Reduced temperature in Red Sea
+               ii0 = 148 + nn_hls - 1   ;   ii1 = 160 + nn_hls - 1
+               sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ,  4:10 ) = 7.0_wp
+               sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 11:13 ) = 6.5_wp
+               sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 14:20 ) = 6.0_wp
+            ENDIF
+         ENDIF
 !!gm end
-      !
-      ptsd(:,:,:,jp_tem) = sf_tsd(jp_tem)%fnow(:,:,:)    ! NO mask
-      ptsd(:,:,:,jp_sal) = sf_tsd(jp_sal)%fnow(:,:,:) 
+         IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = itile )            ! Revert to tile domain
+      ENDIF
+      !
+      DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpk )
+         ptsd(ji,jj,jk,jp_tem) = sf_tsd(jp_tem)%fnow(ji,jj,jk)    ! NO mask
+         ptsd(ji,jj,jk,jp_sal) = sf_tsd(jp_sal)%fnow(ji,jj,jk)
+      END_3D
       !
       IF( ln_sco ) THEN                   !==   s- or mixed s-zps-coordinate   ==!
          !
-         IF( kt == nit000 .AND. lwp )THEN
-            WRITE(numout,*)
-            WRITE(numout,*) 'dta_tsd: interpolates T & S data onto the s- or mixed s-z-coordinate mesh'
-         ENDIF
-         !
-         DO_2D( 1, 1, 1, 1 )                  ! vertical interpolation of T & S
+         IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+            IF( kt == nit000 .AND. lwp )THEN
+               WRITE(numout,*)
+               WRITE(numout,*) 'dta_tsd: interpolates T & S data onto the s- or mixed s-z-coordinate mesh'
+            ENDIF
+         ENDIF
+         !
+         ! NOTE: [tiling-comms-merge] This fix was necessary to take out tra_adv lbc_lnk statements in the zps case, but did not work in the zco case
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )                  ! vertical interpolation of T & S
             DO jk = 1, jpk                        ! determines the intepolated T-S profiles at each (i,j) points
                zl = gdept_0(ji,jj,jk)
@@ -215,9 +227,12 @@
       ELSE                                !==   z- or zps- coordinate   ==!
          !                             
-         ptsd(:,:,:,jp_tem) = ptsd(:,:,:,jp_tem) * tmask(:,:,:)    ! Mask
-         ptsd(:,:,:,jp_sal) = ptsd(:,:,:,jp_sal) * tmask(:,:,:)
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpk )
+            ptsd(ji,jj,jk,jp_tem) = ptsd(ji,jj,jk,jp_tem) * tmask(ji,jj,jk)    ! Mask
+            ptsd(ji,jj,jk,jp_sal) = ptsd(ji,jj,jk,jp_sal) * tmask(ji,jj,jk)
+         END_3D
          !
          IF( ln_zps ) THEN                      ! zps-coordinate (partial steps) interpolation at the last ocean level
-            DO_2D( 1, 1, 1, 1 )
+            ! NOTE: [tiling-comms-merge] This fix was necessary to take out tra_adv lbc_lnk statements in the zps case
+            DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
                ik = mbkt(ji,jj) 
                IF( ik > 1 ) THEN
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynhpg.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynhpg.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynhpg.F90	(revision 14055)
@@ -302,6 +302,7 @@
       INTEGER  ::   iku, ikv                         ! temporary integers
       REAL(wp) ::   zcoef0, zcoef1, zcoef2, zcoef3   ! temporary scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zhpi, zhpj
-      REAL(wp), DIMENSION(jpi,jpj) :: zgtsu, zgtsv, zgru, zgrv
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zhpi, zhpj
+      REAL(wp), DIMENSION(jpi,jpj,jpts)   :: zgtsu, zgtsv
+      REAL(wp), DIMENSION(jpi,jpj)     :: zgru, zgrv
       !!----------------------------------------------------------------------
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynspg.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynspg.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynspg.F90	(revision 14055)
@@ -6,4 +6,6 @@
    !! History :  1.0  ! 2005-12  (C. Talandier, G. Madec, V. Garnier)  Original code
    !!            3.2  ! 2009-07  (R. Benshila)  Suppression of rigid-lid option
+   !!            4.2  ! 2020-12  (G. Madec, E. Clementi) add Bernoulli Head for
+   !!                            wave coupling
    !!----------------------------------------------------------------------
 
@@ -19,4 +21,5 @@
    USE sbc_ice , ONLY : snwice_mass, snwice_mass_b
    USE sbcapr         ! surface boundary condition: atmospheric pressure
+   USE sbcwave,  ONLY : bhd_wave
    USE dynspg_exp     ! surface pressure gradient     (dyn_spg_exp routine)
    USE dynspg_ts      ! surface pressure gradient     (dyn_spg_ts  routine)
@@ -143,4 +146,11 @@
          ENDIF
          !
+         IF( ln_wave .and. ln_bern_srfc ) THEN          !== Add J terms: depth-independent Bernoulli head
+            DO_2D( 0, 0, 0, 0 )
+               spgu(ji,jj) = spgu(ji,jj) + ( bhd_wave(ji+1,jj) - bhd_wave(ji,jj) ) / e1u(ji,jj)   !++ bhd_wave from wave model in m2/s2 [BHD parameters in WW3]
+               spgv(ji,jj) = spgv(ji,jj) + ( bhd_wave(ji,jj+1) - bhd_wave(ji,jj) ) / e2v(ji,jj)
+            END_2D
+         ENDIF
+         !
          DO_3D( 0, 0, 0, 0, 1, jpkm1 )       !== Add all terms to the general trend
             puu(ji,jj,jk,Krhs) = puu(ji,jj,jk,Krhs) + spgu(ji,jj)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynspg_ts.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynspg_ts.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynspg_ts.F90	(revision 14055)
@@ -900,21 +900,21 @@
          !                                   ! ---------------
          IF( ln_rstart .AND. ln_bt_fw .AND. (.NOT.l_1st_euler) ) THEN    !* Read the restart file
-            CALL iom_get( numror, jpdom_auto, 'ub2_b'  , ub2_b  (:,:), cd_type = 'U', psgn = -1._wp, ldxios = lrxios )   
-            CALL iom_get( numror, jpdom_auto, 'vb2_b'  , vb2_b  (:,:), cd_type = 'V', psgn = -1._wp, ldxios = lrxios ) 
-            CALL iom_get( numror, jpdom_auto, 'un_bf'  , un_bf  (:,:), cd_type = 'U', psgn = -1._wp, ldxios = lrxios )   
-            CALL iom_get( numror, jpdom_auto, 'vn_bf'  , vn_bf  (:,:), cd_type = 'V', psgn = -1._wp, ldxios = lrxios ) 
+            CALL iom_get( numror, jpdom_auto, 'ub2_b'  , ub2_b  (:,:), cd_type = 'U', psgn = -1._wp )   
+            CALL iom_get( numror, jpdom_auto, 'vb2_b'  , vb2_b  (:,:), cd_type = 'V', psgn = -1._wp ) 
+            CALL iom_get( numror, jpdom_auto, 'un_bf'  , un_bf  (:,:), cd_type = 'U', psgn = -1._wp )   
+            CALL iom_get( numror, jpdom_auto, 'vn_bf'  , vn_bf  (:,:), cd_type = 'V', psgn = -1._wp ) 
             IF( .NOT.ln_bt_av ) THEN
-               CALL iom_get( numror, jpdom_auto, 'sshbb_e'  , sshbb_e(:,:), cd_type = 'T', psgn =  1._wp, ldxios = lrxios )   
-               CALL iom_get( numror, jpdom_auto, 'ubb_e'    ,   ubb_e(:,:), cd_type = 'U', psgn = -1._wp, ldxios = lrxios )   
-               CALL iom_get( numror, jpdom_auto, 'vbb_e'    ,   vbb_e(:,:), cd_type = 'V', psgn = -1._wp, ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'sshb_e'   ,  sshb_e(:,:), cd_type = 'T', psgn =  1._wp, ldxios = lrxios ) 
-               CALL iom_get( numror, jpdom_auto, 'ub_e'     ,    ub_e(:,:), cd_type = 'U', psgn = -1._wp, ldxios = lrxios )   
-               CALL iom_get( numror, jpdom_auto, 'vb_e'     ,    vb_e(:,:), cd_type = 'V', psgn = -1._wp, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'sshbb_e'  , sshbb_e(:,:), cd_type = 'T', psgn =  1._wp )   
+               CALL iom_get( numror, jpdom_auto, 'ubb_e'    ,   ubb_e(:,:), cd_type = 'U', psgn = -1._wp )   
+               CALL iom_get( numror, jpdom_auto, 'vbb_e'    ,   vbb_e(:,:), cd_type = 'V', psgn = -1._wp )
+               CALL iom_get( numror, jpdom_auto, 'sshb_e'   ,  sshb_e(:,:), cd_type = 'T', psgn =  1._wp ) 
+               CALL iom_get( numror, jpdom_auto, 'ub_e'     ,    ub_e(:,:), cd_type = 'U', psgn = -1._wp )   
+               CALL iom_get( numror, jpdom_auto, 'vb_e'     ,    vb_e(:,:), cd_type = 'V', psgn = -1._wp )
             ENDIF
 #if defined key_agrif
             ! Read time integrated fluxes
             IF ( .NOT.Agrif_Root() ) THEN
-               CALL iom_get( numror, jpdom_auto, 'ub2_i_b'  , ub2_i_b(:,:), cd_type = 'U', psgn = -1._wp, ldxios = lrxios )   
-               CALL iom_get( numror, jpdom_auto, 'vb2_i_b'  , vb2_i_b(:,:), cd_type = 'V', psgn = -1._wp, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'ub2_i_b'  , ub2_i_b(:,:), cd_type = 'U', psgn = -1._wp )   
+               CALL iom_get( numror, jpdom_auto, 'vb2_i_b'  , vb2_i_b(:,:), cd_type = 'V', psgn = -1._wp )
             ELSE
                ub2_i_b(:,:) = 0._wp   ;   vb2_i_b(:,:) = 0._wp   ! used in the 1st update of agrif
@@ -935,26 +935,24 @@
          !                                   ! -------------------
          IF(lwp) WRITE(numout,*) '---- ts_rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'ub2_b'   , ub2_b  (:,:), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'vb2_b'   , vb2_b  (:,:), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'un_bf'   , un_bf  (:,:), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'vn_bf'   , vn_bf  (:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'ub2_b'   , ub2_b  (:,:) )
+         CALL iom_rstput( kt, nitrst, numrow, 'vb2_b'   , vb2_b  (:,:) )
+         CALL iom_rstput( kt, nitrst, numrow, 'un_bf'   , un_bf  (:,:) )
+         CALL iom_rstput( kt, nitrst, numrow, 'vn_bf'   , vn_bf  (:,:) )
          !
          IF (.NOT.ln_bt_av) THEN
-            CALL iom_rstput( kt, nitrst, numrow, 'sshbb_e'  , sshbb_e(:,:), ldxios = lwxios ) 
-            CALL iom_rstput( kt, nitrst, numrow, 'ubb_e'    ,   ubb_e(:,:), ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'vbb_e'    ,   vbb_e(:,:), ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'sshb_e'   ,  sshb_e(:,:), ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'ub_e'     ,    ub_e(:,:), ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'vb_e'     ,    vb_e(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'sshbb_e'  , sshbb_e(:,:) ) 
+            CALL iom_rstput( kt, nitrst, numrow, 'ubb_e'    ,   ubb_e(:,:) )
+            CALL iom_rstput( kt, nitrst, numrow, 'vbb_e'    ,   vbb_e(:,:) )
+            CALL iom_rstput( kt, nitrst, numrow, 'sshb_e'   ,  sshb_e(:,:) )
+            CALL iom_rstput( kt, nitrst, numrow, 'ub_e'     ,    ub_e(:,:) )
+            CALL iom_rstput( kt, nitrst, numrow, 'vb_e'     ,    vb_e(:,:) )
          ENDIF
 #if defined key_agrif
          ! Save time integrated fluxes
          IF ( .NOT.Agrif_Root() ) THEN
-            CALL iom_rstput( kt, nitrst, numrow, 'ub2_i_b'  , ub2_i_b(:,:), ldxios = lwxios )
-            CALL iom_rstput( kt, nitrst, numrow, 'vb2_i_b'  , vb2_i_b(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'ub2_i_b'  , ub2_i_b(:,:) )
+            CALL iom_rstput( kt, nitrst, numrow, 'vb2_i_b'  , vb2_i_b(:,:) )
          ENDIF
 #endif
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
       ENDIF
       !
@@ -1048,28 +1046,4 @@
       !                             ! read restart when needed
       CALL ts_rst( nit000, 'READ' )
-      !
-      IF( lwxios ) THEN
-! define variables in restart file when writing with XIOS
-         CALL iom_set_rstw_var_active('ub2_b')
-         CALL iom_set_rstw_var_active('vb2_b')
-         CALL iom_set_rstw_var_active('un_bf')
-         CALL iom_set_rstw_var_active('vn_bf')
-         !
-         IF (.NOT.ln_bt_av) THEN
-            CALL iom_set_rstw_var_active('sshbb_e')
-            CALL iom_set_rstw_var_active('ubb_e')
-            CALL iom_set_rstw_var_active('vbb_e')
-            CALL iom_set_rstw_var_active('sshb_e')
-            CALL iom_set_rstw_var_active('ub_e')
-            CALL iom_set_rstw_var_active('vb_e')
-         ENDIF
-#if defined key_agrif
-         ! Save time integrated fluxes
-         IF ( .NOT.Agrif_Root() ) THEN
-            CALL iom_set_rstw_var_active('ub2_i_b')
-            CALL iom_set_rstw_var_active('vb2_i_b')
-         ENDIF
-#endif
-      ENDIF
       !
    END SUBROUTINE dyn_spg_ts_init
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynvor.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynvor.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynvor.F90	(revision 14055)
@@ -21,4 +21,5 @@
    !!             -   ! 2018-03  (G. Madec)  add two new schemes (ln_dynvor_enT and ln_dynvor_eet)
    !!             -   ! 2018-04  (G. Madec)  add pre-computed gradient for metric term calculation
+   !!            4.2  ! 2020-12  (G. Madec, E. Clementi) add vortex force trends (ln_vortex_force=T)
    !!----------------------------------------------------------------------
 
@@ -37,5 +38,5 @@
    USE trddyn         ! trend manager: dynamics
    USE sbcwave        ! Surface Waves (add Stokes-Coriolis force)
-   USE sbc_oce , ONLY : ln_stcor    ! use Stoke-Coriolis force
+   USE sbc_oce,  ONLY : ln_stcor, ln_vortex_force   ! use Stoke-Coriolis force
    !
    USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
@@ -121,17 +122,12 @@
          ALLOCATE( ztrdu(jpi,jpj,jpk), ztrdv(jpi,jpj,jpk) )
          !
-         ztrdu(:,:,:) = puu(:,:,:,Krhs)            !* planetary vorticity trend (including Stokes-Coriolis force)
+         ztrdu(:,:,:) = puu(:,:,:,Krhs)            !* planetary vorticity trend
          ztrdv(:,:,:) = pvv(:,:,:,Krhs)
          SELECT CASE( nvor_scheme )
          CASE( np_ENS )           ;   CALL vor_ens( kt, Kmm, ncor, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! enstrophy conserving scheme
-            IF( ln_stcor )            CALL vor_ens( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
          CASE( np_ENE, np_MIX )   ;   CALL vor_ene( kt, Kmm, ncor, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! energy conserving scheme
-            IF( ln_stcor )            CALL vor_ene( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
          CASE( np_ENT )           ;   CALL vor_enT( kt, Kmm, ncor, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! energy conserving scheme (T-pts)
-            IF( ln_stcor )            CALL vor_enT( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
          CASE( np_EET )           ;   CALL vor_eeT( kt, Kmm, ncor, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! energy conserving scheme (een with e3t)
-            IF( ln_stcor )            CALL vor_eeT( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
          CASE( np_EEN )           ;   CALL vor_een( kt, Kmm, ncor, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! energy & enstrophy scheme
-            IF( ln_stcor )            CALL vor_een( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
          END SELECT
          ztrdu(:,:,:) = puu(:,:,:,Krhs) - ztrdu(:,:,:)
@@ -161,21 +157,43 @@
          CASE( np_ENT )                        !* energy conserving scheme  (T-pts)
                              CALL vor_enT( kt, Kmm, ntot, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! total vorticity trend
-            IF( ln_stcor )   CALL vor_enT( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            IF( ln_stcor .AND. .NOT. ln_vortex_force )  THEN
+                             CALL vor_enT( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend 
+            ELSE IF( ln_stcor .AND. ln_vortex_force )   THEN
+                             CALL vor_enT( kt, Kmm, ntot, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend and vortex force
+            ENDIF
          CASE( np_EET )                        !* energy conserving scheme (een scheme using e3t)
                              CALL vor_eeT( kt, Kmm, ntot, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! total vorticity trend
-            IF( ln_stcor )   CALL vor_eeT( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            IF( ln_stcor .AND. .NOT. ln_vortex_force )  THEN
+                             CALL vor_eeT( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            ELSE IF( ln_stcor .AND. ln_vortex_force )   THEN
+                             CALL vor_eeT( kt, Kmm, ntot, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend and vortex force
+            ENDIF
          CASE( np_ENE )                        !* energy conserving scheme
                              CALL vor_ene( kt, Kmm, ntot, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! total vorticity trend
-            IF( ln_stcor )   CALL vor_ene( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            IF( ln_stcor .AND. .NOT. ln_vortex_force )  THEN
+                             CALL vor_ene( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            ELSE IF( ln_stcor .AND. ln_vortex_force )   THEN
+                             CALL vor_ene( kt, Kmm, ntot, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend and vortex force
+            ENDIF
          CASE( np_ENS )                        !* enstrophy conserving scheme
                              CALL vor_ens( kt, Kmm, ntot, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )  ! total vorticity trend
-            IF( ln_stcor )   CALL vor_ens( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )  ! add the Stokes-Coriolis trend
+
+            IF( ln_stcor .AND. .NOT. ln_vortex_force )  THEN
+                             CALL vor_ens( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )  ! add the Stokes-Coriolis trend
+            ELSE IF( ln_stcor .AND. ln_vortex_force )   THEN
+                             CALL vor_ens( kt, Kmm, ntot, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )  ! add the Stokes-Coriolis trend and vortex force
+            ENDIF
          CASE( np_MIX )                        !* mixed ene-ens scheme
                              CALL vor_ens( kt, Kmm, nrvm, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! relative vorticity or metric trend (ens)
                              CALL vor_ene( kt, Kmm, ncor, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! planetary vorticity trend (ene)
-            IF( ln_stcor )   CALL vor_ene( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            IF( ln_stcor )        CALL vor_ene( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )        ! add the Stokes-Coriolis trend
+            IF( ln_vortex_force ) CALL vor_ens( kt, Kmm, nrvm, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add vortex force
          CASE( np_EEN )                        !* energy and enstrophy conserving scheme
                              CALL vor_een( kt, Kmm, ntot, puu(:,:,:,Kmm) , pvv(:,:,:,Kmm) , puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! total vorticity trend
-            IF( ln_stcor )   CALL vor_een( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            IF( ln_stcor .AND. .NOT. ln_vortex_force )  THEN
+                             CALL vor_een( kt, Kmm, ncor, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend
+            ELSE IF( ln_stcor .AND. ln_vortex_force )   THEN
+                             CALL vor_een( kt, Kmm, ntot, usd, vsd, puu(:,:,:,Krhs), pvv(:,:,:,Krhs) )   ! add the Stokes-Coriolis trend and vortex force
+            ENDIF
          END SELECT
          !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynzad.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynzad.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/DYN/dynzad.F90	(revision 14055)
@@ -16,4 +16,5 @@
    USE trd_oce        ! trends: ocean variables
    USE trddyn         ! trend manager: dynamics
+   USE sbcwave, ONLY: wsd   ! Surface Waves (add vertical Stokes-drift)
    !
    USE in_out_manager ! I/O manager
@@ -79,5 +80,9 @@
       DO jk = 2, jpkm1                ! Vertical momentum advection at level w and u- and v- vertical
          DO_2D( 0, 1, 0, 1 )              ! vertical fluxes
+          IF( ln_vortex_force ) THEN
+            zww(ji,jj) = 0.25_wp * e1e2t(ji,jj) * ( ww(ji,jj,jk) + wsd(ji,jj,jk) )
+          ELSE
             zww(ji,jj) = 0.25_wp * e1e2t(ji,jj) * ww(ji,jj,jk)
+          ENDIF
          END_2D
          DO_2D( 0, 0, 0, 0 )              ! vertical momentum advection at w-point
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icb_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icb_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icb_oce.F90	(revision 14055)
@@ -57,10 +57,11 @@
    TYPE, PUBLIC ::   point              !: properties of an individual iceberg (position, mass, size, etc...)
       INTEGER  ::   year
-      REAL(wp) ::   xi , yj                                                   ! iceberg coordinates in the (i,j) referential (global)
+      REAL(wp) ::   xi , yj , zk                                              ! iceberg coordinates in the (i,j) referential (global) and deepest level affected
       REAL(wp) ::   e1 , e2                                                   ! horizontal scale factors at the iceberg position
       REAL(wp) ::   lon, lat, day                                             ! geographic position
       REAL(wp) ::   mass, thickness, width, length, uvel, vvel                ! iceberg physical properties
-      REAL(wp) ::   uo, vo, ui, vi, ua, va, ssh_x, ssh_y, sst, cn, hi, sss    ! properties of iceberg environment 
+      REAL(wp) ::   ssu, ssv, ui, vi, ua, va, ssh_x, ssh_y, sst, sss, cn, hi  ! properties of iceberg environment 
       REAL(wp) ::   mass_of_bits, heat_density
+      INTEGER  ::   kb                                                   ! icb bottom level
    END TYPE point
 
@@ -85,9 +86,12 @@
    ! Extra arrays with bigger halo, needed when interpolating forcing onto iceberg position
    ! particularly for MPP when iceberg can lie inside T grid but outside U, V, or f grid
-   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   uo_e, vo_e
-   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ff_e, tt_e, fr_e, ss_e
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ssu_e, ssv_e
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   sst_e, sss_e, fr_e
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ua_e, va_e
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ssh_e
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   tmask_e, umask_e, vmask_e
+   REAl(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   rlon_e, rlat_e, ff_e
+   REAl(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::   uoce_e, voce_e, toce_e, e3t_e
+   !
 #if defined key_si3 || defined key_cice
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   hi_e, ui_e, vi_e
@@ -117,4 +121,5 @@
    INTEGER , PUBLIC ::   nn_verbose_write                !: timesteps between verbose messages
    REAL(wp), PUBLIC ::   rn_rho_bergs                    !: Density of icebergs
+   REAL(wp), PUBLIC ::   rho_berg_1_oce                  !: convertion factor (thickness to draft) (rn_rho_bergs/pp_rho_seawater)
    REAL(wp), PUBLIC ::   rn_LoW_ratio                    !: Initial ratio L/W for newly calved icebergs
    REAL(wp), PUBLIC ::   rn_bits_erosion_fraction        !: Fraction of erosion melt flux to divert to bergy bits
@@ -124,4 +129,5 @@
    LOGICAL , PUBLIC ::   ln_time_average_weight          !: Time average the weight on the ocean    !!gm I don't understand that !
    REAL(wp), PUBLIC ::   rn_speed_limit                  !: CFL speed limit for a berg
+   LOGICAL , PUBLIC ::   ln_M2016, ln_icb_grd            !: use Nacho's Merino 2016 work
    !
    ! restart
@@ -135,4 +141,5 @@
    REAL(wp), DIMENSION(nclasses), PUBLIC ::   rn_initial_thickness !  Single instance of an icebergs type initialised in icebergs_init and updated in icebergs_run
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   src_calving, src_calving_hflx    !: accumulate input ice
+   INTEGER , PUBLIC             , SAVE                     ::   micbkb                           !: deepest level affected by icebergs
    INTEGER , PUBLIC             , SAVE                     ::   numicb                           !: iceberg IO
    INTEGER , PUBLIC             , SAVE, DIMENSION(nkounts) ::   num_bergs                        !: iceberg counter
@@ -171,6 +178,6 @@
       !
       ! expanded arrays for bilinear interpolation
-      ALLOCATE( uo_e(0:jpi+1,0:jpj+1) , ua_e(0:jpi+1,0:jpj+1) ,    &
-         &      vo_e(0:jpi+1,0:jpj+1) , va_e(0:jpi+1,0:jpj+1) ,    &
+      ALLOCATE( ssu_e(0:jpi+1,0:jpj+1) , ua_e(0:jpi+1,0:jpj+1) ,   &
+         &      ssv_e(0:jpi+1,0:jpj+1) , va_e(0:jpi+1,0:jpj+1) ,   &
 #if defined key_si3 || defined key_cice
          &      ui_e(0:jpi+1,0:jpj+1) ,                            &
@@ -178,7 +185,7 @@
          &      hi_e(0:jpi+1,0:jpj+1) ,                            &
 #endif
-         &      ff_e(0:jpi+1,0:jpj+1) , fr_e(0:jpi+1,0:jpj+1)  ,   &
-         &      tt_e(0:jpi+1,0:jpj+1) , ssh_e(0:jpi+1,0:jpj+1) ,   &
-         &      ss_e(0:jpi+1,0:jpj+1) ,                            & 
+         &      fr_e(0:jpi+1,0:jpj+1) ,                            &
+         &      sst_e(0:jpi+1,0:jpj+1) , ssh_e(0:jpi+1,0:jpj+1) ,  &
+         &      sss_e(0:jpi+1,0:jpj+1) ,                           & 
          &      first_width(nclasses) , first_length(nclasses) ,   &
          &      src_calving (jpi,jpj) ,                            &
@@ -186,6 +193,12 @@
       icb_alloc = icb_alloc + ill
 
+      IF ( ln_M2016 ) THEN
+         ALLOCATE( uoce_e(0:jpi+1,0:jpj+1,jpk), voce_e(0:jpi+1,0:jpj+1,jpk), &
+            &      toce_e(0:jpi+1,0:jpj+1,jpk), e3t_e(0:jpi+1,0:jpj+1,jpk) , STAT=ill )
+         icb_alloc = icb_alloc + ill
+      END IF
+      !
       ALLOCATE( tmask_e(0:jpi+1,0:jpj+1), umask_e(0:jpi+1,0:jpj+1), vmask_e(0:jpi+1,0:jpj+1), &
-         &      STAT=ill)
+         &      rlon_e(0:jpi+1,0:jpj+1) , rlat_e(0:jpi+1,0:jpj+1) , ff_e(0:jpi+1,0:jpj+1)   , STAT=ill)
       icb_alloc = icb_alloc + ill
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbclv.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbclv.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbclv.F90	(revision 14055)
@@ -21,5 +21,4 @@
    USE lbclnk         ! NEMO boundary exchanges for gridded data
 
-   USE icb_oce        ! iceberg variables
    USE icbdia         ! iceberg diagnostics
    USE icbutl         ! iceberg utility routines
@@ -142,4 +141,5 @@
                   newpt%mass           = rn_initial_mass     (jn)
                   newpt%thickness      = rn_initial_thickness(jn)
+                  newpt%kb             = 1         ! compute correctly in icbthm if needed        
                   newpt%width          = first_width         (jn)
                   newpt%length         = first_length        (jn)
@@ -172,9 +172,4 @@
       END DO
       !
-      DO jn = 1, nclasses
-         CALL lbc_lnk( 'icbclv', berg_grid%stored_ice(:,:,jn), 'T', 1._wp )
-      END DO
-      CALL lbc_lnk( 'icbclv', berg_grid%stored_heat, 'T', 1._wp )
-      !
       IF( nn_verbose_level > 0 .AND. icntmax > 1 )   WRITE(numicb,*) 'icb_clv: icnt=', icnt,' on', narea
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbdyn.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbdyn.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbdyn.F90	(revision 14055)
@@ -14,4 +14,5 @@
    USE dom_oce        ! NEMO ocean domain
    USE phycst         ! NEMO physical constants
+   USE in_out_manager                      ! IO parameters
    !
    USE icb_oce        ! define iceberg arrays
@@ -97,6 +98,6 @@
          zyj2 = zyj1 + zdt_2 * zv1          ;   zvvel2 = zvvel1 + zdt_2 * zay1
          !
-         CALL icb_ground( zxi2, zxi1, zu1,   &
-            &             zyj2, zyj1, zv1, ll_bounced )
+         CALL icb_ground( berg, zxi2, zxi1, zu1,   &
+            &                   zyj2, zyj1, zv1, ll_bounced )
 
          !                                         !**   A2 = A(X2,V2)
@@ -113,6 +114,6 @@
          zyj3  = zyj1  + zdt_2 * zv2   ;   zvvel3 = zvvel1 + zdt_2 * zay2
          !
-         CALL icb_ground( zxi3, zxi1, zu3,   &
-            &                zyj3, zyj1, zv3, ll_bounced )
+         CALL icb_ground( berg, zxi3, zxi1, zu3,   &
+            &                   zyj3, zyj1, zv3, ll_bounced )
 
          !                                         !**   A3 = A(X3,V3)
@@ -129,6 +130,6 @@
          zyj4 = zyj1 + zdt * zv3   ;   zvvel4 = zvvel1 + zdt * zay3
 
-         CALL icb_ground( zxi4, zxi1, zu4,   &
-            &             zyj4, zyj1, zv4, ll_bounced )
+         CALL icb_ground( berg, zxi4, zxi1, zu4,   &
+            &                   zyj4, zyj1, zv4, ll_bounced )
 
          !                                         !**   A4 = A(X4,V4)
@@ -148,6 +149,6 @@
          zvvel_n = pt%vvel + zdt_6 * (  zay1 + 2.*(zay2 + zay3) + zay4 )
 
-         CALL icb_ground( zxi_n, zxi1, zuvel_n,   &
-            &             zyj_n, zyj1, zvvel_n, ll_bounced )
+         CALL icb_ground( berg, zxi_n, zxi1, zuvel_n,   &
+            &                   zyj_n, zyj1, zvvel_n, ll_bounced )
 
          pt%uvel = zuvel_n                        !** save in berg structure
@@ -156,8 +157,4 @@
          pt%yj   = zyj_n
 
-         ! update actual position
-         pt%lon  = icb_utl_bilin_x(glamt, pt%xi, pt%yj )
-         pt%lat  = icb_utl_bilin(gphit, pt%xi, pt%yj, 'T' )
-
          berg => berg%next                         ! switch to the next berg
          !
@@ -167,6 +164,6 @@
 
 
-   SUBROUTINE icb_ground( pi, pi0, pu,   &
-      &                   pj, pj0, pv, ld_bounced )
+   SUBROUTINE icb_ground( berg, pi, pi0, pu,   &
+      &                         pj, pj0, pv, ld_bounced )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE icb_ground  ***
@@ -177,4 +174,6 @@
       !!                NB two possibilities available one of which is hard-coded here
       !!----------------------------------------------------------------------
+      TYPE(iceberg ), POINTER, INTENT(in   ) ::   berg             ! berg
+      !
       REAL(wp), INTENT(inout) ::   pi , pj      ! current iceberg position
       REAL(wp), INTENT(in   ) ::   pi0, pj0     ! previous iceberg position
@@ -184,5 +183,9 @@
       INTEGER  ::   ii, ii0
       INTEGER  ::   ij, ij0
+      INTEGER  ::   ikb
       INTEGER  ::   ibounce_method
+      !
+      REAL(wp) :: zD 
+      REAL(wp), DIMENSION(jpk) :: ze3t
       !!----------------------------------------------------------------------
       !
@@ -200,5 +203,23 @@
       ij  = mj1( ij  )
       !
-      IF(  tmask(ii,ij,1)  /=   0._wp  )   RETURN           ! berg reach a new t-cell, but an ocean one
+      ! assume icb is grounded if tmask(ii,ij,1) or tmask(ii,ij,ikb), depending of the option is not 0
+      IF ( ln_M2016 .AND. ln_icb_grd ) THEN
+         !
+         ! draught (keel depth)
+         zD = rho_berg_1_oce * berg%current_point%thickness
+         !
+         ! interpol needed data
+         CALL icb_utl_interp( pi, pj, pe3t=ze3t )
+         ! 
+         !compute bottom level
+         CALL icb_utl_getkb( ikb, ze3t, zD )
+         !
+         ! berg reach a new t-cell, but an ocean one
+         ! .AND. needed in case berg hit an isf (tmask(ii,ij,1) == 0 and tmask(ii,ij,ikb) /= 0)
+         IF(  tmask(ii,ij,ikb) /= 0._wp .AND. tmask(ii,ij,1) /= 0._wp ) RETURN
+         !
+      ELSE
+         IF(  tmask(ii,ij,1)  /=   0._wp  )   RETURN           ! berg reach a new t-cell, but an ocean one
+      END IF
       !
       ! From here, berg have reach land: treat grounding/bouncing
@@ -257,23 +278,27 @@
       REAL(wp), PARAMETER ::   pp_Cr0       = 0.06_wp    !
       !
-      INTEGER  ::   itloop
-      REAL(wp) ::   zuo, zui, zua, zuwave, zssh_x, zsst, zcn, zhi, zsss
-      REAL(wp) ::   zvo, zvi, zva, zvwave, zssh_y
+      INTEGER  ::   itloop, ikb, jk
+      REAL(wp) ::   zuo, zssu, zui, zua, zuwave, zssh_x, zcn, zhi
+      REAL(wp) ::   zvo, zssv, zvi, zva, zvwave, zssh_y
       REAL(wp) ::   zff, zT, zD, zW, zL, zM, zF
       REAL(wp) ::   zdrag_ocn, zdrag_atm, zdrag_ice, zwave_rad
-      REAL(wp) ::   z_ocn, z_atm, z_ice
+      REAL(wp) ::   z_ocn, z_atm, z_ice, zdep
       REAL(wp) ::   zampl, zwmod, zCr, zLwavelength, zLcutoff, zLtop
       REAL(wp) ::   zlambda, zdetA, zA11, zA12, zaxe, zaye, zD_hi
       REAL(wp) ::   zuveln, zvveln, zus, zvs, zspeed, zloc_dx, zspeed_new
+      REAL(wp), DIMENSION(jpk) :: zuoce, zvoce, ze3t, zdepw
       !!----------------------------------------------------------------------
 
       ! Interpolate gridded fields to berg
       nknberg = berg%number(1)
-      CALL icb_utl_interp( pxi, pe1, zuo, zui, zua, zssh_x,                     &
-         &                 pyj, pe2, zvo, zvi, zva, zssh_y, zsst, zcn, zhi, zff, zsss )
+      CALL icb_utl_interp( pxi, pyj, pe1=pe1, pe2=pe2,     &   ! scale factor
+         &                 pssu=zssu, pui=zui, pua=zua,    &   ! oce/ice/atm velocities
+         &                 pssv=zssv, pvi=zvi, pva=zva,    &   ! oce/ice/atm velocities
+         &                 pssh_i=zssh_x, pssh_j=zssh_y,   &   ! ssh gradient
+         &                 phi=zhi, pff=zff)                   ! ice thickness and coriolis
 
       zM = berg%current_point%mass
       zT = berg%current_point%thickness               ! total thickness
-      zD = ( rn_rho_bergs / pp_rho_seawater ) * zT    ! draught (keel depth)
+      zD = rho_berg_1_oce * zT                        ! draught (keel depth)
       zF = zT - zD                                    ! freeboard
       zW = berg%current_point%width
@@ -282,7 +307,7 @@
       zhi   = MIN( zhi   , zD    )
       zD_hi = MAX( 0._wp, zD-zhi )
-
-      ! Wave radiation
-      zuwave = zua - zuo   ;   zvwave = zva - zvo     ! Use wind speed rel. to ocean for wave model
+ 
+     ! Wave radiation
+      zuwave = zua - zssu   ;   zvwave = zva - zssv   ! Use wind speed rel. to ocean for wave model
       zwmod  = zuwave*zuwave + zvwave*zvwave          ! The wave amplitude and length depend on the  current;
       !                                               ! wind speed relative to the ocean. Actually wmod is wmod**2 here.
@@ -309,4 +334,22 @@
       IF( abs(zui) + abs(zvi) == 0._wp )   z_ice = 0._wp
 
+      ! lateral velocities
+      ! default ssu and ssv
+      ! ln_M2016: mean velocity along the profile
+      IF ( ln_M2016 ) THEN
+         ! interpol needed data
+         CALL icb_utl_interp( pxi, pyj, puoce=zuoce, pvoce=zvoce, pe3t=ze3t )   ! 3d velocities
+        
+         !compute bottom level
+         CALL icb_utl_getkb( ikb, ze3t, zD )
+         
+         ! compute mean velocity 
+         CALL icb_utl_zavg(zuo, zuoce, ze3t, zD, ikb)
+         CALL icb_utl_zavg(zvo, zvoce, ze3t, zD, ikb)
+      ELSE
+         zuo = zssu
+         zvo = zssv
+      END IF
+
       zuveln = puvel   ;   zvveln = pvvel ! Copy starting uvel, vvel
       !
@@ -321,7 +364,7 @@
          ! Explicit accelerations
          !zaxe= zff*pvvel -grav*zssh_x +zwave_rad*zuwave &
-         !    -zdrag_ocn*(puvel-zuo) -zdrag_atm*(puvel-zua) -zdrag_ice*(puvel-zui)
+         !    -zdrag_ocn*(puvel-zssu) -zdrag_atm*(puvel-zua) -zdrag_ice*(puvel-zui)
          !zaye=-zff*puvel -grav*zssh_y +zwave_rad*zvwave &
-         !    -zdrag_ocn*(pvvel-zvo) -zdrag_atm*(pvvel-zva) -zdrag_ice*(pvvel-zvi)
+         !    -zdrag_ocn*(pvvel-zssv) -zdrag_atm*(pvvel-zva) -zdrag_ice*(pvvel-zvi)
          zaxe = -grav * zssh_x + zwave_rad * zuwave
          zaye = -grav * zssh_y + zwave_rad * zvwave
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbini.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbini.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbini.F90	(revision 14055)
@@ -73,13 +73,21 @@
       !
       IF( .NOT. ln_icebergs )   RETURN
-
+      !
       !                          ! allocate gridded fields
       IF( icb_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'icb_alloc : unable to allocate arrays' )
       !
       !                          ! initialised variable with extra haloes to zero
-      uo_e(:,:) = 0._wp   ;   vo_e(:,:) = 0._wp   ;
-      ua_e(:,:) = 0._wp   ;   va_e(:,:) = 0._wp   ;
-      ff_e(:,:) = 0._wp   ;   tt_e(:,:) = 0._wp   ;
-      fr_e(:,:) = 0._wp   ;   ss_e(:,:) = 0._wp   ;
+      ssu_e(:,:) = 0._wp   ;   ssv_e(:,:) = 0._wp   ;
+      ua_e(:,:)  = 0._wp   ;   va_e(:,:)  = 0._wp   ;
+      ff_e(:,:)  = 0._wp   ;   sst_e(:,:) = 0._wp   ;
+      fr_e(:,:)  = 0._wp   ;   sss_e(:,:) = 0._wp   ;
+      !
+      IF ( ln_M2016 ) THEN
+         toce_e(:,:,:) = 0._wp
+         uoce_e(:,:,:) = 0._wp
+         voce_e(:,:,:) = 0._wp
+         e3t_e(:,:,:)  = 0._wp
+      END IF
+      !
 #if defined key_si3
       hi_e(:,:) = 0._wp   ;
@@ -100,4 +108,10 @@
       first_width (:) = SQRT(  rn_initial_mass(:) / ( rn_LoW_ratio * rn_rho_bergs * rn_initial_thickness(:) )  )
       first_length(:) = rn_LoW_ratio * first_width(:)
+      rho_berg_1_oce  = rn_rho_bergs / pp_rho_seawater  ! scale factor used for convertion thickness to draft
+      !
+      ! deepest level affected by icebergs
+      ! can be tuned but the safest is this 
+      ! (with z* and z~ the depth of each level change overtime, so the more robust micbkb is jpk)
+      micbkb = jpk
 
       berg_grid%calving      (:,:)   = 0._wp
@@ -240,7 +254,17 @@
       vmask_e(:,:) = 0._wp   ;   vmask_e(1:jpi,1:jpj) = vmask(:,:,1)
       CALL lbc_lnk_icb( 'icbini', tmask_e, 'T', +1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbini', umask_e, 'T', +1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbini', vmask_e, 'T', +1._wp, 1, 1 )
-      !
+      CALL lbc_lnk_icb( 'icbini', umask_e, 'U', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbini', vmask_e, 'V', +1._wp, 1, 1 )
+
+      ! definition of extended lat/lon array needed by icb_bilin_h
+      rlon_e(:,:) = 0._wp     ;  rlon_e(1:jpi,1:jpj) = glamt(:,:) 
+      rlat_e(:,:) = 0._wp     ;  rlat_e(1:jpi,1:jpj) = gphit(:,:)
+      CALL lbc_lnk_icb( 'icbini', rlon_e, 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbini', rlat_e, 'T', +1._wp, 1, 1 )
+      !
+      ! definnitionn of extennded ff_f array needed by icb_utl_interp
+      ff_e(:,:) = 0._wp       ;  ff_e(1:jpi,1:jpj) = ff_f(:,:)
+      CALL lbc_lnk_icb( 'icbini', ff_e, 'F', +1._wp, 1, 1 )
+
       ! assign each new iceberg with a unique number constructed from the processor number
       ! and incremented by the total number of processors
@@ -338,6 +362,5 @@
                localpt%xi = REAL( mig(ji), wp )
                localpt%yj = REAL( mjg(jj), wp )
-               localpt%lon = icb_utl_bilin(glamt, localpt%xi, localpt%yj, 'T' )
-               localpt%lat = icb_utl_bilin(gphit, localpt%xi, localpt%yj, 'T' )
+               CALL icb_utl_interp( localpt%xi, localpt%yj, plat=localpt%lat, plon=localpt%lon )   
                localpt%mass      = rn_initial_mass     (iberg)
                localpt%thickness = rn_initial_thickness(iberg)
@@ -350,4 +373,5 @@
                localpt%uvel = 0._wp
                localpt%vvel = 0._wp
+               localpt%kb   = 1
                CALL icb_utl_incr()
                localberg%number(:) = num_bergs(:)
@@ -383,6 +407,7 @@
          &              rn_bits_erosion_fraction        , rn_sicn_shift       , ln_passive_mode      ,   &
          &              ln_time_average_weight          , nn_test_icebergs    , rn_test_box          ,   &
-         &              ln_use_calving , rn_speed_limit , cn_dir, sn_icb      ,                          &
-         &              cn_icbrst_indir, cn_icbrst_in   , cn_icbrst_outdir    , cn_icbrst_out
+         &              ln_use_calving , rn_speed_limit , cn_dir, sn_icb      , ln_M2016             ,   &
+         &              cn_icbrst_indir, cn_icbrst_in   , cn_icbrst_outdir    , cn_icbrst_out        ,   &
+         &              ln_icb_grd
       !!----------------------------------------------------------------------
 
@@ -463,4 +488,7 @@
             &                    'bits_erosion_fraction = ', rn_bits_erosion_fraction
 
+         WRITE(numout,*) '   Use icb module modification from Merino et al. (2016) : ln_M2016 = ', ln_M2016
+         WRITE(numout,*) '       ground icebergs if icb bottom lvl hit the oce bottom level : ln_icb_grd = ', ln_icb_grd
+
          WRITE(numout,*) '   Shift of sea-ice concentration in erosion flux modulation ',   &
             &                    '(0<sicn_shift<1)    rn_sicn_shift  = ', rn_sicn_shift
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbstp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbstp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbstp.F90	(revision 14055)
@@ -52,5 +52,5 @@
 CONTAINS
 
-   SUBROUTINE icb_stp( kt )
+   SUBROUTINE icb_stp( kt, Kmm )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE icb_stp  ***
@@ -61,4 +61,5 @@
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! time step index
+      INTEGER, INTENT(in) ::   Kmm  ! ocean time level index
       !
       LOGICAL ::   ll_sample_traj, ll_budget, ll_verbose   ! local logical
@@ -70,4 +71,7 @@
       !
       nktberg = kt
+      !
+      !CALL test_icb_utl_getkb
+      !CALL ctl_stop('end test icb')
       !
       IF( nn_test_icebergs < 0 .OR. ln_use_calving ) THEN !* read calving data
@@ -92,5 +96,5 @@
       !
       !                                   !* copy nemo forcing arrays into iceberg versions with extra halo
-      CALL icb_utl_copy()                 ! only necessary for variables not on T points
+      CALL icb_utl_copy( Kmm )                 ! only necessary for variables not on T points
       !
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbthm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbthm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbthm.F90	(revision 14055)
@@ -49,11 +49,12 @@
       INTEGER, INTENT(in) ::   kt   ! timestep number, just passed to icb_utl_print_berg
       !
-      INTEGER  ::   ii, ij
-      REAL(wp) ::   zM, zT, zW, zL, zSST, zVol, zLn, zWn, zTn, znVol, zIC, zDn
+      INTEGER  ::   ii, ij, jk, ikb
+      REAL(wp) ::   zM, zT, zW, zL, zSST, zVol, zLn, zWn, zTn, znVol, zIC, zDn, zD, zvb, zub, ztb
+      REAL(wp) ::   zMv, zMe, zMb, zmelt, zdvo, zdvob, zdva, zdM, zSs, zdMe, zdMb, zdMv
       REAL(wp) ::   zSSS, zfzpt
-      REAL(wp) ::   zMv, zMe, zMb, zmelt, zdvo, zdva, zdM, zSs, zdMe, zdMb, zdMv
       REAL(wp) ::   zMnew, zMnew1, zMnew2, zheat_hcflux, zheat_latent, z1_12
       REAL(wp) ::   zMbits, znMbits, zdMbitsE, zdMbitsM, zLbits, zAbits, zMbb
-      REAL(wp) ::   zxi, zyj, zff, z1_rday, z1_e1e2, zdt, z1_dt, z1_dt_e1e2
+      REAL(wp) ::   zxi, zyj, zff, z1_rday, z1_e1e2, zdt, z1_dt, z1_dt_e1e2, zdepw
+      REAL(wp), DIMENSION(jpk) :: ztoce, zuoce, zvoce, ze3t, zzMv
       TYPE(iceberg), POINTER ::   this, next
       TYPE(point)  , POINTER ::   pt
@@ -85,7 +86,18 @@
          pt => this%current_point
          nknberg = this%number(1)
-         CALL icb_utl_interp( pt%xi, pt%e1, pt%uo, pt%ui, pt%ua, pt%ssh_x,   &
-            &                 pt%yj, pt%e2, pt%vo, pt%vi, pt%va, pt%ssh_y,   &
-            &                 pt%sst, pt%cn, pt%hi, zff, pt%sss )
+
+         CALL icb_utl_interp( pt%xi, pt%yj,            &   ! position
+             &                 pssu=pt%ssu, pua=pt%ua, &   ! oce/atm velocities
+             &                 pssv=pt%ssv, pva=pt%va, &   ! oce/atm velocities
+             &                 psst=pt%sst, pcn=pt%cn, &
+             &                 psss=pt%sss             )
+
+         IF ( nn_sample_rate > 0 .AND. MOD(kt-1,nn_sample_rate) == 0 ) THEN
+            CALL icb_utl_interp( pt%xi, pt%yj, pe1=pt%e1, pe2=pt%e2,                 &
+               &                 pui=pt%ui, pssh_i=pt%ssh_x, &
+               &                 pvi=pt%vi, pssh_j=pt%ssh_y, &
+               &                 phi=pt%hi,                  &
+               &                 plat=pt%lat, plon=pt%lon )
+         END IF
          !
          zSST = pt%sst
@@ -95,6 +107,5 @@
          zM   = pt%mass
          zT   = pt%thickness                               ! total thickness
-       ! D   = (rn_rho_bergs/pp_rho_seawater)*zT ! draught (keel depth)
-       ! F   = zT - D ! freeboard
+         zD   = rho_berg_1_oce * zT                        ! draught (keel depth)
          zW   = pt%width
          zL   = pt%length
@@ -108,16 +119,48 @@
 
          ! Environment
-         zdvo = SQRT( (pt%uvel-pt%uo)**2 + (pt%vvel-pt%vo)**2 )
-         zdva = SQRT( (pt%ua  -pt%uo)**2 + (pt%va  -pt%vo)**2 )
-         zSs  = 1.5_wp * SQRT( zdva ) + 0.1_wp * zdva                ! Sea state      (eqn M.A9)
-
+         ! default sst, ssu and ssv
+         ! ln_M2016: use temp, u and v profile
+         IF ( ln_M2016 ) THEN
+
+            ! load t, u, v and e3 profile at icb position
+            CALL icb_utl_interp( pt%xi, pt%yj, ptoce=ztoce, puoce=zuoce, pvoce=zvoce, pe3t=ze3t )
+            
+            !compute bottom level
+            CALL icb_utl_getkb( pt%kb, ze3t, zD )
+
+            ikb = MIN(pt%kb,mbkt(ii,ij))                             ! limit pt%kb by mbkt 
+                                                                     ! => bottom temperature used to fill ztoce(mbkt:jpk)
+            ztb = ztoce(ikb)                                         ! basal temperature
+            zub = zuoce(ikb)
+            zvb = zvoce(ikb)
+         ELSE
+            ztb = pt%sst
+            zub = pt%ssu
+            zvb = pt%ssv
+         END IF
+
+         zdvob = SQRT( (pt%uvel-zub)**2 + (pt%vvel-zvb)**2 )        ! relative basal velocity
+         zdva  = SQRT( (pt%ua  -pt%ssu)**2 + (pt%va  -pt%ssv)**2 )  ! relative wind
+         zSs   = 1.5_wp * SQRT( zdva ) + 0.1_wp * zdva              ! Sea state      (eqn M.A9)
+         !
          ! Melt rates in m/s (i.e. division by rday)
-         zMv = MAX( 7.62d-3*zSST+1.29d-3*(zSST**2)                    , 0._wp ) * z1_rday      ! Buoyant convection at sides (eqn M.A10)
+         ! Buoyant convection at sides (eqn M.A10)
+         IF ( ln_M2016 ) THEN
+            ! averaging along all the iceberg draft
+            zzMv(:) = MAX( 7.62d-3*ztoce(:)+1.29d-3*(ztoce(:)**2), 0._wp ) * z1_rday
+            CALL icb_utl_zavg(zMv, zzMv, ze3t, zD, ikb )
+         ELSE
+            zMv = MAX( 7.62d-3*zSST+1.29d-3*(zSST**2), 0._wp ) * z1_rday
+         END IF
+         !
+         ! Basal turbulent melting     (eqn M.A7 )
          IF ( zSST > zfzpt ) THEN                                                              ! Calculate basal melting only if SST above freezing point  
-            zMb = MAX( 0.58_wp*(zdvo**0.8_wp)*(zSST+4.0_wp)/(zL**0.2_wp) , 0._wp ) * z1_rday   ! Basal turbulent melting     (eqn M.A7 )
+            zMb = MAX( 0.58_wp*(zdvob**0.8_wp)*(ztb+4.0_wp)/(zL**0.2_wp) , 0._wp ) * z1_rday
          ELSE
             zMb = 0._wp                                                                        ! No basal melting if SST below freezing point     
          ENDIF
-         zMe = MAX( z1_12*(zSST+2.)*zSs*(1._wp+COS(rpi*(zIC**3)))     , 0._wp ) * z1_rday      ! Wave erosion                (eqn M.A8 )
+         !
+         ! Wave erosion                (eqn M.A8 )
+         zMe = MAX( z1_12*(zSST+2.)*zSs*(1._wp+COS(rpi*(zIC**3)))     , 0._wp ) * z1_rday
 
          IF( ln_operator_splitting ) THEN      ! Operator split update of volume/mass
@@ -207,5 +250,5 @@
 
          ! Rolling
-         zDn = ( rn_rho_bergs / pp_rho_seawater ) * zTn       ! draught (keel depth)
+         zDn = rho_berg_1_oce * zTn       ! draught (keel depth)
          IF( zDn > 0._wp .AND. MAX(zWn,zLn) < SQRT( 0.92*(zDn**2) + 58.32*zDn ) ) THEN
             zT  = zTn
@@ -224,4 +267,5 @@
 
 !!gm  add a test to avoid over melting ?
+!!pm  I agree, over melting could break conservation (more melt than calving)
 
          IF( zMnew <= 0._wp ) THEN       ! Delete the berg if completely melted
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbtrj.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbtrj.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbtrj.F90	(revision 14055)
@@ -40,5 +40,5 @@
    INTEGER ::   numberid, nstepid, nscaling_id
    INTEGER ::   nlonid, nlatid, nxid, nyid, nuvelid, nvvelid, nmassid
-   INTEGER ::   nuoid, nvoid, nuaid, nvaid, nuiid, nviid
+   INTEGER ::   nssuid, nssvid, nuaid, nvaid, nuiid, nviid
    INTEGER ::   nsshxid, nsshyid, nsstid, ncntid, nthkid
    INTEGER ::   nthicknessid, nwidthid, nlengthid
@@ -111,6 +111,6 @@
       iret = NF90_DEF_VAR( ntrajid, 'uvel'          , NF90_DOUBLE, n_dim          , nuvelid          )
       iret = NF90_DEF_VAR( ntrajid, 'vvel'          , NF90_DOUBLE, n_dim          , nvvelid          )
-      iret = NF90_DEF_VAR( ntrajid, 'uto'           , NF90_DOUBLE, n_dim          , nuoid            )
-      iret = NF90_DEF_VAR( ntrajid, 'vto'           , NF90_DOUBLE, n_dim          , nvoid            )
+      iret = NF90_DEF_VAR( ntrajid, 'ssu'           , NF90_DOUBLE, n_dim          , nssuid           )
+      iret = NF90_DEF_VAR( ntrajid, 'ssv'           , NF90_DOUBLE, n_dim          , nssvid           )
       iret = NF90_DEF_VAR( ntrajid, 'uta'           , NF90_DOUBLE, n_dim          , nuaid            )
       iret = NF90_DEF_VAR( ntrajid, 'vta'           , NF90_DOUBLE, n_dim          , nvaid            )
@@ -148,8 +148,8 @@
       iret = NF90_PUT_ATT( ntrajid, nvvelid         , 'long_name', 'meridional velocity' )
       iret = NF90_PUT_ATT( ntrajid, nvvelid         , 'units'    , 'm/s' )
-      iret = NF90_PUT_ATT( ntrajid, nuoid           , 'long_name', 'ocean u component' )
-      iret = NF90_PUT_ATT( ntrajid, nuoid           , 'units'    , 'm/s' )
-      iret = NF90_PUT_ATT( ntrajid, nvoid           , 'long_name', 'ocean v component' )
-      iret = NF90_PUT_ATT( ntrajid, nvoid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nssuid          , 'long_name', 'ocean u component' )
+      iret = NF90_PUT_ATT( ntrajid, nssuid          , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nssvid          , 'long_name', 'ocean v component' )
+      iret = NF90_PUT_ATT( ntrajid, nssvid          , 'units'    , 'm/s' )
       iret = NF90_PUT_ATT( ntrajid, nuaid           , 'long_name', 'atmosphere u component' )
       iret = NF90_PUT_ATT( ntrajid, nuaid           , 'units'    , 'm/s' )
@@ -231,6 +231,6 @@
          iret = NF90_PUT_VAR( ntrajid, nuvelid         , pt%uvel          , (/ jn /) )
          iret = NF90_PUT_VAR( ntrajid, nvvelid         , pt%vvel          , (/ jn /) )
-         iret = NF90_PUT_VAR( ntrajid, nuoid           , pt%uo            , (/ jn /) )
-         iret = NF90_PUT_VAR( ntrajid, nvoid           , pt%vo            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nssuid          , pt%ssu           , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nssvid          , pt%ssv           , (/ jn /) )
          iret = NF90_PUT_VAR( ntrajid, nuaid           , pt%ua            , (/ jn /) )
          iret = NF90_PUT_VAR( ntrajid, nvaid           , pt%va            , (/ jn /) )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbutl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbutl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ICB/icbutl.F90	(revision 14055)
@@ -8,12 +8,16 @@
    !!            -    !                            Removal of mapping from another grid
    !!            -    !  2011-04  (Alderson)       Split into separate modules
+   !!           4.2   !  2020-07  (P. Mathiot)     simplification of interpolation routine
+   !!                 !                            and add Nacho Merino work
    !!----------------------------------------------------------------------
 
    !!----------------------------------------------------------------------
    !!   icb_utl_interp   :
-   !!   icb_utl_bilin    :
-   !!   icb_utl_bilin_e  :
+   !!   icb_utl_pos      : compute bottom left corner indice, weight and mask
+   !!   icb_utl_bilin_h  : interpolation field to icb position
+   !!   icb_utl_bilin_e  : interpolation of scale factor to icb position
    !!----------------------------------------------------------------------
    USE par_oce                             ! ocean parameters
+   USE oce,    ONLY: ts, uu, vv
    USE dom_oce                             ! ocean domain
    USE in_out_manager                      ! IO parameters
@@ -31,8 +35,14 @@
    PRIVATE
 
+   INTERFACE icb_utl_bilin_h
+      MODULE PROCEDURE icb_utl_bilin_2d_h, icb_utl_bilin_3d_h
+   END INTERFACE
+
    PUBLIC   icb_utl_copy          ! routine called in icbstp module
+   PUBLIC   icb_utl_getkb         ! routine called in icbdyn and icbthm modules
+   PUBLIC   test_icb_utl_getkb    ! routine called in icbdyn and icbthm modules
+   PUBLIC   icb_utl_zavg          ! routine called in icbdyn and icbthm modules
    PUBLIC   icb_utl_interp        ! routine called in icbdyn, icbthm modules
-   PUBLIC   icb_utl_bilin         ! routine called in icbini, icbdyn modules
-   PUBLIC   icb_utl_bilin_x       ! routine called in icbdyn module
+   PUBLIC   icb_utl_bilin_h       ! routine called in icbdyn module
    PUBLIC   icb_utl_add           ! routine called in icbini.F90, icbclv, icblbc and icbrst modules
    PUBLIC   icb_utl_delete        ! routine called in icblbc, icbthm modules
@@ -54,5 +64,5 @@
 CONTAINS
 
-   SUBROUTINE icb_utl_copy()
+   SUBROUTINE icb_utl_copy( Kmm )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE icb_utl_copy  ***
@@ -62,29 +72,31 @@
       !! ** Method  : - blah blah
       !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(0:jpi+1,0:jpj+1) :: ztmp
 #if defined key_si3
       REAL(wp), DIMENSION(jpi,jpj) :: zssh_lead_m    !    ocean surface (ssh_m) if ice is not embedded
       !                                              !    ocean surface in leads if ice is embedded   
 #endif
+      INTEGER :: jk   ! vertical loop index
+      INTEGER :: Kmm  ! ocean time levelindex
+      !
       ! copy nemo forcing arrays into iceberg versions with extra halo
       ! only necessary for variables not on T points
       ! and ssh which is used to calculate gradients
-
-      uo_e(1:jpi,1:jpj) = ssu_m(:,:) * umask(:,:,1)
-      vo_e(1:jpi,1:jpj) = ssv_m(:,:) * vmask(:,:,1)
+      !
+      ! surface forcing
+      !
+      ssu_e(1:jpi,1:jpj) = ssu_m(:,:) * umask(:,:,1)
+      ssv_e(1:jpi,1:jpj) = ssv_m(:,:) * vmask(:,:,1)
+      sst_e(1:jpi,1:jpj) = sst_m(:,:)
+      sss_e(1:jpi,1:jpj) = sss_m(:,:)
+      fr_e (1:jpi,1:jpj) = fr_i (:,:)
+      ua_e (1:jpi,1:jpj) = utau (:,:) * umask(:,:,1) ! maybe mask useless because mask applied in sbcblk
+      va_e (1:jpi,1:jpj) = vtau (:,:) * vmask(:,:,1) ! maybe mask useless because mask applied in sbcblk
       ff_e(1:jpi,1:jpj) = ff_f (:,:) 
-      tt_e(1:jpi,1:jpj) = sst_m(:,:)
-      ss_e(1:jpi,1:jpj) = sss_m(:,:)
-      fr_e(1:jpi,1:jpj) = fr_i (:,:)
-      ua_e(1:jpi,1:jpj) = utau (:,:) * umask(:,:,1) ! maybe mask useless because mask applied in sbcblk
-      va_e(1:jpi,1:jpj) = vtau (:,:) * vmask(:,:,1) ! maybe mask useless because mask applied in sbcblk
-      !
-      CALL lbc_lnk_icb( 'icbutl', uo_e, 'U', -1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', vo_e, 'V', -1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', ff_e, 'F', +1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', ua_e, 'U', -1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', va_e, 'V', -1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', fr_e, 'T', +1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', tt_e, 'T', +1._wp, 1, 1 )
-      CALL lbc_lnk_icb( 'icbutl', ss_e, 'T', +1._wp, 1, 1 )
+      !
+      CALL lbc_lnk_icb( 'icbutl', ssu_e, 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', ssv_e, 'V', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', ua_e , 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', va_e , 'V', -1._wp, 1, 1 )
 #if defined key_si3
       hi_e(1:jpi, 1:jpj) = hm_i (:,:)  
@@ -96,18 +108,35 @@
       ssh_e(1:jpi, 1:jpj) = zssh_lead_m(:,:) * tmask(:,:,1)
       !
-      CALL lbc_lnk_icb( 'icbutl', hi_e , 'T', +1._wp, 1, 1 )
       CALL lbc_lnk_icb( 'icbutl', ui_e , 'U', -1._wp, 1, 1 )
       CALL lbc_lnk_icb( 'icbutl', vi_e , 'V', -1._wp, 1, 1 )
 #else
-      ssh_e(1:jpi, 1:jpj) = ssh_m(:,:) * tmask(:,:,1)
+      ssh_e(1:jpi, 1:jpj) = ssh_m(:,:) * tmask(:,:,1)         
 #endif
-      CALL lbc_lnk_icb( 'icbutl', ssh_e, 'T', +1._wp, 1, 1 )
+      !
+      ! (PM) could be improve with a 3d lbclnk gathering both variables
+      ! should be done once extra haloe generalised
+      IF ( ln_M2016 ) THEN
+         DO jk = 1,jpk
+            ! uoce
+            ztmp(1:jpi,1:jpj) = uu(:,:,jk,Kmm)
+            CALL lbc_lnk_icb( 'icbutl', ztmp, 'U', -1._wp, 1, 1 )
+            uoce_e(:,:,jk) = ztmp(:,:)
+            !
+            ! voce
+            ztmp(1:jpi,1:jpj) = vv(:,:,jk,Kmm)
+            CALL lbc_lnk_icb( 'icbutl', ztmp, 'V', -1._wp, 1, 1 )
+            voce_e(:,:,jk) = ztmp(:,:)
+         END DO
+         toce_e(1:jpi,1:jpj,1:jpk) = ts(:,:,:,1,Kmm)
+         e3t_e (1:jpi,1:jpj,1:jpk) = e3t(:,:,:,Kmm)
+      END IF
       !
    END SUBROUTINE icb_utl_copy
 
 
-   SUBROUTINE icb_utl_interp( pi, pe1, puo, pui, pua, pssh_i,   &
-      &                       pj, pe2, pvo, pvi, pva, pssh_j,   &
-      &                       psst, pcn, phi, pff, psss        )
+   SUBROUTINE icb_utl_interp( pi, pj, pe1 , pssu, pui, pua, pssh_i,         &
+      &                               pe2 , pssv, pvi, pva, pssh_j,         &
+      &                               psst, psss, pcn, phi, pff   ,         &
+      &                               plon, plat, ptoce, puoce, pvoce, pe3t )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE icb_utl_interp  ***
@@ -127,49 +156,100 @@
       !!----------------------------------------------------------------------
       REAL(wp), INTENT(in   ) ::   pi , pj                        ! position in (i,j) referential
-      REAL(wp), INTENT(  out) ::   pe1, pe2                       ! i- and j scale factors
-      REAL(wp), INTENT(  out) ::   puo, pvo, pui, pvi, pua, pva   ! ocean, ice and wind speeds
-      REAL(wp), INTENT(  out) ::   pssh_i, pssh_j                 ! ssh i- & j-gradients
-      REAL(wp), INTENT(  out) ::   psst, pcn, phi, pff, psss      ! SST, ice concentration, ice thickness, Coriolis, SSS
-      !
+      REAL(wp), INTENT(  out), OPTIONAL ::   pe1, pe2                       ! i- and j scale factors
+      REAL(wp), INTENT(  out), OPTIONAL ::   pssu, pssv, pui, pvi, pua, pva ! ocean, ice and wind speeds
+      REAL(wp), INTENT(  out), OPTIONAL ::   pssh_i, pssh_j                 ! ssh i- & j-gradients
+      REAL(wp), INTENT(  out), OPTIONAL ::   psst, psss, pcn, phi, pff      ! SST, SSS, ice concentration, ice thickness, Coriolis
+      REAL(wp), INTENT(  out), OPTIONAL ::   plat, plon                     ! position
+      REAL(wp), DIMENSION(jpk), INTENT(  out), OPTIONAL ::   ptoce, puoce, pvoce, pe3t   ! 3D variables
+      !
+      REAL(wp), DIMENSION(4) :: zwT  , zwU  , zwV  , zwF   ! interpolation weight
+      REAL(wp), DIMENSION(4) :: zmskF, zmskU, zmskV, zmskT ! mask
+      REAL(wp), DIMENSION(4) :: zwTp, zmskTp, zwTm, zmskTm
+      REAL(wp), DIMENSION(4,jpk) :: zw1d
+      INTEGER                :: iiT, iiU, iiV, iiF, ijT, ijU, ijV, ijF ! bottom left corner
+      INTEGER                :: iiTp, iiTm, ijTp, ijTm
       REAL(wp) ::   zcd, zmod       ! local scalars
       !!----------------------------------------------------------------------
-
-      pe1 = icb_utl_bilin_e( e1t, e1u, e1v, e1f, pi, pj )      ! scale factors
-      pe2 = icb_utl_bilin_e( e2t, e2u, e2v, e2f, pi, pj )
-      !
-      puo  = icb_utl_bilin_h( uo_e, pi, pj, 'U', .false.  )    ! ocean velocities
-      pvo  = icb_utl_bilin_h( vo_e, pi, pj, 'V', .false.  )
-      psst = icb_utl_bilin_h( tt_e, pi, pj, 'T', .true.   )    ! SST
-      psss = icb_utl_bilin_h( ss_e, pi, pj, 'T', .true.   )    ! SSS
-      pcn  = icb_utl_bilin_h( fr_e, pi, pj, 'T', .true.   )    ! ice concentration
-      pff  = icb_utl_bilin_h( ff_e, pi, pj, 'F', .false.  )    ! Coriolis parameter
-      !
-      pua  = icb_utl_bilin_h( ua_e, pi, pj, 'U', .true.   )    ! 10m wind
-      pva  = icb_utl_bilin_h( va_e, pi, pj, 'V', .true.   )    ! here (ua,va) are stress => rough conversion from stress to speed
-      zcd  = 1.22_wp * 1.5e-3_wp                               ! air density * drag coefficient 
-      zmod = 1._wp / MAX(  1.e-20, SQRT(  zcd * SQRT( pua*pua + pva*pva)  )  )
-      pua  = pua * zmod                                       ! note: stress module=0 necessarly implies ua=va=0
-      pva  = pva * zmod
-
+      !
+      ! get position, weight and mask 
+      CALL icb_utl_pos( pi, pj, 'T', iiT, ijT, zwT, zmskT )
+      CALL icb_utl_pos( pi, pj, 'U', iiU, ijU, zwU, zmskU )
+      CALL icb_utl_pos( pi, pj, 'V', iiV, ijV, zwV, zmskV )
+      CALL icb_utl_pos( pi, pj, 'F', iiF, ijF, zwF, zmskF )
+      !
+      ! metrics and coordinates
+      IF ( PRESENT(pe1 ) ) pe1 = icb_utl_bilin_e( e1t, e1u, e1v, e1f, pi, pj )      ! scale factors
+      IF ( PRESENT(pe2 ) ) pe2 = icb_utl_bilin_e( e2t, e2u, e2v, e2f, pi, pj )
+      IF ( PRESENT(plon) ) plon= icb_utl_bilin_h( rlon_e, iiT, ijT, zwT, .true.  )
+      IF ( PRESENT(plat) ) plat= icb_utl_bilin_h( rlat_e, iiT, ijT, zwT, .false. )
+      !
+      IF ( PRESENT(pssu) ) pssu = icb_utl_bilin_h( ssu_e, iiU, ijU, zwU        , .false. ) ! ocean velocities
+      IF ( PRESENT(pssv) ) pssv = icb_utl_bilin_h( ssv_e, iiV, ijV, zwV        , .false. ) !
+      IF ( PRESENT(psst) ) psst = icb_utl_bilin_h( sst_e, iiT, ijT, zwT * zmskT, .false. ) ! sst
+      IF ( PRESENT(psss) ) psss = icb_utl_bilin_h( sss_e, iiT, ijT, zwT * zmskT, .false. ) ! sss
+      IF ( PRESENT(pcn ) ) pcn  = icb_utl_bilin_h( fr_e , iiT, ijT, zwT * zmskT, .false. ) ! ice concentration
+      IF ( PRESENT(pff ) ) pff  = icb_utl_bilin_h( ff_e , iiF, ijF, zwF        , .false. ) ! Coriolis parameter
+      !
+      IF ( PRESENT(pua) .AND. PRESENT(pva) ) THEN
+         pua  = icb_utl_bilin_h( ua_e, iiU, ijU, zwU * zmskU, .false. ) ! 10m wind
+         pva  = icb_utl_bilin_h( va_e, iiV, ijV, zwV * zmskV, .false. ) ! here (ua,va) are stress => rough conversion from stress to speed
+         zcd  = 1.22_wp * 1.5e-3_wp                               ! air density * drag coefficient 
+         zmod = 1._wp / MAX(  1.e-20, SQRT(  zcd * SQRT( pua*pua + pva*pva)  )  )
+         pua  = pua * zmod                                       ! note: stress module=0 necessarly implies ua=va=0
+         pva  = pva * zmod
+      END IF
+      !
 #if defined key_si3
-      pui = icb_utl_bilin_h( ui_e , pi, pj, 'U', .false. )    ! sea-ice velocities
-      pvi = icb_utl_bilin_h( vi_e , pi, pj, 'V', .false. )
-      phi = icb_utl_bilin_h( hi_e , pi, pj, 'T', .true.  )    ! ice thickness
+      IF ( PRESENT(pui) ) pui = icb_utl_bilin_h( ui_e , iiU, ijU, zwU        , .false. ) ! sea-ice velocities
+      IF ( PRESENT(pvi) ) pvi = icb_utl_bilin_h( vi_e , iiV, ijV, zwV        , .false. )
+      IF ( PRESENT(phi) ) phi = icb_utl_bilin_h( hi_e , iiT, ijT, zwT * zmskT, .false. ) ! ice thickness
 #else
-      pui = 0._wp
-      pvi = 0._wp
-      phi = 0._wp
+      IF ( PRESENT(pui) ) pui = 0._wp
+      IF ( PRESENT(pvi) ) pvi = 0._wp
+      IF ( PRESENT(phi) ) phi = 0._wp
 #endif
-
+      !
       ! Estimate SSH gradient in i- and j-direction (centred evaluation)
-      pssh_i = ( icb_utl_bilin_h( ssh_e, pi+0.1_wp, pj, 'T', .true. ) -   &
-         &       icb_utl_bilin_h( ssh_e, pi-0.1_wp, pj, 'T', .true. )  ) / ( 0.2_wp * pe1 )
-      pssh_j = ( icb_utl_bilin_h( ssh_e, pi, pj+0.1_wp, 'T', .true. ) -   &
-         &       icb_utl_bilin_h( ssh_e, pi, pj-0.1_wp, 'T', .true. )  ) / ( 0.2_wp * pe2 )
+      IF ( PRESENT(pssh_i) .AND. PRESENT(pssh_j) ) THEN
+         CALL icb_utl_pos( pi+0.1, pj    , 'T', iiTp, ijTp, zwTp, zmskTp )
+         CALL icb_utl_pos( pi-0.1, pj    , 'T', iiTm, ijTm, zwTm, zmskTm )
+         !
+         IF ( .NOT. PRESENT(pe1) ) pe1 = icb_utl_bilin_e( e1t, e1u, e1v, e1f, pi, pj )
+         pssh_i = ( icb_utl_bilin_h( ssh_e, iiTp, ijTp, zwTp*zmskTp, .false. ) -   &
+            &       icb_utl_bilin_h( ssh_e, iiTm, ijTm, zwTm*zmskTm, .false. )  ) / ( 0.2_wp * pe1 )
+         !
+         CALL icb_utl_pos( pi    , pj+0.1, 'T', iiTp, ijTp, zwTp, zmskTp )
+         CALL icb_utl_pos( pi    , pj-0.1, 'T', iiTm, ijTm, zwTm, zmskTm )
+         !
+         IF ( .NOT. PRESENT(pe2) ) pe2 = icb_utl_bilin_e( e2t, e2u, e2v, e2f, pi, pj )
+         pssh_j = ( icb_utl_bilin_h( ssh_e, iiTp, ijTp, zwTp*zmskTp, .false. ) -   &
+            &       icb_utl_bilin_h( ssh_e, iiTm, ijTm, zwTm*zmskTm, .false. )  ) / ( 0.2_wp * pe2 )
+      END IF
+      !
+      ! 3d interpolation
+      IF ( PRESENT(puoce) .AND. PRESENT(pvoce) ) THEN
+         ! no need to mask as 0 is a valid data for land
+         zw1d(1,:) = zwU(1) ; zw1d(2,:) = zwU(2) ; zw1d(3,:) = zwU(3) ; zw1d(4,:) = zwU(4) ;
+         puoce(:) = icb_utl_bilin_h( uoce_e , iiU, ijU, zw1d )
+
+         zw1d(1,:) = zwV(1) ; zw1d(2,:) = zwV(2) ; zw1d(3,:) = zwV(3) ; zw1d(4,:) = zwV(4) ;
+         pvoce(:) = icb_utl_bilin_h( voce_e , iiV, ijV, zw1d )
+      END IF
+
+      IF ( PRESENT(ptoce) ) THEN
+         ! for temperature we need to mask the weight properly
+         ! no need of extra halo as it is a T point variable
+         zw1d(1,:) = tmask(iiT  ,ijT  ,:) * zwT(1) * zmskT(1)
+         zw1d(2,:) = tmask(iiT+1,ijT  ,:) * zwT(2) * zmskT(2)
+         zw1d(3,:) = tmask(iiT  ,ijT+1,:) * zwT(3) * zmskT(3)
+         zw1d(4,:) = tmask(iiT+1,ijT+1,:) * zwT(4) * zmskT(4)
+         ptoce(:) = icb_utl_bilin_h( toce_e , iiT, ijT, zw1d )
+      END IF
+      !
+      IF ( PRESENT(pe3t)  ) pe3t(:)  = e3t_e(iiT,ijT,:)    ! as in Nacho tarball need to be fix once we are able to reproduce Nacho results
       !
    END SUBROUTINE icb_utl_interp
 
-
-   REAL(wp) FUNCTION icb_utl_bilin_h( pfld, pi, pj, cd_type, plmask )
+   SUBROUTINE icb_utl_pos( pi, pj, cd_type, kii, kij, pw, pmsk )
       !!----------------------------------------------------------------------
       !!                  ***  FUNCTION icb_utl_bilin  ***
@@ -182,13 +262,12 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(0:jpi+1,0:jpj+1), INTENT(in) ::   pfld      ! field to be interpolated
-      REAL(wp)                            , INTENT(in) ::   pi, pj    ! targeted coordinates in (i,j) referential
-      CHARACTER(len=1)                    , INTENT(in) ::   cd_type   ! type of pfld array grid-points: = T , U , V or F points
-      LOGICAL                             , INTENT(in) ::   plmask    ! special treatment of mask point
-      !
-      INTEGER  ::   ii, ij   ! local integer
-      REAL(wp) ::   zi, zj   ! local real
-      REAL(wp) :: zw1, zw2, zw3, zw4
-      REAL(wp), DIMENSION(4) :: zmask
+      REAL(wp)              , INTENT(IN)  ::   pi, pj    ! targeted coordinates in (i,j) referential
+      CHARACTER(len=1)      , INTENT(IN)  ::   cd_type   ! point type
+      REAL(wp), DIMENSION(4), INTENT(OUT) ::   pw, pmsk  ! weight and mask
+      INTEGER ,               INTENT(OUT) ::   kii, kij  ! bottom left corner position in local domain
+      !
+      REAL(wp) :: zwi, zwj ! distance to bottom left corner
+      INTEGER  :: ierr 
+      !
       !!----------------------------------------------------------------------
       !
@@ -198,73 +277,85 @@
          ! since we're looking for four T points containing quadrant we're in of 
          ! current T cell
-         ii = MAX(0, INT( pi     ))
-         ij = MAX(0, INT( pj     ))    ! T-point
-         zi = pi - REAL(ii,wp)
-         zj = pj - REAL(ij,wp)
+         kii = MAX(0, INT( pi        ))
+         kij = MAX(0, INT( pj        ))    ! T-point
+         zwi = pi - REAL(kii,wp)
+         zwj = pj - REAL(kij,wp)
       CASE ( 'U' )
-         ii = MAX(0, INT( pi-0.5_wp ))
-         ij = MAX(0, INT( pj     ))    ! U-point
-         zi = pi - 0.5_wp - REAL(ii,wp)
-         zj = pj - REAL(ij,wp)
+         kii = MAX(0, INT( pi-0.5_wp ))
+         kij = MAX(0, INT( pj        ))    ! U-point
+         zwi = pi - 0.5_wp - REAL(kii,wp)
+         zwj = pj - REAL(kij,wp)
       CASE ( 'V' )
-         ii = MAX(0, INT( pi     ))
-         ij = MAX(0, INT( pj-0.5_wp ))    ! V-point
-         zi = pi - REAL(ii,wp)
-         zj = pj - 0.5_wp - REAL(ij,wp)
+         kii = MAX(0, INT( pi        ))
+         kij = MAX(0, INT( pj-0.5_wp ))    ! V-point
+         zwi = pi - REAL(kii,wp)
+         zwj = pj - 0.5_wp - REAL(kij,wp)
       CASE ( 'F' )
-         ii = MAX(0, INT( pi-0.5_wp ))
-         ij = MAX(0, INT( pj-0.5_wp ))    ! F-point
-         zi = pi - 0.5_wp - REAL(ii,wp)
-         zj = pj - 0.5_wp - REAL(ij,wp)
+         kii = MAX(0, INT( pi-0.5_wp ))
+         kij = MAX(0, INT( pj-0.5_wp ))    ! F-point
+         zwi = pi - 0.5_wp - REAL(kii,wp)
+         zwj = pj - 0.5_wp - REAL(kij,wp)
       END SELECT
+      !
+      ! compute weight
+      pw(1) = (1._wp-zwi) * (1._wp-zwj)
+      pw(2) =        zwi  * (1._wp-zwj)
+      pw(3) = (1._wp-zwi) *        zwj
+      pw(4) =        zwi  *        zwj
+      !
+      ! find position in this processor. Prevent near edge problems (see #1389)
+      !
+      IF (TRIM(cd_type) == 'T' ) THEN
+         ierr = 0
+         IF    ( kii <  mig( 1 ) ) THEN   ;  ierr = ierr + 1
+         ELSEIF( kii >= mig(jpi) ) THEN   ;  ierr = ierr + 1
+         ENDIF
+         !
+         IF    ( kij <  mjg( 1 ) ) THEN   ;   ierr = ierr + 1
+         ELSEIF( kij >= mjg(jpj) ) THEN   ;   ierr = ierr + 1
+         ENDIF
+         !
+         IF ( ierr > 0 ) THEN
+            WRITE(numout,*) 'bottom left corner T point out of bound'
+            WRITE(numout,*) pi, kii, mig( 1 ), mig(jpi)
+            WRITE(numout,*) pj, kij, mjg( 1 ), mjg(jpj)
+            WRITE(numout,*) pmsk
+            CALL ctl_stop('STOP','icb_utl_bilin_h: an icebergs coordinates is out of valid range (out of bound error)')
+         END IF
+      END IF
       !
       ! find position in this processor. Prevent near edge problems (see #1389)
       ! (PM) will be useless if extra halo is used in NEMO
       !
-      IF    ( ii <= mig(1)-1 ) THEN   ;   ii = 0
-      ELSEIF( ii  > mig(jpi) ) THEN   ;   ii = jpi
-      ELSE                            ;   ii = mi1(ii)
+      IF    ( kii <= mig(1)-1 ) THEN   ;   kii = 0
+      ELSEIF( kii  > mig(jpi) ) THEN   ;   kii = jpi
+      ELSE                             ;   kii = mi1(kii)
       ENDIF
-      IF    ( ij <= mjg(1)-1 ) THEN   ;   ij = 0
-      ELSEIF( ij  > mjg(jpj) ) THEN   ;   ij = jpj
-      ELSE                            ;   ij = mj1(ij)
+      IF    ( kij <= mjg(1)-1 ) THEN   ;   kij = 0
+      ELSEIF( kij  > mjg(jpj) ) THEN   ;   kij = jpj
+      ELSE                             ;   kij = mj1(kij)
       ENDIF
       !
       ! define mask array 
-      IF (plmask) THEN
-         ! land value is not used in the interpolation
-         SELECT CASE ( cd_type )
-         CASE ( 'T' )
-            zmask = (/tmask_e(ii,ij), tmask_e(ii+1,ij), tmask_e(ii,ij+1), tmask_e(ii+1,ij+1)/)
-         CASE ( 'U' )
-            zmask = (/umask_e(ii,ij), umask_e(ii+1,ij), umask_e(ii,ij+1), umask_e(ii+1,ij+1)/)
-         CASE ( 'V' )
-            zmask = (/vmask_e(ii,ij), vmask_e(ii+1,ij), vmask_e(ii,ij+1), vmask_e(ii+1,ij+1)/)
-         CASE ( 'F' )
-            ! F case only used for coriolis, ff_f is not mask so zmask = 1
-            zmask = 1.
-         END SELECT
-      ELSE
-         ! land value is used during interpolation
-         zmask = 1.
-      END iF
-      !
-      ! compute weight
-      zw1 = zmask(1) * (1._wp-zi) * (1._wp-zj)
-      zw2 = zmask(2) *        zi  * (1._wp-zj)
-      zw3 = zmask(3) * (1._wp-zi) *        zj
-      zw4 = zmask(4) *        zi  *        zj
-      !
-      ! compute interpolated value
-      icb_utl_bilin_h = ( pfld(ii,ij)*zw1 + pfld(ii+1,ij)*zw2 + pfld(ii,ij+1)*zw3 + pfld(ii+1,ij+1)*zw4 ) / MAX(1.e-20, zw1+zw2+zw3+zw4) 
-      !
-   END FUNCTION icb_utl_bilin_h
-
-
-   REAL(wp) FUNCTION icb_utl_bilin( pfld, pi, pj, cd_type )
+      ! land value is not used in the interpolation
+      SELECT CASE ( cd_type )
+      CASE ( 'T' )
+         pmsk = (/tmask_e(kii,kij), tmask_e(kii+1,kij), tmask_e(kii,kij+1), tmask_e(kii+1,kij+1)/)
+      CASE ( 'U' )
+         pmsk = (/umask_e(kii,kij), umask_e(kii+1,kij), umask_e(kii,kij+1), umask_e(kii+1,kij+1)/)
+      CASE ( 'V' )
+         pmsk = (/vmask_e(kii,kij), vmask_e(kii+1,kij), vmask_e(kii,kij+1), vmask_e(kii+1,kij+1)/)
+      CASE ( 'F' )
+         ! F case only used for coriolis, ff_f is not mask so zmask = 1
+         pmsk = 1.
+      END SELECT
+   END SUBROUTINE icb_utl_pos
+
+   REAL(wp) FUNCTION icb_utl_bilin_2d_h( pfld, pii, pij, pw, pllon )
       !!----------------------------------------------------------------------
       !!                  ***  FUNCTION icb_utl_bilin  ***
       !!
       !! ** Purpose :   bilinear interpolation at berg location depending on the grid-point type
+      !!                this version deals with extra halo points
       !!
       !!       !!gm  CAUTION an optional argument should be added to handle
@@ -272,63 +363,35 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pfld      ! field to be interpolated
-      REAL(wp)                    , INTENT(in) ::   pi, pj    ! targeted coordinates in (i,j) referential
-      CHARACTER(len=1)            , INTENT(in) ::   cd_type   ! type of pfld array grid-points: = T , U , V or F points
-      !
-      INTEGER  ::   ii, ij   ! local integer
-      REAL(wp) ::   zi, zj   ! local real
-      !!----------------------------------------------------------------------
-      !
-      SELECT CASE ( cd_type )
-         CASE ( 'T' )
-            ! note that here there is no +0.5 added
-            ! since we're looking for four T points containing quadrant we're in of 
-            ! current T cell
-            ii = MAX(1, INT( pi     ))
-            ij = MAX(1, INT( pj     ))    ! T-point
-            zi = pi - REAL(ii,wp)
-            zj = pj - REAL(ij,wp)
-         CASE ( 'U' )
-            ii = MAX(1, INT( pi-0.5 ))
-            ij = MAX(1, INT( pj     ))    ! U-point
-            zi = pi - 0.5 - REAL(ii,wp)
-            zj = pj - REAL(ij,wp)
-         CASE ( 'V' )
-            ii = MAX(1, INT( pi     ))
-            ij = MAX(1, INT( pj-0.5 ))    ! V-point
-            zi = pi - REAL(ii,wp)
-            zj = pj - 0.5 - REAL(ij,wp)
-         CASE ( 'F' )
-            ii = MAX(1, INT( pi-0.5 ))
-            ij = MAX(1, INT( pj-0.5 ))    ! F-point
-            zi = pi - 0.5 - REAL(ii,wp)
-            zj = pj - 0.5 - REAL(ij,wp)
-      END SELECT
-      !
-      ! find position in this processor. Prevent near edge problems (see #1389)
-      IF    ( ii < mig( 1 ) ) THEN   ;   ii = 1
-      ELSEIF( ii > mig(jpi) ) THEN   ;   ii = jpi
-      ELSE                           ;   ii = mi1(ii)
+      REAL(wp), DIMENSION(0:jpi+1,0:jpj+1), INTENT(in) ::   pfld      ! field to be interpolated
+      REAL(wp), DIMENSION(4)              , INTENT(in) ::   pw        ! weight
+      LOGICAL                             , INTENT(in) ::   pllon     ! input data is a longitude
+      INTEGER ,                             INTENT(in) ::   pii, pij  ! bottom left corner
+      !
+      REAL(wp), DIMENSION(4) :: zdat ! input data
+      !!----------------------------------------------------------------------
+      !
+      ! data
+      zdat(1) = pfld(pii  ,pij  )
+      zdat(2) = pfld(pii+1,pij  )
+      zdat(3) = pfld(pii  ,pij+1)
+      zdat(4) = pfld(pii+1,pij+1)
+      !
+      IF( pllon .AND. MAXVAL(zdat) - MINVAL(zdat) > 90._wp ) THEN
+         WHERE( zdat < 0._wp ) zdat = zdat + 360._wp
       ENDIF
-      IF    ( ij < mjg( 1 ) ) THEN   ;   ij = 1
-      ELSEIF( ij > mjg(jpj) ) THEN   ;   ij = jpj
-      ELSE                           ;   ij  = mj1(ij)
-      ENDIF
-      !
-      IF( ii == jpi )   ii = ii-1      
-      IF( ij == jpj )   ij = ij-1
-      !
-      icb_utl_bilin = ( pfld(ii,ij  ) * (1.-zi) + pfld(ii+1,ij  ) * zi ) * (1.-zj)   &
-         &          + ( pfld(ii,ij+1) * (1.-zi) + pfld(ii+1,ij+1) * zi ) *     zj
-      !
-   END FUNCTION icb_utl_bilin
-
-
-   REAL(wp) FUNCTION icb_utl_bilin_x( pfld, pi, pj )
-      !!----------------------------------------------------------------------
-      !!                  ***  FUNCTION icb_utl_bilin_x  ***
+      !
+      ! compute interpolated value
+      icb_utl_bilin_2d_h = ( zdat(1)*pw(1) + zdat(2)*pw(2) + zdat(3)*pw(3) + zdat(4)*pw(4) ) / MAX(1.e-20, pw(1)+pw(2)+pw(3)+pw(4)) 
+      !
+      IF( pllon .AND. icb_utl_bilin_2d_h > 180._wp ) icb_utl_bilin_2d_h = icb_utl_bilin_2d_h - 360._wp
+      !
+   END FUNCTION icb_utl_bilin_2d_h
+
+   FUNCTION icb_utl_bilin_3d_h( pfld, pii, pij, pw )
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION icb_utl_bilin  ***
       !!
       !! ** Purpose :   bilinear interpolation at berg location depending on the grid-point type
-      !!                Special case for interpolating longitude
+      !!                this version deals with extra halo points
       !!
       !!       !!gm  CAUTION an optional argument should be added to handle
@@ -336,48 +399,26 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pfld      ! field to be interpolated
-      REAL(wp)                    , INTENT(in) ::   pi, pj    ! targeted coordinates in (i,j) referential
-      !
-      INTEGER                                  ::   ii, ij   ! local integer
-      REAL(wp)                                 ::   zi, zj   ! local real
-      REAL(wp)                                 ::   zret     ! local real
-      REAL(wp), DIMENSION(4)                   ::   z4
-      !!----------------------------------------------------------------------
-      !
-      ! note that here there is no +0.5 added
-      ! since we're looking for four T points containing quadrant we're in of 
-      ! current T cell
-      ii = MAX(1, INT( pi     ))
-      ij = MAX(1, INT( pj     ))    ! T-point
-      zi = pi - REAL(ii,wp)
-      zj = pj - REAL(ij,wp)
-      !
-      ! find position in this processor. Prevent near edge problems (see #1389)
-      IF    ( ii < mig( 1 ) ) THEN   ;   ii = 1
-      ELSEIF( ii > mig(jpi) ) THEN   ;   ii = jpi
-      ELSE                           ;   ii = mi1(ii)
-      ENDIF
-      IF    ( ij < mjg( 1 ) ) THEN   ;   ij = 1
-      ELSEIF( ij > mjg(jpj) ) THEN   ;   ij = jpj
-      ELSE                           ;   ij  = mj1(ij)
-      ENDIF
-      !
-      IF( ii == jpi )   ii = ii-1      
-      IF( ij == jpj )   ij = ij-1
-      !
-      z4(1) = pfld(ii  ,ij  )
-      z4(2) = pfld(ii+1,ij  )
-      z4(3) = pfld(ii  ,ij+1)
-      z4(4) = pfld(ii+1,ij+1)
-      IF( MAXVAL(z4) - MINVAL(z4) > 90._wp ) THEN
-         WHERE( z4 < 0._wp ) z4 = z4 + 360._wp
-      ENDIF
-      !
-      zret = (z4(1) * (1.-zi) + z4(2) * zi) * (1.-zj) + (z4(3) * (1.-zi) + z4(4) * zi) * zj
-      IF( zret > 180._wp ) zret = zret - 360._wp
-      icb_utl_bilin_x = zret
-      !
-   END FUNCTION icb_utl_bilin_x
-
+      REAL(wp), DIMENSION(0:jpi+1,0:jpj+1, jpk), INTENT(in) ::   pfld      ! field to be interpolated
+      REAL(wp), DIMENSION(4,jpk)               , INTENT(in) ::   pw        ! weight
+      INTEGER ,                                  INTENT(in) ::   pii, pij  ! bottom left corner
+      REAL(wp), DIMENSION(jpk) :: icb_utl_bilin_3d_h
+      !
+      REAL(wp), DIMENSION(4,jpk) :: zdat ! input data
+      INTEGER :: jk
+      !!----------------------------------------------------------------------
+      !
+      ! data
+      zdat(1,:) = pfld(pii  ,pij  ,:)
+      zdat(2,:) = pfld(pii+1,pij  ,:)
+      zdat(3,:) = pfld(pii  ,pij+1,:)
+      zdat(4,:) = pfld(pii+1,pij+1,:)
+      !
+      ! compute interpolated value
+      DO jk=1,jpk
+         icb_utl_bilin_3d_h(jk) =   ( zdat(1,jk)*pw(1,jk) + zdat(2,jk)*pw(2,jk) + zdat(3,jk)*pw(3,jk) + zdat(4,jk)*pw(4,jk) ) &
+            &                     /   MAX(1.e-20, pw(1,jk)+pw(2,jk)+pw(3,jk)+pw(4,jk)) 
+      END DO
+      !
+   END FUNCTION icb_utl_bilin_3d_h
 
    REAL(wp) FUNCTION icb_utl_bilin_e( pet, peu, pev, pef, pi, pj )
@@ -390,10 +431,9 @@
       !!----------------------------------------------------------------------
       REAL(wp), DIMENSION(:,:), INTENT(in) ::   pet, peu, pev, pef   ! horizontal scale factor to be interpolated at t-,u-,v- & f-pts
-      REAL(wp)                , INTENT(in) ::   pi, pj               ! targeted coordinates in (i,j) referential
-      !
-      INTEGER  ::   ii, ij, icase, ierr   ! local integer
+      REAL(wp)                , INTENT(IN) ::   pi , pj              ! iceberg position
       !
       ! weights corresponding to corner points of a T cell quadrant
       REAL(wp) ::   zi, zj          ! local real
+      INTEGER  ::   ii, ij          ! bottom left corner coordinate in local domain
       !
       ! values at corner points of a T cell quadrant
@@ -402,6 +442,7 @@
       !!----------------------------------------------------------------------
       !
+      ! cannot used iiT because need ii/ij reltaive to global indices not local one
       ii = MAX(1, INT( pi ))   ;   ij = MAX(1, INT( pj ))            ! left bottom T-point (i,j) indices
-
+      ! 
       ! fractional box spacing
       ! 0   <= zi < 0.5, 0   <= zj < 0.5   -->  NW quadrant of current T cell
@@ -413,20 +454,7 @@
       zj = pj - REAL(ij,wp)
 
-      ! find position in this processor. Prevent near edge problems (see #1389)
-      !
-      ierr = 0
-      IF    ( ii < mig( 1 ) ) THEN   ;   ii = 1       ; ierr = ierr + 1
-      ELSEIF( ii > mig(jpi) ) THEN   ;   ii = jpi     ; ierr = ierr + 1
-      ELSE                           ;   ii = mi1(ii)
-      ENDIF
-      IF    ( ij < mjg( 1 ) ) THEN   ;   ij = 1       ; ierr = ierr + 1
-      ELSEIF( ij > mjg(jpj) ) THEN   ;   ij = jpj     ; ierr = ierr + 1
-      ELSE                           ;   ij  = mj1(ij)
-      ENDIF
-      !
-      IF( ii == jpi ) THEN ; ii = ii-1 ; ierr = ierr + 1 ; END IF     
-      IF( ij == jpj ) THEN ; ij = ij-1 ; ierr = ierr + 1 ; END IF
-      !
-      IF ( ierr > 0 ) CALL ctl_stop('STOP','icb_utl_bilin_e: an icebergs coordinates is out of valid range (out of bound error)')
+      ! conversion to local domain (no need to do a sanity check already done in icbpos)
+      ii = mi1(ii)
+      ij = mj1(ij)
       !
       IF(    0.0_wp <= zi .AND. zi < 0.5_wp   ) THEN
@@ -465,4 +493,51 @@
    END FUNCTION icb_utl_bilin_e
 
+   SUBROUTINE icb_utl_getkb( kb, pe3, pD )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE icb_utl_getkb         ***
+      !!
+      !! ** Purpose :   compute the latest level affected by icb
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER,                INTENT(out):: kb
+      REAL(wp), DIMENSION(:), INTENT(in) :: pe3
+      REAL(wp),               INTENT(in) :: pD
+      !!
+      INTEGER  :: jk
+      REAL(wp) :: zdepw
+      !!----------------------------------------------------------------------
+      !!
+      zdepw = pe3(1) ; kb = 2
+      DO WHILE ( zdepw <  pD)
+         zdepw = zdepw + pe3(kb)
+         kb = kb + 1
+      END DO
+      kb = MIN(kb - 1,jpk)
+   END SUBROUTINE
+
+   SUBROUTINE icb_utl_zavg(pzavg, pdat, pe3, pD, kb )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE icb_utl_getkb         ***
+      !!
+      !! ** Purpose :   compute the vertical average of ocean properties affected by icb
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER,                INTENT(in ) :: kb        ! deepest level affected by icb
+      REAL(wp), DIMENSION(:), INTENT(in ) :: pe3, pdat ! vertical profile
+      REAL(wp),               INTENT(in ) :: pD        ! draft
+      REAL(wp),               INTENT(out) :: pzavg     ! z average
+      !!----------------------------------------------------------------------
+      INTEGER  :: jk
+      REAL(wp) :: zdep
+      !!----------------------------------------------------------------------
+      pzavg = 0.0 ; zdep = 0.0
+      DO jk = 1,kb-1
+         pzavg = pzavg + pe3(jk)*pdat(jk)
+         zdep  = zdep  + pe3(jk)
+      END DO
+      ! if kb is limited by mbkt  => bottom value is used between bathy and icb tail
+      ! if kb not limited by mbkt => ocean value over mask is used (ie 0.0 for u, v)
+      pzavg = ( pzavg + (pD - zdep)*pdat(kb)) / pD
+   END SUBROUTINE
 
    SUBROUTINE icb_utl_add( bergvals, ptvals )
@@ -653,5 +728,5 @@
       WRITE(numicb, 9200) kt, berg%number(1), &
                    pt%xi, pt%yj, pt%lon, pt%lat, pt%uvel, pt%vvel,  &
-                   pt%uo, pt%vo, pt%ua, pt%va, pt%ui, pt%vi
+                   pt%ssu, pt%ssv, pt%ua, pt%va, pt%ui, pt%vi
       CALL flush( numicb )
  9200 FORMAT(5x,i5,2x,i10,6(2x,2f10.4))
@@ -679,5 +754,5 @@
          WRITE(numicb,'(a," pe=(",i3,")")' ) cd_label, narea
          WRITE(numicb,'(a8,4x,a6,12x,a5,15x,a7,19x,a3,17x,a5,17x,a5,17x,a5)' )   &
-            &         'timestep', 'number', 'xi,yj','lon,lat','u,v','uo,vo','ua,va','ui,vi'
+            &         'timestep', 'number', 'xi,yj','lon,lat','u,v','ssu,ssv','ua,va','ui,vi'
       ENDIF
       DO WHILE( ASSOCIATED(this) )
@@ -823,4 +898,75 @@
    END FUNCTION icb_utl_heat
 
+   SUBROUTINE test_icb_utl_getkb
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION test_icb_utl_getkb  ***
+      !!
+      !! ** Purpose : Test routine icb_utl_getkb, icb_utl_zavg
+      !! ** Methode : Call each subroutine with specific input data
+      !!              What should be the output is easy to determined and check 
+      !!              if NEMO return the correct answer.
+      !! ** Comments : not called, if needed a CALL test_icb_utl_getkb need to be added in icb_step
+      !!----------------------------------------------------------------------
+      INTEGER :: ikb
+      REAL(wp) :: zD, zout
+      REAL(wp), DIMENSION(jpk) :: ze3, zin
+      WRITE(numout,*) 'Test icb_utl_getkb : '
+      zD = 0.0 ; ze3= 20.0
+      WRITE(numout,*) 'INPUT : zD = ',zD,' ze3 = ',ze3(1)
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      WRITE(numout,*) 'OUTPUT : kb = ',ikb
+
+      zD = 8000000.0 ; ze3= 20.0
+      WRITE(numout,*) 'INPUT : zD = ',zD,' ze3 = ',ze3(1)
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      WRITE(numout,*) 'OUTPUT : kb = ',ikb
+
+      zD = 80.0 ; ze3= 20.0
+      WRITE(numout,*) 'INPUT : zD = ',zD,' ze3 = ',ze3(1)
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      WRITE(numout,*) 'OUTPUT : kb = ',ikb
+
+      zD = 85.0 ; ze3= 20.0
+      WRITE(numout,*) 'INPUT : zD = ',zD,' ze3 = ',ze3(1)
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      WRITE(numout,*) 'OUTPUT : kb = ',ikb
+
+      zD = 75.0 ; ze3= 20.0
+      WRITE(numout,*) 'INPUT : zD = ',zD,' ze3 = ',ze3(1)
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      WRITE(numout,*) 'OUTPUT : kb = ',ikb
+
+      WRITE(numout,*) '=================================='
+      WRITE(numout,*) 'Test icb_utl_zavg'
+      zD = 0.0 ; ze3= 20.0 ; zin=1.0
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      CALL icb_utl_zavg(zout, zin, ze3, zD, ikb)
+      WRITE(numout,*) 'INPUT  : zD = ',zD,' ze3 = ',ze3(1),' zin = ', zin, ' ikb = ',ikb
+      WRITE(numout,*) 'OUTPUT : zout = ',zout
+
+      zD = 50.0 ; ze3= 20.0 ; zin=1.0; zin(3:jpk) = 0.0
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      CALL icb_utl_zavg(zout, zin, ze3, zD, ikb)
+      WRITE(numout,*) 'INPUT  : zD = ',zD,' ze3 = ',ze3(1),' zin = ', zin, ' ikb = ',ikb
+      WRITE(numout,*) 'OUTPUT : zout = ',zout
+      CALL FLUSH(numout)
+
+      zD = 80.0 ; ze3= 20.0 ; zin=1.0; zin(3:jpk) = 0.0
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      CALL icb_utl_zavg(zout, zin, ze3, zD, ikb)
+      WRITE(numout,*) 'INPUT  : zD = ',zD,' ze3 = ',ze3(1),' zin = ', zin, ' ikb = ',ikb
+      WRITE(numout,*) 'OUTPUT : zout = ',zout
+
+      zD = 80 ; ze3= 20.0 ; zin=1.0 ; zin(3:jpk) = 0.0
+      CALL icb_utl_getkb(ikb, ze3, zD)
+      ikb = 2
+      CALL icb_utl_zavg(zout, zin, ze3, zD, ikb)
+      WRITE(numout,*) 'INPUT  : zD = ',zD,' ze3 = ',ze3(1),' zin = ', zin, ' ikb = ',ikb
+      WRITE(numout,*) 'OUTPUT : zout = ',zout
+
+      CALL FLUSH(numout)
+
+   END SUBROUTINE test_icb_utl_getkb
+
    !!======================================================================
 END MODULE icbutl
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/in_out_manager.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/in_out_manager.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/in_out_manager.F90	(revision 14055)
@@ -89,9 +89,14 @@
    LOGICAL ::   lrst_abl              !: logical to control the abl restart write 
    INTEGER ::   numror = 0            !: logical unit for ocean restart (read). Init to 0 is needed for SAS (in daymod.F90)
-   INTEGER ::   numrir                !: logical unit for ice   restart (read)
-   INTEGER ::   numrar                !: logical unit for abl   restart (read)
-   INTEGER ::   numrow                !: logical unit for ocean restart (write)
-   INTEGER ::   numriw                !: logical unit for ice   restart (write)
-   INTEGER ::   numraw                !: logical unit for abl   restart (write)
+   INTEGER ::   numrir = 0            !: logical unit for ice   restart (read)
+   INTEGER ::   numrar = 0            !: logical unit for abl   restart (read)
+   INTEGER ::   numrow = 0            !: logical unit for ocean restart (write)
+   INTEGER ::   numriw = 0            !: logical unit for ice   restart (write)
+   INTEGER ::   numraw = 0            !: logical unit for abl   restart (write)
+   INTEGER ::   numrtr = 0            !: trc restart (read )
+   INTEGER ::   numrtw = 0            !: trc restart (write )
+   INTEGER ::   numrsr = 0            !: logical unit for sed restart (read)
+   INTEGER ::   numrsw = 0            !: logical unit for sed restart (write)
+
    INTEGER ::   nrst_lst              !: number of restart to output next
 
@@ -165,7 +170,16 @@
    LOGICAL       ::   lwp      = .FALSE.    !: boolean : true on the 1st processor only .OR. sn_cfctl%l_oceout=T
    LOGICAL       ::   lsp_area = .TRUE.     !: to make a control print over a specific area
-   CHARACTER(lc) ::   cxios_context         !: context name used in xios
-   CHARACTER(lc) ::   crxios_context         !: context name used in xios to read restart
-   CHARACTER(lc) ::   cwxios_context        !: context name used in xios to write restart file
+   CHARACTER(LEN=lc) ::   cxios_context     !: context name used in xios
+   CHARACTER(LEN=lc) ::   cr_ocerst_cxt     !: context name used in xios to read OCE restart
+   CHARACTER(LEN=lc) ::   cw_ocerst_cxt     !: context name used in xios to write OCE restart file
+   CHARACTER(LEN=lc) ::   cr_icerst_cxt     !: context name used in xios to read SI3 restart
+   CHARACTER(LEN=lc) ::   cw_icerst_cxt     !: context name used in xios to write SI3 restart file
+   CHARACTER(LEN=lc) ::   cr_toprst_cxt     !: context name used in xios to read TOP restart
+   CHARACTER(LEN=lc) ::   cw_toprst_cxt     !: context name used in xios to write TOP restart file
+   CHARACTER(LEN=lc) ::   cr_sedrst_cxt     !: context name used in xios to read SEDIMENT restart
+   CHARACTER(LEN=lc) ::   cw_sedrst_cxt     !: context name used in xios to write SEDIMENT restart file
+
+
+
 
    !! * Substitutions
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom.F90	(revision 14055)
@@ -29,5 +29,4 @@
    USE in_out_manager  ! I/O manager
    USE lib_mpp           ! MPP library
-#if defined key_iomput
    USE sbc_oce  , ONLY :   nn_fsbc, ght_abl, ghw_abl, e3t_abl, e3w_abl, jpka, jpkam1
    USE icb_oce  , ONLY :   nclasses, class_num       !  !: iceberg classes
@@ -37,4 +36,5 @@
    USE phycst          ! physical constants
    USE dianam          ! build name of file
+#if defined key_iomput
    USE xios
 # endif
@@ -46,4 +46,6 @@
    USE lib_fortran 
    USE diu_bulk, ONLY : ln_diurnal_only, ln_diurnal
+   USE iom_nf90
+   USE netcdf
 
    IMPLICIT NONE
@@ -58,4 +60,5 @@
    PUBLIC iom_chkatt, iom_getatt, iom_putatt, iom_getszuld, iom_rstput, iom_delay_rst, iom_put
    PUBLIC iom_use, iom_context_finalize, iom_update_file_name, iom_miss_val
+   PUBLIC iom_xios_setid
 
    PRIVATE iom_rp0d_sp, iom_rp1d_sp, iom_rp2d_sp, iom_rp3d_sp
@@ -69,7 +72,8 @@
    PRIVATE iom_set_domain_attr, iom_set_axis_attr, iom_set_field_attr, iom_set_file_attr, iom_get_file_attr, iom_set_grid_attr
    PRIVATE set_grid, set_grid_bounds, set_scalar, set_xmlatt, set_mooring, iom_sdate
-   PRIVATE iom_set_rst_context, iom_set_rstw_active, iom_set_rstr_active
+   PRIVATE iom_set_rst_context, iom_set_vars_active
 # endif
-   PUBLIC iom_set_rstw_var_active, iom_set_rstw_core, iom_set_rst_vars
+   PRIVATE set_xios_context
+   PRIVATE iom_set_rstw_active
 
    INTERFACE iom_get
@@ -101,5 +105,5 @@
 CONTAINS
 
-   SUBROUTINE iom_init( cdname, fname, ld_closedef ) 
+   SUBROUTINE iom_init( cdname, kdid, ld_closedef ) 
       !!----------------------------------------------------------------------
       !!                     ***  ROUTINE   ***
@@ -109,5 +113,5 @@
       !!----------------------------------------------------------------------
       CHARACTER(len=*),           INTENT(in)  :: cdname
-      CHARACTER(len=*), OPTIONAL, INTENT(in)  :: fname
+      INTEGER         , OPTIONAL, INTENT(in)  :: kdid          
       LOGICAL         , OPTIONAL, INTENT(in)  :: ld_closedef
 #if defined key_iomput
@@ -118,12 +122,15 @@
       INTEGER             :: irefyear, irefmonth, irefday
       INTEGER           :: ji
-      LOGICAL :: llrst_context              ! is context related to restart
+      LOGICAL           :: llrst_context              ! is context related to restart
+      LOGICAL           :: llrstr, llrstw 
+      INTEGER           :: inum
       !
       REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zt_bnds, zw_bnds
       REAL(wp), DIMENSION(2,jpkam1)         :: za_bnds   ! ABL vertical boundaries
-      LOGICAL ::   ll_closedef = .TRUE.
+      LOGICAL ::   ll_closedef
       LOGICAL ::   ll_exist
       !!----------------------------------------------------------------------
       !
+      ll_closedef = .TRUE.
       IF ( PRESENT(ld_closedef) ) ll_closedef = ld_closedef
       !
@@ -134,5 +141,14 @@
       CALL xios_context_initialize(TRIM(clname), mpi_comm_oce)
       CALL iom_swap( cdname )
-      llrst_context =  (TRIM(cdname) == TRIM(crxios_context) .OR. TRIM(cdname) == TRIM(cwxios_context))
+
+      llrstr = (cdname == cr_ocerst_cxt) .OR. (cdname == cr_icerst_cxt)
+      llrstr = llrstr .OR. (cdname == cr_toprst_cxt)
+      llrstr = llrstr .OR. (cdname == cr_sedrst_cxt)
+
+      llrstw = (cdname == cw_ocerst_cxt) .OR. (cdname == cw_icerst_cxt)
+      llrstw = llrstw .OR. (cdname == cw_toprst_cxt)
+      llrstw = llrstw .OR. (cdname == cw_sedrst_cxt)
+
+      llrst_context = llrstr .OR. llrstw
 
       ! Calendar type is now defined in xml file 
@@ -153,5 +169,5 @@
       IF(.NOT.llrst_context) CALL set_scalar
       !
-      IF( TRIM(cdname) == TRIM(cxios_context) ) THEN  
+      IF( cdname == cxios_context ) THEN  
          CALL set_grid( "T", glamt, gphit, .FALSE., .FALSE. ) 
          CALL set_grid( "U", glamu, gphiu, .FALSE., .FALSE. )
@@ -197,72 +213,70 @@
       ! vertical grid definition
       IF(.NOT.llrst_context) THEN
-          CALL iom_set_axis_attr(  "deptht", paxis = gdept_1d )
-          CALL iom_set_axis_attr(  "depthu", paxis = gdept_1d )
-          CALL iom_set_axis_attr(  "depthv", paxis = gdept_1d )
-          CALL iom_set_axis_attr(  "depthw", paxis = gdepw_1d )
+         CALL iom_set_axis_attr(  "deptht", paxis = gdept_1d )
+         CALL iom_set_axis_attr(  "depthu", paxis = gdept_1d )
+         CALL iom_set_axis_attr(  "depthv", paxis = gdept_1d )
+         CALL iom_set_axis_attr(  "depthw", paxis = gdepw_1d )
 
           ! ABL
-          IF( .NOT. ALLOCATED(ght_abl) ) THEN   ! force definition for xml files (xios) 
-             ALLOCATE( ght_abl(jpka), ghw_abl(jpka), e3t_abl(jpka), e3w_abl(jpka) )   ! default allocation needed by iom
-             ght_abl(:) = -1._wp   ;   ghw_abl(:) = -1._wp
-             e3t_abl(:) = -1._wp   ;   e3w_abl(:) = -1._wp
-          ENDIF
-          CALL iom_set_axis_attr( "ght_abl", ght_abl(2:jpka) )
-          CALL iom_set_axis_attr( "ghw_abl", ghw_abl(2:jpka) )
+         IF( .NOT. ALLOCATED(ght_abl) ) THEN   ! force definition for xml files (xios) 
+            ALLOCATE( ght_abl(jpka), ghw_abl(jpka), e3t_abl(jpka), e3w_abl(jpka) )   ! default allocation needed by iom
+            ght_abl(:) = -1._wp   ;   ghw_abl(:) = -1._wp
+            e3t_abl(:) = -1._wp   ;   e3w_abl(:) = -1._wp
+         ENDIF
+         CALL iom_set_axis_attr( "ght_abl", ght_abl(2:jpka) )
+         CALL iom_set_axis_attr( "ghw_abl", ghw_abl(2:jpka) )
           
-          ! Add vertical grid bounds
-          zt_bnds(2,:      ) = gdept_1d(:)
-          zt_bnds(1,2:jpk  ) = gdept_1d(1:jpkm1)
-          zt_bnds(1,1      ) = gdept_1d(1) - e3w_1d(1)
-          zw_bnds(1,:      ) = gdepw_1d(:)
-          zw_bnds(2,1:jpkm1) = gdepw_1d(2:jpk)
-          zw_bnds(2,jpk:   ) = gdepw_1d(jpk) + e3t_1d(jpk)
-          CALL iom_set_axis_attr(  "deptht", bounds=zw_bnds )
-          CALL iom_set_axis_attr(  "depthu", bounds=zw_bnds )
-          CALL iom_set_axis_attr(  "depthv", bounds=zw_bnds )
-          CALL iom_set_axis_attr(  "depthw", bounds=zt_bnds )
-
-          ! ABL
-          za_bnds(1,:) = ghw_abl(1:jpkam1)
-          za_bnds(2,:) = ghw_abl(2:jpka  )
-          CALL iom_set_axis_attr( "ght_abl", bounds=za_bnds )
-          za_bnds(1,:) = ght_abl(2:jpka  )
-          za_bnds(2,:) = ght_abl(2:jpka  ) + e3w_abl(2:jpka)
-          CALL iom_set_axis_attr( "ghw_abl", bounds=za_bnds )
-
-          CALL iom_set_axis_attr(  "nfloat", (/ (REAL(ji,wp), ji=1,jpnfl) /) )
+         ! Add vertical grid bounds
+         zt_bnds(2,:      ) = gdept_1d(:)
+         zt_bnds(1,2:jpk  ) = gdept_1d(1:jpkm1)
+         zt_bnds(1,1      ) = gdept_1d(1) - e3w_1d(1)
+         zw_bnds(1,:      ) = gdepw_1d(:)
+         zw_bnds(2,1:jpkm1) = gdepw_1d(2:jpk)
+         zw_bnds(2,jpk:   ) = gdepw_1d(jpk) + e3t_1d(jpk)
+         CALL iom_set_axis_attr(  "deptht", bounds=zw_bnds )
+         CALL iom_set_axis_attr(  "depthu", bounds=zw_bnds )
+         CALL iom_set_axis_attr(  "depthv", bounds=zw_bnds )
+         CALL iom_set_axis_attr(  "depthw", bounds=zt_bnds )
+
+         ! ABL
+         za_bnds(1,:) = ghw_abl(1:jpkam1)
+         za_bnds(2,:) = ghw_abl(2:jpka  )
+         CALL iom_set_axis_attr( "ght_abl", bounds=za_bnds )
+         za_bnds(1,:) = ght_abl(2:jpka  )
+         za_bnds(2,:) = ght_abl(2:jpka  ) + e3w_abl(2:jpka)
+         CALL iom_set_axis_attr( "ghw_abl", bounds=za_bnds )
+
+         CALL iom_set_axis_attr(  "nfloat", (/ (REAL(ji,wp), ji=1,jpnfl) /) )
 # if defined key_si3
-          CALL iom_set_axis_attr( "ncatice", (/ (REAL(ji,wp), ji=1,jpl) /) )
-          ! SIMIP diagnostics (4 main arctic straits)
-          CALL iom_set_axis_attr( "nstrait", (/ (REAL(ji,wp), ji=1,4) /) )
+         CALL iom_set_axis_attr( "ncatice", (/ (REAL(ji,wp), ji=1,jpl) /) )
+         ! SIMIP diagnostics (4 main arctic straits)
+         CALL iom_set_axis_attr( "nstrait", (/ (REAL(ji,wp), ji=1,4) /) )
 # endif
 #if defined key_top
-          IF( ALLOCATED(profsed) ) CALL iom_set_axis_attr( "profsed", paxis = profsed )
-#endif
-          CALL iom_set_axis_attr( "icbcla", class_num )
-          CALL iom_set_axis_attr( "iax_20C", (/ REAL(20,wp) /) )   ! strange syntaxe and idea...
-          CALL iom_set_axis_attr( "iax_26C", (/ REAL(26,wp) /) )   ! strange syntaxe and idea...
-          CALL iom_set_axis_attr( "iax_28C", (/ REAL(28,wp) /) )   ! strange syntaxe and idea...
-          ! for diaprt, we need to define an axis which size can be 1 (default) or 5 (if the file subbasins.nc exists)
-          INQUIRE( FILE = 'subbasins.nc', EXIST = ll_exist )
-          nbasin = 1 + 4 * COUNT( (/ll_exist/) )
-          CALL iom_set_axis_attr( "basin"  , (/ (REAL(ji,wp), ji=1,nbasin) /) )
+         IF( ALLOCATED(profsed) ) CALL iom_set_axis_attr( "profsed", paxis = profsed )
+#endif
+         CALL iom_set_axis_attr( "icbcla", class_num )
+         CALL iom_set_axis_attr( "iax_20C", (/ REAL(20,wp) /) )   ! strange syntaxe and idea...
+         CALL iom_set_axis_attr( "iax_26C", (/ REAL(26,wp) /) )   ! strange syntaxe and idea...
+         CALL iom_set_axis_attr( "iax_28C", (/ REAL(28,wp) /) )   ! strange syntaxe and idea...
+         ! for diaprt, we need to define an axis which size can be 1 (default) or 5 (if the file subbasins.nc exists)
+         INQUIRE( FILE = 'subbasins.nc', EXIST = ll_exist )
+         nbasin = 1 + 4 * COUNT( (/ll_exist/) )
+         CALL iom_set_axis_attr( "basin"  , (/ (REAL(ji,wp), ji=1,nbasin) /) )
       ENDIF
       !
       ! automatic definitions of some of the xml attributs
-      IF( TRIM(cdname) == TRIM(crxios_context) ) THEN
-!set names of the fields in restart file IF using XIOS to read data
-          CALL iom_set_rst_context(.TRUE.)
-          CALL iom_set_rst_vars(rst_rfields)
-!set which fields are to be read from restart file
-          CALL iom_set_rstr_active()
-      ELSE IF( TRIM(cdname) == TRIM(cwxios_context) ) THEN
-!set names of the fields in restart file IF using XIOS to write data
-          CALL iom_set_rst_context(.FALSE.)
-          CALL iom_set_rst_vars(rst_wfields)
-!set which fields are to be written to a restart file
-          CALL iom_set_rstw_active(fname)
+      IF(llrstr) THEN
+         IF(PRESENT(kdid)) THEN
+            CALL iom_set_rst_context(.TRUE.)
+!set which fields will be read from restart file
+            CALL iom_set_vars_active(kdid)
+         ELSE
+            CALL ctl_stop( 'iom_init:', 'restart read with XIOS: missing pointer to NETCDF file' )
+         ENDIF
+      ELSE IF(llrstw) THEN
+         CALL iom_set_rstw_file(iom_file(kdid)%name)
       ELSE
-          CALL set_xmlatt
+         CALL set_xmlatt
       ENDIF
       !
@@ -280,5 +294,5 @@
    END SUBROUTINE iom_init
 
-   SUBROUTINE iom_init_closedef
+   SUBROUTINE iom_init_closedef(cdname)
       !!----------------------------------------------------------------------
       !!            ***  SUBROUTINE iom_init_closedef  ***
@@ -288,8 +302,24 @@
       !!
       !!----------------------------------------------------------------------
-
+      CHARACTER(len=*), OPTIONAL, INTENT(IN) :: cdname
 #if defined key_iomput
-      CALL xios_close_context_definition()
-      CALL xios_update_calendar( 0 )
+      LOGICAL :: llrstw
+
+      llrstw = .FALSE.
+      IF(PRESENT(cdname)) THEN
+         llrstw = (cdname == cw_ocerst_cxt)
+         llrstw = llrstw .OR. (cdname == cw_icerst_cxt)
+         llrstw = llrstw .OR. (cdname == cw_toprst_cxt)
+         llrstw = llrstw .OR. (cdname == cw_sedrst_cxt)
+      ENDIF
+
+      IF( llrstw ) THEN
+!set names of the fields in restart file IF using XIOS to write data
+         CALL iom_set_rst_context(.FALSE.)
+         CALL xios_close_context_definition()
+      ELSE
+         CALL xios_close_context_definition()
+         CALL xios_update_calendar( 0 )
+      ENDIF
 #else
       IF( .FALSE. )   WRITE(numout,*) 'iom_init_closedef: should not see this'   ! useless statement to avoid compilation warnings
@@ -298,252 +328,143 @@
    END SUBROUTINE iom_init_closedef
 
-   SUBROUTINE iom_set_rstw_var_active(field)
+   SUBROUTINE iom_set_vars_active(idnum)
       !!---------------------------------------------------------------------
-      !!                   ***  SUBROUTINE  iom_set_rstw_var_active  ***
-      !!
-      !! ** Purpose :  enable variable in restart file when writing with XIOS 
+      !!                   ***  SUBROUTINE  iom_set_vars_active  ***
+      !!
+      !! ** Purpose :  define filename in XIOS context for reading file,
+      !!               enable variables present in a file for reading with XIOS 
+      !!               id of the file is assumed to be rrestart.
       !!---------------------------------------------------------------------
-   CHARACTER(len = *), INTENT(IN) :: field
-   INTEGER :: i
-   LOGICAL :: llis_set
-   CHARACTER(LEN=256) :: clinfo    ! info character
-
+      INTEGER, INTENT(IN) :: idnum 
+      
 #if defined key_iomput
-   llis_set = .FALSE.
-
-   DO i = 1, max_rst_fields
-       IF(TRIM(rst_wfields(i)%vname) == field) THEN 
-          rst_wfields(i)%active = .TRUE.
-          llis_set = .TRUE.
-          EXIT
-       ENDIF
-   ENDDO
-!Warn if variable is not in defined in rst_wfields
-   IF(.NOT.llis_set) THEN
-      WRITE(ctmp1,*) 'iom_set_rstw_var_active: variable ', field ,' is available for writing but not defined' 
-      CALL ctl_stop( 'iom_set_rstw_var_active:', ctmp1 )
-   ENDIF
-#else
-        clinfo = 'iom_set_rstw_var_active: key_iomput is needed to use XIOS restart read/write functionality'
-        CALL ctl_stop('STOP', TRIM(clinfo))
-#endif
-
-   END SUBROUTINE iom_set_rstw_var_active
-
-   SUBROUTINE iom_set_rstr_active()
+      INTEGER                                    :: ndims, nvars, natts, unlimitedDimId, dimlen, xtype,mdims
+      TYPE(xios_field)                           :: field_hdl
+      TYPE(xios_file)                            :: file_hdl
+      TYPE(xios_filegroup)                       :: filegroup_hdl
+      INTEGER                                    :: dimids(4), jv,i, idim
+      CHARACTER(LEN=256)                         :: clinfo               ! info character
+      INTEGER, ALLOCATABLE                       :: indimlens(:)
+      CHARACTER(LEN=nf90_max_name), ALLOCATABLE  :: indimnames(:)
+      CHARACTER(LEN=nf90_max_name)               :: dimname, varname
+      INTEGER                                    :: iln
+      CHARACTER(LEN=lc)                          :: fname
+      LOGICAL                                    :: lmeta
+!metadata in restart file for restart read with XIOS
+      INTEGER, PARAMETER                         :: NMETA = 10
+      CHARACTER(LEN=lc)                          :: meta(NMETA)
+
+
+      meta(1) = "nav_lat"
+      meta(2) = "nav_lon"
+      meta(3) = "nav_lev"
+      meta(4) = "time_instant"
+      meta(5) = "time_instant_bounds"
+      meta(6) = "time_counter"
+      meta(7) = "time_counter_bounds"
+      meta(8) = "x"
+      meta(9) = "y"
+      meta(10) = "numcat"
+
+      clinfo = '          iom_set_vars_active, file: '//TRIM(iom_file(idnum)%name)
+
+      iln = INDEX( iom_file(idnum)%name, '.nc' )
+!XIOS doee not need .nc
+      IF(iln > 0) THEN
+        fname =  iom_file(idnum)%name(1:iln-1)
+      ELSE
+        fname =  iom_file(idnum)%name
+      ENDIF
+
+!set name of the restart file and enable available fields
+      CALL xios_get_handle("file_definition", filegroup_hdl )
+      CALL xios_add_child(filegroup_hdl, file_hdl, 'rrestart')
+      CALL xios_set_file_attr( "rrestart", name=fname, type="one_file",      &
+           par_access="collective", enabled=.TRUE., mode="read",              &
+                                                    output_freq=xios_timestep )
+
+      CALL iom_nf90_check( nf90_inquire(iom_file(idnum)%nfid, ndims, nvars, natts ), clinfo )
+      ALLOCATE(indimlens(ndims), indimnames(ndims))
+      CALL iom_nf90_check( nf90_inquire(iom_file(idnum)%nfid, unlimitedDimId = unlimitedDimId ), clinfo )
+
+      DO idim = 1, ndims
+         CALL iom_nf90_check( nf90_inquire_dimension(iom_file(idnum)%nfid, idim, dimname, dimlen ), clinfo )
+         indimlens(idim) = dimlen
+         indimnames(idim) = dimname
+      ENDDO
+
+      DO jv =1, nvars
+         lmeta = .FALSE.
+         CALL iom_nf90_check( nf90_inquire_variable(iom_file(idnum)%nfid, jv, varname, xtype, ndims, dimids, natts ), clinfo )
+         DO i = 1, NMETA
+           IF(varname == meta(i)) THEN
+             lmeta = .TRUE.
+           ENDIF
+         ENDDO
+         IF(.NOT.lmeta) THEN
+            CALL xios_add_child(file_hdl, field_hdl, varname)
+            mdims = ndims
+
+            IF(ANY(dimids(1:ndims) == unlimitedDimId)) THEN
+               mdims = mdims - 1
+            ENDIF
+
+            IF(mdims == 3) THEN
+               CALL xios_set_attr (field_hdl, enabled = .TRUE., name = varname,   &
+                                   domain_ref="grid_N",                           &
+                                   axis_ref=iom_axis(indimlens(dimids(mdims))),   &
+                                   prec = 8, operation = "instant"                )
+            ELSEIF(mdims == 2) THEN
+               CALL xios_set_attr (field_hdl, enabled = .TRUE., name = varname,  &
+                                   domain_ref="grid_N", prec = 8,                &
+                                   operation = "instant"                         ) 
+            ELSEIF(mdims == 1) THEN
+               CALL xios_set_attr (field_hdl, enabled = .TRUE., name = varname, &
+                                   axis_ref=iom_axis(indimlens(dimids(mdims))), &
+                                   prec = 8, operation = "instant"              )
+            ELSEIF(mdims == 0) THEN
+               CALL xios_set_attr (field_hdl, enabled = .TRUE., name = varname, &
+                                   scalar_ref = "grid_scalar", prec = 8,        &
+                                   operation = "instant"                        )
+            ELSE
+               WRITE(ctmp1,*) 'iom_set_vars_active: variable ', TRIM(varname) ,' incorrect number of dimensions' 
+               CALL ctl_stop( 'iom_set_vars_active:', ctmp1 )
+            ENDIF
+         ENDIF
+      ENDDO
+      DEALLOCATE(indimlens, indimnames)
+#endif
+   END SUBROUTINE iom_set_vars_active
+
+   SUBROUTINE iom_set_rstw_file(cdrst_file)
       !!---------------------------------------------------------------------
-      !!                   ***  SUBROUTINE  iom_set_rstr_active  ***
-      !!
-      !! ** Purpose :  define file name in XIOS context for reading restart file,
-      !!               enable variables present in restart file for reading with XIOS 
+      !!                   ***  SUBROUTINE iom_set_rstw_file   ***
+      !!
+      !! ** Purpose :  define file name in XIOS context for writing restart
       !!---------------------------------------------------------------------
-
-!sets enabled = .TRUE. for each field in restart file
-   CHARACTER(len=256) :: rst_file
-
+      CHARACTER(len=*) :: cdrst_file
 #if defined key_iomput
-   TYPE(xios_field) :: field_hdl
-   TYPE(xios_file) :: file_hdl
-   TYPE(xios_filegroup) :: filegroup_hdl
-   INTEGER :: i
-   CHARACTER(lc)  ::   clpath
-
-        clpath = TRIM(cn_ocerst_indir)
-        IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
-        IF( TRIM(Agrif_CFixed()) == '0' ) THEN
-           rst_file = TRIM(clpath)//TRIM(cn_ocerst_in)
-        ELSE
-           rst_file = TRIM(clpath)//TRIM(Agrif_CFixed())//'_'//TRIM(cn_ocerst_in)
-        ENDIF
+      TYPE(xios_file) :: file_hdl
+      TYPE(xios_filegroup) :: filegroup_hdl
+
 !set name of the restart file and enable available fields
-        if(lwp) WRITE(numout,*) 'Setting restart filename (for XIOS) to: ',rst_file
-        CALL xios_get_handle("file_definition", filegroup_hdl )
-        CALL xios_add_child(filegroup_hdl, file_hdl, 'rrestart')
-        CALL xios_set_file_attr( "rrestart", name=trim(rst_file), type="one_file", &
-             par_access="collective", enabled=.TRUE., mode="read",                 &
-             output_freq=xios_timestep)
-!define variables for restart context
-        DO i = 1, max_rst_fields
-         IF( TRIM(rst_rfields(i)%vname) /= "NO_NAME") THEN
-           IF( iom_varid( numror, TRIM(rst_rfields(i)%vname), ldstop = .FALSE. ) > 0 ) THEN
-                CALL xios_add_child(file_hdl, field_hdl, TRIM(rst_rfields(i)%vname))
-                SELECT CASE (TRIM(rst_rfields(i)%grid))
-                 CASE ("grid_N_3D")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
-                        domain_ref="grid_N", axis_ref="nav_lev", operation = "instant")
-                 CASE ("grid_N")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
-                        domain_ref="grid_N", operation = "instant") 
-                CASE ("grid_vector")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
-                         axis_ref="nav_lev", operation = "instant")
-                 CASE ("grid_scalar")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
-                        scalar_ref = "grid_scalar", operation = "instant")
-                END SELECT
-                IF(lwp) WRITE(numout,*) 'XIOS read: ', TRIM(rst_rfields(i)%vname), ' enabled in ', TRIM(rst_file)
-           ENDIF
-         ENDIF
-        END DO
-#endif
-   END SUBROUTINE iom_set_rstr_active
-
-   SUBROUTINE iom_set_rstw_core(cdmdl)
-      !!---------------------------------------------------------------------
-      !!                   ***  SUBROUTINE  iom_set_rstw_core  ***
-      !!
-      !! ** Purpose :  set variables which are always in restart file 
-      !!---------------------------------------------------------------------
-   CHARACTER (len=*), INTENT (IN) :: cdmdl ! model OPA or SAS
-   CHARACTER(LEN=256)             :: clinfo    ! info character
-#if defined key_iomput
-   IF(cdmdl == "OPA") THEN
-!from restart.F90
-   CALL iom_set_rstw_var_active("rn_Dt")
-   IF ( .NOT. ln_diurnal_only ) THEN
-        CALL iom_set_rstw_var_active('ub'  )
-        CALL iom_set_rstw_var_active('vb'  )
-        CALL iom_set_rstw_var_active('tb'  )
-        CALL iom_set_rstw_var_active('sb'  )
-        CALL iom_set_rstw_var_active('sshb')
-        !
-        CALL iom_set_rstw_var_active('un'  )
-        CALL iom_set_rstw_var_active('vn'  )
-        CALL iom_set_rstw_var_active('tn'  )
-        CALL iom_set_rstw_var_active('sn'  )
-        CALL iom_set_rstw_var_active('sshn')
-        CALL iom_set_rstw_var_active('rhop')
-      ENDIF
-      IF(ln_diurnal) CALL iom_set_rstw_var_active('Dsst')
-!from trasbc.F90
-         CALL iom_set_rstw_var_active('sbc_hc_b')
-         CALL iom_set_rstw_var_active('sbc_sc_b')
-   ENDIF
-#else
-        clinfo = 'iom_set_rstw_core: key_iomput is needed to use XIOS restart read/write functionality'
-        CALL ctl_stop('STOP', TRIM(clinfo))
-#endif
-   END SUBROUTINE iom_set_rstw_core
-
-   SUBROUTINE iom_set_rst_vars(fields)
-      !!---------------------------------------------------------------------
-      !!                   ***  SUBROUTINE iom_set_rst_vars   ***
-      !!
-      !! ** Purpose :  Fill array fields with the information about all 
-      !!               possible variables and corresponding grids definition 
-      !!               for reading/writing restart with XIOS
-      !!---------------------------------------------------------------------
-   TYPE(RST_FIELD), INTENT(INOUT) :: fields(max_rst_fields)
-   INTEGER :: i
-
-        i = 0
-        i = i + 1; fields(i)%vname="rn_Dt";            fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="un";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="ub";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="vn";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="vb";             fields(i)%grid="grid_N_3D"  
-        i = i + 1; fields(i)%vname="tn";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="tb";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="sn";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="sb";             fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="sshn";           fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sshb";           fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="rhop";           fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="kt";             fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="ndastp";         fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="adatrj";         fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="utau_b";         fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="vtau_b";         fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="qns_b";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="emp_b";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sfx_b";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="en" ;            fields(i)%grid="grid_N_3D" 
-        i = i + 1; fields(i)%vname="avt_k";            fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="avm_k";            fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="dissl";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="sbc_hc_b";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sbc_sc_b";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="qsr_hc_b";       fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="fraqsr_1lev";    fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="greenland_icesheet_mass"
-                                               fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="greenland_icesheet_timelapsed"
-                                               fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="greenland_icesheet_mass_roc"
-                                               fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="antarctica_icesheet_mass"
-                                               fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="antarctica_icesheet_timelapsed"
-                                               fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="antarctica_icesheet_mass_roc"
-                                               fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="frc_v";          fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="frc_t";          fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="frc_s";          fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="frc_wn_t";       fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="frc_wn_s";       fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="ssh_ini";        fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="e3t_ini";        fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="hc_loc_ini";     fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="sc_loc_ini";     fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="ssh_hc_loc_ini"; fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ssh_sc_loc_ini"; fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="tilde_e3t_b";    fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="tilde_e3t_n";    fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="hdiv_lf";        fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ub2_b";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="vb2_b";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sshbb_e";        fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ubb_e";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="vbb_e";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sshb_e";         fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ub_e";           fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="vb_e";           fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="fwf_isf_b";      fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="isf_sc_b";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="isf_hc_b";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ssh_ibb";        fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="rnf_b";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="rnf_hc_b";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="rnf_sc_b";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="nn_fsbc";        fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="ssu_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ssv_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sst_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="sss_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ssh_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="e3t_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="frq_m";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="avmb";           fields(i)%grid="grid_vector"
-        i = i + 1; fields(i)%vname="avtb";           fields(i)%grid="grid_vector"
-        i = i + 1; fields(i)%vname="ub2_i_b";        fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="vb2_i_b";        fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="ntime";          fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="Dsst";           fields(i)%grid="grid_scalar"
-        i = i + 1; fields(i)%vname="tmask";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="umask";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="vmask";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="smask";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="gdepw_n";        fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="e3t_n";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="e3u_n";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="e3v_n";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="surf_ini";       fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="e3t_b";          fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="hmxl_n";         fields(i)%grid="grid_N_3D"
-        i = i + 1; fields(i)%vname="un_bf";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="vn_bf";          fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="hbl";            fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="hbli";           fields(i)%grid="grid_N"
-        i = i + 1; fields(i)%vname="wn";             fields(i)%grid="grid_N_3D"
-
-        IF( i-1 > max_rst_fields) THEN
-           WRITE(ctmp1,*) 'E R R O R : iom_set_rst_vars SIZE of RST_FIELD array is too small'
-           CALL ctl_stop( 'iom_set_rst_vars:', ctmp1 )
-        ENDIF
-   END SUBROUTINE iom_set_rst_vars
-
-
-   SUBROUTINE iom_set_rstw_active(cdrst_file)
+      IF(lwp) WRITE(numout,*) 'Setting restart filename (for XIOS write) to: ', TRIM(cdrst_file)
+      CALL xios_get_handle("file_definition", filegroup_hdl )
+      CALL xios_add_child(filegroup_hdl, file_hdl, 'wrestart')
+      IF(nxioso.eq.1) THEN 
+         CALL xios_set_file_attr( "wrestart", type="one_file", enabled=.TRUE.,& 
+                                       mode="write", output_freq=xios_timestep) 
+         IF(lwp) write(numout,*) 'OPEN ', trim(cdrst_file), ' in one_file mode' 
+      ELSE  
+         CALL xios_set_file_attr( "wrestart", type="multiple_file", enabled=.TRUE.,& 
+                                            mode="write", output_freq=xios_timestep) 
+         IF(lwp) write(numout,*) 'OPEN ', trim(cdrst_file), ' in multiple_file mode' 
+      ENDIF 
+      CALL xios_set_file_attr( "wrestart", name=trim(cdrst_file))
+#endif
+   END SUBROUTINE iom_set_rstw_file
+
+
+   SUBROUTINE iom_set_rstw_active(sdfield, rd0, rs0, rd1, rs1, rd2, rs2, rd3, rs3)
       !!---------------------------------------------------------------------
       !!                   ***  SUBROUTINE iom_set_rstw_active   ***
@@ -553,51 +474,110 @@
       !!---------------------------------------------------------------------
 !sets enabled = .TRUE. for each field in restart file
-   CHARACTER(len=*) :: cdrst_file
+      CHARACTER(len = *), INTENT(IN)                     :: sdfield
+      REAL(dp), OPTIONAL, INTENT(IN)                     :: rd0
+      REAL(sp), OPTIONAL, INTENT(IN)                     :: rs0
+      REAL(dp), OPTIONAL, INTENT(IN), DIMENSION(:)       :: rd1
+      REAL(sp), OPTIONAL, INTENT(IN), DIMENSION(:)       :: rs1
+      REAL(dp), OPTIONAL, INTENT(IN), DIMENSION(:, :)    :: rd2
+      REAL(sp), OPTIONAL, INTENT(IN), DIMENSION(:, :)    :: rs2
+      REAL(dp), OPTIONAL, INTENT(IN), DIMENSION(:, :, :) :: rd3  
+      REAL(sp), OPTIONAL, INTENT(IN), DIMENSION(:, :, :) :: rs3
 #if defined key_iomput
-   TYPE(xios_field) :: field_hdl
-   TYPE(xios_file) :: file_hdl
-   TYPE(xios_filegroup) :: filegroup_hdl
-   INTEGER :: i
-   CHARACTER(lc)  ::   clpath
-
-!set name of the restart file and enable available fields
-        IF(lwp) WRITE(numout,*) 'Setting restart filename (for XIOS write) to: ',cdrst_file
-        CALL xios_get_handle("file_definition", filegroup_hdl )
-        CALL xios_add_child(filegroup_hdl, file_hdl, 'wrestart')
-        IF(nxioso.eq.1) THEN 
-           CALL xios_set_file_attr( "wrestart", type="one_file", enabled=.TRUE.,& 
-                                    mode="write", output_freq=xios_timestep) 
-           if(lwp) write(numout,*) 'OPEN ', trim(cdrst_file), ' in one_file mode' 
-        ELSE  
-           CALL xios_set_file_attr( "wrestart", type="multiple_file", enabled=.TRUE.,& 
-                                    mode="write", output_freq=xios_timestep) 
-           if(lwp) write(numout,*) 'OPEN ', trim(cdrst_file), ' in multiple_file mode' 
-        ENDIF 
-        CALL xios_set_file_attr( "wrestart", name=trim(cdrst_file))
+      TYPE(xios_field) :: field_hdl
+      TYPE(xios_file) :: file_hdl
+
+      CALL xios_get_handle("wrestart", file_hdl)
 !define fields for restart context
-        DO i = 1, max_rst_fields
-         IF( rst_wfields(i)%active ) THEN
-                CALL xios_add_child(file_hdl, field_hdl, TRIM(rst_wfields(i)%vname))
-                SELECT CASE (TRIM(rst_wfields(i)%grid))
-                 CASE ("grid_N_3D")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
-                        domain_ref="grid_N", axis_ref="nav_lev", prec = 8, operation = "instant")
-                 CASE ("grid_N")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
-                        domain_ref="grid_N", prec = 8, operation = "instant") 
-                 CASE ("grid_vector")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
-                         axis_ref="nav_lev", prec = 8, operation = "instant")
-                 CASE ("grid_scalar")
-                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
-                        scalar_ref = "grid_scalar", prec = 8, operation = "instant")
-                END SELECT
-         ENDIF
-        END DO
+      CALL xios_add_child(file_hdl, field_hdl, sdfield)
+
+      IF(PRESENT(rd3)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             domain_ref = "grid_N",                       &
+                             axis_ref = iom_axis(size(rd3, 3)),           &
+                             prec = 8, operation = "instant"              )
+      ELSEIF(PRESENT(rs3)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             domain_ref = "grid_N",                       &
+                             axis_ref = iom_axis(size(rd3, 3)),           &
+                             prec = 4, operation = "instant"              )
+      ELSEIF(PRESENT(rd2)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             domain_ref = "grid_N", prec = 8,             &
+                             operation = "instant"                        ) 
+      ELSEIF(PRESENT(rs2)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             domain_ref = "grid_N", prec = 4,             &
+                             operation = "instant"                        )
+      ELSEIF(PRESENT(rd1)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             axis_ref = iom_axis(size(rd1, 1)),           &
+                             prec = 8, operation = "instant"              )
+      ELSEIF(PRESENT(rs1)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             axis_ref = iom_axis(size(rd1, 1)),           &
+                             prec = 4, operation = "instant"              )
+      ELSEIF(PRESENT(rd0)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             scalar_ref = "grid_scalar", prec = 8,        &
+                             operation = "instant"                        )
+      ELSEIF(PRESENT(rs0)) THEN
+         CALL xios_set_attr (field_hdl, enabled = .TRUE., name = sdfield, &
+                             scalar_ref = "grid_scalar", prec = 4,        &
+                             operation = "instant"                        )
+      ENDIF
 #endif
    END SUBROUTINE iom_set_rstw_active
 
+   FUNCTION iom_axis(idlev) result(axis_ref)
+      !!---------------------------------------------------------------------
+      !!                   ***  FUNCTION  iom_axis  ***
+      !!
+      !! ** Purpose : Used for grid definition when XIOS is used to read/write
+      !!              restart. Returns axis corresponding to the number of levels
+      !!              given as an input variable. Axes are defined in routine 
+      !!              iom_set_rst_context
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(IN) :: idlev
+      CHARACTER(len=lc)   :: axis_ref
+      CHARACTER(len=12)   :: str
+      IF(idlev == jpk) THEN
+         axis_ref="nav_lev"
+#if defined key_si3
+      ELSEIF(idlev == jpl) THEN
+         axis_ref="numcat"
+#endif         
+      ELSE
+         write(str, *) idlev
+         CALL ctl_stop( 'iom_axis', 'Definition for axis with '//TRIM(ADJUSTL(str))//' levels missing')
+      ENDIF
+   END FUNCTION iom_axis
+
+   FUNCTION iom_xios_setid(cdname) result(kid)
+     !!---------------------------------------------------------------------
+      !!                   ***  FUNCTION    ***
+      !!
+      !! ** Purpose : this function returns first available id to keep information about file 
+      !!              sets filename in iom_file structure and sets name
+      !!              of XIOS context depending on cdcomp
+      !!              corresponds to iom_nf90_open
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   ) :: cdname      ! File name
+      INTEGER                         :: kid      ! identifier of the opened file
+      INTEGER                         :: jl
+
+      kid = 0
+      DO jl = jpmax_files, 1, -1
+         IF( iom_file(jl)%nfid == 0 )   kid = jl
+      ENDDO
+
+      iom_file(kid)%name   = TRIM(cdname)
+      iom_file(kid)%nfid   = 1
+      iom_file(kid)%nvars  = 0
+      iom_file(kid)%irec   = -1
+
+   END FUNCTION iom_xios_setid
+
    SUBROUTINE iom_set_rst_context(ld_rstr) 
-     !!---------------------------------------------------------------------
+      !!---------------------------------------------------------------------
       !!                   ***  SUBROUTINE  iom_set_rst_context  ***
       !!
@@ -606,30 +586,71 @@
       !!               
       !!---------------------------------------------------------------------
-   LOGICAL, INTENT(IN)               :: ld_rstr
-!ld_rstr is true for restart context. There is no need to define grid for 
-!restart read, because it's read from file
+      LOGICAL, INTENT(IN)               :: ld_rstr
+      INTEGER :: ji
 #if defined key_iomput
-   TYPE(xios_domaingroup)            :: domaingroup_hdl 
-   TYPE(xios_domain)                 :: domain_hdl 
-   TYPE(xios_axisgroup)              :: axisgroup_hdl 
-   TYPE(xios_axis)                   :: axis_hdl 
-   TYPE(xios_scalar)                 :: scalar_hdl 
-   TYPE(xios_scalargroup)            :: scalargroup_hdl 
-
-     CALL xios_get_handle("domain_definition",domaingroup_hdl) 
-     CALL xios_add_child(domaingroup_hdl, domain_hdl, "grid_N") 
-     CALL set_grid("N", glamt, gphit, .TRUE., ld_rstr) 
+      TYPE(xios_domaingroup)            :: domaingroup_hdl 
+      TYPE(xios_domain)                 :: domain_hdl 
+      TYPE(xios_axisgroup)              :: axisgroup_hdl 
+      TYPE(xios_axis)                   :: axis_hdl 
+      TYPE(xios_scalar)                 :: scalar_hdl 
+      TYPE(xios_scalargroup)            :: scalargroup_hdl 
+
+      CALL xios_get_handle("domain_definition",domaingroup_hdl) 
+      CALL xios_add_child(domaingroup_hdl, domain_hdl, "grid_N") 
+      CALL set_grid("N", glamt, gphit, .TRUE., ld_rstr) 
  
-     CALL xios_get_handle("axis_definition",axisgroup_hdl) 
-     CALL xios_add_child(axisgroup_hdl, axis_hdl, "nav_lev") 
+      CALL xios_get_handle("axis_definition",axisgroup_hdl) 
+      CALL xios_add_child(axisgroup_hdl, axis_hdl, "nav_lev") 
 !AGRIF fails to compile when unit= is in call to xios_set_axis_attr
-!    CALL xios_set_axis_attr( "nav_lev", long_name="Vertical levels",  unit="m", positive="down") 
-     CALL xios_set_axis_attr( "nav_lev", long_name="Vertical levels in meters", positive="down")
-     CALL iom_set_axis_attr( "nav_lev", paxis = gdept_1d ) 
-
-     CALL xios_get_handle("scalar_definition", scalargroup_hdl) 
-     CALL xios_add_child(scalargroup_hdl, scalar_hdl, "grid_scalar") 
+!     CALL xios_set_axis_attr( "nav_lev", long_name="Vertical levels",  unit="m", positive="down") 
+      CALL xios_set_axis_attr( "nav_lev", long_name = "Vertical levels in meters", positive = "down")
+      CALL iom_set_axis_attr( "nav_lev", paxis = gdept_1d ) 
+#if defined key_si3
+      CALL xios_add_child(axisgroup_hdl, axis_hdl, "numcat")
+      CALL iom_set_axis_attr( "numcat", (/ (REAL(ji,wp), ji=1,jpl) /) )
+#endif
+      CALL xios_get_handle("scalar_definition", scalargroup_hdl) 
+      CALL xios_add_child(scalargroup_hdl, scalar_hdl, "grid_scalar") 
 #endif
    END SUBROUTINE iom_set_rst_context
+
+
+   SUBROUTINE set_xios_context(kdid, cdcont) 
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_set_rst_context  ***
+      !!
+      !! ** Purpose : set correct XIOS context based on kdid
+      !!               
+      !!---------------------------------------------------------------------
+      INTEGER,           INTENT(IN)     :: kdid           ! Identifier of the file
+      CHARACTER(LEN=lc), INTENT(OUT)    :: cdcont         ! name of the context for XIOS read/write
+      
+      cdcont = "NONE"
+
+      IF(lrxios) THEN
+         IF(kdid == numror) THEN
+            cdcont = cr_ocerst_cxt
+         ELSEIF(kdid == numrir) THEN
+            cdcont = cr_icerst_cxt 
+         ELSEIF(kdid == numrtr) THEN
+            cdcont = cr_toprst_cxt
+         ELSEIF(kdid == numrsr) THEN
+            cdcont = cr_sedrst_cxt
+         ENDIF
+      ENDIF
+
+      IF(lwxios) THEN
+         IF(kdid == numrow) THEN
+            cdcont = cw_ocerst_cxt
+         ELSEIF(kdid == numriw) THEN
+            cdcont = cw_icerst_cxt
+         ELSEIF(kdid == numrtw) THEN
+            cdcont = cw_toprst_cxt
+         ELSEIF(kdid == numrsw) THEN
+            cdcont = cw_sedrst_cxt
+         ENDIF
+      ENDIF
+   END SUBROUTINE set_xios_context
+
 
    SUBROUTINE iom_swap( cdname )
@@ -642,5 +663,4 @@
 #if defined key_iomput
       TYPE(xios_context) :: nemo_hdl
-
       IF( TRIM(Agrif_CFixed()) == '0' ) THEN
         CALL xios_get_handle(TRIM(cdname),nemo_hdl)
@@ -892,5 +912,5 @@
    !!                   INTERFACE iom_get
    !!----------------------------------------------------------------------
-   SUBROUTINE iom_g0d_sp( kiomid, cdvar, pvar, ktime, ldxios )
+   SUBROUTINE iom_g0d_sp( kiomid, cdvar, pvar, ktime )
       INTEGER         , INTENT(in   )                 ::   kiomid    ! Identifier of the file
       CHARACTER(len=*), INTENT(in   )                 ::   cdvar     ! Name of the variable
@@ -898,5 +918,4 @@
       REAL(dp)                                        ::   ztmp_pvar ! tmp var to read field
       INTEGER         , INTENT(in   ),     OPTIONAL   ::   ktime     ! record number
-      LOGICAL         , INTENT(in   ),     OPTIONAL   ::   ldxios    ! use xios to read restart
       !
       INTEGER                                         ::   idvar     ! variable id
@@ -906,10 +925,9 @@
       CHARACTER(LEN=100)                              ::   clname    ! file name
       CHARACTER(LEN=1)                                ::   cldmspc   !
-      LOGICAL                                         ::   llxios
-      !
-      llxios = .FALSE.
-      IF( PRESENT(ldxios) ) llxios = ldxios
-
-      IF(.NOT.llxios) THEN  ! read data using default library
+      CHARACTER(LEN=lc)                               ::   context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      IF(context == "NONE") THEN  ! read data using default library
          itime = 1
          IF( PRESENT(ktime) ) itime = ktime
@@ -934,7 +952,7 @@
 #if defined key_iomput
          IF(lwp) WRITE(numout,*) 'XIOS RST READ (0D): ', trim(cdvar)
-         CALL iom_swap( TRIM(crxios_context) )
+         CALL iom_swap(context)
          CALL xios_recv_field( trim(cdvar), pvar)
-         CALL iom_swap( TRIM(cxios_context) )
+         CALL iom_swap(cxios_context)
 #else
          WRITE(ctmp1,*) 'Can not use XIOS in iom_g0d, file: '//trim(clname)//', var:'//trim(cdvar)
@@ -944,10 +962,9 @@
    END SUBROUTINE iom_g0d_sp
 
-   SUBROUTINE iom_g0d_dp( kiomid, cdvar, pvar, ktime, ldxios )
+   SUBROUTINE iom_g0d_dp( kiomid, cdvar, pvar, ktime )
       INTEGER         , INTENT(in   )                 ::   kiomid    ! Identifier of the file
       CHARACTER(len=*), INTENT(in   )                 ::   cdvar     ! Name of the variable
       REAL(dp)        , INTENT(  out)                 ::   pvar      ! read field
       INTEGER         , INTENT(in   ),     OPTIONAL   ::   ktime     ! record number
-      LOGICAL         , INTENT(in   ),     OPTIONAL   ::   ldxios    ! use xios to read restart
       !
       INTEGER                                         ::   idvar     ! variable id
@@ -957,10 +974,9 @@
       CHARACTER(LEN=100)                              ::   clname    ! file name
       CHARACTER(LEN=1)                                ::   cldmspc   !
-      LOGICAL                                         ::   llxios
-      !
-      llxios = .FALSE.
-      IF( PRESENT(ldxios) ) llxios = ldxios
-
-      IF(.NOT.llxios) THEN  ! read data using default library
+      CHARACTER(LEN=lc)                               ::   context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      IF(context == "NONE") THEN  ! read data using default library
          itime = 1
          IF( PRESENT(ktime) ) itime = ktime
@@ -984,7 +1000,7 @@
 #if defined key_iomput
          IF(lwp) WRITE(numout,*) 'XIOS RST READ (0D): ', trim(cdvar)
-         CALL iom_swap( TRIM(crxios_context) )
+         CALL iom_swap(context)
          CALL xios_recv_field( trim(cdvar), pvar)
-         CALL iom_swap( TRIM(cxios_context) )
+         CALL iom_swap(cxios_context)
 #else
          WRITE(ctmp1,*) 'Can not use XIOS in iom_g0d, file: '//trim(clname)//', var:'//trim(cdvar)
@@ -994,5 +1010,5 @@
    END SUBROUTINE iom_g0d_dp
 
-   SUBROUTINE iom_g1d_sp( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount, ldxios )
+   SUBROUTINE iom_g1d_sp( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount )
       INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
       INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
@@ -1003,5 +1019,4 @@
       INTEGER         , INTENT(in   ), DIMENSION(1), OPTIONAL ::   kstart    ! start axis position of the reading 
       INTEGER         , INTENT(in   ), DIMENSION(1), OPTIONAL ::   kcount    ! number of points in each axis
-      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
       !
       IF( kiomid > 0 ) THEN
@@ -1009,6 +1024,5 @@
             ALLOCATE(ztmp_pvar(size(pvar,1)))
             CALL iom_get_123d( kiomid, kdom       , cdvar        , pv_r1d=ztmp_pvar,   &
-              &                                                     ktime=ktime, kstart=kstart, kcount=kcount, &
-              &                                                     ldxios=ldxios )
+              &                                                     ktime=ktime, kstart=kstart, kcount=kcount )
             pvar = ztmp_pvar
             DEALLOCATE(ztmp_pvar)
@@ -1018,5 +1032,5 @@
 
 
-   SUBROUTINE iom_g1d_dp( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount, ldxios )
+   SUBROUTINE iom_g1d_dp( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount )
       INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
       INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
@@ -1026,14 +1040,12 @@
       INTEGER         , INTENT(in   ), DIMENSION(1), OPTIONAL ::   kstart    ! start axis position of the reading 
       INTEGER         , INTENT(in   ), DIMENSION(1), OPTIONAL ::   kcount    ! number of points in each axis
-      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
       !
       IF( kiomid > 0 ) THEN
          IF( iom_file(kiomid)%nfid > 0 ) CALL iom_get_123d( kiomid, kdom       , cdvar        , pv_r1d=pvar,   &
-              &                                                     ktime=ktime, kstart=kstart, kcount=kcount, &
-              &                                                     ldxios=ldxios )
+              &                                                     ktime=ktime, kstart=kstart, kcount=kcount)
       ENDIF
    END SUBROUTINE iom_g1d_dp
 
-   SUBROUTINE iom_g2d_sp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount, ldxios)
+   SUBROUTINE iom_g2d_sp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount)
       INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
       INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
@@ -1047,5 +1059,4 @@
       INTEGER         , INTENT(in   ), DIMENSION(2), OPTIONAL ::   kstart    ! start axis position of the reading 
       INTEGER         , INTENT(in   ), DIMENSION(2), OPTIONAL ::   kcount    ! number of points in each axis
-      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
       !
       IF( kiomid > 0 ) THEN
@@ -1054,5 +1065,5 @@
             CALL iom_get_123d( kiomid, kdom, cdvar      , pv_r2d = ztmp_pvar  , ktime = ktime,   &
              &                                                      cd_type = cd_type, psgn   = psgn  , kfill = kfill,   &
-             &                                                      kstart  = kstart , kcount = kcount, ldxios=ldxios  )
+             &                                                      kstart  = kstart , kcount = kcount  )
             pvar = ztmp_pvar
             DEALLOCATE(ztmp_pvar)
@@ -1061,5 +1072,5 @@
    END SUBROUTINE iom_g2d_sp
 
-   SUBROUTINE iom_g2d_dp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount, ldxios)
+   SUBROUTINE iom_g2d_dp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount)
       INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
       INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
@@ -1072,14 +1083,13 @@
       INTEGER         , INTENT(in   ), DIMENSION(2), OPTIONAL ::   kstart    ! start axis position of the reading 
       INTEGER         , INTENT(in   ), DIMENSION(2), OPTIONAL ::   kcount    ! number of points in each axis
-      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
       !
       IF( kiomid > 0 ) THEN
          IF( iom_file(kiomid)%nfid > 0 ) CALL iom_get_123d( kiomid, kdom, cdvar      , pv_r2d = pvar  , ktime = ktime,   &
             &                                                       cd_type = cd_type, psgn   = psgn  , kfill = kfill,   &
-            &                                                       kstart  = kstart , kcount = kcount, ldxios=ldxios  )
+            &                                                       kstart  = kstart , kcount = kcount                )
       ENDIF
    END SUBROUTINE iom_g2d_dp
 
-   SUBROUTINE iom_g3d_sp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount, ldxios )
+   SUBROUTINE iom_g3d_sp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount )
       INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
       INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
@@ -1093,5 +1103,4 @@
       INTEGER         , INTENT(in   ), DIMENSION(3), OPTIONAL ::   kstart    ! start axis position of the reading 
       INTEGER         , INTENT(in   ), DIMENSION(3), OPTIONAL ::   kcount    ! number of points in each axis
-      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
       !
       IF( kiomid > 0 ) THEN
@@ -1100,5 +1109,5 @@
             CALL iom_get_123d( kiomid, kdom, cdvar      , pv_r3d = ztmp_pvar  , ktime = ktime,   &
             &                                                       cd_type = cd_type, psgn   = psgn  , kfill = kfill,   &
-            &                                                       kstart  = kstart , kcount = kcount, ldxios=ldxios  )
+            &                                                       kstart  = kstart , kcount = kcount                )
             pvar = ztmp_pvar
             DEALLOCATE(ztmp_pvar)
@@ -1107,5 +1116,5 @@
    END SUBROUTINE iom_g3d_sp
 
-   SUBROUTINE iom_g3d_dp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount, ldxios )
+   SUBROUTINE iom_g3d_dp( kiomid, kdom, cdvar, pvar, ktime, cd_type, psgn, kfill, kstart, kcount )
       INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
       INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
@@ -1118,5 +1127,4 @@
       INTEGER         , INTENT(in   ), DIMENSION(3), OPTIONAL ::   kstart    ! start axis position of the reading 
       INTEGER         , INTENT(in   ), DIMENSION(3), OPTIONAL ::   kcount    ! number of points in each axis
-      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
       !
       IF( kiomid > 0 ) THEN
@@ -1124,5 +1132,5 @@
             CALL iom_get_123d( kiomid, kdom, cdvar      , pv_r3d = pvar  , ktime = ktime,   &
             &                                                       cd_type = cd_type, psgn   = psgn  , kfill = kfill,   &
-            &                                                       kstart  = kstart , kcount = kcount, ldxios=ldxios  )
+            &                                                       kstart  = kstart , kcount = kcount                )
          END IF
       ENDIF
@@ -1132,5 +1140,5 @@
 
    SUBROUTINE iom_get_123d( kiomid , kdom, cdvar, pv_r1d, pv_r2d, pv_r3d, ktime ,   &
-         &                  cd_type, psgn, kfill, kstart, kcount, ldxios )
+         &                  cd_type, psgn, kfill, kstart, kcount )
       !!-----------------------------------------------------------------------
       !!                  ***  ROUTINE  iom_get_123d  ***
@@ -1152,8 +1160,6 @@
       INTEGER , DIMENSION(:)     , INTENT(in   ), OPTIONAL ::   kstart    ! start position of the reading in each axis 
       INTEGER , DIMENSION(:)     , INTENT(in   ), OPTIONAL ::   kcount    ! number of points to be read in each axis
-      LOGICAL                    , INTENT(in   ), OPTIONAL ::   ldxios    ! use XIOS to read restart
       !
       LOGICAL                        ::   llok        ! true if ok!
-      LOGICAL                        ::   llxios      ! local definition for XIOS read
       INTEGER                        ::   jl          ! loop on number of dimension 
       INTEGER                        ::   idom        ! type of domain
@@ -1182,15 +1188,14 @@
       REAL(dp)                       ::   gma, gmi
       !---------------------------------------------------------------------
-      !
+      CHARACTER(LEN=lc)                               ::   context
+      !
+      CALL set_xios_context(kiomid, context)
       inlev = -1
       IF( PRESENT(pv_r3d) )   inlev = SIZE(pv_r3d, 3)
       !
-      llxios = .FALSE.
-      IF( PRESENT(ldxios) )   llxios = ldxios
-      !
       idom = kdom
       istop = nstop
       !
-      IF(.NOT.llxios) THEN
+      IF(context == "NONE") THEN
          clname = iom_file(kiomid)%name   !   esier to read
          clinfo = '          iom_get_123d, file: '//trim(clname)//', var: '//trim(cdvar)
@@ -1359,18 +1364,28 @@
 #if defined key_iomput
 !would be good to be able to check which context is active and swap only if current is not restart
-         CALL iom_swap( TRIM(crxios_context) ) 
+         idvar = iom_varid( kiomid, cdvar )
+         CALL iom_swap(context)
+         zsgn = 1._wp
+         IF( PRESENT(psgn   ) )   zsgn    = psgn
+         cl_type = 'T'
+         IF( PRESENT(cd_type) )   cl_type = cd_type
+
          IF( PRESENT(pv_r3d) ) THEN
             IF(lwp) WRITE(numout,*) 'XIOS RST READ (3D): ',TRIM(cdvar)
-            CALL xios_recv_field( trim(cdvar), pv_r3d)
-            IF(idom /= jpdom_unknown )   CALL lbc_lnk( 'iom', pv_r3d,'Z', -999., kfillmode = jpfillnothing)
+            CALL xios_recv_field( trim(cdvar), pv_r3d(:, :, :))
+            IF(idom /= jpdom_unknown .AND. cl_type /= 'Z' ) THEN
+               CALL lbc_lnk( 'iom', pv_r3d, cl_type, zsgn, kfillmode = kfill)
+            ENDIF
          ELSEIF( PRESENT(pv_r2d) ) THEN
             IF(lwp) WRITE(numout,*) 'XIOS RST READ (2D): ', TRIM(cdvar)
-            CALL xios_recv_field( trim(cdvar), pv_r2d)
-            IF(idom /= jpdom_unknown )   CALL lbc_lnk('iom', pv_r2d,'Z',-999., kfillmode = jpfillnothing)
+            CALL xios_recv_field( trim(cdvar), pv_r2d(:, :))
+            IF(idom /= jpdom_unknown .AND. cl_type /= 'Z' ) THEN
+               CALL lbc_lnk('iom', pv_r2d, cl_type, zsgn, kfillmode = kfill)
+            ENDIF
          ELSEIF( PRESENT(pv_r1d) ) THEN
             IF(lwp) WRITE(numout,*) 'XIOS RST READ (1D): ', TRIM(cdvar)
             CALL xios_recv_field( trim(cdvar), pv_r1d)
          ENDIF
-         CALL iom_swap( TRIM(cxios_context) )
+         CALL iom_swap(cxios_context)
 #else
          istop = istop + 1 
@@ -1387,12 +1402,12 @@
       zofs = iom_file(kiomid)%ofs(idvar)      ! offset
       IF(     PRESENT(pv_r1d) ) THEN
-         IF( zscf /= 1. )   pv_r1d(:) = pv_r1d(:) * zscf 
-         IF( zofs /= 0. )   pv_r1d(:) = pv_r1d(:) + zofs
+         IF( zscf /= 1._wp )   pv_r1d(:) = pv_r1d(:) * zscf 
+         IF( zofs /= 0._wp )   pv_r1d(:) = pv_r1d(:) + zofs
       ELSEIF( PRESENT(pv_r2d) ) THEN
-         IF( zscf /= 1.)   pv_r2d(:,:) = pv_r2d(:,:) * zscf
-         IF( zofs /= 0.)   pv_r2d(:,:) = pv_r2d(:,:) + zofs
+         IF( zscf /= 1._wp)   pv_r2d(:,:) = pv_r2d(:,:) * zscf
+         IF( zofs /= 0._wp)   pv_r2d(:,:) = pv_r2d(:,:) + zofs
       ELSEIF( PRESENT(pv_r3d) ) THEN
-         IF( zscf /= 1.)   pv_r3d(:,:,:) = pv_r3d(:,:,:) * zscf
-         IF( zofs /= 0.)   pv_r3d(:,:,:) = pv_r3d(:,:,:) + zofs
+         IF( zscf /= 1._wp)   pv_r3d(:,:,:) = pv_r3d(:,:,:) * zscf
+         IF( zofs /= 0._wp)   pv_r3d(:,:,:) = pv_r3d(:,:,:) + zofs
       ENDIF
       !
@@ -1568,5 +1583,5 @@
    !!                   INTERFACE iom_rstput
    !!----------------------------------------------------------------------
-   SUBROUTINE iom_rp0d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp0d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1575,16 +1590,26 @@
       REAL(sp)        , INTENT(in)                         ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
-      LOGICAL :: llx                ! local xios write flag
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx                ! local xios write flag
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-          IF(lwp) write(numout,*) 'RESTART: write (XIOS 0D) ',trim(cdvar)
-          CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 0D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 0D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rs0 = pvar ) 
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1598,5 +1623,5 @@
    END SUBROUTINE iom_rp0d_sp
 
-   SUBROUTINE iom_rp0d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp0d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1605,16 +1630,26 @@
       REAL(dp)        , INTENT(in)                         ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
-      LOGICAL :: llx                ! local xios write flag
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx                ! local xios write flag
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-          IF(lwp) write(numout,*) 'RESTART: write (XIOS 0D) ',trim(cdvar)
-          CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 0D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 0D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rd0 = pvar ) 
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1629,5 +1664,5 @@
 
 
-   SUBROUTINE iom_rp1d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp1d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1636,16 +1671,26 @@
       REAL(sp)        , INTENT(in), DIMENSION(          :) ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL                                    ::   ldxios   ! xios write flag
-      LOGICAL :: llx                ! local xios write flag
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx                ! local xios write flag
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-         IF(lwp) write(numout,*) 'RESTART: write (XIOS 1D) ',trim(cdvar)
-         CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 1D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 1D)',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rs1 = pvar )
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1659,5 +1704,5 @@
    END SUBROUTINE iom_rp1d_sp
 
-   SUBROUTINE iom_rp1d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp1d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1666,16 +1711,26 @@
       REAL(dp)        , INTENT(in), DIMENSION(          :) ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL                                    ::   ldxios   ! xios write flag
-      LOGICAL :: llx                ! local xios write flag
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx                ! local xios write flag
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-         IF(lwp) write(numout,*) 'RESTART: write (XIOS 1D) ',trim(cdvar)
-         CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 1D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 1D)',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rd1 = pvar )
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1690,5 +1745,5 @@
 
 
-   SUBROUTINE iom_rp2d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp2d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1697,16 +1752,26 @@
       REAL(sp)        , INTENT(in), DIMENSION(:,    :    ) ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
-      LOGICAL :: llx
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL            :: llx
+      INTEGER            :: ivid   ! variable id
+      CHARACTER(LEN=lc)  :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-         IF(lwp) write(numout,*) 'RESTART: write (XIOS 2D) ',trim(cdvar)
-         CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 2D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 2D)',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rs2 = pvar )
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1720,5 +1785,5 @@
    END SUBROUTINE iom_rp2d_sp
 
-   SUBROUTINE iom_rp2d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp2d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1727,16 +1792,26 @@
       REAL(dp)        , INTENT(in), DIMENSION(:,    :    ) ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
-      LOGICAL :: llx
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-         IF(lwp) write(numout,*) 'RESTART: write (XIOS 2D) ',trim(cdvar)
-         CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 2D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 2D)',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rd2 = pvar )
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1751,5 +1826,5 @@
 
 
-   SUBROUTINE iom_rp3d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp3d_sp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1758,16 +1833,26 @@
       REAL(sp)        , INTENT(in),       DIMENSION(:,:,:) ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
-      LOGICAL :: llx                 ! local xios write flag
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx                 ! local xios write flag
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-         IF(lwp) write(numout,*) 'RESTART: write (XIOS 3D) ',trim(cdvar)
-         CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 3D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 3D)',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rs3 = pvar )
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1781,5 +1866,5 @@
    END SUBROUTINE iom_rp3d_sp
 
-   SUBROUTINE iom_rp3d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+   SUBROUTINE iom_rp3d_dp( kt, kwrite, kiomid, cdvar, pvar, ktype )
       INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
       INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
@@ -1788,16 +1873,26 @@
       REAL(dp)        , INTENT(in),       DIMENSION(:,:,:) ::   pvar     ! written field
       INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
-      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
-      LOGICAL :: llx                 ! local xios write flag
-      INTEGER :: ivid   ! variable id
-
-      llx = .FALSE.
-      IF(PRESENT(ldxios)) llx = ldxios
+      !
+      LOGICAL           :: llx                 ! local xios write flag
+      INTEGER           :: ivid   ! variable id
+      CHARACTER(LEN=lc) :: context
+      !
+      CALL set_xios_context(kiomid, context)
+
+      llx = .NOT. (context == "NONE")
+
       IF( llx ) THEN
 #ifdef key_iomput
-      IF( kt == kwrite ) THEN
-         IF(lwp) write(numout,*) 'RESTART: write (XIOS 3D) ',trim(cdvar)
-         CALL xios_send_field(trim(cdvar), pvar)
-      ENDIF
+         IF( kt == kwrite ) THEN
+            IF(lwp) write(numout,*) 'RESTART: write (XIOS 3D) ',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_put(trim(cdvar), pvar)
+            CALL iom_swap(cxios_context)
+         ELSE
+            IF(lwp) write(numout,*) 'RESTART: define (XIOS 3D)',trim(cdvar)
+            CALL iom_swap(context)
+            CALL iom_set_rstw_active( trim(cdvar), rd3 = pvar )
+            CALL iom_swap(cxios_context)
+         ENDIF
 #endif
       ELSE
@@ -1865,5 +1960,5 @@
       CHARACTER(LEN=*), INTENT(in) ::   cdname
       REAL(sp)        , INTENT(in) ::   pfield0d
-!!      REAL(wp)        , DIMENSION(jpi,jpj) ::   zz     ! masson
+      !!      REAL(wp)        , DIMENSION(jpi,jpj) ::   zz     ! masson
 #if defined key_iomput
 !!clem      zz(:,:)=pfield0d
@@ -2145,5 +2240,5 @@
       CALL iom_swap( cdname )   ! swap to cdname context
       CALL xios_update_calendar(kt)
-      IF( cdname /= TRIM(cxios_context) )   CALL iom_swap( TRIM(cxios_context) )   ! return back to nemo context
+      IF( cdname /= TRIM(cxios_context) )   CALL iom_swap( cxios_context )   ! return back to nemo context
    END SUBROUTINE iom_setkt
 
@@ -2159,5 +2254,5 @@
          CALL iom_swap( cdname )   ! swap to cdname context
          CALL xios_context_finalize() ! finalize the context
-         IF( cdname /= TRIM(cxios_context) ) CALL iom_swap( TRIM(cxios_context) )   ! return back to nemo context
+         IF( cdname /= cxios_context ) CALL iom_swap( cxios_context )   ! return back to nemo context
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom_def.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom_def.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom_def.F90	(revision 14055)
@@ -9,4 +9,5 @@
    !!----------------------------------------------------------------------
    USE par_kind
+   USE netcdf
 
    IMPLICIT NONE
@@ -36,7 +37,8 @@
    INTEGER, PUBLIC            ::   nxioso = 0          !: type of restart file when writing using XIOS 1 - single, 2 - multiple
 !XIOS read restart   
-   LOGICAL, PUBLIC            ::   lrxios = .FALSE.     !: read single file restart using XIOS
+   LOGICAL, PUBLIC            ::   lrxios = .FALSE.     !: read single file restart using XIOS main switch
    LOGICAL, PUBLIC            ::   lxios_sini = .FALSE. ! is restart in a single file
-   LOGICAL, PUBLIC            ::   lxios_set  = .FALSE. 
+
+
 
    TYPE, PUBLIC ::   file_descriptor
@@ -59,13 +61,5 @@
    END TYPE file_descriptor
    TYPE(file_descriptor), DIMENSION(jpmax_files), PUBLIC ::   iom_file !: array containing the info for all opened files
-   INTEGER, PARAMETER, PUBLIC                   :: max_rst_fields = 95 !: maximum number of restart variables defined in iom_set_rst_vars
-   TYPE, PUBLIC :: RST_FIELD  
-    CHARACTER(len=30) :: vname = "NO_NAME" ! names of variables in restart file
-    CHARACTER(len=30) :: grid = "NO_GRID"
-    LOGICAL           :: active =.FALSE. ! for restart write only: true - write field, false do not write field
-   END TYPE RST_FIELD
 !$AGRIF_END_DO_NOT_TREAT
-   !
-   TYPE(RST_FIELD), PUBLIC, SAVE :: rst_wfields(max_rst_fields), rst_rfields(max_rst_fields)
    !
    !! * Substitutions
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom_nf90.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom_nf90.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/iom_nf90.F90	(revision 14055)
@@ -31,4 +31,5 @@
    PUBLIC iom_nf90_open  , iom_nf90_close, iom_nf90_varid, iom_nf90_get, iom_nf90_rstput
    PUBLIC iom_nf90_chkatt, iom_nf90_getatt, iom_nf90_putatt
+   PUBLIC iom_nf90_check
 
    INTERFACE iom_nf90_get
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/prtctl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/prtctl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/prtctl.F90	(revision 14055)
@@ -8,4 +8,5 @@
    !!----------------------------------------------------------------------
    USE dom_oce          ! ocean space and time domain variables
+   USE domutl, ONLY : is_tile
    USE in_out_manager   ! I/O manager
    USE mppini           ! distributed memory computing
@@ -26,4 +27,6 @@
    PUBLIC prt_ctl_init    ! called by nemogcm.F90 and prt_ctl_trc_init
 
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
    !!----------------------------------------------------------------------
    !! NEMO/OCE 4.0 , NEMO Consortium (2018)
@@ -35,4 +38,33 @@
    SUBROUTINE prt_ctl (tab2d_1, tab3d_1, tab4d_1, tab2d_2, tab3d_2, mask1, mask2,   &
       &                 clinfo, clinfo1, clinfo2, clinfo3, kdim )
+      !!
+      REAL(wp),         DIMENSION(:,:)    , INTENT(in), OPTIONAL ::   tab2d_1
+      REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   tab3d_1
+      REAL(wp),         DIMENSION(:,:,:,:), INTENT(in), OPTIONAL ::   tab4d_1
+      REAL(wp),         DIMENSION(:,:)    , INTENT(in), OPTIONAL ::   tab2d_2
+      REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   tab3d_2
+      REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   mask1
+      REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   mask2
+      CHARACTER(len=*), DIMENSION(:)      , INTENT(in), OPTIONAL ::   clinfo    ! information about the tab3d array
+      CHARACTER(len=*)                    , INTENT(in), OPTIONAL ::   clinfo1
+      CHARACTER(len=*)                    , INTENT(in), OPTIONAL ::   clinfo2
+      CHARACTER(len=*)                    , INTENT(in), OPTIONAL ::   clinfo3
+      INTEGER                             , INTENT(in), OPTIONAL ::   kdim
+      !
+      INTEGER :: itab2d_1, itab3d_1, itab4d_1, itab2d_2, itab3d_2
+      !!
+      IF( PRESENT(tab2d_1)  ) THEN ; itab2d_1 = is_tile(tab2d_1)  ; ELSE ; itab2d_1 = 0 ; ENDIF
+      IF( PRESENT(tab3d_1)  ) THEN ; itab3d_1 = is_tile(tab3d_1)  ; ELSE ; itab3d_1 = 0 ; ENDIF
+      IF( PRESENT(tab4d_1)  ) THEN ; itab4d_1 = is_tile(tab4d_1)  ; ELSE ; itab4d_1 = 0 ; ENDIF
+      IF( PRESENT(tab2d_2)  ) THEN ; itab2d_2 = is_tile(tab2d_2)  ; ELSE ; itab2d_2 = 0 ; ENDIF
+      IF( PRESENT(tab3d_2)  ) THEN ; itab3d_2 = is_tile(tab3d_2)  ; ELSE ; itab3d_2 = 0 ; ENDIF
+
+      CALL prt_ctl_t (tab2d_1, itab2d_1, tab3d_1, itab3d_1, tab4d_1, itab4d_1, tab2d_2, itab2d_2, tab3d_2, itab3d_2,  &
+      &               mask1, mask2, clinfo, clinfo1, clinfo2, clinfo3, kdim )
+   END SUBROUTINE prt_ctl
+
+
+   SUBROUTINE prt_ctl_t (tab2d_1, ktab2d_1, tab3d_1, ktab3d_1, tab4d_1, ktab4d_1, tab2d_2, ktab2d_2, tab3d_2, ktab3d_2,  &
+      &                  mask1, mask2, clinfo, clinfo1, clinfo2, clinfo3, kdim )
       !!----------------------------------------------------------------------
       !!                     ***  ROUTINE prt_ctl  ***
@@ -70,9 +102,10 @@
       !!                    clinfo3 : additional information 
       !!----------------------------------------------------------------------
-      REAL(wp),         DIMENSION(:,:)    , INTENT(in), OPTIONAL ::   tab2d_1
-      REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   tab3d_1
-      REAL(wp),         DIMENSION(:,:,:,:), INTENT(in), OPTIONAL ::   tab4d_1
-      REAL(wp),         DIMENSION(:,:)    , INTENT(in), OPTIONAL ::   tab2d_2
-      REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   tab3d_2
+      INTEGER                             , INTENT(in)           ::   ktab2d_1, ktab3d_1, ktab4d_1, ktab2d_2, ktab3d_2
+      REAL(wp),         DIMENSION(A2D_T(ktab2d_1))    , INTENT(in), OPTIONAL ::   tab2d_1
+      REAL(wp),         DIMENSION(A2D_T(ktab3d_1),:)  , INTENT(in), OPTIONAL ::   tab3d_1
+      REAL(wp),         DIMENSION(A2D_T(ktab4d_1),:,:), INTENT(in), OPTIONAL ::   tab4d_1
+      REAL(wp),         DIMENSION(A2D_T(ktab2d_2))    , INTENT(in), OPTIONAL ::   tab2d_2
+      REAL(wp),         DIMENSION(A2D_T(ktab3d_2),:)  , INTENT(in), OPTIONAL ::   tab3d_2
       REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   mask1
       REAL(wp),         DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   mask2
@@ -106,8 +139,8 @@
 
          ! define shoter names...
-         iis = nall_ictls(jl)
-         iie = nall_ictle(jl)
-         jjs = nall_jctls(jl)
-         jje = nall_jctle(jl)
+         iis = MAX( nall_ictls(jl), ntsi )
+         iie = MIN( nall_ictle(jl), ntei )
+         jjs = MAX( nall_jctls(jl), ntsj )
+         jje = MIN( nall_jctle(jl), ntej )
 
          IF( PRESENT(clinfo) ) THEN   ;   inum = numprt_top(jl)
@@ -115,83 +148,86 @@
          ENDIF
 
-         DO jn = 1, itra
-
-            IF( PRESENT(clinfo3) ) THEN
-               IF    ( clinfo3 == 'tra-ta' )   THEN
-                  zvctl1 = t_ctl(jl)
-               ELSEIF( clinfo3 == 'tra'    )   THEN
-                  zvctl1 = t_ctl(jl)
-                  zvctl2 = s_ctl(jl)
-               ELSEIF( clinfo3 == 'dyn'    )   THEN
-                  zvctl1 = u_ctl(jl)
-                  zvctl2 = v_ctl(jl)
+         ! Compute the sum control only where the tile domain and control print area overlap
+         IF( iie >= iis .AND. jje >= jjs ) THEN
+            DO jn = 1, itra
+
+               IF( PRESENT(clinfo3) ) THEN
+                  IF    ( clinfo3 == 'tra-ta' )   THEN
+                     zvctl1 = t_ctl(jl)
+                  ELSEIF( clinfo3 == 'tra'    )   THEN
+                     zvctl1 = t_ctl(jl)
+                     zvctl2 = s_ctl(jl)
+                  ELSEIF( clinfo3 == 'dyn'    )   THEN
+                     zvctl1 = u_ctl(jl)
+                     zvctl2 = v_ctl(jl)
+                  ELSE
+                     zvctl1 = tra_ctl(jn,jl)
+                  ENDIF
+               ENDIF
+
+               ! 2D arrays
+               IF( PRESENT(tab2d_1) ) THEN
+                  IF( PRESENT(mask1) ) THEN   ;   zsum1 = SUM( tab2d_1(iis:iie,jjs:jje) * mask1(iis:iie,jjs:jje,1) )
+                  ELSE                        ;   zsum1 = SUM( tab2d_1(iis:iie,jjs:jje)                            )
+                  ENDIF
+               ENDIF
+               IF( PRESENT(tab2d_2) ) THEN
+                  IF( PRESENT(mask2) ) THEN   ;   zsum2 = SUM( tab2d_2(iis:iie,jjs:jje) * mask2(iis:iie,jjs:jje,1) )
+                  ELSE                        ;   zsum2 = SUM( tab2d_2(iis:iie,jjs:jje)                            )
+                  ENDIF
+               ENDIF
+
+               ! 3D arrays
+               IF( PRESENT(tab3d_1) ) THEN
+                  IF( PRESENT(mask1) ) THEN   ;   zsum1 = SUM( tab3d_1(iis:iie,jjs:jje,1:kdir) * mask1(iis:iie,jjs:jje,1:kdir) )
+                  ELSE                        ;   zsum1 = SUM( tab3d_1(iis:iie,jjs:jje,1:kdir)                                 )
+                  ENDIF
+               ENDIF
+               IF( PRESENT(tab3d_2) ) THEN
+                  IF( PRESENT(mask2) ) THEN   ;   zsum2 = SUM( tab3d_2(iis:iie,jjs:jje,1:kdir) * mask2(iis:iie,jjs:jje,1:kdir) )
+                  ELSE                        ;   zsum2 = SUM( tab3d_2(iis:iie,jjs:jje,1:kdir)                                 )
+                  ENDIF
+               ENDIF
+
+               ! 4D arrays
+               IF( PRESENT(tab4d_1) ) THEN
+                  IF( PRESENT(mask1) ) THEN   ;   zsum1 = SUM( tab4d_1(iis:iie,jjs:jje,1:kdir,jn) * mask1(iis:iie,jjs:jje,1:kdir) )
+                  ELSE                        ;   zsum1 = SUM( tab4d_1(iis:iie,jjs:jje,1:kdir,jn)                                 )
+                  ENDIF
+               ENDIF
+
+               ! Print the result
+               IF( PRESENT(clinfo ) )   cl1  = clinfo(jn)
+               IF( PRESENT(clinfo3) )   THEN
+                  !
+                  IF( PRESENT(tab2d_2) .OR. PRESENT(tab3d_2) ) THEN
+                     WRITE(inum, "(3x,a,' : ',D23.16,3x,a,' : ',D23.16)") cl1, zsum1 - zvctl1, cl2, zsum2 - zvctl2
+                  ELSE
+                     WRITE(inum, "(3x,a,' : ',D23.16                  )") cl1, zsum1 - zvctl1
+                  ENDIF
+                  !
+                  SELECT CASE( clinfo3 )
+                  CASE ( 'tra-ta' )
+                     t_ctl(jl) = zsum1
+                  CASE ( 'tra' )
+                     t_ctl(jl) = zsum1
+                     s_ctl(jl) = zsum2
+                  CASE ( 'dyn' )
+                     u_ctl(jl) = zsum1
+                     v_ctl(jl) = zsum2
+                  CASE default
+                     tra_ctl(jn,jl) = zsum1
+                  END SELECT
+               ELSEIF ( PRESENT(tab2d_2) .OR. PRESENT(tab3d_2) )   THEN
+                  WRITE(inum, "(3x,a,' : ',D23.16,3x,a,' : ',D23.16)") cl1, zsum1, cl2, zsum2
                ELSE
-                  zvctl1 = tra_ctl(jn,jl)
-               ENDIF
-            ENDIF
-
-            ! 2D arrays
-            IF( PRESENT(tab2d_1) ) THEN
-               IF( PRESENT(mask1) ) THEN   ;   zsum1 = SUM( tab2d_1(iis:iie,jjs:jje) * mask1(iis:iie,jjs:jje,1) )
-               ELSE                        ;   zsum1 = SUM( tab2d_1(iis:iie,jjs:jje)                            )
-               ENDIF
-            ENDIF
-            IF( PRESENT(tab2d_2) ) THEN
-               IF( PRESENT(mask2) ) THEN   ;   zsum2 = SUM( tab2d_2(iis:iie,jjs:jje) * mask2(iis:iie,jjs:jje,1) )
-               ELSE                        ;   zsum2 = SUM( tab2d_2(iis:iie,jjs:jje)                            )
-               ENDIF
-            ENDIF
-
-            ! 3D arrays
-            IF( PRESENT(tab3d_1) ) THEN
-               IF( PRESENT(mask1) ) THEN   ;   zsum1 = SUM( tab3d_1(iis:iie,jjs:jje,1:kdir) * mask1(iis:iie,jjs:jje,1:kdir) )
-               ELSE                        ;   zsum1 = SUM( tab3d_1(iis:iie,jjs:jje,1:kdir)                                 )
-               ENDIF
-            ENDIF
-            IF( PRESENT(tab3d_2) ) THEN
-               IF( PRESENT(mask2) ) THEN   ;   zsum2 = SUM( tab3d_2(iis:iie,jjs:jje,1:kdir) * mask2(iis:iie,jjs:jje,1:kdir) )
-               ELSE                        ;   zsum2 = SUM( tab3d_2(iis:iie,jjs:jje,1:kdir)                                 )
-               ENDIF
-            ENDIF
-
-            ! 4D arrays
-            IF( PRESENT(tab4d_1) ) THEN
-               IF( PRESENT(mask1) ) THEN   ;   zsum1 = SUM( tab4d_1(iis:iie,jjs:jje,1:kdir,jn) * mask1(iis:iie,jjs:jje,1:kdir) )
-               ELSE                        ;   zsum1 = SUM( tab4d_1(iis:iie,jjs:jje,1:kdir,jn)                                 )
-               ENDIF
-            ENDIF
-
-            ! Print the result
-            IF( PRESENT(clinfo ) )   cl1  = clinfo(jn)
-            IF( PRESENT(clinfo3) )   THEN
-               !
-               IF( PRESENT(tab2d_2) .OR. PRESENT(tab3d_2) ) THEN
-                  WRITE(inum, "(3x,a,' : ',D23.16,3x,a,' : ',D23.16)") cl1, zsum1 - zvctl1, cl2, zsum2 - zvctl2
-               ELSE
-                  WRITE(inum, "(3x,a,' : ',D23.16                  )") cl1, zsum1 - zvctl1
-               ENDIF
-               !
-               SELECT CASE( clinfo3 )
-               CASE ( 'tra-ta' ) 
-                  t_ctl(jl) = zsum1
-               CASE ( 'tra' ) 
-                  t_ctl(jl) = zsum1
-                  s_ctl(jl) = zsum2
-               CASE ( 'dyn' ) 
-                  u_ctl(jl) = zsum1
-                  v_ctl(jl) = zsum2
-               CASE default
-                  tra_ctl(jn,jl) = zsum1
-               END SELECT
-            ELSEIF ( PRESENT(tab2d_2) .OR. PRESENT(tab3d_2) )   THEN
-               WRITE(inum, "(3x,a,' : ',D23.16,3x,a,' : ',D23.16)") cl1, zsum1, cl2, zsum2
-            ELSE
-               WRITE(inum, "(3x,a,' : ',D23.16                  )") cl1, zsum1
-            ENDIF
-
-         END DO
+                  WRITE(inum, "(3x,a,' : ',D23.16                  )") cl1, zsum1
+               ENDIF
+
+            END DO
+         ENDIF
       END DO
       !
-   END SUBROUTINE prt_ctl
+   END SUBROUTINE prt_ctl_t
 
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/restart.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/restart.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/IOM/restart.F90	(revision 14055)
@@ -110,5 +110,5 @@
             ELSE
 #if defined key_iomput
-               cwxios_context = "rstw_"//TRIM(ADJUSTL(clkt))
+               cw_ocerst_cxt = "rstw_"//TRIM(ADJUSTL(clkt))
                IF( TRIM(Agrif_CFixed()) == '0' ) THEN
                   clpname = clname
@@ -116,6 +116,6 @@
                   clpname = TRIM(Agrif_CFixed())//"_"//clname   
                ENDIF
-               CALL iom_init( cwxios_context, TRIM(clpath)//TRIM(clpname), .false. )
-               CALL xios_update_calendar(nitrst)
+               numrow = iom_xios_setid(TRIM(clpath)//TRIM(clpname))
+               CALL iom_init( cw_ocerst_cxt, kdid = numrow, ld_closedef = .false. )
                CALL iom_swap(      cxios_context          )
 #else
@@ -143,30 +143,30 @@
       INTEGER, INTENT(in) ::   Kbb, Kmm   ! ocean time level indices
       !!----------------------------------------------------------------------
-                     IF(lwxios) CALL iom_swap(      cwxios_context          )
-                     CALL iom_rstput( kt, nitrst, numrow, 'rdt'    , rn_Dt       , ldxios = lwxios)   ! dynamics time step
-                     CALL iom_delay_rst( 'WRITE', 'OCE', numrow )   ! save only ocean delayed global communication variables
+                     CALL iom_rstput( kt, nitrst, numrow, 'rdt'    , rn_Dt       )   ! dynamics time step
+                     IF(.NOT.lwxios) CALL iom_delay_rst( 'WRITE', 'OCE', numrow )   ! save only ocean delayed global communication variables
 
       IF ( .NOT. ln_diurnal_only ) THEN
-                     CALL iom_rstput( kt, nitrst, numrow, 'ub'     , uu(:,:,:       ,Kbb), ldxios = lwxios        )     ! before fields
-                     CALL iom_rstput( kt, nitrst, numrow, 'vb'     , vv(:,:,:       ,Kbb), ldxios = lwxios        )
-                     CALL iom_rstput( kt, nitrst, numrow, 'tb'     , ts(:,:,:,jp_tem,Kbb), ldxios = lwxios )
-                     CALL iom_rstput( kt, nitrst, numrow, 'sb'     , ts(:,:,:,jp_sal,Kbb), ldxios = lwxios )
-                     CALL iom_rstput( kt, nitrst, numrow, 'sshb'   ,ssh(:,:         ,Kbb), ldxios = lwxios      )
+                     CALL iom_rstput( kt, nitrst, numrow, 'ub'     , uu(:,:,:       ,Kbb) )     ! before fields
+                     CALL iom_rstput( kt, nitrst, numrow, 'vb'     , vv(:,:,:       ,Kbb) )
+                     CALL iom_rstput( kt, nitrst, numrow, 'tb'     , ts(:,:,:,jp_tem,Kbb) )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sb'     , ts(:,:,:,jp_sal,Kbb) )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sshb'   , ssh(:,:         ,Kbb))
                      !
-                     CALL iom_rstput( kt, nitrst, numrow, 'un'     , uu(:,:,:       ,Kmm), ldxios = lwxios        )     ! now fields
-                     CALL iom_rstput( kt, nitrst, numrow, 'vn'     , vv(:,:,:       ,Kmm), ldxios = lwxios        )
-                     CALL iom_rstput( kt, nitrst, numrow, 'tn'     , ts(:,:,:,jp_tem,Kmm), ldxios = lwxios )
-                     CALL iom_rstput( kt, nitrst, numrow, 'sn'     , ts(:,:,:,jp_sal,Kmm), ldxios = lwxios )
-                     CALL iom_rstput( kt, nitrst, numrow, 'sshn'   ,ssh(:,:         ,Kmm), ldxios = lwxios      )
-                     CALL iom_rstput( kt, nitrst, numrow, 'rhop'   , rhop, ldxios = lwxios      )
+                     CALL iom_rstput( kt, nitrst, numrow, 'un'     , uu(:,:,:       ,Kmm) )     ! now fields
+                     CALL iom_rstput( kt, nitrst, numrow, 'vn'     , vv(:,:,:       ,Kmm) )
+                     CALL iom_rstput( kt, nitrst, numrow, 'tn'     , ts(:,:,:,jp_tem,Kmm) )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sn'     , ts(:,:,:,jp_sal,Kmm) )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sshn'   , ssh(:,:         ,Kmm))
+                     CALL iom_rstput( kt, nitrst, numrow, 'rhop'   , rhop      )
       ENDIF
       
-      IF (ln_diurnal) CALL iom_rstput( kt, nitrst, numrow, 'Dsst', x_dsst, ldxios = lwxios )  
-      IF(lwxios) CALL iom_swap(      cxios_context          )
+      IF (ln_diurnal) CALL iom_rstput( kt, nitrst, numrow, 'Dsst', x_dsst )  
       IF( kt == nitrst ) THEN
          IF(.NOT.lwxios) THEN
             CALL iom_close( numrow )     ! close the restart file (only at last time step)
          ELSE
-            CALL iom_context_finalize(      cwxios_context          )
+            CALL iom_context_finalize(      cw_ocerst_cxt          )
+            iom_file(numrow)%nfid       = 0
+            numrow = 0
          ENDIF
 !!gm         IF( .NOT. lk_trdmld )   lrst_oce = .FALSE.
@@ -191,6 +191,7 @@
       !!                the file has already been opened
       !!----------------------------------------------------------------------
-      LOGICAL        ::   llok
-      CHARACTER(lc)  ::   clpath   ! full path to ocean output restart file
+      LOGICAL             ::   llok
+      CHARACTER(len=lc)   ::   clpath   ! full path to ocean output restart file
+      CHARACTER(len=lc+2) ::   clpname  ! file name including agrif prefix
       !!----------------------------------------------------------------------
       !
@@ -209,18 +210,18 @@
 ! can handle checking if variable is in the restart file (there will be no need to open
 ! restart)
-         IF(.NOT.lxios_set) lrxios = lrxios.AND.lxios_sini
+         lrxios = lrxios.AND.lxios_sini
+
          IF( lrxios) THEN
-             crxios_context = 'nemo_rst'
-             IF( .NOT.lxios_set ) THEN
-                 IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS'
-                 CALL iom_init( crxios_context )
-                 lxios_set = .TRUE.
-             ENDIF
-         ENDIF
-         IF( TRIM(Agrif_CFixed()) /= '0' .AND. lrxios) THEN
-             CALL iom_init( crxios_context )
-             IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS for AGRIF'
-             lxios_set = .TRUE.
-         ENDIF 
+             cr_ocerst_cxt = 'oce_rst'
+             IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS'
+!            IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+!               clpname = cn_ocerst_in
+!            ELSE
+!               clpname = TRIM(Agrif_CFixed())//"_"//cn_ocerst_in   
+!            ENDIF
+             CALL iom_init( cr_ocerst_cxt, kdid = numror, ld_closedef = .TRUE. )
+             CALL iom_swap(      cxios_context          )
+         ENDIF
+
       ENDIF
 
@@ -246,5 +247,5 @@
       ! Check dynamics and tracer time-step consistency and force Euler restart if changed
       IF( iom_varid( numror, 'rdt', ldstop = .FALSE. ) > 0 )   THEN
-         CALL iom_get( numror, 'rdt', zrdt, ldxios = lrxios )
+         CALL iom_get( numror, 'rdt', zrdt )
          IF( zrdt /= rn_Dt ) THEN
             IF(lwp) WRITE( numout,*)
@@ -256,24 +257,24 @@
       ENDIF
 
-      CALL iom_delay_rst( 'READ', 'OCE', numror )   ! read only ocean delayed global communication variables
+      IF(.NOT.lrxios ) CALL iom_delay_rst( 'READ', 'OCE', numror )   ! read only ocean delayed global communication variables
       
       ! Diurnal DSST 
-      IF( ln_diurnal ) CALL iom_get( numror, jpdom_auto, 'Dsst' , x_dsst, ldxios = lrxios ) 
+      IF( ln_diurnal ) CALL iom_get( numror, jpdom_auto, 'Dsst' , x_dsst ) 
       IF ( ln_diurnal_only ) THEN 
          IF(lwp) WRITE( numout, * ) &
          &   "rst_read:- ln_diurnal_only set, setting rhop=rho0" 
          rhop = rho0
-         CALL iom_get( numror, jpdom_auto, 'tn'     , w3d, ldxios = lrxios ) 
+         CALL iom_get( numror, jpdom_auto, 'tn'     , w3d ) 
          ts(:,:,1,jp_tem,Kmm) = w3d(:,:,1)
          RETURN 
       ENDIF  
-      
+
       IF( iom_varid( numror, 'ub', ldstop = .FALSE. ) > 0 ) THEN
          ! before fields
-         CALL iom_get( numror, jpdom_auto, 'ub'     , uu(:,:,:       ,Kbb), ldxios = lrxios, cd_type = 'U', psgn = -1._wp )
-         CALL iom_get( numror, jpdom_auto, 'vb'     , vv(:,:,:       ,Kbb), ldxios = lrxios, cd_type = 'V', psgn = -1._wp )
-         CALL iom_get( numror, jpdom_auto, 'tb'     , ts(:,:,:,jp_tem,Kbb), ldxios = lrxios )
-         CALL iom_get( numror, jpdom_auto, 'sb'     , ts(:,:,:,jp_sal,Kbb), ldxios = lrxios )
-         CALL iom_get( numror, jpdom_auto, 'sshb'   ,ssh(:,:         ,Kbb), ldxios = lrxios )
+         CALL iom_get( numror, jpdom_auto, 'ub'     , uu(:,:,:       ,Kbb), cd_type = 'U', psgn = -1._wp )
+         CALL iom_get( numror, jpdom_auto, 'vb'     , vv(:,:,:       ,Kbb), cd_type = 'V', psgn = -1._wp )
+         CALL iom_get( numror, jpdom_auto, 'tb'     , ts(:,:,:,jp_tem,Kbb) )
+         CALL iom_get( numror, jpdom_auto, 'sb'     , ts(:,:,:,jp_sal,Kbb) )
+         CALL iom_get( numror, jpdom_auto, 'sshb'   ,ssh(:,:         ,Kbb) )
       ELSE
          l_1st_euler =  .TRUE.      ! before field not found, forced euler 1st time-step
@@ -281,11 +282,11 @@
       !
       ! now fields
-      CALL iom_get( numror, jpdom_auto, 'un'     , uu(:,:,:       ,Kmm), ldxios = lrxios, cd_type = 'U', psgn = -1._wp )
-      CALL iom_get( numror, jpdom_auto, 'vn'     , vv(:,:,:       ,Kmm), ldxios = lrxios, cd_type = 'V', psgn = -1._wp )
-      CALL iom_get( numror, jpdom_auto, 'tn'     , ts(:,:,:,jp_tem,Kmm), ldxios = lrxios )
-      CALL iom_get( numror, jpdom_auto, 'sn'     , ts(:,:,:,jp_sal,Kmm), ldxios = lrxios )
-      CALL iom_get( numror, jpdom_auto, 'sshn'   ,ssh(:,:         ,Kmm), ldxios = lrxios )
+      CALL iom_get( numror, jpdom_auto, 'un'     , uu(:,:,:       ,Kmm), cd_type = 'U', psgn = -1._wp )
+      CALL iom_get( numror, jpdom_auto, 'vn'     , vv(:,:,:       ,Kmm), cd_type = 'V', psgn = -1._wp )
+      CALL iom_get( numror, jpdom_auto, 'tn'     , ts(:,:,:,jp_tem,Kmm) )
+      CALL iom_get( numror, jpdom_auto, 'sn'     , ts(:,:,:,jp_sal,Kmm) )
+      CALL iom_get( numror, jpdom_auto, 'sshn'   ,ssh(:,:         ,Kmm) )
       IF( iom_varid( numror, 'rhop', ldstop = .FALSE. ) > 0 ) THEN
-         CALL iom_get( numror, jpdom_auto, 'rhop'   , rhop, ldxios = lrxios )   ! now    potential density
+         CALL iom_get( numror, jpdom_auto, 'rhop'   , rhop )   ! now    potential density
       ELSE
          CALL eos( ts(:,:,:,:,Kmm), rhd, rhop, gdept(:,:,:,Kmm) )   
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfcav.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfcav.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfcav.F90	(revision 14055)
@@ -183,7 +183,10 @@
       ! cavity mask
       mskisf_cav(:,:)    = (1._wp - tmask(:,:,1)) * ssmask(:,:)
-      !
-      !================
-      ! 2: read restart
+      !================
+      ! 2: activate restart
+      !================
+      !
+      !================
+      ! 3: read restart
       !================
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfcpl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfcpl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfcpl.F90	(revision 14055)
@@ -120,13 +120,4 @@
       e3t(:,:,:,Kbb)   = e3t(:,:,:,Kmm)
 #endif 
-      ! prepare writing restart
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('ssmask')
-         CALL iom_set_rstw_var_active('tmask')
-         CALL iom_set_rstw_var_active('e3t_n')
-         CALL iom_set_rstw_var_active('e3u_n')
-         CALL iom_set_rstw_var_active('e3v_n')
-      END IF
-      !
    END SUBROUTINE isfcpl_init
    ! 
@@ -153,12 +144,10 @@
       END DO 
       !
-      IF( lwxios ) CALL iom_swap( cwxios_context )
-      CALL iom_rstput( kt, nitrst, numrow, 'tmask'  , tmask , ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, 'ssmask' , ssmask, ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, 'e3t_n'  , ze3t , ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, 'e3u_n'  , ze3u , ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, 'e3v_n'  , ze3v , ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, 'gdepw_n', zgdepw , ldxios = lwxios )
-      IF( lwxios ) CALL iom_swap( cxios_context )
+      CALL iom_rstput( kt, nitrst, numrow, 'tmask'  , tmask  )
+      CALL iom_rstput( kt, nitrst, numrow, 'ssmask' , ssmask )
+      CALL iom_rstput( kt, nitrst, numrow, 'e3t_n'  , ze3t   )
+      CALL iom_rstput( kt, nitrst, numrow, 'e3u_n'  , ze3u   )
+      CALL iom_rstput( kt, nitrst, numrow, 'e3v_n'  , ze3v   )
+      CALL iom_rstput( kt, nitrst, numrow, 'gdepw_n', zgdepw )
       !
    END SUBROUTINE isfcpl_rst_write
@@ -183,5 +172,5 @@
       !!----------------------------------------------------------------------
       !
-      CALL iom_get( numror, jpdom_auto, 'ssmask'  , zssmask_b, ldxios = lrxios   ) ! need to extrapolate T/S
+      CALL iom_get( numror, jpdom_auto, 'ssmask'  , zssmask_b   ) ! need to extrapolate T/S
 
       ! compute new ssh if we open a full water column 
@@ -264,7 +253,7 @@
       !!----------------------------------------------------------------------
       ! 
-      CALL iom_get( numror, jpdom_auto, 'tmask'  , ztmask_b, ldxios = lrxios   ) ! need to extrapolate T/S
-      !CALL iom_get( numror, jpdom_auto, 'wmask'  , zwmask_b, ldxios = lrxios   ) ! need to extrapolate T/S
-      !CALL iom_get( numror, jpdom_auto, 'gdepw_n', zdepw_b(:,:,:), ldxios = lrxios ) ! need to interpol vertical profile (vvl)
+      CALL iom_get( numror, jpdom_auto, 'tmask'  , ztmask_b   ) ! need to extrapolate T/S
+      !CALL iom_get( numror, jpdom_auto, 'wmask'  , zwmask_b  ) ! need to extrapolate T/S
+      !CALL iom_get( numror, jpdom_auto, 'gdepw_n', zdepw_b(:,:,:) ) ! need to interpol vertical profile (vvl)
       !
       ! 
@@ -410,7 +399,7 @@
       !!----------------------------------------------------------------------
       !
-      CALL iom_get( numror, jpdom_auto, 'tmask'  , ztmask_b, ldxios = lrxios )
-      CALL iom_get( numror, jpdom_auto, 'e3u_n'  , ze3u_b  , ldxios = lrxios )
-      CALL iom_get( numror, jpdom_auto, 'e3v_n'  , ze3v_b  , ldxios = lrxios )
+      CALL iom_get( numror, jpdom_auto, 'tmask'  , ztmask_b )
+      CALL iom_get( numror, jpdom_auto, 'e3u_n'  , ze3u_b   )
+      CALL iom_get( numror, jpdom_auto, 'e3v_n'  , ze3v_b   )
       !
       ! 1.0: compute horizontal volume flux divergence difference before-after coupling
@@ -520,8 +509,8 @@
 
       ! get restart variable
-      CALL iom_get( numror, jpdom_auto, 'tmask'  , ztmask_b(:,:,:), ldxios = lrxios   ) ! need to extrapolate T/S
-      CALL iom_get( numror, jpdom_auto, 'e3t_n'  , ze3t_b(:,:,:)  , ldxios = lrxios )
-      CALL iom_get( numror, jpdom_auto, 'tn'     , zt_b(:,:,:)    , ldxios = lrxios )
-      CALL iom_get( numror, jpdom_auto, 'sn'     , zs_b(:,:,:)    , ldxios = lrxios )
+      CALL iom_get( numror, jpdom_auto, 'tmask'  , ztmask_b(:,:,:) ) ! need to extrapolate T/S
+      CALL iom_get( numror, jpdom_auto, 'e3t_n'  , ze3t_b(:,:,:)   )
+      CALL iom_get( numror, jpdom_auto, 'tn'     , zt_b(:,:,:)     )
+      CALL iom_get( numror, jpdom_auto, 'sn'     , zs_b(:,:,:)     )
 
       ! compute run length
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfrst.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfrst.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ISF/isfrst.F90	(revision 14055)
@@ -53,7 +53,7 @@
       IF( iom_varid( numror, cfwf_b, ldstop = .FALSE. ) > 0 ) THEN
          IF(lwp) WRITE(numout,*) '          nit000-1 isf tracer content forcing fields read in the restart file'
-         CALL iom_get( numror, jpdom_auto, cfwf_b, pfwf_b(:,:)        , ldxios = lrxios )   ! before ice shelf melt
-         CALL iom_get( numror, jpdom_auto, chc_b , ptsc_b (:,:,jp_tem), ldxios = lrxios )   ! before ice shelf heat flux
-         CALL iom_get( numror, jpdom_auto, csc_b , ptsc_b (:,:,jp_sal), ldxios = lrxios )   ! before ice shelf heat flux
+         CALL iom_get( numror, jpdom_auto, cfwf_b, pfwf_b(:,:)         )   ! before ice shelf melt
+         CALL iom_get( numror, jpdom_auto, chc_b , ptsc_b (:,:,jp_tem) )   ! before ice shelf heat flux
+         CALL iom_get( numror, jpdom_auto, csc_b , ptsc_b (:,:,jp_sal) )   ! before ice shelf heat flux
       ELSE
          pfwf_b(:,:)   = pfwf(:,:)
@@ -61,10 +61,4 @@
       ENDIF
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active(TRIM(chc_b ))
-         CALL iom_set_rstw_var_active(TRIM(csc_b ))
-         CALL iom_set_rstw_var_active(TRIM(cfwf_b))
-      ENDIF
-
    END SUBROUTINE isfrst_read
    ! 
@@ -95,9 +89,7 @@
       !
       ! write restart variable
-      IF( lwxios ) CALL iom_swap( cwxios_context )
-      CALL iom_rstput( kt, nitrst, numrow, cfwf_b, pfwf(:,:)       , ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, chc_b , ptsc(:,:,jp_tem), ldxios = lwxios )
-      CALL iom_rstput( kt, nitrst, numrow, csc_b , ptsc(:,:,jp_sal), ldxios = lwxios )
-      IF( lwxios ) CALL iom_swap( cxios_context )
+      CALL iom_rstput( kt, nitrst, numrow, cfwf_b, pfwf(:,:)        )
+      CALL iom_rstput( kt, nitrst, numrow, chc_b , ptsc(:,:,jp_tem) )
+      CALL iom_rstput( kt, nitrst, numrow, csc_b , ptsc(:,:,jp_sal) )
       !
    END SUBROUTINE isfrst_write
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbc_lnk_multi_generic.h90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbc_lnk_multi_generic.h90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbc_lnk_multi_generic.h90	(revision 14055)
@@ -40,5 +40,5 @@
       &                    , pt9 , cdna9 , psgn9 , pt10, cdna10, psgn10, pt11, cdna11, psgn11, pt12, cdna12, psgn12  &
       &                    , pt13, cdna13, psgn13, pt14, cdna14, psgn14, pt15, cdna15, psgn15, pt16, cdna16, psgn16  &
-      &                    , kfillmode, pfillval, lsend, lrecv )
+      &                    , kfillmode, pfillval, lsend, lrecv, ncsten )
       !!---------------------------------------------------------------------
       CHARACTER(len=*)     ,                   INTENT(in   ) ::   cdname  ! name of the calling subroutine
@@ -55,4 +55,5 @@
       REAL(wp)             , OPTIONAL        , INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
       LOGICAL, DIMENSION(4), OPTIONAL        , INTENT(in   ) ::   lsend, lrecv   ! indicate how communications are to be carried out
+      LOGICAL              , OPTIONAL        , INTENT(in   ) ::   ncsten
       !!
       INTEGER                          ::   kfld        ! number of elements that will be attributed
@@ -84,5 +85,5 @@
       IF( PRESENT(psgn16) )   CALL ROUTINE_LOAD( pt16, cdna16, psgn16, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
       !
-      CALL lbc_lnk_ptr( cdname, ptab_ptr, cdna_ptr, psgn_ptr, kfld, kfillmode, pfillval, lsend, lrecv )
+      CALL lbc_lnk_ptr( cdname, ptab_ptr, cdna_ptr, psgn_ptr, kfld, kfillmode, pfillval, lsend, lrecv, ncsten )
       !
    END SUBROUTINE ROUTINE_MULTI
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbc_lnk_nc_generic.h90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbc_lnk_nc_generic.h90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbc_lnk_nc_generic.h90	(revision 14055)
@@ -0,0 +1,113 @@
+#if defined SINGLE_PRECISION
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k,l)   REAL(sp), DIMENSION(i,j)
+#      define PTR_TYPE              TYPE(PTR_2D_sp)
+#      define PTR_ptab              pt2d
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k,l)   REAL(sp), DIMENSION(i,j,k)
+#      define PTR_TYPE              TYPE(PTR_3D_sp)
+#      define PTR_ptab              pt3d
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_TYPE(i,j,k,l)   REAL(sp), DIMENSION(i,j,k,l)
+#      define PTR_TYPE              TYPE(PTR_4D_sp)
+#      define PTR_ptab              pt4d
+#   endif
+#   define PRECISION sp
+#else
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k,l)   REAL(dp), DIMENSION(i,j)
+#      define PTR_TYPE              TYPE(PTR_2D_dp)
+#      define PTR_ptab              pt2d
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k,l)   REAL(dp), DIMENSION(i,j,k)
+#      define PTR_TYPE              TYPE(PTR_3D_dp)
+#      define PTR_ptab              pt3d
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_TYPE(i,j,k,l)   REAL(dp), DIMENSION(i,j,k,l)
+#      define PTR_TYPE              TYPE(PTR_4D_dp)
+#      define PTR_ptab              pt4d
+#   endif
+#   define PRECISION dp
+#endif
+
+   SUBROUTINE ROUTINE_MULTI_NC( cdname                                                                             &
+      &                    , pt1 , cdna1 , psgn1 , pt2 , cdna2 , psgn2 , pt3 , cdna3 , psgn3 , pt4 , cdna4 , psgn4   &
+      &                    , pt5 , cdna5 , psgn5 , pt6 , cdna6 , psgn6 , pt7 , cdna7 , psgn7 , pt8 , cdna8 , psgn8   &
+      &                    , pt9 , cdna9 , psgn9 , pt10, cdna10, psgn10, pt11, cdna11, psgn11, pt12, cdna12, psgn12  &
+      &                    , pt13, cdna13, psgn13, pt14, cdna14, psgn14, pt15, cdna15, psgn15, pt16, cdna16, psgn16  &
+      &                    , kfillmode, pfillval, lsend, lrecv, ncsten )
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*)   ,                   INTENT(in   ) :: cdname  ! name of the calling subroutine
+      ARRAY_TYPE(:,:,:,:)          , TARGET, INTENT(inout) :: pt1     ! arrays on which the lbc is applied
+      ARRAY_TYPE(:,:,:,:), OPTIONAL, TARGET, INTENT(inout) :: pt2  , pt3  , pt4  , pt5  , pt6  , pt7  , pt8  , pt9  , &
+         &                                                    pt10  , pt11  , pt12  , pt13  , pt14  , pt15  , pt16
+      CHARACTER(len=1)                     , INTENT(in   ) :: cdna1   ! nature of pt2D. array grid-points
+      CHARACTER(len=1)   , OPTIONAL        , INTENT(in   ) :: cdna2, cdna3, cdna4, cdna5, cdna6, cdna7, cdna8, cdna9, &
+         &                                                    cdna10, cdna11, cdna12, cdna13, cdna14, cdna15, cdna16
+      REAL(wp)                             , INTENT(in   ) :: psgn1   ! sign used across the north fold
+      REAL(wp)           , OPTIONAL        , INTENT(in   ) :: psgn2, psgn3, psgn4, psgn5, psgn6, psgn7, psgn8, psgn9, &
+         &                                                    psgn10, psgn11, psgn12, psgn13, psgn14, psgn15, psgn16
+      INTEGER            , OPTIONAL        , INTENT(in   ) :: kfillmode   ! filling method for halo over land (default = constant)
+      REAL(wp)           , OPTIONAL        , INTENT(in   ) :: pfillval    ! background value (used at closed boundaries)
+      LOGICAL, DIMENSION(4), OPTIONAL      , INTENT(in   ) :: lsend, lrecv   ! indicate how communications are to be carried out
+      LOGICAL            , OPTIONAL      , INTENT(in   ) :: ncsten
+      !!
+      INTEGER                          ::   kfld        ! number of elements that will be attributed
+      PTR_TYPE         , DIMENSION(16) ::   ptab_ptr    ! pointer array
+      CHARACTER(len=1) , DIMENSION(16) ::   cdna_ptr    ! nature of ptab_ptr grid-points
+      REAL(wp)         , DIMENSION(16) ::   psgn_ptr    ! sign used across the north fold boundary
+      !!---------------------------------------------------------------------
+      !
+      kfld = 0          ! initial array of pointer size
+      !
+      !                 ! Load the first array
+      CALL ROUTINE_NC_LOAD( pt1, cdna1, psgn1, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      !
+      !                 ! Look if more arrays are added
+      IF( PRESENT(psgn2 ) )   CALL ROUTINE_NC_LOAD( pt2 , cdna2 , psgn2 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn3 ) )   CALL ROUTINE_NC_LOAD( pt3 , cdna3 , psgn3 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn4 ) )   CALL ROUTINE_NC_LOAD( pt4 , cdna4 , psgn4 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn5 ) )   CALL ROUTINE_NC_LOAD( pt5 , cdna5 , psgn5 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn6 ) )   CALL ROUTINE_NC_LOAD( pt6 , cdna6 , psgn6 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn7 ) )   CALL ROUTINE_NC_LOAD( pt7 , cdna7 , psgn7 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn8 ) )   CALL ROUTINE_NC_LOAD( pt8 , cdna8 , psgn8 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn9 ) )   CALL ROUTINE_NC_LOAD( pt9 , cdna9 , psgn9 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn10) )   CALL ROUTINE_NC_LOAD( pt10, cdna10, psgn10, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn11) )   CALL ROUTINE_NC_LOAD( pt11, cdna11, psgn11, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn12) )   CALL ROUTINE_NC_LOAD( pt12, cdna12, psgn12, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn13) )   CALL ROUTINE_NC_LOAD( pt13, cdna13, psgn13, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn14) )   CALL ROUTINE_NC_LOAD( pt14, cdna14, psgn14, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn15) )   CALL ROUTINE_NC_LOAD( pt15, cdna15, psgn15, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn16) )   CALL ROUTINE_NC_LOAD( pt16, cdna16, psgn16, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      !
+      CALL lbc_lnk_nc    ( cdname,               ptab_ptr, cdna_ptr, psgn_ptr, kfld, kfillmode, pfillval, lsend, lrecv, ncsten )
+      !
+   END SUBROUTINE ROUTINE_MULTI_NC
+
+
+   SUBROUTINE ROUTINE_NC_LOAD( ptab, cdna, psgn, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      !!---------------------------------------------------------------------
+      ARRAY_TYPE(:,:,:,:)   , TARGET, INTENT(inout) ::   ptab       ! arrays on which the lbc is applied
+      CHARACTER(len=1)              , INTENT(in   ) ::   cdna       ! nature of pt2d array grid-points
+      REAL(wp)                      , INTENT(in   ) ::   psgn       ! sign used across the north fold boundary
+      PTR_TYPE        , DIMENSION(:), INTENT(inout) ::   ptab_ptr   ! array of pointers
+      CHARACTER(len=1), DIMENSION(:), INTENT(inout) ::   cdna_ptr   ! nature of pt2d_array array grid-points
+      REAL(wp)        , DIMENSION(:), INTENT(inout) ::   psgn_ptr   ! sign used across the north fold boundary
+      INTEGER                       , INTENT(inout) ::   kfld       ! number of elements that has been attributed
+      !!---------------------------------------------------------------------
+      !
+      kfld                    =  kfld + 1
+      ptab_ptr(kfld)%PTR_ptab => ptab
+      cdna_ptr(kfld)          =  cdna
+      psgn_ptr(kfld)          =  psgn
+      !
+   END SUBROUTINE ROUTINE_NC_LOAD
+
+#undef PRECISION
+#undef ARRAY_TYPE
+#undef PTR_TYPE
+#undef PTR_ptab
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbclnk.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbclnk.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lbclnk.F90	(revision 14055)
@@ -39,4 +39,12 @@
       MODULE PROCEDURE   lbc_lnk_2d_multi_dp , lbc_lnk_3d_multi_dp, lbc_lnk_4d_multi_dp
    END INTERFACE
+   INTERFACE lbc_lnk_nc_multi
+      MODULE PROCEDURE   lbc_lnk_nc_2d_sp, lbc_lnk_nc_3d_sp, lbc_lnk_nc_4d_sp
+      MODULE PROCEDURE   lbc_lnk_nc_2d_dp, lbc_lnk_nc_3d_dp, lbc_lnk_nc_4d_dp
+   END INTERFACE
+   INTERFACE lbc_lnk_nc
+      MODULE PROCEDURE   mpp_lnk_nc_2d_sp, mpp_lnk_nc_3d_sp, mpp_lnk_nc_4d_sp
+      MODULE PROCEDURE   mpp_lnk_nc_2d_dp, mpp_lnk_nc_3d_dp, mpp_lnk_nc_4d_dp
+   END INTERFACE
    !
    INTERFACE lbc_lnk_icb
@@ -52,7 +60,9 @@
    END INTERFACE
 
-   PUBLIC   lbc_lnk       ! ocean/ice lateral boundary conditions
-   PUBLIC   lbc_lnk_multi ! modified ocean/ice lateral boundary conditions
-   PUBLIC   lbc_lnk_icb   ! iceberg lateral boundary conditions
+   PUBLIC   lbc_lnk            ! ocean/ice lateral boundary conditions
+   PUBLIC   lbc_lnk_multi      ! modified ocean/ice lateral boundary conditions
+   PUBLIC   lbc_lnk_icb        ! iceberg lateral boundary conditions
+   PUBLIC   lbc_lnk_nc         ! ocean/ice lateral boundary conditions (MPI3 version)
+   PUBLIC   lbc_lnk_nc_multi   ! modified ocean/ice lateral boundary conditions (MPI3 version)
 
 #if   defined key_mpp_mpi
@@ -250,4 +260,146 @@
 #  undef DIM_4d
 
+   !!----------------------------------------------------------------------
+   !!                   ***   load_ptr_(2,3,4)d   ***
+   !!
+   !!   * Dummy Argument :
+   !!       in    ==>   ptab       ! array to be loaded (2D, 3D or 4D)
+   !!                   cd_nat     ! nature of pt2d array grid-points
+   !!                   psgn       ! sign used across the north fold boundary
+   !!       inout <=>   ptab_ptr   ! array of 2D, 3D or 4D pointers
+   !!                   cdna_ptr   ! nature of ptab array grid-points
+   !!                   psgn_ptr   ! sign used across the north fold boundary
+   !!                   kfld       ! number of elements that has been attributed
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!                  ***   lbc_lnk_nc(2,3,4)d_multi   ***
+   !!                     ***   load_ptr_(2,3,4)d   ***
+   !!
+   !!   * Argument : dummy argument use in lbc_lnk_nc_multi_... routines
+   !!
+   !!----------------------------------------------------------------------
+
+   !!
+   !!   ----   SINGLE PRECISION VERSIONS
+   !!
+#  define SINGLE_PRECISION
+#  define DIM_2d
+#     define ROUTINE_NC_LOAD           load_ptr_nc_2d_sp
+#     define ROUTINE_MULTI_NC          lbc_lnk_nc_2d_sp
+#     include "lbc_lnk_nc_generic.h90"
+#     undef ROUTINE_MULTI_NC
+#     undef ROUTINE_NC_LOAD
+#  undef DIM_2d
+
+#  define DIM_3d
+#     define ROUTINE_NC_LOAD           load_ptr_nc_3d_sp
+#     define ROUTINE_MULTI_NC          lbc_lnk_nc_3d_sp
+#     include "lbc_lnk_nc_generic.h90"
+#     undef ROUTINE_MULTI_NC
+#     undef ROUTINE_NC_LOAD
+#  undef DIM_3d
+
+#  define DIM_4d
+#     define ROUTINE_NC_LOAD           load_ptr_nc_4d_sp
+#     define ROUTINE_MULTI_NC          lbc_lnk_nc_4d_sp
+#     include "lbc_lnk_nc_generic.h90"
+#     undef ROUTINE_MULTI_NC
+#     undef ROUTINE_NC_LOAD
+#  undef DIM_4d
+#  undef SINGLE_PRECISION
+   !!
+   !!   ----   DOUBLE PRECISION VERSIONS
+   !!
+
+#  define DIM_2d
+#     define ROUTINE_NC_LOAD           load_ptr_nc_2d_dp
+#     define ROUTINE_MULTI_NC          lbc_lnk_nc_2d_dp
+#     include "lbc_lnk_nc_generic.h90"
+#     undef ROUTINE_MULTI_NC
+#     undef ROUTINE_NC_LOAD
+#  undef DIM_2d
+
+#  define DIM_3d
+#     define ROUTINE_NC_LOAD           load_ptr_nc_3d_dp
+#     define ROUTINE_MULTI_NC          lbc_lnk_nc_3d_dp
+#     include "lbc_lnk_nc_generic.h90"
+#     undef ROUTINE_MULTI_NC
+#     undef ROUTINE_NC_LOAD
+#  undef DIM_3d
+
+#  define DIM_4d
+#     define ROUTINE_NC_LOAD           load_ptr_nc_4d_dp
+#     define ROUTINE_MULTI_NC          lbc_lnk_nc_4d_dp
+#     include "lbc_lnk_nc_generic.h90"
+#     undef ROUTINE_MULTI_NC
+#     undef ROUTINE_NC_LOAD
+#  undef DIM_4d
+
+   !!----------------------------------------------------------------------
+   !!                   ***  routine mpp_lnk_nc_(2,3,4)d  ***
+   !!
+   !!   * Argument : dummy argument use in mpp_lnk_... routines
+   !!                ptab      :   array or pointer of arrays on which the boundary condition is applied
+   !!                cd_nat    :   nature of array grid-points
+   !!                psgn      :   sign used across the north fold boundary
+   !!                kfld      :   optional, number of pt3d arrays
+   !!                kfillmode :   optional, method to be use to fill the halos (see jpfill* variables)
+   !!                pfillval  :   optional, background value (used with jpfillcopy)
+   !!----------------------------------------------------------------------
+   !
+   !                       !==  2D array and array of 2D pointer  ==!
+   !
+   !!
+   !!   ----   SINGLE PRECISION VERSIONS
+   !!
+# define SINGLE_PRECISION
+#  define DIM_2d
+#     define ROUTINE_NC           mpp_lnk_nc_2d_sp
+#     include "mpp_nc_generic.h90"
+#     undef ROUTINE_NC
+#  undef DIM_2d
+   !
+   !                       !==  3D array and array of 3D pointer  ==!
+   !
+#  define DIM_3d
+#     define ROUTINE_NC           mpp_lnk_nc_3d_sp
+#     include "mpp_nc_generic.h90"
+#     undef ROUTINE_NC
+#  undef DIM_3d
+   !
+   !                       !==  4D array and array of 4D pointer  ==!
+   !
+#  define DIM_4d
+#     define ROUTINE_NC           mpp_lnk_nc_4d_sp
+#     include "mpp_nc_generic.h90"
+#     undef ROUTINE_NC
+#  undef DIM_4d
+# undef SINGLE_PRECISION
+
+   !!
+   !!   ----   DOUBLE PRECISION VERSIONS
+   !!
+#  define DIM_2d
+#     define ROUTINE_NC           mpp_lnk_nc_2d_dp
+#     include "mpp_nc_generic.h90"
+#     undef ROUTINE_NC
+#  undef DIM_2d
+   !
+   !                       !==  3D array and array of 3D pointer  ==!
+   !
+#  define DIM_3d
+#     define ROUTINE_NC           mpp_lnk_nc_3d_dp
+#     include "mpp_nc_generic.h90"
+#     undef ROUTINE_NC
+#  undef DIM_3d
+   !
+   !                       !==  4D array and array of 4D pointer  ==!
+   !
+#  define DIM_4d
+#     define ROUTINE_NC           mpp_lnk_nc_4d_dp
+#     include "mpp_nc_generic.h90"
+#     undef ROUTINE_NC
+#  undef DIM_4d
 
    !!----------------------------------------------------------------------
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lib_mpp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lib_mpp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/lib_mpp.F90	(revision 14055)
@@ -66,4 +66,5 @@
    PUBLIC   mppscatter, mppgather
    PUBLIC   mpp_ini_znl
+   PUBLIC   mpp_ini_nc
    PUBLIC   mppsend, mpprecv                          ! needed by TAM and ICB routines
    PUBLIC   mppsend_sp, mpprecv_sp                          ! needed by TAM and ICB routines
@@ -137,4 +138,8 @@
    INTEGER         ::   ndim_rank_znl   !  number of processors on the same zonal average
    INTEGER, DIMENSION(:), ALLOCATABLE, SAVE ::   nrank_znl  ! dimension ndim_rank_znl, number of the procs into the same znl domain
+
+   ! variables used for MPI3 neighbourhood collectives
+   INTEGER, PUBLIC :: mpi_nc_com                   ! MPI3 neighbourhood collectives communicator
+   INTEGER, PUBLIC :: mpi_nc_all_com               ! MPI3 neighbourhood collectives communicator (with diagionals)
 
    ! North fold condition in mpp_mpi with jpni > 1 (PUBLIC for TAM)
@@ -1067,4 +1072,151 @@
 
    END SUBROUTINE mpp_ini_znl
+
+   SUBROUTINE mpp_ini_nc
+      !!----------------------------------------------------------------------
+      !!               ***  routine mpp_ini_nc  ***
+      !!
+      !! ** Purpose :   Initialize special communicators for MPI3 neighbourhood
+      !!                collectives
+      !!
+      !! ** Method  : - Create graph communicators starting from the processes   
+      !!                distribution along i and j directions
+      !
+      !! ** output
+      !!         mpi_nc_com = MPI3 neighbourhood collectives communicator
+      !!         mpi_nc_all_com = MPI3 neighbourhood collectives communicator
+      !!                          (with diagonals)
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(:), ALLOCATABLE :: ineigh, ineighalls, ineighallr
+      INTEGER :: ideg, idegalls, idegallr, icont, icont1
+      INTEGER :: ierr
+      LOGICAL, PARAMETER :: ireord = .FALSE.
+
+#if defined key_mpp_mpi
+
+      ideg = 0
+      idegalls = 0
+      idegallr = 0
+      icont = 0
+      icont1 = 0
+
+      IF (nbondi .eq. 1) THEN
+         ideg = ideg + 1
+      ELSEIF (nbondi .eq. -1) THEN
+         ideg = ideg + 1
+      ELSEIF (nbondi .eq. 0) THEN
+         ideg = ideg + 2
+      ENDIF
+
+      IF (nbondj .eq. 1) THEN
+         ideg = ideg + 1
+      ELSEIF (nbondj .eq. -1) THEN
+         ideg = ideg + 1
+      ELSEIF (nbondj .eq. 0) THEN
+         ideg = ideg + 2
+      ENDIF
+
+      idegalls = ideg
+      idegallr = ideg
+
+      IF (nones .ne. -1) idegalls = idegalls + 1
+      IF (nonws .ne. -1) idegalls = idegalls + 1
+      IF (noses .ne. -1) idegalls = idegalls + 1
+      IF (nosws .ne. -1) idegalls = idegalls + 1
+      IF (noner .ne. -1) idegallr = idegallr + 1
+      IF (nonwr .ne. -1) idegallr = idegallr + 1
+      IF (noser .ne. -1) idegallr = idegallr + 1
+      IF (noswr .ne. -1) idegallr = idegallr + 1
+
+      ALLOCATE(ineigh(ideg))
+      ALLOCATE(ineighalls(idegalls))
+      ALLOCATE(ineighallr(idegallr))
+
+      IF (nbondi .eq. 1) THEN
+         icont = icont + 1
+         ineigh(icont) = nowe
+         ineighalls(icont) = nowe
+         ineighallr(icont) = nowe
+      ELSEIF (nbondi .eq. -1) THEN
+         icont = icont + 1
+         ineigh(icont) = noea
+         ineighalls(icont) = noea
+         ineighallr(icont) = noea
+      ELSEIF (nbondi .eq. 0) THEN
+         icont = icont + 1
+         ineigh(icont) = nowe
+         ineighalls(icont) = nowe
+         ineighallr(icont) = nowe
+         icont = icont + 1
+         ineigh(icont) = noea
+         ineighalls(icont) = noea
+         ineighallr(icont) = noea
+      ENDIF
+
+      IF (nbondj .eq. 1) THEN
+         icont = icont + 1
+         ineigh(icont) = noso
+         ineighalls(icont) = noso
+         ineighallr(icont) = noso
+      ELSEIF (nbondj .eq. -1) THEN
+         icont = icont + 1
+         ineigh(icont) = nono
+         ineighalls(icont) = nono
+         ineighallr(icont) = nono
+      ELSEIF (nbondj .eq. 0) THEN
+         icont = icont + 1
+         ineigh(icont) = noso
+         ineighalls(icont) = noso
+         ineighallr(icont) = noso
+         icont = icont + 1
+         ineigh(icont) = nono
+         ineighalls(icont) = nono
+         ineighallr(icont) = nono
+      ENDIF
+
+      icont1 = icont
+      IF (nosws .ne. -1) THEN
+         icont = icont + 1
+         ineighalls(icont) = nosws
+      ENDIF
+      IF (noses .ne. -1) THEN
+         icont = icont + 1
+         ineighalls(icont) = noses
+      ENDIF
+      IF (nonws .ne. -1) THEN
+         icont = icont + 1
+         ineighalls(icont) = nonws
+      ENDIF
+      IF (nones .ne. -1) THEN
+         icont = icont + 1
+         ineighalls(icont) = nones
+      ENDIF
+      IF (noswr .ne. -1) THEN
+         icont1 = icont1 + 1
+         ineighallr(icont1) = noswr
+      ENDIF
+      IF (noser .ne. -1) THEN
+         icont1 = icont1 + 1
+         ineighallr(icont1) = noser
+      ENDIF
+      IF (nonwr .ne. -1) THEN
+         icont1 = icont1 + 1
+         ineighallr(icont1) = nonwr
+      ENDIF
+      IF (noner .ne. -1) THEN
+         icont1 = icont1 + 1
+         ineighallr(icont1) = noner
+      ENDIF
+
+      CALL MPI_Dist_graph_create_adjacent(mpi_comm_oce, ideg, ineigh, MPI_UNWEIGHTED, ideg, ineigh, MPI_UNWEIGHTED, MPI_INFO_NULL, ireord, mpi_nc_com, ierr)
+      CALL MPI_Dist_graph_create_adjacent(mpi_comm_oce, idegallr, ineighallr, MPI_UNWEIGHTED, idegalls, ineighalls, MPI_UNWEIGHTED, MPI_INFO_NULL, ireord, mpi_nc_all_com, ierr)
+
+      DEALLOCATE (ineigh)
+      DEALLOCATE (ineighalls)
+      DEALLOCATE (ineighallr)
+#endif
+   END SUBROUTINE mpp_ini_nc
+
 
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mpp_lnk_generic.h90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mpp_lnk_generic.h90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mpp_lnk_generic.h90	(revision 14055)
@@ -72,8 +72,8 @@
 
 #if defined MULTI
-   SUBROUTINE ROUTINE_LNK( cdname, ptab, cd_nat, psgn, kfld, kfillmode, pfillval, lsend, lrecv )
+   SUBROUTINE ROUTINE_LNK( cdname, ptab, cd_nat, psgn, kfld, kfillmode, pfillval, lsend, lrecv, ncsten )
       INTEGER             , INTENT(in   ) ::   kfld        ! number of pt3d arrays
 #else
-   SUBROUTINE ROUTINE_LNK( cdname, ptab, cd_nat, psgn      , kfillmode, pfillval, lsend, lrecv )
+   SUBROUTINE ROUTINE_LNK( cdname, ptab, cd_nat, psgn      , kfillmode, pfillval, lsend, lrecv, ncsten )
 #endif
       ARRAY_TYPE(:,:,:,:,:)                                        ! array or pointer of arrays on which the boundary condition is applied
@@ -84,4 +84,5 @@
       REAL(wp),             OPTIONAL, INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
       LOGICAL, DIMENSION(4),OPTIONAL, INTENT(in   ) ::   lsend, lrecv  ! communication with other 4 proc
+      LOGICAL,              OPTIONAL, INTENT(in   ) ::   ncsten      ! 5-point or 9-point stencil
       !
       INTEGER  ::    ji,  jj,  jk,  jl,  jf      ! dummy loop indices
@@ -100,4 +101,12 @@
       !!----------------------------------------------------------------------
       !
+#if defined key_mpi3
+#   if defined MULTI
+      CALL lbc_lnk_nc    ( cdname,  ptab, cd_nat, psgn, kfld, kfillmode, pfillval, lsend, lrecv, ncsten )
+#   else
+      CALL lbc_lnk_nc_multi(cdname, ptab, cd_nat, psgn, kfillmode=kfillmode, pfillval=pfillval, lsend=lsend, lrecv=lrecv, ncsten=ncsten)
+#   endif
+#else
+
       ! ----------------------------------------- !
       !     0. local variables initialization     !
@@ -387,4 +396,5 @@
       IF( llrecv_no )   DEALLOCATE( zrcv_no )
       !
+#endif
    END SUBROUTINE ROUTINE_LNK
 #undef PRECISION
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mpp_nc_generic.h90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mpp_nc_generic.h90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mpp_nc_generic.h90	(revision 14055)
@@ -0,0 +1,950 @@
+#   define NAT_IN(k)                cd_nat(k)   
+#   define SGN_IN(k)                psgn(k)
+#   define F_SIZE(ptab)             kfld
+#   define OPT_K(k)                 ,ipf
+#   if defined DIM_2d
+#      if defined SINGLE_PRECISION
+#         define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_2D_sp)                , INTENT(inout) ::   ptab(f)
+#      else
+#         define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_2D_dp)                , INTENT(inout) ::   ptab(f)
+#      endif
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt2d(i,j)
+#      define K_SIZE(ptab)             1
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_3d
+#      if defined SINGLE_PRECISION
+#         define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_3D_sp)                , INTENT(inout) ::   ptab(f)
+#      else
+#         define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_3D_dp)                , INTENT(inout) ::   ptab(f)
+#      endif
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt3d(i,j,k)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt3d,3)
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_4d
+#      if defined SINGLE_PRECISION
+#         define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_4D_sp)                , INTENT(inout) ::   ptab(f)
+#      else
+#         define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_4D_dp)                , INTENT(inout) ::   ptab(f)
+#      endif
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt4d(i,j,k,l)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt4d,3)
+#      define L_SIZE(ptab)             SIZE(ptab(1)%pt4d,4)
+#   endif
+#   if defined SINGLE_PRECISION
+#      define PRECISION sp
+#      define MPI_TYPE MPI_REAL
+#   else
+#      define PRECISION dp
+#      define MPI_TYPE MPI_DOUBLE_PRECISION
+#   endif
+
+   SUBROUTINE ROUTINE_NC( cdname, ptab, cd_nat, psgn, kfld, kfillmode, pfillval, lsend, lrecv, ncsten )
+      INTEGER             , INTENT(in   ) ::   kfld        ! number of pt3d arrays
+      ARRAY_TYPE(:,:,:,:,:)                                        ! array or pointer of arrays on which the boundary condition is applied
+      CHARACTER(len=*)              , INTENT(in   ) ::   cdname      ! name of the calling subroutine
+      CHARACTER(len=1)              , INTENT(in   ) ::   NAT_IN(:)   ! nature of array grid-points
+      REAL(wp)                      , INTENT(in   ) ::   SGN_IN(:)   ! sign used across the north fold boundary
+      INTEGER ,             OPTIONAL, INTENT(in   ) ::   kfillmode   ! filling method for halo over land (default = constant)
+      REAL(wp),             OPTIONAL, INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
+      LOGICAL, DIMENSION(4),OPTIONAL, INTENT(in   ) ::   lsend, lrecv  ! communication with other 4 proc
+      LOGICAL,              OPTIONAL, INTENT(in   ) ::   ncsten      ! 5-point or 9-point stencil
+      !
+      INTEGER  ::   ji,  jj,  jk,  jl,  jf                                      ! dummy loop indices
+      INTEGER  ::   ipi, ipj, ipk, ipl, ipf                                     ! dimension of the input array
+      INTEGER  ::   ishift, ishift2, idx, icount, icount1                       ! local integers
+      INTEGER  ::   idims, idimr, isizet, isizets, isizetr, izsnd, izrcv        ! local integers
+      INTEGER  ::   ierr
+      INTEGER  ::   ifill_we, ifill_ea, ifill_so, ifill_no
+      INTEGER  ::   ifill_web, ifill_eab
+      REAL(wp) ::   zland
+      INTEGER , DIMENSION(MPI_STATUS_SIZE)                        ::   istate              ! for mpi_isend
+      REAL(PRECISION), DIMENSION(:), ALLOCATABLE                  ::   zsnd, zrcv          ! halos arrays
+      INTEGER , DIMENSION(:), ALLOCATABLE                         ::   isizes              ! number of elements to be sent
+      INTEGER , DIMENSION(:), ALLOCATABLE                         ::   isizer              ! number of elements to be received
+      INTEGER , DIMENSION(:), ALLOCATABLE                         ::   idatatys, idatatyr  ! datatype of halos arrays
+      INTEGER (KIND=MPI_ADDRESS_KIND), DIMENSION (:), ALLOCATABLE ::   idispls, idisplr    ! displacement in halos arrays
+      LOGICAL  ::   llsend_we, llsend_ea, llsend_no, llsend_so       ! communication send
+      LOGICAL  ::   llrecv_we, llrecv_ea, llrecv_no, llrecv_so       ! communication receive 
+      LOGICAL  ::   lldo_nfd                                         ! do north pole folding
+      LOGICAL  ::   llncall                                          ! default: 9-point stencil
+
+      !!----------------------------------------------------------------------
+      !
+      ! ----------------------------------------- !
+      !     0. local variables initialization     !
+      ! ----------------------------------------- !
+      !
+      llncall = .TRUE. 
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      ipl = L_SIZE(ptab)   ! 4th    -
+      ipf = F_SIZE(ptab)   ! 5th    -      use in "multi" case (array of pointers)
+      !
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, ipk, ipl, ipf, ld_lbc = .TRUE. )
+      !
+      IF     ( PRESENT(lsend) .AND. PRESENT(lrecv) ) THEN
+         llsend_we = lsend(1)   ;   llsend_ea = lsend(2)   ;   llsend_so = lsend(3)   ;   llsend_no = lsend(4)
+         llrecv_we = lrecv(1)   ;   llrecv_ea = lrecv(2)   ;   llrecv_so = lrecv(3)   ;   llrecv_no = lrecv(4)
+      ELSE IF( PRESENT(lsend) .OR.  PRESENT(lrecv) ) THEN
+         WRITE(ctmp1,*) ' E R R O R : Routine ', cdname, '  is calling lbc_lnk with only one of the two arguments lsend or lrecv'
+         WRITE(ctmp2,*) ' ========== '
+         CALL ctl_stop( ' ', ctmp1, ctmp2, ' ' )
+      ELSE   ! send and receive with every neighbour
+         llsend_we = nbondi ==  1 .OR. nbondi == 0   ! keep for compatibility, should be defined in mppini
+         llsend_ea = nbondi == -1 .OR. nbondi == 0   ! keep for compatibility, should be defined in mppini
+         llsend_so = nbondj ==  1 .OR. nbondj == 0   ! keep for compatibility, should be defined in mppini
+         llsend_no = nbondj == -1 .OR. nbondj == 0   ! keep for compatibility, should be defined in mppini
+         llrecv_we = llsend_we   ;   llrecv_ea = llsend_ea   ;   llrecv_so = llsend_so   ;   llrecv_no = llsend_no
+      END IF
+         
+      lldo_nfd = npolj /= 0                      ! keep for compatibility, should be defined in mppini
+
+      zland = 0._wp                                     ! land filling value: zero by default
+      IF( PRESENT( pfillval ) )   zland = pfillval      ! set land value
+
+
+      ! define the method we will use to fill the halos in each direction
+      IF(              llrecv_we ) THEN   ;   ifill_we = jpfillmpi
+      ELSEIF(           l_Iperio ) THEN   ;   ifill_we = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_we = kfillmode
+      ELSE                                ;   ifill_we = jpfillcst
+      END IF
+      IF(               l_Iperio ) THEN   ;   ifill_web = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_web = kfillmode
+      ELSE                                ;   ifill_web = jpfillcst
+      END IF
+      !
+      IF(              llrecv_ea ) THEN   ;   ifill_ea = jpfillmpi
+      ELSEIF(           l_Iperio ) THEN   ;   ifill_ea = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_ea = kfillmode
+      ELSE                                ;   ifill_ea = jpfillcst
+      END IF
+      IF(               l_Iperio ) THEN   ;   ifill_eab = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_eab = kfillmode
+      ELSE                                ;   ifill_eab = jpfillcst
+      END IF
+      !
+      IF(              llrecv_so ) THEN   ;   ifill_so = jpfillmpi
+      ELSEIF(           l_Jperio ) THEN   ;   ifill_so = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_so = kfillmode
+      ELSE                                ;   ifill_so = jpfillcst
+      END IF
+      !
+      IF(              llrecv_no ) THEN   ;   ifill_no = jpfillmpi
+      ELSEIF(           l_Jperio ) THEN   ;   ifill_no = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_no = kfillmode
+      ELSE                                ;   ifill_no = jpfillcst
+      END IF
+      !
+      IF(PRESENT(ncsten)) llncall = ncsten 
+#if defined PRINT_CAUTION
+      !
+      ! ================================================================================== !
+      ! CAUTION: semi-column notation is often impossible because of the cpp preprocessing !
+      ! ================================================================================== !
+      !
+#endif
+      !
+      ! -------------------------------------------------- !
+      !     1. Do west, east, south and north MPI exchange !
+      ! -------------------------------------------------- !
+      !
+      ! Allocate local temporary arrays to be sent/received. Fill arrays to be sent
+
+      idims = 0
+      idimr = 0
+      izsnd = 0
+      izrcv = 0
+
+      IF(llsend_we) idims = idims + 1
+      IF(llsend_ea) idims = idims + 1
+      IF(llsend_so) idims = idims + 1
+      IF(llsend_no) idims = idims + 1
+
+      idimr = idims
+
+      IF(llncall) THEN
+         IF(noswr .ne. -1) idimr = idimr + 1
+         IF(noser .ne. -1) idimr = idimr + 1
+         IF(nonwr .ne. -1) idimr = idimr + 1
+         IF(noner .ne. -1) idimr = idimr + 1
+      
+         IF(nosws .ne. -1) idims = idims + 1
+         IF(noses .ne. -1) idims = idims + 1
+         IF(nonws .ne. -1) idims = idims + 1
+         IF(nones .ne. -1) idims = idims + 1
+      END IF
+
+      IF(llsend_we) izsnd = izsnd + nn_hls * (jpj - 2*nn_hls) * ipk * ipl * ipf
+      IF(llsend_ea) izsnd = izsnd + nn_hls * (jpj - 2*nn_hls) * ipk * ipl * ipf
+      IF(llsend_so) izsnd = izsnd + (jpi - 2*nn_hls) * nn_hls * ipk * ipl * ipf
+      IF(llsend_no) izsnd = izsnd + (jpi - 2*nn_hls) * nn_hls * ipk * ipl * ipf
+
+      izrcv = izsnd
+      
+      IF(llncall) THEN
+         IF(noswr .ne. -1) izrcv = izrcv + nn_hls * nn_hls * ipk * ipl * ipf
+         IF(noser .ne. -1) izrcv = izrcv + nn_hls * nn_hls * ipk * ipl * ipf
+         IF(nonwr .ne. -1) izrcv = izrcv + nn_hls * nn_hls * ipk * ipl * ipf
+         IF(noner .ne. -1) izrcv = izrcv + nn_hls * nn_hls * ipk * ipl * ipf
+
+         IF(nosws .ne. -1) izsnd = izsnd + nn_hls * nn_hls * ipk * ipl * ipf
+         IF(noses .ne. -1) izsnd = izsnd + nn_hls * nn_hls * ipk * ipl * ipf
+         IF(nonws .ne. -1) izsnd = izsnd + nn_hls * nn_hls * ipk * ipl * ipf
+         IF(nones .ne. -1) izsnd = izsnd + nn_hls * nn_hls * ipk * ipl * ipf
+      END IF
+
+      ALLOCATE(zsnd(izsnd))
+      ALLOCATE(zrcv(izrcv))
+      ALLOCATE(isizes(idims))
+      ALLOCATE(isizer(idimr))
+      ALLOCATE(idatatys(idims))
+      ALLOCATE(idatatyr(idimr))
+      ALLOCATE(idispls(idims))
+      ALLOCATE(idisplr(idimr))
+
+      zrcv(:)=-1
+      zsnd(:)=-1
+      isizes(:) = 0
+      isizer(:) = 0
+      idispls(:) = 0
+      idisplr(:) = 0
+      isizet = 0 
+     
+      idx = 1
+      icount = 1
+
+      IF(llsend_we) THEN
+         DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = nn_hls + 1, jpj - nn_hls  ;  DO ji = 1, nn_hls
+            zsnd(idx) = ARRAY_IN(nn_hls+ji,jj,jk,jl,jf)
+            idx = idx + 1
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+         isizes(icount) = nn_hls * (jpj - 2*nn_hls) * ipk * ipl * ipf
+         IF(icount .gt. 1) isizet = isizet + isizes(icount - 1)
+         idispls(icount) = jpbyt*isizet
+         icount = icount + 1
+      END IF
+
+      IF(llsend_ea) THEN
+         ishift = jpi-2*nn_hls
+
+         DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = nn_hls + 1, jpj - nn_hls  ;  DO ji = 1, nn_hls
+            zsnd(idx) = ARRAY_IN(ishift+ji,jj,jk,jl,jf)
+            idx = idx + 1
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+         isizes(icount) = nn_hls * (jpj - 2*nn_hls) * ipk * ipl * ipf
+         IF(icount .gt. 1) isizet = isizet + isizes(icount - 1)
+         idispls(icount) = jpbyt*isizet
+         icount = icount + 1
+      END IF
+
+      IF(llsend_so) THEN
+         DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = 1, nn_hls  ;  DO ji = nn_hls + 1, jpi - nn_hls
+            zsnd(idx) = ARRAY_IN(ji,nn_hls+jj,jk,jl,jf)
+            idx = idx + 1
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+         isizes(icount) = (jpi - 2*nn_hls) * nn_hls * ipk * ipl * ipf
+         IF(icount .gt. 1) isizet = isizet + isizes(icount - 1)
+         idispls(icount) = jpbyt*isizet
+         icount = icount + 1
+      END IF
+
+      IF(llsend_no) THEN
+         ishift = jpj-2*nn_hls
+
+         DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = 1, nn_hls  ;  DO ji = nn_hls + 1, jpi - nn_hls
+            zsnd(idx) = ARRAY_IN(ji,ishift+jj,jk,jl,jf)
+            idx = idx + 1
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+         isizes(icount) = (jpi - 2*nn_hls) * nn_hls * ipk * ipl * ipf
+         IF(icount .gt. 1) isizet = isizet + isizes(icount - 1)
+         idispls(icount) = jpbyt*isizet
+         icount = icount + 1
+      END IF
+
+      isizer(:) = isizes(:)
+      idisplr(:) = idispls(:)
+      
+      icount1 = icount
+      isizets = isizet 
+      isizetr = isizet 
+
+      IF(llncall) THEN
+         IF(noswr .ne. -1) THEN
+            isizer(icount1) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount1 .gt. 1) isizetr = isizetr + isizer(icount1 - 1)
+            idisplr(icount1) = jpbyt*isizetr
+            icount1 = icount1 + 1
+         END IF
+         IF(noser .ne. -1) THEN
+            isizer(icount1) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount1 .gt. 1) isizetr = isizetr + isizer(icount1 - 1)
+            idisplr(icount1) = jpbyt*isizetr
+            icount1 = icount1 + 1
+         END IF
+         IF(nonwr .ne. -1) THEN
+            isizer(icount1) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount1 .gt. 1) isizetr = isizetr + isizer(icount1 - 1)
+            idisplr(icount1) = jpbyt*isizetr
+            icount1 = icount1 + 1
+         END IF
+         IF(noner .ne. -1) THEN
+            isizer(icount1) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount1 .gt. 1) isizetr = isizetr + isizer(icount1 - 1)
+            idisplr(icount1) = jpbyt*isizetr
+            icount1 = icount1 + 1
+         END IF
+
+         IF(nosws .ne. -1) THEN
+            DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = 1, nn_hls  ;  DO ji = 1, nn_hls
+               zsnd(idx) = ARRAY_IN(nn_hls+ji,nn_hls+jj,jk,jl,jf)
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+            isizes(icount) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount .gt. 1) isizets = isizets + isizes(icount - 1)
+            idispls(icount) = jpbyt*isizets
+            icount = icount + 1
+         END IF
+         IF(noses .ne. -1) THEN
+            ishift = jpi-2*nn_hls
+            DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = 1, nn_hls  ;  DO ji = 1, nn_hls
+               zsnd(idx) = ARRAY_IN(ji+ishift,nn_hls+jj,jk,jl,jf)
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+            isizes(icount) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount .gt. 1) isizets = isizets + isizes(icount - 1)
+            idispls(icount) = jpbyt*isizets
+            icount = icount + 1
+         END IF
+         IF(nonws .ne. -1) THEN
+            ishift = jpj-2*nn_hls
+            DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = 1, nn_hls  ;  DO ji = 1, nn_hls
+               zsnd(idx) = ARRAY_IN(nn_hls+ji,jj+ishift,jk,jl,jf)
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+            isizes(icount) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount .gt. 1) isizets = isizets + isizes(icount - 1)
+            idispls(icount) = jpbyt*isizets
+            icount = icount + 1
+         END IF
+         IF(nones .ne. -1) THEN
+            ishift = jpi-2*nn_hls
+            ishift2 = jpj-2*nn_hls
+            DO jf = 1, ipf  ;  DO jl = 1, ipl  ;  DO jk = 1, ipk  ;  DO jj = 1, nn_hls  ;  DO ji = 1, nn_hls
+               zsnd(idx) = ARRAY_IN(ji+ishift,jj+ishift2,jk,jl,jf)
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+            isizes(icount) = nn_hls * nn_hls * ipk * ipl * ipf
+            IF(icount .gt. 1) isizets = isizets + isizes(icount - 1)
+            idispls(icount) = jpbyt*isizets
+            icount = icount + 1
+         END IF
+      END IF
+
+      idatatys(:) = MPI_TYPE
+      idatatyr(:) = MPI_TYPE
+
+      IF(llncall) THEN
+         IF( ln_timing ) CALL tic_tac(.TRUE.)
+         CALL mpi_neighbor_alltoallw (zsnd, isizes, idispls, idatatys, zrcv, isizer, idisplr, idatatyr, mpi_nc_all_com, ierr)
+         IF( ln_timing ) CALL tic_tac(.FALSE.)
+      ELSE
+         IF( ln_timing ) CALL tic_tac(.TRUE.)
+         CALL mpi_neighbor_alltoallw (zsnd, isizes, idispls, idatatys, zrcv, isizer, idisplr, idatatyr, mpi_nc_com, ierr)
+         IF( ln_timing ) CALL tic_tac(.FALSE.)
+      END IF
+
+      ! --------------------------------------------------- !
+      !     2. Fill east and west north and south halos     !
+      ! --------------------------------------------------- !
+      !
+      !!! Patch to solve MPI3 bug when we have only two processes columns
+      IF(jpni .eq. 2) THEN
+         ! ---------------------
+         ! 2.2 fill eastern halo
+         ! ---------------------
+         idx = 1
+         ishift = jpi - nn_hls                ! fill halo from ji = jpi-nn_hls+1 to jpi
+         SELECT CASE ( ifill_ea )
+         CASE ( jpfillnothing )               ! no filling
+         CASE ( jpfillmpi   )                 ! use data received by MPI
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = nn_hls + 1, jpj - nn_hls   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zrcv(idx)   ! jpi - nn_hls + 1 -> jpi
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillperio )                 ! use east-weast periodicity
+            ishift2 = nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+         ! ----------------------
+         ! 2.1 fill weastern halo
+         ! ----------------------
+         SELECT CASE ( ifill_we )
+         CASE ( jpfillnothing )               ! no filling
+         CASE ( jpfillmpi   )                 ! use data received by MPI
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = nn_hls + 1, jpj - nn_hls   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)   ! 1 -> nn_hls
+               idx = idx + 1
+            END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillperio )                 ! use east-weast periodicity
+            ishift2 = jpi - 2 * nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(nn_hls+1,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+
+      ELSE
+
+         ! ----------------------
+         ! 2.1 fill weastern halo
+         ! ----------------------
+         idx = 1
+         SELECT CASE ( ifill_we )
+         CASE ( jpfillnothing )               ! no filling 
+         CASE ( jpfillmpi   )                 ! use data received by MPI 
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = nn_hls + 1, jpj - nn_hls   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)   ! 1 -> nn_hls
+               idx = idx + 1
+            END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillperio )                 ! use east-weast periodicity
+            ishift2 = jpi - 2 * nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(nn_hls+1,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+         ! ---------------------
+         ! 2.2 fill eastern halo
+         ! ---------------------
+         ishift = jpi - nn_hls                ! fill halo from ji = jpi-nn_hls+1 to jpi 
+         SELECT CASE ( ifill_ea )
+         CASE ( jpfillnothing )               ! no filling 
+         CASE ( jpfillmpi   )                 ! use data received by MPI 
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = nn_hls + 1, jpj - nn_hls   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zrcv(idx)   ! jpi - nn_hls + 1 -> jpi
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillperio )                 ! use east-weast periodicity
+            ishift2 = nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, nn_hls
+               ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+
+      ENDIF
+
+      !!! Patch to solve MPI3 bug when we have only two processes rows
+      IF(jpnj .eq. 2) THEN
+         ! ----------------------
+         ! 2.3 fill northern halo
+         ! ----------------------
+         ishift = jpj - nn_hls                ! fill halo from jj = jpj-nn_hls+1 to jpj 
+         SELECT CASE ( ifill_no )
+         CASE ( jpfillnothing )               ! no filling 
+         CASE ( jpfillmpi   )                 ! use data received by MPI 
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = nn_hls + 1, jpi - nn_hls
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = zrcv(idx)   ! jpj-nn_hls+1 -> jpj
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+            IF(nonwr .eq. -1) THEN
+               ishift = jpj - nn_hls
+               SELECT CASE ( ifill_web )
+                  CASE ( jpfillperio )
+                     ishift2 = jpi - 2 * nn_hls
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(nn_hls+1,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+            IF(noner .eq. -1) THEN
+               ishift = jpi - nn_hls
+               ishift2 = jpj - nn_hls
+               SELECT CASE ( ifill_eab )
+                  CASE ( jpfillperio )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift2, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ji,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift2, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift2, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+         CASE ( jpfillperio )                 ! use north-south periodicity
+            ishift2 = nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = ARRAY_IN(ji,ishift2+jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = ARRAY_IN(ji,ishift,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+
+         ! ----------------------
+         ! 2.4 fill southern halo
+         ! ----------------------
+         SELECT CASE ( ifill_so )
+         CASE ( jpfillnothing )               ! no filling 
+         CASE ( jpfillmpi   )                 ! use data received by MPI 
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = nn_hls + 1, jpi - nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)   ! 1 -> nn_hls
+               idx = idx + 1
+            END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+            IF(noswr .eq. -1) THEN
+               SELECT CASE ( ifill_web )
+                  CASE ( jpfillperio )
+                     ishift2 = jpi - 2 * nn_hls
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(nn_hls+1,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+            IF(noser .eq. -1) THEN
+               ishift = jpi - nn_hls
+               SELECT CASE ( ifill_eab )
+                  CASE ( jpfillperio )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ji+nn_hls,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+         CASE ( jpfillperio )                 ! use north-south periodicity
+            ishift2 = jpj - 2 * nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ji,ishift2+jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ji,nn_hls+1,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+      ELSE
+         ! ----------------------
+         ! 2.3 fill southern halo
+         ! ----------------------
+         SELECT CASE ( ifill_so )
+         CASE ( jpfillnothing )               ! no filling 
+         CASE ( jpfillmpi   )                 ! use data received by MPI 
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = nn_hls + 1, jpi - nn_hls
+               ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)   ! 1 -> nn_hls
+               idx = idx + 1
+            END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+            IF(noswr .eq. -1) THEN
+               SELECT CASE ( ifill_web )
+                  CASE ( jpfillperio )
+                     ishift2 = jpi - 2 * nn_hls
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(nn_hls+1,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+            IF(noser .eq. -1) THEN
+               ishift = jpi - nn_hls
+               SELECT CASE ( ifill_eab )
+                  CASE ( jpfillperio )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ji+nn_hls,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+         CASE ( jpfillperio )                 ! use north-south periodicity
+            ishift2 = jpj - 2 * nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ji,ishift2+jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ji,nn_hls+1,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+
+         ! ----------------------
+         ! 2.4 fill northern halo
+         ! ----------------------
+         ishift = jpj - nn_hls                ! fill halo from jj = jpj-nn_hls+1 to jpj 
+         SELECT CASE ( ifill_no )
+         CASE ( jpfillnothing )               ! no filling 
+         CASE ( jpfillmpi   )                 ! use data received by MPI 
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = nn_hls + 1, jpi - nn_hls
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = zrcv(idx)   ! jpj-nn_hls+1 -> jpj
+               idx = idx + 1
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+            IF(nonwr .eq. -1) THEN
+               ishift = jpj - nn_hls
+               SELECT CASE ( ifill_web )
+                  CASE ( jpfillperio )
+                     ishift2 = jpi - 2 * nn_hls
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(nn_hls+1,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+            IF(noner .eq. -1) THEN
+               ishift = jpi - nn_hls
+               ishift2 = jpj - nn_hls
+               SELECT CASE ( ifill_eab )
+                  CASE ( jpfillperio )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift2, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ji,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+
+                  CASE ( jpfillcopy  )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift2, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                  CASE ( jpfillcst   )
+                     DO jf = 1, ipf  ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1 + ishift2, jpj   ;  DO ji = 1, nn_hls
+                        ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+                     END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+               END SELECT
+            END IF
+         CASE ( jpfillperio )                 ! use north-south periodicity
+            ishift2 = nn_hls
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = ARRAY_IN(ji,ishift2+jj,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcopy  )                 ! filling with inner domain values
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = ARRAY_IN(ji,ishift,jk,jl,jf)
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         CASE ( jpfillcst   )                 ! filling with constant value
+            DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;   DO ji = 1, jpi
+               ARRAY_IN(ji,ishift+jj,jk,jl,jf) = zland
+            END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+         END SELECT
+      ENDIF
+
+      IF(llncall) THEN
+
+         !!! Patch to solve MPI3 bug when we have only two processes columns
+         IF(jpni .eq. 2) THEN
+            !!! Patch to solve MPI3 bug when we have only two processes rows
+            IF(jpnj .eq. 2) THEN
+               ! ---------------------------
+               ! 2.5 fill east-nouthern halo
+               ! ---------------------------
+                 IF(noner .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    ishift2 = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj+ishift2,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.6 fill west-nouthern halo
+               ! ---------------------------
+                 IF(nonwr .ne. -1) THEN
+                    ishift = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj+ishift,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.7 fill east-southern halo
+               ! ---------------------------
+                 IF(noser .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.8 fill west-southern halo
+               ! ---------------------------
+                 IF(noswr .ne. -1) THEN
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+
+            ELSE
+               ! ---------------------------
+               ! 2.5 fill east-southern halo
+               ! ---------------------------
+                 IF(noser .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.6 fill west-southern halo
+               ! ---------------------------
+                 IF(noswr .ne. -1) THEN
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.7 fill east-nouthern halo
+               ! ---------------------------
+                 IF(noner .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    ishift2 = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj+ishift2,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.8 fill west-nouthern halo
+               ! ---------------------------
+                 IF(nonwr .ne. -1) THEN
+                    ishift = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj+ishift,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+            ENDIF
+         ELSE
+            !!! Patch to solve MPI3 bug when we have only two processes rows
+            IF(jpnj .eq. 2) THEN
+               ! ---------------------------
+               ! 2.5 fill west-nouthern halo
+               ! ---------------------------
+                 IF(nonwr .ne. -1) THEN
+                    ishift = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj+ishift,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.6 fill east-nouthern halo
+               ! ---------------------------
+                 IF(noner .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    ishift2 = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj+ishift2,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.7 fill west-southern halo
+               ! ---------------------------
+                 IF(noswr .ne. -1) THEN
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.8 fill east-southern halo
+               ! ---------------------------
+                 IF(noser .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+
+            ELSE
+               ! ---------------------------
+               ! 2.5 fill west-southern halo
+               ! ---------------------------
+                 IF(noswr .ne. -1) THEN
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.6 fill east-southern halo
+               ! ---------------------------
+                 IF(noser .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.7 fill west-nouthern halo
+               ! ---------------------------
+                 IF(nonwr .ne. -1) THEN
+                    ishift = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji,jj+ishift,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+               ! ---------------------------
+               ! 2.8 fill east-nouthern halo
+               ! ---------------------------
+                 IF(noner .ne. -1) THEN
+                    ishift = jpi - nn_hls
+                    ishift2 = jpj - nn_hls
+                    DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, nn_hls   ;  DO ji = 1, nn_hls
+                       ARRAY_IN(ji+ishift,jj+ishift2,jk,jl,jf) = zrcv(idx)
+                       idx = idx + 1
+                    END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+                 END IF
+            ENDIF
+         END IF
+      END IF
+
+
+      !
+      ! -------------------------------------------- !
+      !     3. deallocate local temporary arrays     !
+      ! -------------------------------------------- !
+      !
+      DEALLOCATE( zsnd )
+      DEALLOCATE( zrcv )
+      DEALLOCATE(isizes)
+      DEALLOCATE(isizer)
+      DEALLOCATE(idatatys)
+      DEALLOCATE(idatatyr)
+      DEALLOCATE(idispls)
+      DEALLOCATE(idisplr)
+      !
+      ! ------------------------------- !
+      !     4. north fold treatment     !
+      ! ------------------------------- !
+      !
+      IF( lldo_nfd .AND. ifill_no /= jpfillnothing ) THEN
+         !
+         SELECT CASE ( jpni )
+         CASE ( 1 )     ;   CALL lbc_nfd( ptab, NAT_IN(:), SGN_IN(:)                  OPT_K(:) )   ! only 1 northern proc, no mpp
+         CASE DEFAULT   ;   CALL mpp_nfd( ptab, NAT_IN(:), SGN_IN(:), ifill_no, zland OPT_K(:) )   ! for all northern procs.
+         END SELECT
+         !
+         ifill_no = jpfillnothing  ! force to do nothing for the northern halo as we just done the north pole folding
+         !
+      ENDIF
+
+   END SUBROUTINE ROUTINE_NC
+
+#undef PRECISION
+#undef ARRAY_TYPE
+#undef NAT_IN
+#undef SGN_IN
+#undef ARRAY_IN
+#undef K_SIZE
+#undef L_SIZE
+#undef F_SIZE
+#undef OPT_K
+#undef MPI_TYPE
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mppini.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mppini.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LBC/mppini.F90	(revision 14055)
@@ -542,9 +542,4 @@
       ij = ijn(narea)
       !
-      ! set default neighbours
-      noso = ii_noso(narea)
-      nowe = ii_nowe(narea)
-      noea = ii_noea(narea)
-      nono = ii_nono(narea)
       jpi    = ijpi(ii,ij)  
 !!$      Nis0  = iis0(ii,ij)
@@ -558,4 +553,63 @@
       njmpp = ijmppt(ii,ij)
       jpk = jpkglo                              ! third dim
+
+      ! set default neighbours
+      noso = ii_noso(narea)
+      nowe = ii_nowe(narea)
+      noea = ii_noea(narea)
+      nono = ii_nono(narea)
+
+      nones = -1
+      nonws = -1
+      noses = -1
+      nosws = -1
+      
+      noner = -1
+      nonwr = -1
+      noser = -1
+      noswr = -1
+
+      IF((nbondi .eq. -1) .or. (nbondi .eq. 0)) THEN ! east neighbour exists
+         IF(ibondj(iin(noea+1),ijn(noea+1)) .eq. 0) THEN
+            nones = ii_nono(noea+1)                  ! east neighbour has north and south neighbours
+            noses = ii_noso(noea+1)
+         ELSEIF(ibondj(iin(noea+1),ijn(noea+1)) .eq. -1) THEN
+            nones = ii_nono(noea+1)                  ! east neighbour has north neighbour
+         ELSEIF(ibondj(iin(noea+1),ijn(noea+1)) .eq. 1) THEN
+            noses = ii_noso(noea+1)                  ! east neighbour has south neighbour
+         END IF
+      END IF
+      IF((nbondi .eq. 1) .or. (nbondi .eq. 0)) THEN  ! west neighbour exists
+         IF(ibondj(iin(nowe+1),ijn(nowe+1)) .eq. 0) THEN
+            nonws = ii_nono(nowe+1)                  ! west neighbour has north and south neighbours
+            nosws = ii_noso(nowe+1)
+         ELSEIF(ibondj(iin(nowe+1),ijn(nowe+1)) .eq. -1) THEN
+            nonws = ii_nono(nowe+1)                  ! west neighbour has north neighbour
+         ELSEIF(ibondj(iin(nowe+1),ijn(nowe+1)) .eq. 1)  THEN
+            nosws = ii_noso(nowe+1)                  ! west neighbour has north neighbour
+         END IF
+      END IF
+
+      IF((nbondj .eq. -1) .or. (nbondj .eq. 0)) THEN ! north neighbour exists
+         IF(ibondi(iin(nono+1),ijn(nono+1)) .eq. 0) THEN
+            noner = ii_noea(nono+1)                  ! north neighbour has east and west neighbours
+            nonwr = ii_nowe(nono+1)
+         ELSEIF(ibondi(iin(nono+1),ijn(nono+1)) .eq. -1) THEN
+            noner = ii_noea(nono+1)                  ! north neighbour has east neighbour
+         ELSEIF(ibondi(iin(nono+1),ijn(nono+1)) .eq. 1) THEN
+            nonwr = ii_nowe(nono+1)                  ! north neighbour has west neighbour
+         END IF
+      END IF
+      IF((nbondj .eq. 1) .or. (nbondj .eq. 0)) THEN  ! south neighbour exists
+         IF(ibondi(iin(noso+1),ijn(noso+1)) .eq. 0) THEN
+            noser = ii_noea(noso+1)                  ! south neighbour has east and west neighbours
+            noswr = ii_nowe(noso+1)
+         ELSEIF(ibondi(iin(noso+1),ijn(noso+1)) .eq. -1) THEN
+            noser = ii_noea(noso+1)                  ! south neighbour has east neighbour
+         ELSEIF(ibondi(iin(noso+1),ijn(noso+1)) .eq. 1) THEN
+            noswr = ii_nowe(noso+1)                  ! south neighbour has west neighbour
+         END IF
+      END IF
+
       !
       CALL init_doloop                          ! set start/end indices of do-loop, depending on the halo width value (nn_hls) 
@@ -648,4 +702,7 @@
          ENDIF
       ENDIF
+
+      !
+      CALL mpp_ini_nc        ! Initialize communicator for neighbourhood collective communications
       !
       CALL init_ioipsl       ! Prepare NetCDF output file (if necessary)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LDF/ldfc1d_c2d.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LDF/ldfc1d_c2d.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LDF/ldfc1d_c2d.F90	(revision 14055)
@@ -140,5 +140,6 @@
          END_2D
       CASE( 'TRA' )                       ! U- and V-points
-         DO_2D( 1, 1, 1, 1 )
+         ! NOTE: [tiling-comms-merge] Change needed to preserve results with respect to the trunk
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
             pah1(ji,jj,1) = pUfac * MAX( e1u(ji,jj), e2u(ji,jj) )**knn
             pah2(ji,jj,1) = pUfac * MAX( e1v(ji,jj), e2v(ji,jj) )**knn
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LDF/ldftra.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LDF/ldftra.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/LDF/ldftra.F90	(revision 14055)
@@ -427,5 +427,6 @@
          zaht_min = 0.2_wp * aht0                                       ! minimum value for aht
          zDaht    = aht0 - zaht_min                                      
-         DO_2D( 1, 1, 1, 1 )
+         ! NOTE: [tiling-comms-merge] Change needed to preserve results with respect to the trunk
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
             !!gm CAUTION : here we assume lat/lon grid in 20deg N/S band (like all ORCA cfg)
             !!     ==>>>   The Coriolis value is identical for t- & u_points, and for v- and f-points
@@ -725,22 +726,24 @@
       !! ** Action  : pu, pv increased by the eiv transport
       !!----------------------------------------------------------------------
-      INTEGER                         , INTENT(in   ) ::   kt        ! ocean time-step index
-      INTEGER                         , INTENT(in   ) ::   kit000    ! first time step index
-      INTEGER                         , INTENT(in   ) ::   Kmm, Krhs ! ocean time level indices
-      CHARACTER(len=3)                , INTENT(in   ) ::   cdtype    ! =TRA or TRC (tracer indicator)
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pu      ! in : 3 ocean transport components   [m3/s]
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pv      ! out: 3 ocean transport components   [m3/s]
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pw      ! increased by the eiv                [m3/s]
+      INTEGER                     , INTENT(in   ) ::   kt        ! ocean time-step index
+      INTEGER                     , INTENT(in   ) ::   kit000    ! first time step index
+      INTEGER                     , INTENT(in   ) ::   Kmm, Krhs ! ocean time level indices
+      CHARACTER(len=3)            , INTENT(in   ) ::   cdtype    ! =TRA or TRC (tracer indicator)
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   pu        ! in : 3 ocean transport components   [m3/s]
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   pv        ! out: 3 ocean transport components   [m3/s]
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   pw        ! increased by the eiv                [m3/s]
       !!
       INTEGER  ::   ji, jj, jk                 ! dummy loop indices
       REAL(wp) ::   zuwk, zuwk1, zuwi, zuwi1   ! local scalars
       REAL(wp) ::   zvwk, zvwk1, zvwj, zvwj1   !   -      -
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zpsi_uw, zpsi_vw
-      !!----------------------------------------------------------------------
-      !
-      IF( kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'ldf_eiv_trp : eddy induced advection on ', cdtype,' :'
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   add to velocity fields the eiv component'
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zpsi_uw, zpsi_vw
+      !!----------------------------------------------------------------------
+      !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'ldf_eiv_trp : eddy induced advection on ', cdtype,' :'
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   add to velocity fields the eiv component'
+         ENDIF
       ENDIF
 
@@ -781,11 +784,11 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   psi_uw, psi_vw   ! streamfunction   [m3/s]
-      INTEGER                         , INTENT(in   ) ::   Kmm   ! ocean time level indices
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   psi_uw, psi_vw   ! streamfunction   [m3/s]
+      INTEGER                     , INTENT(in   ) ::   Kmm   ! ocean time level indices
       !
       INTEGER  ::   ji, jj, jk    ! dummy loop indices
       REAL(wp) ::   zztmp   ! local scalar
-      REAL(wp), DIMENSION(jpi,jpj)     ::   zw2d   ! 2D workspace
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zw3d   ! 3D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls))     ::   zw2d   ! 2D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zw3d   ! 3D workspace
       !!----------------------------------------------------------------------
       !
@@ -793,6 +796,4 @@
 !!gm     to be redesigned....   
       !                                                  !==  eiv stream function: output  ==!
-      CALL lbc_lnk_multi( 'ldftra', psi_uw, 'U', -1.0_wp , psi_vw, 'V', -1.0_wp )
-      !
 !!gm      CALL iom_put( "psi_eiv_uw", psi_uw )                 ! output
 !!gm      CALL iom_put( "psi_eiv_vw", psi_vw )
@@ -802,12 +803,12 @@
       zw3d(:,:,jpk) = 0._wp                                    ! bottom value always 0
       !
-      DO jk = 1, jpkm1                                         ! e2u e3u u_eiv = -dk[psi_uw]
-         zw3d(:,:,jk) = ( psi_uw(:,:,jk+1) - psi_uw(:,:,jk) ) / ( e2u(:,:) * e3u(:,:,jk,Kmm) )
-      END DO
+      DO_3D( 0, 0, 0, 0, 1, jpkm1 )                                  ! e2u e3u u_eiv = -dk[psi_uw]
+         zw3d(ji,jj,jk) = ( psi_uw(ji,jj,jk+1) - psi_uw(ji,jj,jk) ) / ( e2u(ji,jj) * e3u(ji,jj,jk,Kmm) )
+      END_3D
       CALL iom_put( "uoce_eiv", zw3d )
       !
-      DO jk = 1, jpkm1                                         ! e1v e3v v_eiv = -dk[psi_vw]
-         zw3d(:,:,jk) = ( psi_vw(:,:,jk+1) - psi_vw(:,:,jk) ) / ( e1v(:,:) * e3v(:,:,jk,Kmm) )
-      END DO
+      DO_3D( 0, 0, 0, 0, 1, jpkm1 )                                  ! e1v e3v v_eiv = -dk[psi_vw]
+         zw3d(ji,jj,jk) = ( psi_vw(ji,jj,jk+1) - psi_vw(ji,jj,jk) ) / ( e1v(ji,jj) * e3v(ji,jj,jk,Kmm) )
+      END_3D
       CALL iom_put( "voce_eiv", zw3d )
       !
@@ -816,9 +817,10 @@
             &              + psi_uw(ji,jj,jk) - psi_uw(ji-1,jj  ,jk)  ) / e1e2t(ji,jj)
       END_3D
-      CALL lbc_lnk( 'ldftra', zw3d, 'T', 1.0_wp )      ! lateral boundary condition
       CALL iom_put( "woce_eiv", zw3d )
       !
       IF( iom_use('weiv_masstr') ) THEN   ! vertical mass transport & its square value
-         zw2d(:,:) = rho0 * e1e2t(:,:)
+         DO_2D( 0, 0, 0, 0 )
+            zw2d(ji,jj) = rho0 * e1e2t(ji,jj)
+         END_2D
          DO jk = 1, jpk
             zw3d(:,:,jk) = zw3d(:,:,jk) * zw2d(:,:)
@@ -844,6 +846,4 @@
            zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
         END_3D
-        CALL lbc_lnk( 'ldftra', zw2d, 'U', -1.0_wp )
-        CALL lbc_lnk( 'ldftra', zw3d, 'U', -1.0_wp )
         CALL iom_put( "ueiv_heattr"  , zztmp * zw2d )                  ! heat transport in i-direction
         CALL iom_put( "ueiv_heattr3d", zztmp * zw3d )                  ! heat transport in i-direction
@@ -865,7 +865,6 @@
          zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
       END_3D
-      CALL lbc_lnk( 'ldftra', zw2d, 'V', -1.0_wp )
-      CALL iom_put( "veiv_heattr", zztmp * zw2d )                  !  heat transport in j-direction
-      CALL iom_put( "veiv_heattr", zztmp * zw3d )                  !  heat transport in j-direction
+      CALL iom_put( "veiv_heattr"  , zztmp * zw2d )                  !  heat transport in j-direction
+      CALL iom_put( "veiv_heattr3d", zztmp * zw3d )                  !  heat transport in j-direction
       !
       IF( iom_use( 'sophteiv' ) )   CALL dia_ptr_hst( jp_tem, 'eiv', 0.5 * zw3d )
@@ -880,6 +879,4 @@
            zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
         END_3D
-        CALL lbc_lnk( 'ldftra', zw2d, 'U', -1.0_wp )
-        CALL lbc_lnk( 'ldftra', zw3d, 'U', -1.0_wp )
         CALL iom_put( "ueiv_salttr", zztmp * zw2d )                  ! salt transport in i-direction
         CALL iom_put( "ueiv_salttr3d", zztmp * zw3d )                ! salt transport in i-direction
@@ -892,7 +889,6 @@
          zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
       END_3D
-      CALL lbc_lnk( 'ldftra', zw2d, 'V', -1.0_wp )
-      CALL iom_put( "veiv_salttr", zztmp * zw2d )                  !  salt transport in j-direction
-      CALL iom_put( "veiv_salttr", zztmp * zw3d )                  !  salt transport in j-direction
+      CALL iom_put( "veiv_salttr"  , zztmp * zw2d )                  !  salt transport in j-direction
+      CALL iom_put( "veiv_salttr3d", zztmp * zw3d )                  !  salt transport in j-direction
       !
       IF( iom_use( 'sopsteiv' ) ) CALL dia_ptr_hst( jp_sal, 'eiv', 0.5 * zw3d )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/cpl_oasis3.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/cpl_oasis3.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/cpl_oasis3.F90	(revision 14055)
@@ -66,5 +66,5 @@
    INTEGER                    ::   nsnd         ! total number of fields sent 
    INTEGER                    ::   ncplmodel    ! Maximum number of models to/from which NEMO is potentialy sending/receiving data
-   INTEGER, PUBLIC, PARAMETER ::   nmaxfld=60   ! Maximum number of coupling fields
+   INTEGER, PUBLIC, PARAMETER ::   nmaxfld=62   ! Maximum number of coupling fields
    INTEGER, PUBLIC, PARAMETER ::   nmaxcat=5    ! Maximum number of coupling fields
    INTEGER, PUBLIC, PARAMETER ::   nmaxcpl=5    ! Maximum number of coupling fields
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbc_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbc_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbc_oce.F90	(revision 14055)
@@ -12,4 +12,5 @@
    !!            4.0  ! 2016-06  (L. Brodeau) new unified bulk routine (based on AeroBulk)
    !!            4.0  ! 2019-03  (F. Lemarié, G. Samson) add compatibility with ABL mode
+   !!            4.2  ! 2020-12  (G. Madec, E. Clementi) modified wave parameters in namelist
    !!----------------------------------------------------------------------
 
@@ -36,4 +37,5 @@
    LOGICAL , PUBLIC ::   ln_blk         !: bulk formulation
    LOGICAL , PUBLIC ::   ln_abl         !: Atmospheric boundary layer model
+   LOGICAL , PUBLIC ::   ln_wave        !: wave in the system (forced or coupled)
 #if defined key_oasis3
    LOGICAL , PUBLIC ::   lk_oasis = .TRUE.  !: OASIS used
@@ -56,13 +58,4 @@
    !                                             !:  = 1 global mean of e-p-r set to zero at each nn_fsbc time step
    !                                             !:  = 2 annual global mean of e-p-r set to zero
-   LOGICAL , PUBLIC ::   ln_wave        !: true if some coupling with wave model
-   LOGICAL , PUBLIC ::   ln_cdgw        !: true if neutral drag coefficient from wave model
-   LOGICAL , PUBLIC ::   ln_sdw         !: true if 3d stokes drift from wave model
-   LOGICAL , PUBLIC ::   ln_tauwoc       !: true if normalized stress from wave is used
-   LOGICAL , PUBLIC ::   ln_tauw        !: true if ocean stress components from wave is used
-   LOGICAL , PUBLIC ::   ln_stcor       !: true if Stokes-Coriolis term is used
-   !
-   INTEGER , PUBLIC ::   nn_sdrift      ! type of parameterization to calculate vertical Stokes drift
-   !
    LOGICAL , PUBLIC ::   ln_icebergs    !: Icebergs
    !
@@ -71,5 +64,19 @@
    !                                   !!* namsbc_cpl namelist *
    INTEGER , PUBLIC ::   nn_cats_cpl    !: Number of sea ice categories over which the coupling is carried out
-
+   !
+   !                                   !!* namsbc_wave namelist *
+   LOGICAL , PUBLIC ::   ln_sdw         !: =T 3d stokes drift from wave model
+   LOGICAL , PUBLIC ::   ln_stcor       !: =T if Stokes-Coriolis and tracer advection terms are used
+   LOGICAL , PUBLIC ::   ln_cdgw        !: =T neutral drag coefficient from wave model
+   LOGICAL , PUBLIC ::   ln_tauoc       !: =T if normalized stress from wave is used
+   LOGICAL , PUBLIC ::   ln_wave_test   !: =T wave test case (constant Stokes drift)
+   LOGICAL , PUBLIC ::   ln_charn       !: =T Chranock coefficient from wave model
+   LOGICAL , PUBLIC ::   ln_taw         !: =T wind stress corrected by wave intake
+   LOGICAL , PUBLIC ::   ln_phioc       !: =T TKE surface BC from wave model 
+   LOGICAL , PUBLIC ::   ln_bern_srfc   !: Bernoulli head, waves' inuced pressure
+   LOGICAL , PUBLIC ::   ln_breivikFV_2016 !: Breivik 2016 profile
+   LOGICAL , PUBLIC ::   ln_vortex_force !: vortex force activation
+   LOGICAL , PUBLIC ::   ln_stshear     !: Stoked Drift shear contribution in zdftke
+   !
    !!----------------------------------------------------------------------
    !!           switch definition (improve readability)
@@ -81,18 +88,5 @@
    INTEGER , PUBLIC, PARAMETER ::   jp_purecpl = 5        !: Pure ocean-atmosphere Coupled formulation
    INTEGER , PUBLIC, PARAMETER ::   jp_none    = 6        !: for OPA when doing coupling via SAS module
-
-   !!----------------------------------------------------------------------
-   !!           Stokes drift parametrization definition
-   !!----------------------------------------------------------------------
-   INTEGER , PUBLIC, PARAMETER ::   jp_breivik_2014 = 0     !: Breivik  2014: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
-   INTEGER , PUBLIC, PARAMETER ::   jp_li_2017      = 1     !: Li et al 2017: Stokes drift based on Phillips spectrum (Breivik 2016)
-   !  with depth averaged profile
-   INTEGER , PUBLIC, PARAMETER ::   jp_peakfr       = 2     !: Li et al 2017: using the peak wave number read from wave model instead
-   !  of the inverse depth scale
-   LOGICAL , PUBLIC            ::   ll_st_bv2014  = .FALSE. !  logical indicator, .true. if Breivik 2014 parameterisation is active.
-   LOGICAL , PUBLIC            ::   ll_st_li2017  = .FALSE. !  logical indicator, .true. if Li 2017 parameterisation is active.
-   LOGICAL , PUBLIC            ::   ll_st_bv_li   = .FALSE. !  logical indicator, .true. if either Breivik or Li parameterisation is active.
-   LOGICAL , PUBLIC            ::   ll_st_peakfr  = .FALSE. !  logical indicator, .true. if using Li 2017 with peak wave number
-
+   !
    !!----------------------------------------------------------------------
    !!           component definition
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcapr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcapr.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcapr.F90	(revision 14055)
@@ -65,5 +65,4 @@
       CHARACTER(len=100) ::  cn_dir   ! Root directory for location of ssr files
       TYPE(FLD_N)        ::  sn_apr   ! informations about the fields to be read
-      LOGICAL            ::  lrxios   ! read restart using XIOS?
       !!
       NAMELIST/namsbc_apr/ cn_dir, sn_apr, ln_ref_apr, rn_pref, ln_apr_obc
@@ -108,7 +107,4 @@
             CALL ctl_warn( 'sbc_apr: use inverse barometer ssh at open boundary ONLY requires ln_apr_dyn=T' )
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('ssh_ibb')
-      ENDIF
    END SUBROUTINE sbc_apr_init
 
@@ -154,5 +150,5 @@
          IF( ln_rstart .AND. iom_varid( numror, 'ssh_ibb', ldstop = .FALSE. ) > 0 ) THEN 
             IF(lwp) WRITE(numout,*) 'sbc_apr:   ssh_ibb read in the restart file'
-            CALL iom_get( numror, jpdom_auto, 'ssh_ibb', ssh_ibb, ldxios = lrxios )   ! before inv. barometer ssh
+            CALL iom_get( numror, jpdom_auto, 'ssh_ibb', ssh_ibb )   ! before inv. barometer ssh
             !
          ELSE                                         !* no restart: set from nit000 values
@@ -167,7 +163,5 @@
          IF(lwp) WRITE(numout,*) 'sbc_apr : ssh_ib written in ocean restart file at it= ', kt,' date= ', ndastp
          IF(lwp) WRITE(numout,*) '~~~~'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'ssh_ibb' , ssh_ib, ldxios = lwxios )
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'ssh_ibb' , ssh_ib )
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcblk.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcblk.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcblk.F90	(revision 14055)
@@ -314,23 +314,4 @@
          ENDIF
       END DO
-      !
-      IF( ln_wave ) THEN
-         !Activated wave module but neither drag nor stokes drift activated
-         IF( .NOT.(ln_cdgw .OR. ln_sdw .OR. ln_tauwoc .OR. ln_stcor ) )   THEN
-            CALL ctl_stop( 'STOP',  'Ask for wave coupling but ln_cdgw=F, ln_sdw=F, ln_tauwoc=F, ln_stcor=F' )
-            !drag coefficient read from wave model definable only with mfs bulk formulae and core
-         ELSEIF(ln_cdgw .AND. .NOT. ln_NCAR )       THEN
-            CALL ctl_stop( 'drag coefficient read from wave model definable only with NCAR and CORE bulk formulae')
-         ELSEIF(ln_stcor .AND. .NOT. ln_sdw)                             THEN
-            CALL ctl_stop( 'Stokes-Coriolis term calculated only if activated Stokes Drift ln_sdw=T')
-         ENDIF
-      ELSE
-         IF( ln_cdgw .OR. ln_sdw .OR. ln_tauwoc .OR. ln_stcor )                &
-            &   CALL ctl_stop( 'Not Activated Wave Module (ln_wave=F) but asked coupling ',    &
-            &                  'with drag coefficient (ln_cdgw =T) '  ,                        &
-            &                  'or Stokes Drift (ln_sdw=T) ' ,                                 &
-            &                  'or ocean stress modification due to waves (ln_tauwoc=T) ',      &
-            &                  'or Stokes-Coriolis term (ln_stcori=T)'  )
-      ENDIF
       !
       IF( ln_abl ) THEN       ! ABL: read 3D fields for wind, temperature, humidity and pressure gradient
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcblk_algo_ecmwf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcblk_algo_ecmwf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcblk_algo_ecmwf.F90	(revision 14055)
@@ -17,4 +17,5 @@
    !!----------------------------------------------------------------------
    !! History :  4.0  !  2016-02  (L.Brodeau)   Original code
+   !!            4.2  !  2020-12  (G. Madec, E. Clementi) Charnock coeff from wave model
    !!----------------------------------------------------------------------
 
@@ -31,5 +32,5 @@
    USE in_out_manager  ! I/O manager
    USE prtctl          ! Print control
-   USE sbcwave, ONLY   :  cdn_wave ! wave module
+   USE sbcwave, ONLY   : charn ! wave module
 #if defined key_si3 || defined key_cice
    USE sbc_ice         ! Surface boundary condition: ice fields
@@ -233,5 +234,10 @@
       u_star = 0.035_wp*U_blk*ztmp1/ztmp0       ! (u* = 0.035*Un10)
 
-      z0     = charn0*u_star*u_star/grav + 0.11_wp*znu_a/u_star
+      IF (ln_charn)  THEN          !  Charnock value if wave coupling
+         z0     = charn*u_star*u_star/grav + 0.11_wp*znu_a/u_star
+      ELSE
+         z0     = charn0*u_star*u_star/grav + 0.11_wp*znu_a/u_star
+      ENDIF
+
       z0     = MIN( MAX(ABS(z0), 1.E-9) , 1._wp )                      ! (prevents FPE from stupid values from masked region later on)
 
@@ -302,5 +308,9 @@
          ztmp2  = u_star*u_star
          ztmp1  = znu_a/u_star
-         z0     = MIN( ABS( alpha_M*ztmp1 + charn0*ztmp2/grav ) , 0.001_wp)
+         IF (ln_charn) THEN     ! Charnock value if wave coupling
+            z0  = MIN( ABS( alpha_M*ztmp1 + charn*ztmp2/grav ) , 0.001_wp)         
+         ELSE
+            z0     = MIN( ABS( alpha_M*ztmp1 + charn0*ztmp2/grav ) , 0.001_wp)
+         ENDIF
          z0t    = MIN( ABS( alpha_H*ztmp1                     ) , 0.001_wp)   ! eq.3.26, Chap.3, p.34, IFS doc - Cy31r1
          z0q    = MIN( ABS( alpha_Q*ztmp1                     ) , 0.001_wp)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbccpl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbccpl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbccpl.F90	(revision 14055)
@@ -8,4 +8,5 @@
    !!            3.1  ! 2009_02  (G. Madec, S. Masson, E. Maisonave, A. Caubel) generic coupled interface
    !!            3.4  ! 2011_11  (C. Harris) more flexibility + multi-category fields
+   !!            4.2  ! 2020-12  (G. Madec, E. Clementi)  wave coupling updates
    !!----------------------------------------------------------------------
 
@@ -106,20 +107,26 @@
    INTEGER, PARAMETER ::   jpr_fraqsr = 42   ! fraction of solar net radiation absorbed in the first ocean level
    INTEGER, PARAMETER ::   jpr_mslp   = 43   ! mean sea level pressure 
-   INTEGER, PARAMETER ::   jpr_hsig   = 44   ! Hsig 
-   INTEGER, PARAMETER ::   jpr_phioc  = 45   ! Wave=>ocean energy flux 
-   INTEGER, PARAMETER ::   jpr_sdrftx = 46   ! Stokes drift on grid 1 
-   INTEGER, PARAMETER ::   jpr_sdrfty = 47   ! Stokes drift on grid 2 
+   !**  surface wave coupling  **
+   INTEGER, PARAMETER ::   jpr_hsig   = 44   ! Hsig
+   INTEGER, PARAMETER ::   jpr_phioc  = 45   ! Wave=>ocean energy flux
+   INTEGER, PARAMETER ::   jpr_sdrftx = 46   ! Stokes drift on grid 1
+   INTEGER, PARAMETER ::   jpr_sdrfty = 47   ! Stokes drift on grid 2
    INTEGER, PARAMETER ::   jpr_wper   = 48   ! Mean wave period
    INTEGER, PARAMETER ::   jpr_wnum   = 49   ! Mean wavenumber
-   INTEGER, PARAMETER ::   jpr_tauwoc = 50   ! Stress fraction adsorbed by waves
+   INTEGER, PARAMETER ::   jpr_wstrf  = 50   ! Stress fraction adsorbed by waves
    INTEGER, PARAMETER ::   jpr_wdrag  = 51   ! Neutral surface drag coefficient
-   INTEGER, PARAMETER ::   jpr_isf    = 52
-   INTEGER, PARAMETER ::   jpr_icb    = 53
-   INTEGER, PARAMETER ::   jpr_wfreq  = 54   ! Wave peak frequency
-   INTEGER, PARAMETER ::   jpr_tauwx  = 55   ! x component of the ocean stress from waves
-   INTEGER, PARAMETER ::   jpr_tauwy  = 56   ! y component of the ocean stress from waves
-   INTEGER, PARAMETER ::   jpr_ts_ice = 57   ! Sea ice surface temp
-
-   INTEGER, PARAMETER ::   jprcv      = 57   ! total number of fields received  
+   INTEGER, PARAMETER ::   jpr_charn  = 52   ! Chranock coefficient
+   INTEGER, PARAMETER ::   jpr_twox   = 53   ! wave to ocean momentum flux
+   INTEGER, PARAMETER ::   jpr_twoy   = 54   ! wave to ocean momentum flux
+   INTEGER, PARAMETER ::   jpr_tawx   = 55   ! net wave-supported stress
+   INTEGER, PARAMETER ::   jpr_tawy   = 56   ! net wave-supported stress
+   INTEGER, PARAMETER ::   jpr_bhd    = 57   ! Bernoulli head. waves' induced surface pressure
+   INTEGER, PARAMETER ::   jpr_tusd   = 58   ! zonal stokes transport
+   INTEGER, PARAMETER ::   jpr_tvsd   = 59   ! meridional stokes tranmport
+   INTEGER, PARAMETER ::   jpr_isf    = 60
+   INTEGER, PARAMETER ::   jpr_icb    = 61
+   INTEGER, PARAMETER ::   jpr_ts_ice = 62   ! Sea ice surface temp
+
+   INTEGER, PARAMETER ::   jprcv      = 62   ! total number of fields received  
 
    INTEGER, PARAMETER ::   jps_fice   =  1   ! ice fraction sent to the atmosphere
@@ -184,12 +191,12 @@
       &             sn_snd_thick1, sn_snd_cond, sn_snd_mpnd , sn_snd_sstfrz, sn_snd_ttilyr
    !                                   ! Received from the atmosphere
-   TYPE(FLD_C) ::   sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau, sn_rcv_tauw, sn_rcv_dqnsdt, sn_rcv_qsr,  &
+   TYPE(FLD_C) ::   sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau, sn_rcv_dqnsdt, sn_rcv_qsr,  &
       &             sn_rcv_qns , sn_rcv_emp   , sn_rcv_rnf, sn_rcv_ts_ice
    TYPE(FLD_C) ::   sn_rcv_cal, sn_rcv_iceflx, sn_rcv_co2, sn_rcv_mslp, sn_rcv_icb, sn_rcv_isf
-   ! Send to waves 
+   !                                   ! Send to waves 
    TYPE(FLD_C) ::   sn_snd_ifrac, sn_snd_crtw, sn_snd_wlev 
-   ! Received from waves 
-   TYPE(FLD_C) ::   sn_rcv_hsig, sn_rcv_phioc, sn_rcv_sdrfx, sn_rcv_sdrfy, sn_rcv_wper, sn_rcv_wnum, sn_rcv_tauwoc, &
-                    sn_rcv_wdrag, sn_rcv_wfreq
+   !                                   ! Received from waves 
+   TYPE(FLD_C) ::   sn_rcv_hsig, sn_rcv_phioc, sn_rcv_sdrfx, sn_rcv_sdrfy, sn_rcv_wper, sn_rcv_wnum, &
+      &             sn_rcv_wstrf, sn_rcv_wdrag, sn_rcv_charn, sn_rcv_taw, sn_rcv_bhd, sn_rcv_tusd, sn_rcv_tvsd
    !                                   ! Other namelist parameters
    INTEGER     ::   nn_cplmodel           ! Maximum number of models to/from which NEMO is potentialy sending/receiving data
@@ -274,9 +281,9 @@
          &                  sn_snd_ifrac , sn_snd_crtw  , sn_snd_wlev , sn_rcv_hsig  , sn_rcv_phioc ,  & 
          &                  sn_rcv_w10m  , sn_rcv_taumod, sn_rcv_tau  , sn_rcv_dqnsdt, sn_rcv_qsr   ,  & 
-         &                  sn_rcv_sdrfx , sn_rcv_sdrfy , sn_rcv_wper , sn_rcv_wnum  , sn_rcv_tauwoc,  &
-         &                  sn_rcv_wdrag , sn_rcv_qns   , sn_rcv_emp  , sn_rcv_rnf   , sn_rcv_cal   ,  &
-         &                  sn_rcv_iceflx, sn_rcv_co2   , sn_rcv_mslp ,                                &
-         &                  sn_rcv_icb   , sn_rcv_isf   , sn_rcv_wfreq, sn_rcv_tauw  ,                 &
-         &                  sn_rcv_ts_ice
+         &                  sn_rcv_sdrfx , sn_rcv_sdrfy , sn_rcv_wper , sn_rcv_wnum  , sn_rcv_wstrf ,  &
+         &                  sn_rcv_charn , sn_rcv_taw   , sn_rcv_bhd  , sn_rcv_tusd  , sn_rcv_tvsd,    &
+         &                  sn_rcv_wdrag , sn_rcv_qns   , sn_rcv_emp  , sn_rcv_rnf   , sn_rcv_cal  ,   &
+         &                  sn_rcv_iceflx, sn_rcv_co2   , sn_rcv_icb  , sn_rcv_isf   , sn_rcv_ts_ice 
+
       !!---------------------------------------------------------------------
       !
@@ -319,4 +326,6 @@
          WRITE(numout,*)'      sea ice heat fluxes             = ', TRIM(sn_rcv_iceflx%cldes), ' (', TRIM(sn_rcv_iceflx%clcat), ')'
          WRITE(numout,*)'      atm co2                         = ', TRIM(sn_rcv_co2%cldes   ), ' (', TRIM(sn_rcv_co2%clcat   ), ')'
+         WRITE(numout,*)'      Sea ice surface skin temperature= ', TRIM(sn_rcv_ts_ice%cldes), ' (', TRIM(sn_rcv_ts_ice%clcat), ')'
+         WRITE(numout,*)'      surface waves:'
          WRITE(numout,*)'      significant wave heigth         = ', TRIM(sn_rcv_hsig%cldes  ), ' (', TRIM(sn_rcv_hsig%clcat  ), ')' 
          WRITE(numout,*)'      wave to oce energy flux         = ', TRIM(sn_rcv_phioc%cldes ), ' (', TRIM(sn_rcv_phioc%clcat ), ')' 
@@ -325,9 +334,7 @@
          WRITE(numout,*)'      Mean wave period                = ', TRIM(sn_rcv_wper%cldes  ), ' (', TRIM(sn_rcv_wper%clcat  ), ')' 
          WRITE(numout,*)'      Mean wave number                = ', TRIM(sn_rcv_wnum%cldes  ), ' (', TRIM(sn_rcv_wnum%clcat  ), ')' 
-         WRITE(numout,*)'      Wave peak frequency             = ', TRIM(sn_rcv_wfreq%cldes ), ' (', TRIM(sn_rcv_wfreq%clcat ), ')'
-         WRITE(numout,*)'      Stress frac adsorbed by waves   = ', TRIM(sn_rcv_tauwoc%cldes), ' (', TRIM(sn_rcv_tauwoc%clcat ), ')' 
-         WRITE(numout,*)'      Stress components by waves      = ', TRIM(sn_rcv_tauw%cldes  ), ' (', TRIM(sn_rcv_tauw%clcat  ), ')'
+         WRITE(numout,*)'      Stress frac adsorbed by waves   = ', TRIM(sn_rcv_wstrf%cldes ), ' (', TRIM(sn_rcv_wstrf%clcat ), ')'
          WRITE(numout,*)'      Neutral surf drag coefficient   = ', TRIM(sn_rcv_wdrag%cldes ), ' (', TRIM(sn_rcv_wdrag%clcat ), ')' 
-         WRITE(numout,*)'      Sea ice surface skin temperature= ', TRIM(sn_rcv_ts_ice%cldes), ' (', TRIM(sn_rcv_ts_ice%clcat), ')' 
+         WRITE(numout,*)'      Charnock coefficient            = ', TRIM(sn_rcv_charn%cldes ), ' (', TRIM(sn_rcv_charn%clcat ), ')'
          WRITE(numout,*)'  sent fields (multiple ice categories)'
          WRITE(numout,*)'      surface temperature             = ', TRIM(sn_snd_temp%cldes  ), ' (', TRIM(sn_snd_temp%clcat  ), ')'
@@ -351,5 +358,24 @@
          WRITE(numout,*)'                      - mesh          = ', sn_snd_crtw%clvgrd 
       ENDIF
-
+      IF( lwp .AND. ln_wave) THEN                        ! control print
+      WRITE(numout,*)'      surface waves:'
+         WRITE(numout,*)'      Significant wave heigth         = ', TRIM(sn_rcv_hsig%cldes  ), ' (', TRIM(sn_rcv_hsig%clcat  ), ')'
+         WRITE(numout,*)'      Wave to oce energy flux         = ', TRIM(sn_rcv_phioc%cldes ), ' (', TRIM(sn_rcv_phioc%clcat ), ')'
+         WRITE(numout,*)'      Surface Stokes drift grid u     = ', TRIM(sn_rcv_sdrfx%cldes ), ' (', TRIM(sn_rcv_sdrfx%clcat ), ')'
+         WRITE(numout,*)'      Surface Stokes drift grid v     = ', TRIM(sn_rcv_sdrfy%cldes ), ' (', TRIM(sn_rcv_sdrfy%clcat ), ')'
+         WRITE(numout,*)'      Mean wave period                = ', TRIM(sn_rcv_wper%cldes  ), ' (', TRIM(sn_rcv_wper%clcat  ), ')'
+         WRITE(numout,*)'      Mean wave number                = ', TRIM(sn_rcv_wnum%cldes  ), ' (', TRIM(sn_rcv_wnum%clcat  ), ')'
+         WRITE(numout,*)'      Stress frac adsorbed by waves   = ', TRIM(sn_rcv_wstrf%cldes ), ' (', TRIM(sn_rcv_wstrf%clcat ), ')'
+         WRITE(numout,*)'      Neutral surf drag coefficient   = ', TRIM(sn_rcv_wdrag%cldes ), ' (', TRIM(sn_rcv_wdrag%clcat ), ')'
+         WRITE(numout,*)'      Charnock coefficient            = ', TRIM(sn_rcv_charn%cldes ), ' (', TRIM(sn_rcv_charn%clcat ), ')'
+         WRITE(numout,*)' Transport associated to Stokes drift grid u = ', TRIM(sn_rcv_tusd%cldes ), ' (', TRIM(sn_rcv_tusd%clcat ), ')'
+         WRITE(numout,*)' Transport associated to Stokes drift grid v = ', TRIM(sn_rcv_tvsd%cldes ), ' (', TRIM(sn_rcv_tvsd%clcat ), ')'
+         WRITE(numout,*)'      Bernouilli pressure head        = ', TRIM(sn_rcv_bhd%cldes   ), ' (', TRIM(sn_rcv_bhd%clcat  ), ')'
+         WRITE(numout,*)'Wave to ocean momentum flux and Net wave-supported stress = ', TRIM(sn_rcv_taw%cldes ), ' (', TRIM(sn_rcv_taw%clcat ), ')'
+         WRITE(numout,*)'      Surface current to waves        = ', TRIM(sn_snd_crtw%cldes  ), ' (', TRIM(sn_snd_crtw%clcat  ), ')'
+         WRITE(numout,*)'                      - referential   = ', sn_snd_crtw%clvref
+         WRITE(numout,*)'                      - orientation   = ', sn_snd_crtw%clvor
+         WRITE(numout,*)'                      - mesh          = ', sn_snd_crtw%clvgrd
+      ENDIF
       !                                   ! allocate sbccpl arrays
       IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )
@@ -629,9 +655,4 @@
          cpl_wper = .TRUE.
       ENDIF
-      srcv(jpr_wfreq)%clname = 'O_WFreq'     ! wave peak frequency 
-      IF( TRIM(sn_rcv_wfreq%cldes ) == 'coupled' )  THEN
-         srcv(jpr_wfreq)%laction = .TRUE.
-         cpl_wfreq = .TRUE.
-      ENDIF
       srcv(jpr_wnum)%clname = 'O_WNum'       ! mean wave number
       IF( TRIM(sn_rcv_wnum%cldes ) == 'coupled' )  THEN
@@ -639,15 +660,8 @@
          cpl_wnum = .TRUE.
       ENDIF
-      srcv(jpr_tauwoc)%clname = 'O_TauOce'   ! stress fraction adsorbed by the wave
-      IF( TRIM(sn_rcv_tauwoc%cldes ) == 'coupled' )  THEN
-         srcv(jpr_tauwoc)%laction = .TRUE.
-         cpl_tauwoc = .TRUE.
-      ENDIF
-      srcv(jpr_tauwx)%clname = 'O_Tauwx'      ! ocean stress from wave in the x direction
-      srcv(jpr_tauwy)%clname = 'O_Tauwy'      ! ocean stress from wave in the y direction
-      IF( TRIM(sn_rcv_tauw%cldes ) == 'coupled' )  THEN
-         srcv(jpr_tauwx)%laction = .TRUE.
-         srcv(jpr_tauwy)%laction = .TRUE.
-         cpl_tauw = .TRUE.
+      srcv(jpr_wstrf)%clname = 'O_WStrf'     ! stress fraction adsorbed by the wave
+      IF( TRIM(sn_rcv_wstrf%cldes ) == 'coupled' )  THEN
+         srcv(jpr_wstrf)%laction = .TRUE.
+         cpl_wstrf = .TRUE.
       ENDIF
       srcv(jpr_wdrag)%clname = 'O_WDrag'     ! neutral surface drag coefficient
@@ -656,7 +670,36 @@
          cpl_wdrag = .TRUE.
       ENDIF
-      IF( srcv(jpr_tauwoc)%laction .AND. srcv(jpr_tauwx)%laction .AND. srcv(jpr_tauwy)%laction ) &
-            CALL ctl_stop( 'More than one method for modifying the ocean stress has been selected ', &
-                                     '(sn_rcv_tauwoc=coupled and sn_rcv_tauw=coupled)' )
+      srcv(jpr_charn)%clname = 'O_Charn'     ! Chranock coefficient
+      IF( TRIM(sn_rcv_charn%cldes ) == 'coupled' )  THEN
+         srcv(jpr_charn)%laction = .TRUE.
+         cpl_charn = .TRUE.
+      ENDIF
+      srcv(jpr_bhd)%clname = 'O_Bhd'     ! Bernoulli head. waves' induced surface pressure
+      IF( TRIM(sn_rcv_bhd%cldes ) == 'coupled' )  THEN
+         srcv(jpr_bhd)%laction = .TRUE.
+         cpl_bhd = .TRUE.
+      ENDIF
+      srcv(jpr_tusd)%clname = 'O_Tusd'     ! zonal stokes transport
+      IF( TRIM(sn_rcv_tusd%cldes ) == 'coupled' )  THEN
+         srcv(jpr_tusd)%laction = .TRUE.
+         cpl_tusd = .TRUE.
+      ENDIF
+      srcv(jpr_tvsd)%clname = 'O_Tvsd'     ! meridional stokes tranmport
+      IF( TRIM(sn_rcv_tvsd%cldes ) == 'coupled' )  THEN
+         srcv(jpr_tvsd)%laction = .TRUE.
+         cpl_tvsd = .TRUE.
+      ENDIF
+
+      srcv(jpr_twox)%clname = 'O_Twox'     ! wave to ocean momentum flux in the u direction
+      srcv(jpr_twoy)%clname = 'O_Twoy'     ! wave to ocean momentum flux in the v direction
+      srcv(jpr_tawx)%clname = 'O_Tawx'     ! Net wave-supported stress in the u direction
+      srcv(jpr_tawy)%clname = 'O_Tawy'     ! Net wave-supported stress in the v direction
+      IF( TRIM(sn_rcv_taw%cldes ) == 'coupled' )  THEN
+         srcv(jpr_twox)%laction = .TRUE.
+         srcv(jpr_twoy)%laction = .TRUE.
+         srcv(jpr_tawx)%laction = .TRUE.
+         srcv(jpr_tawy)%laction = .TRUE.
+         cpl_taw = .TRUE.
+      ENDIF
       !
       !                                                      ! ------------------------------- !
@@ -1058,5 +1101,4 @@
       !   initialisation of the coupler  !
       ! ================================ !
-
       CALL cpl_define(jprcv, jpsnd, nn_cplmodel)
       
@@ -1071,4 +1113,5 @@
       ENDIF
       xcplmask(:,:,0) = 1. - SUM( xcplmask(:,:,1:nn_cplmodel), dim = 3 )
+      !
       !
    END SUBROUTINE sbc_cpl_init
@@ -1146,4 +1189,8 @@
          IF( ncpl_qsr_freq /= 0) ncpl_qsr_freq = 86400 / ncpl_qsr_freq ! used by top
          
+         IF ( ln_wave .AND. nn_components == 0 ) THEN
+            ncpl_qsr_freq = 1;
+            WRITE(numout,*) 'ncpl_qsr_freq is set to 1 when coupling NEMO with wave (without SAS) '
+         ENDIF
       ENDIF
       !
@@ -1320,9 +1367,4 @@
          IF( srcv(jpr_hsig)%laction ) hsw(:,:) = frcv(jpr_hsig)%z3(:,:,1)
       ! 
-      !                                                      ! ========================= !  
-      !                                                      !    Wave peak frequency    ! 
-      !                                                      ! ========================= !  
-         IF( srcv(jpr_wfreq)%laction ) wfreq(:,:) = frcv(jpr_wfreq)%z3(:,:,1)
-      !
       !                                                      ! ========================= ! 
       !                                                      !    Vertical mixing Qiao   !
@@ -1331,6 +1373,6 @@
 
          ! Calculate the 3D Stokes drift both in coupled and not fully uncoupled mode
-         IF( srcv(jpr_sdrftx)%laction .OR. srcv(jpr_sdrfty)%laction .OR. srcv(jpr_wper)%laction &
-                                      .OR. srcv(jpr_hsig)%laction   .OR. srcv(jpr_wfreq)%laction) THEN
+         IF( srcv(jpr_sdrftx)%laction .OR. srcv(jpr_sdrfty)%laction .OR. &
+             srcv(jpr_wper)%laction .OR. srcv(jpr_hsig)%laction )   THEN
             CALL sbc_stokes( Kmm )
          ENDIF
@@ -1339,19 +1381,48 @@
       !                                                      ! Stress adsorbed by waves  !
       !                                                      ! ========================= ! 
-      IF( srcv(jpr_tauwoc)%laction .AND. ln_tauwoc ) tauoc_wave(:,:) = frcv(jpr_tauwoc)%z3(:,:,1)
-
-      !                                                      ! ========================= !  
-      !                                                      ! Stress component by waves ! 
-      !                                                      ! ========================= !  
-      IF( srcv(jpr_tauwx)%laction .AND. srcv(jpr_tauwy)%laction .AND. ln_tauw ) THEN
-         tauw_x(:,:) = frcv(jpr_tauwx)%z3(:,:,1)
-         tauw_y(:,:) = frcv(jpr_tauwy)%z3(:,:,1)
-      ENDIF
-
+      IF( srcv(jpr_wstrf)%laction .AND. ln_tauoc )  tauoc_wave(:,:) = frcv(jpr_wstrf)%z3(:,:,1)
+      !
       !                                                      ! ========================= ! 
       !                                                      !   Wave drag coefficient   !
       !                                                      ! ========================= ! 
       IF( srcv(jpr_wdrag)%laction .AND. ln_cdgw )   cdn_wave(:,:) = frcv(jpr_wdrag)%z3(:,:,1)
-
+      !
+      !                                                      ! ========================= !
+      !                                                      !   Chranock coefficient    !
+      !                                                      ! ========================= !
+      IF( srcv(jpr_charn)%laction .AND. ln_charn )  charn(:,:) = frcv(jpr_charn)%z3(:,:,1)
+      !
+      !                                                      ! ========================= !
+      !                                                      ! net wave-supported stress !
+      !                                                      ! ========================= !
+      IF( srcv(jpr_tawx)%laction .AND. ln_taw )     tawx(:,:) = frcv(jpr_tawx)%z3(:,:,1)
+      IF( srcv(jpr_tawy)%laction .AND. ln_taw )     tawy(:,:) = frcv(jpr_tawy)%z3(:,:,1)
+      !
+      !                                                      ! ========================= !
+      !                                                      !wave to ocean momentum flux!
+      !                                                      ! ========================= !
+      IF( srcv(jpr_twox)%laction .AND. ln_taw )     twox(:,:) = frcv(jpr_twox)%z3(:,:,1)
+      IF( srcv(jpr_twoy)%laction .AND. ln_taw )     twoy(:,:) = frcv(jpr_twoy)%z3(:,:,1)
+      !                                                      
+      !                                                      ! ========================= !
+      !                                                      !    wave TKE flux at sfc   !
+      !                                                      ! ========================= !
+      IF( srcv(jpr_phioc)%laction .AND. ln_phioc )     phioc(:,:) = frcv(jpr_phioc)%z3(:,:,1)
+      !
+      !                                                      ! ========================= !
+      !                                                      !      Bernoulli head       !
+      !                                                      ! ========================= !
+      IF( srcv(jpr_bhd)%laction .AND. ln_bern_srfc )   bhd_wave(:,:) = frcv(jpr_bhd)%z3(:,:,1)
+      !
+      !                                                      ! ========================= !
+      !                                                      !   Stokes transport u dir  !
+      !                                                      ! ========================= !
+      IF( srcv(jpr_tusd)%laction .AND. ln_breivikFV_2016 )    tusd(:,:) = frcv(jpr_tusd)%z3(:,:,1)
+      !
+      !                                                      ! ========================= !
+      !                                                      !   Stokes transport v dir  !
+      !                                                      ! ========================= !
+      IF( srcv(jpr_tvsd)%laction .AND. ln_breivikFV_2016 )     tvsd(:,:) = frcv(jpr_tvsd)%z3(:,:,1)
+      !
       !  Fields received by SAS when OASIS coupling
       !  (arrays no more filled at sbcssm stage)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcflx.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcflx.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcflx.F90	(revision 14055)
@@ -127,5 +127,5 @@
 
          IF( ln_dm2dc ) THEN   ! modify now Qsr to include the diurnal cycle
-            qsr(:,:) = sbc_dcy( sf(jp_qsr)%fnow(:,:,1) ) * tmask(ji,jj,1)
+            qsr(:,:) = sbc_dcy( sf(jp_qsr)%fnow(:,:,1) ) * tmask(:,:,1)
          ELSE
             DO_2D( 0, 0, 0, 0 )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcmod.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcmod.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcmod.F90	(revision 14055)
@@ -16,4 +16,5 @@
    !!            4.0  ! 2016-06  (L. Brodeau) new general bulk formulation
    !!            4.0  ! 2019-03  (F. Lemarié & G. Samson)  add ABL compatibility (ln_abl=TRUE)
+   !!            4.2  ! 2020-12  (G. Madec, E. Clementi) modified wave forcing and coupling  
    !!----------------------------------------------------------------------
 
@@ -54,4 +55,5 @@
    USE usrdef_sbc     ! user defined: surface boundary condition
    USE closea         ! closed sea
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
    !
    USE prtctl         ! Print control                    (prt_ctl routine)
@@ -70,5 +72,6 @@
 
    INTEGER ::   nsbc   ! type of surface boundary condition (deduced from namsbc informations)
-
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
    !!----------------------------------------------------------------------
    !! NEMO/OCE 4.0 , NEMO Consortium (2018)
@@ -99,7 +102,6 @@
          &             nn_ice   , ln_ice_embd,                                       &
          &             ln_traqsr, ln_dm2dc ,                                         &
-         &             ln_rnf   , nn_fwb   , ln_ssr   , ln_apr_dyn,                  &
-         &             ln_wave  , ln_cdgw  , ln_sdw   , ln_tauwoc , ln_stcor  ,      &
-         &             ln_tauw  , nn_lsm, nn_sdrift
+         &             ln_rnf   , nn_fwb     , ln_ssr   , ln_apr_dyn,                &
+         &             ln_wave  , nn_lsm
       !!----------------------------------------------------------------------
       !
@@ -133,4 +135,5 @@
          WRITE(numout,*) '         bulk         formulation                   ln_blk        = ', ln_blk
          WRITE(numout,*) '         ABL          formulation                   ln_abl        = ', ln_abl
+         WRITE(numout,*) '         Surface wave (forced or coupled)           ln_wave       = ', ln_wave
          WRITE(numout,*) '      Type of coupling (Ocean/Ice/Atmosphere) : '
          WRITE(numout,*) '         ocean-atmosphere coupled formulation       ln_cpl        = ', ln_cpl
@@ -150,32 +153,5 @@
          WRITE(numout,*) '         runoff / runoff mouths                     ln_rnf        = ', ln_rnf
          WRITE(numout,*) '         nb of iterations if land-sea-mask applied  nn_lsm        = ', nn_lsm
-         WRITE(numout,*) '         surface wave                               ln_wave       = ', ln_wave
-         WRITE(numout,*) '               Stokes drift corr. to vert. velocity ln_sdw        = ', ln_sdw
-         WRITE(numout,*) '                  vertical parametrization          nn_sdrift     = ', nn_sdrift
-         WRITE(numout,*) '               wave modified ocean stress           ln_tauwoc     = ', ln_tauwoc
-         WRITE(numout,*) '               wave modified ocean stress component ln_tauw       = ', ln_tauw
-         WRITE(numout,*) '               Stokes coriolis term                 ln_stcor      = ', ln_stcor
-         WRITE(numout,*) '               neutral drag coefficient (CORE,NCAR) ln_cdgw       = ', ln_cdgw
-      ENDIF
-      !
-      IF( .NOT.ln_wave ) THEN
-         ln_sdw = .false. ; ln_cdgw = .false. ; ln_tauwoc = .false. ; ln_tauw = .false. ; ln_stcor = .false.
-      ENDIF 
-      IF( ln_sdw ) THEN
-         IF( .NOT.(nn_sdrift==jp_breivik_2014 .OR. nn_sdrift==jp_li_2017 .OR. nn_sdrift==jp_peakfr) ) &
-            CALL ctl_stop( 'The chosen nn_sdrift for Stokes drift vertical velocity must be 0, 1, or 2' )
-      ENDIF
-      ll_st_bv2014  = ( nn_sdrift==jp_breivik_2014 )
-      ll_st_li2017  = ( nn_sdrift==jp_li_2017 )
-      ll_st_bv_li   = ( ll_st_bv2014 .OR. ll_st_li2017 )
-      ll_st_peakfr  = ( nn_sdrift==jp_peakfr )
-      IF( ln_tauwoc .AND. ln_tauw ) &
-         CALL ctl_stop( 'More than one method for modifying the ocean stress has been selected ', &
-                                  '(ln_tauwoc=.true. and ln_tauw=.true.)' )
-      IF( ln_tauwoc ) &
-         CALL ctl_warn( 'You are subtracting the wave stress to the ocean (ln_tauwoc=.true.)' )
-      IF( ln_tauw ) &
-         CALL ctl_warn( 'The wave modified ocean stress components are used (ln_tauw=.true.) ', &
-                              'This will override any other specification of the ocean stress' )
+      ENDIF
       !
       IF( .NOT.ln_usr ) THEN     ! the model calendar needs some specificities (except in user defined case)
@@ -357,16 +333,23 @@
       IF( nn_ice == 3 )   CALL cice_sbc_init( nsbc, Kbb, Kmm )   ! CICE initialization
       !
-      IF( ln_wave     )   CALL sbc_wave_init                     ! surface wave initialisation
-      !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('utau_b')
-         CALL iom_set_rstw_var_active('vtau_b')
-         CALL iom_set_rstw_var_active('qns_b')
-         ! The 3D heat content due to qsr forcing is treated in traqsr
-         ! CALL iom_set_rstw_var_active('qsr_b')
-         CALL iom_set_rstw_var_active('emp_b')
-         CALL iom_set_rstw_var_active('sfx_b')
-      ENDIF
-
+      IF( ln_wave     ) THEN
+                          CALL sbc_wave_init                     ! surface wave initialisation
+      ELSE
+                          IF(lwp) WRITE(numout,*)
+                          IF(lwp) WRITE(numout,*) '   No surface waves : all wave related logical set to false'
+                          ln_sdw       = .false.
+                          ln_stcor     = .false.
+                          ln_cdgw      = .false.
+                          ln_tauoc     = .false.
+                          ln_wave_test = .false.
+                          ln_charn     = .false.
+                          ln_taw       = .false.
+                          ln_phioc     = .false.
+                          ln_bern_srfc = .false.
+                          ln_breivikFV_2016 = .false.
+                          ln_vortex_force = .false.
+                          ln_stshear  = .false.
+      ENDIF
+      !
    END SUBROUTINE sbc_init
 
@@ -390,4 +373,5 @@
       INTEGER, INTENT(in) ::   kt   ! ocean time step
       INTEGER, INTENT(in) ::   Kbb, Kmm   ! ocean time level indices
+      INTEGER  ::   jj, ji          ! dummy loop argument
       !
       LOGICAL ::   ll_sas, ll_opa   ! local logical
@@ -422,9 +406,8 @@
       !
       IF( .NOT.ll_sas )   CALL sbc_ssm ( kt, Kbb, Kmm )  ! mean ocean sea surface variables (sst_m, sss_m, ssu_m, ssv_m)
-      IF( ln_wave     )   CALL sbc_wave( kt, Kmm )       ! surface waves
-
       !
       !                                            !==  sbc formulation  ==!
       !                                                   
+      !
       SELECT CASE( nsbc )                                ! Compute ocean surface boundary condition
       !                                                  ! (i.e. utau,vtau, qns, qsr, emp, sfx)
@@ -433,4 +416,9 @@
       CASE( jp_blk     )
          IF( ll_sas    )       CALL sbc_cpl_rcv   ( kt, nn_fsbc, nn_ice, Kbb, Kmm )   ! OPA-SAS coupling: SAS receiving fields from OPA
+!!!!!!!!!!! ATTENTION:ln_wave is not only used for oasis coupling !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+         IF( ln_wave )   THEN
+             IF ( lk_oasis )  CALL sbc_cpl_rcv ( kt, nn_fsbc, nn_ice, Kbb, Kmm )   ! OPA-wave coupling
+             CALL sbc_wave ( kt, Kmm )
+         ENDIF
                                CALL sbc_blk       ( kt )                    ! bulk formulation for the ocean
                                !
@@ -446,5 +434,33 @@
       IF( ln_mixcpl )          CALL sbc_cpl_rcv   ( kt, nn_fsbc, nn_ice, Kbb, Kmm )  ! forced-coupled mixed formulation after forcing
       !
-      IF ( ln_wave .AND. (ln_tauwoc .OR. ln_tauw) ) CALL sbc_wstress( )              ! Wind stress provided by waves 
+      IF( ln_wave .AND. ln_tauoc )  THEN            ! Wave stress reduction
+         DO_2D( 0, 0, 0, 0)
+            utau(ji,jj) = utau(ji,jj) * ( tauoc_wave(ji,jj) + tauoc_wave(ji-1,jj) ) * 0.5_wp
+            vtau(ji,jj) = vtau(ji,jj) * ( tauoc_wave(ji,jj) + tauoc_wave(ji,jj-1) ) * 0.5_wp
+         END_2D
+         !
+         CALL lbc_lnk( 'sbcwave', utau, 'U', -1. )
+         CALL lbc_lnk( 'sbcwave', vtau, 'V', -1. )
+         !
+         taum(:,:) = taum(:,:)*tauoc_wave(:,:)
+         !
+         IF( kt == nit000 )   CALL ctl_warn( 'sbc: You are subtracting the wave stress to the ocean.',   &
+            &                                'If not requested select ln_tauoc=.false.' )
+         !
+      ELSEIF( ln_wave .AND. ln_taw ) THEN                  ! Wave stress reduction
+         utau(:,:) = utau(:,:) - tawx(:,:) + twox(:,:)
+         vtau(:,:) = vtau(:,:) - tawy(:,:) + twoy(:,:)
+         CALL lbc_lnk( 'sbcwave', utau, 'U', -1. )
+         CALL lbc_lnk( 'sbcwave', vtau, 'V', -1. )
+         !
+         DO_2D( 0, 0, 0, 0)
+             taum(ji,jj) = sqrt((.5*(utau(ji-1,jj)+utau(ji,jj)))**2 + (.5*(vtau(ji,jj-1)+vtau(ji,jj)))**2)
+         END_2D
+         !
+         IF( kt == nit000 )   CALL ctl_warn( 'sbc: You are subtracting the wave stress to the ocean.',   &
+            &                                'If not requested select ln_taw=.false.' )
+         !
+      ENDIF
+      CALL lbc_lnk( 'sbcmod', taum(:,:), 'T', 1. )
       !
       !                                            !==  Misc. Options  ==!
@@ -459,5 +475,5 @@
 
       IF( ln_icebergs    )   THEN
-                                     CALL icb_stp( kt )           ! compute icebergs
+                                     CALL icb_stp( kt, Kmm )           ! compute icebergs
          ! Icebergs do not melt over the haloes. 
          ! So emp values over the haloes are no more consistent with the inner domain values. 
@@ -510,13 +526,13 @@
             & iom_varid( numror, 'utau_b', ldstop = .FALSE. ) > 0 ) THEN
             IF(lwp) WRITE(numout,*) '          nit000-1 surface forcing fields red in the restart file'
-            CALL iom_get( numror, jpdom_auto, 'utau_b', utau_b, ldxios = lrxios, cd_type = 'U', psgn = -1._wp )   ! before i-stress  (U-point)
-            CALL iom_get( numror, jpdom_auto, 'vtau_b', vtau_b, ldxios = lrxios, cd_type = 'V', psgn = -1._wp )   ! before j-stress  (V-point)
-            CALL iom_get( numror, jpdom_auto,  'qns_b',  qns_b, ldxios = lrxios )   ! before non solar heat flux (T-point)
+            CALL iom_get( numror, jpdom_auto, 'utau_b', utau_b )   ! before i-stress  (U-point)
+            CALL iom_get( numror, jpdom_auto, 'vtau_b', vtau_b )   ! before j-stress  (V-point)
+            CALL iom_get( numror, jpdom_auto,  'qns_b',  qns_b )   ! before non solar heat flux (T-point)
             ! The 3D heat content due to qsr forcing is treated in traqsr
-            ! CALL iom_get( numror, jpdom_auto, 'qsr_b' , qsr_b, ldxios = lrxios  ) ! before     solar heat flux (T-point)
-            CALL iom_get( numror, jpdom_auto, 'emp_b', emp_b, ldxios = lrxios  )    ! before     freshwater flux (T-point)
+            ! CALL iom_get( numror, jpdom_auto, 'qsr_b' , qsr_b  ) ! before     solar heat flux (T-point)
+            CALL iom_get( numror, jpdom_auto, 'emp_b', emp_b  )    ! before     freshwater flux (T-point)
             ! To ensure restart capability with 3.3x/3.4 restart files    !! to be removed in v3.6
             IF( iom_varid( numror, 'sfx_b', ldstop = .FALSE. ) > 0 ) THEN
-               CALL iom_get( numror, jpdom_auto, 'sfx_b', sfx_b, ldxios = lrxios )  ! before salt flux (T-point)
+               CALL iom_get( numror, jpdom_auto, 'sfx_b', sfx_b )  ! before salt flux (T-point)
             ELSE
                sfx_b (:,:) = sfx(:,:)
@@ -538,13 +554,11 @@
             &                    'at it= ', kt,' date= ', ndastp
          IF(lwp) WRITE(numout,*) '~~~~'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'utau_b' , utau, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'vtau_b' , vtau, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'qns_b'  , qns, ldxios = lwxios  )
+         CALL iom_rstput( kt, nitrst, numrow, 'utau_b' , utau )
+         CALL iom_rstput( kt, nitrst, numrow, 'vtau_b' , vtau )
+         CALL iom_rstput( kt, nitrst, numrow, 'qns_b'  , qns  )
          ! The 3D heat content due to qsr forcing is treated in traqsr
          ! CALL iom_rstput( kt, nitrst, numrow, 'qsr_b'  , qsr  )
-         CALL iom_rstput( kt, nitrst, numrow, 'emp_b'  , emp, ldxios = lwxios  )
-         CALL iom_rstput( kt, nitrst, numrow, 'sfx_b'  , sfx, ldxios = lwxios  )
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'emp_b'  , emp  )
+         CALL iom_rstput( kt, nitrst, numrow, 'sfx_b'  , sfx  )
       ENDIF
       !                                                ! ---------------------------------------- !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcrnf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcrnf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcrnf.F90	(revision 14055)
@@ -42,5 +42,5 @@
    REAL(wp)                   ::      rn_dep_max        !: depth over which runoffs is spread       (ln_rnf_depth_ini =T)
    INTEGER                    ::      nn_rnf_depth_file !: create (=1) a runoff depth file or not (=0)
-   LOGICAL                    ::   ln_rnf_icb        !: iceberg flux is specified in a file
+   LOGICAL           , PUBLIC ::   ln_rnf_icb        !: iceberg flux is specified in a file
    LOGICAL                    ::   ln_rnf_tem        !: temperature river runoffs attribute specified in a file
    LOGICAL           , PUBLIC ::   ln_rnf_sal        !: salinity    river runoffs attribute specified in a file
@@ -160,7 +160,7 @@
             & iom_varid( numror, 'rnf_b', ldstop = .FALSE. ) > 0 ) THEN
             IF(lwp) WRITE(numout,*) '          nit000-1 runoff forcing fields red in the restart file', lrxios
-            CALL iom_get( numror, jpdom_auto, 'rnf_b', rnf_b, ldxios = lrxios )     ! before runoff
-            CALL iom_get( numror, jpdom_auto, 'rnf_hc_b', rnf_tsc_b(:,:,jp_tem), ldxios = lrxios )   ! before heat content of runoff
-            CALL iom_get( numror, jpdom_auto, 'rnf_sc_b', rnf_tsc_b(:,:,jp_sal), ldxios = lrxios )   ! before salinity content of runoff
+            CALL iom_get( numror, jpdom_auto, 'rnf_b', rnf_b )     ! before runoff
+            CALL iom_get( numror, jpdom_auto, 'rnf_hc_b', rnf_tsc_b(:,:,jp_tem) )   ! before heat content of runoff
+            CALL iom_get( numror, jpdom_auto, 'rnf_sc_b', rnf_tsc_b(:,:,jp_sal) )   ! before salinity content of runoff
          ELSE                                                   !* no restart: set from nit000 values
             IF(lwp) WRITE(numout,*) '          nit000-1 runoff forcing fields set to nit000'
@@ -176,9 +176,7 @@
             &                    'at it= ', kt,' date= ', ndastp
          IF(lwp) WRITE(numout,*) '~~~~'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'rnf_b' , rnf, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'rnf_hc_b', rnf_tsc(:,:,jp_tem), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'rnf_sc_b', rnf_tsc(:,:,jp_sal), ldxios = lwxios )
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'rnf_b' , rnf )
+         CALL iom_rstput( kt, nitrst, numrow, 'rnf_hc_b', rnf_tsc(:,:,jp_tem) )
+         CALL iom_rstput( kt, nitrst, numrow, 'rnf_sc_b', rnf_tsc(:,:,jp_sal) )
       ENDIF
       !
@@ -480,10 +478,4 @@
       ENDIF
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('rnf_b')
-         CALL iom_set_rstw_var_active('rnf_hc_b')
-         CALL iom_set_rstw_var_active('rnf_sc_b')
-      ENDIF
-
    END SUBROUTINE sbc_rnf_init
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcssm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcssm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcssm.F90	(revision 14055)
@@ -154,15 +154,13 @@
             IF(lwp) WRITE(numout,*) '~~~~~~~'
             zf_sbc = REAL( nn_fsbc, wp )
-            IF( lwxios ) CALL iom_swap(      cwxios_context          )
-            CALL iom_rstput( kt, nitrst, numrow, 'nn_fsbc', zf_sbc, ldxios = lwxios )    ! sbc frequency
-            CALL iom_rstput( kt, nitrst, numrow, 'ssu_m'  , ssu_m, ldxios = lwxios  )    ! sea surface mean fields
-            CALL iom_rstput( kt, nitrst, numrow, 'ssv_m'  , ssv_m, ldxios = lwxios  )
-            CALL iom_rstput( kt, nitrst, numrow, 'sst_m'  , sst_m, ldxios = lwxios  )
-            CALL iom_rstput( kt, nitrst, numrow, 'sss_m'  , sss_m, ldxios = lwxios  )
-            CALL iom_rstput( kt, nitrst, numrow, 'ssh_m'  , ssh_m, ldxios = lwxios  )
-            CALL iom_rstput( kt, nitrst, numrow, 'e3t_m'  , e3t_m, ldxios = lwxios  )
-            CALL iom_rstput( kt, nitrst, numrow, 'frq_m'  , frq_m, ldxios = lwxios  )
-            !
-            IF( lwxios ) CALL iom_swap(      cxios_context          )
+            CALL iom_rstput( kt, nitrst, numrow, 'nn_fsbc', zf_sbc )    ! sbc frequency
+            CALL iom_rstput( kt, nitrst, numrow, 'ssu_m'  , ssu_m  )    ! sea surface mean fields
+            CALL iom_rstput( kt, nitrst, numrow, 'ssv_m'  , ssv_m  )
+            CALL iom_rstput( kt, nitrst, numrow, 'sst_m'  , sst_m  )
+            CALL iom_rstput( kt, nitrst, numrow, 'sss_m'  , sss_m  )
+            CALL iom_rstput( kt, nitrst, numrow, 'ssh_m'  , ssh_m  )
+            CALL iom_rstput( kt, nitrst, numrow, 'e3t_m'  , e3t_m  )
+            CALL iom_rstput( kt, nitrst, numrow, 'frq_m'  , frq_m  )
+            !
          ENDIF
          !
@@ -208,14 +206,14 @@
          IF( ln_rstart .AND. iom_varid( numror, 'nn_fsbc', ldstop = .FALSE. ) > 0 ) THEN
             l_ssm_mean = .TRUE.
-            CALL iom_get( numror            , 'nn_fsbc', zf_sbc,ldxios = lrxios )     ! sbc frequency of previous run
-            CALL iom_get( numror, jpdom_auto, 'ssu_m'  , ssu_m, ldxios = lrxios, cd_type = 'U', psgn = -1._wp )    ! sea surface mean velocity    (U-point)
-            CALL iom_get( numror, jpdom_auto, 'ssv_m'  , ssv_m, ldxios = lrxios, cd_type = 'V', psgn = -1._wp )    !   "         "    velocity    (V-point)
-            CALL iom_get( numror, jpdom_auto, 'sst_m'  , sst_m, ldxios = lrxios )    !   "         "    temperature (T-point)
-            CALL iom_get( numror, jpdom_auto, 'sss_m'  , sss_m, ldxios = lrxios )    !   "         "    salinity    (T-point)
-            CALL iom_get( numror, jpdom_auto, 'ssh_m'  , ssh_m, ldxios = lrxios )    !   "         "    height      (T-point)
-            CALL iom_get( numror, jpdom_auto, 'e3t_m'  , e3t_m, ldxios = lrxios )    ! 1st level thickness          (T-point)
+            CALL iom_get( numror            , 'nn_fsbc', zf_sbc )     ! sbc frequency of previous run
+            CALL iom_get( numror, jpdom_auto, 'ssu_m'  , ssu_m, cd_type = 'U', psgn = -1._wp )    ! sea surface mean velocity    (U-point)
+            CALL iom_get( numror, jpdom_auto, 'ssv_m'  , ssv_m, cd_type = 'V', psgn = -1._wp )    !   "         "    velocity    (V-point)
+            CALL iom_get( numror, jpdom_auto, 'sst_m'  , sst_m )    !   "         "    temperature (T-point)
+            CALL iom_get( numror, jpdom_auto, 'sss_m'  , sss_m )    !   "         "    salinity    (T-point)
+            CALL iom_get( numror, jpdom_auto, 'ssh_m'  , ssh_m )    !   "         "    height      (T-point)
+            CALL iom_get( numror, jpdom_auto, 'e3t_m'  , e3t_m )    ! 1st level thickness          (T-point)
             ! fraction of solar net radiation absorbed in 1st T level
             IF( iom_varid( numror, 'frq_m', ldstop = .FALSE. ) > 0 ) THEN
-               CALL iom_get( numror, jpdom_auto, 'frq_m'  , frq_m, ldxios = lrxios  )
+               CALL iom_get( numror, jpdom_auto, 'frq_m'  , frq_m  )
             ELSE
                frq_m(:,:) = 1._wp   ! default definition
@@ -255,15 +253,4 @@
       IF( .NOT. ln_traqsr )   fraqsr_1lev(:,:) = 1._wp   ! default definition: qsr 100% in the fisrt level 
       !
-      IF( lwxios.AND.nn_fsbc > 1 ) THEN
-         CALL iom_set_rstw_var_active('nn_fsbc')
-         CALL iom_set_rstw_var_active('ssu_m')
-         CALL iom_set_rstw_var_active('ssv_m')
-         CALL iom_set_rstw_var_active('sst_m')
-         CALL iom_set_rstw_var_active('sss_m')
-         CALL iom_set_rstw_var_active('ssh_m')
-         CALL iom_set_rstw_var_active('e3t_m')
-         CALL iom_set_rstw_var_active('frq_m')
-      ENDIF
-
    END SUBROUTINE sbc_ssm_init
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcwave.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcwave.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/SBC/sbcwave.F90	(revision 14055)
@@ -9,15 +9,17 @@
    !!             -   !  2016-12  (G. Madec, E. Clementi) update Stoke drift computation
    !!                                                    + add sbc_wave_ini routine
+   !!            4.2  !  2020-12  (G. Madec, E. Clementi) updates, new Stoke drift computation 
+   !!                                                    according to Couvelard et al.,2019
    !!----------------------------------------------------------------------
 
    !!----------------------------------------------------------------------
    !!   sbc_stokes    : calculate 3D Stokes-drift velocities
-   !!   sbc_wave      : wave data from wave model in netcdf files 
+   !!   sbc_wave      : wave data from wave model: forced (netcdf files) or coupled mode
    !!   sbc_wave_init : initialisation fo surface waves 
    !!----------------------------------------------------------------------
-   USE phycst         ! physical constants 
+   USE phycst         ! physical constants
    USE oce            ! ocean variables
-   USE sbc_oce	       ! Surface boundary condition: ocean fields
-   USE zdf_oce,  ONLY : ln_zdfswm
+   USE dom_oce        ! ocean domain variables
+   USE sbc_oce        ! Surface boundary condition: ocean fields
    USE bdy_oce        ! open boundary condition variables
    USE domvvl         ! domain: variable volume layers
@@ -26,5 +28,5 @@
    USE in_out_manager ! I/O manager
    USE lib_mpp        ! distribued memory computing library
-   USE fldread	       ! read input fields
+   USE fldread        ! read input fields
 
    IMPLICIT NONE
@@ -32,19 +34,21 @@
 
    PUBLIC   sbc_stokes      ! routine called in sbccpl
-   PUBLIC   sbc_wstress     ! routine called in sbcmod 
    PUBLIC   sbc_wave        ! routine called in sbcmod
    PUBLIC   sbc_wave_init   ! routine called in sbcmod
    
    ! Variables checking if the wave parameters are coupled (if not, they are read from file)
-   LOGICAL, PUBLIC ::   cpl_hsig   = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_phioc  = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_sdrftx = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_sdrfty = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_wper   = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_wfreq  = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_wnum   = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_tauwoc = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_tauw   = .FALSE.
-   LOGICAL, PUBLIC ::   cpl_wdrag  = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_hsig          = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_phioc         = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_sdrftx        = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_sdrfty        = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wper          = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wnum          = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wstrf         = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wdrag         = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_charn         = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_taw           = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_bhd           = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_tusd          = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_tvsd          = .FALSE.
 
    INTEGER ::   jpfld    ! number of files to read for stokes drift
@@ -53,22 +57,32 @@
    INTEGER ::   jp_hsw   ! index of significant wave hight      (m)      at T-point
    INTEGER ::   jp_wmp   ! index of mean wave period            (s)      at T-point
-   INTEGER ::   jp_wfr   ! index of wave peak frequency         (1/s)    at T-point
 
    TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_cd      ! structure of input fields (file informations, fields read) Drag Coefficient
    TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_sd      ! structure of input fields (file informations, fields read) Stokes Drift
    TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_wn      ! structure of input fields (file informations, fields read) wave number for Qiao
-   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_tauwoc  ! structure of input fields (file informations, fields read) normalized wave stress into the ocean
-   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_tauw    ! structure of input fields (file informations, fields read) ocean stress components from wave model
-
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   cdn_wave            !:
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   hsw, wmp, wnum      !: 
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   wfreq               !: 
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauoc_wave          !:  
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauw_x, tauw_y      !:  
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tsd2d               !: 
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   div_sd              !: barotropic stokes drift divergence
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   ut0sd, vt0sd        !: surface Stokes drift velocities at t-point
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) ::   usd  , vsd  , wsd   !: Stokes drift velocities at u-, v- & w-points, resp.
-
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_tauoc   ! structure of input fields (file informations, fields read) normalized wave stress into the ocean
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   cdn_wave        !: Neutral drag coefficient at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   hsw             !: Significant Wave Height at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   wmp             !: Wave Mean Period at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   wnum            !: Wave Number at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauoc_wave      !: stress reduction factor  at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tsd2d           !: Surface Stokes Drift module at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   div_sd          !: barotropic stokes drift divergence
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   ut0sd, vt0sd    !: surface Stokes drift velocities at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) ::   usd, vsd, wsd   !: Stokes drift velocities at u-, v- & w-points, resp.u
+!
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   charn           !: charnock coefficient at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tawx            !: Net wave-supported stress, u
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tawy            !: Net wave-supported stress, v
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   twox            !: wave-ocean momentum flux, u
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   twoy            !: wave-ocean momentum flux, v
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauoc_wavex     !: stress reduction factor  at, u component
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauoc_wavey     !: stress reduction factor  at, v component
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   phioc           !: tke flux from wave model
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   KZN2            !: Kz*N2
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   bhd_wave        !: Bernoulli head. wave induce pression
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tusd, tvsd      !: Stokes drift transport
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) ::   ZMX             !: Kz*N2
    !! * Substitutions
 #  include "do_loop_substitute.h90"
@@ -88,28 +102,79 @@
       !!                2014 (DOI: 10.1175/JPO-D-14-0020.1)
       !!
-      !! ** Method  : - Calculate Stokes transport speed 
-      !!              - Calculate horizontal divergence 
-      !!              - Integrate the horizontal divergenze from the bottom 
-      !! ** action  
+      !! ** Method  : - Calculate the horizontal Stokes drift velocity (Breivik et al. 2014)
+      !!              - Calculate its horizontal divergence
+      !!              - Calculate the vertical Stokes drift velocity
+      !!              - Calculate the barotropic Stokes drift divergence
+      !!
+      !! ** action  : - tsd2d         : module of the surface Stokes drift velocity
+      !!              - usd, vsd, wsd : 3 components of the Stokes drift velocity
+      !!              - div_sd        : barotropic Stokes drift divergence
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in) :: Kmm ! ocean time level index
       INTEGER  ::   jj, ji, jk   ! dummy loop argument
       INTEGER  ::   ik           ! local integer 
-      REAL(wp) ::  ztransp, zfac, zsp0
-      REAL(wp) ::  zdepth, zsqrt_depth,  zexp_depth, z_two_thirds, zsqrtpi !sqrt of pi
-      REAL(wp) ::  zbot_u, zbot_v, zkb_u, zkb_v, zke3_u, zke3_v, zda_u, zda_v
-      REAL(wp) ::  zstokes_psi_u_bot, zstokes_psi_v_bot
-      REAL(wp) ::  zdep_u, zdep_v, zkh_u, zkh_v
-      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   zk_t, zk_u, zk_v, zu0_sd, zv0_sd     ! 2D workspace
-      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   zstokes_psi_u_top, zstokes_psi_v_top ! 2D workspace
-      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ze3divh                              ! 3D workspace
-      !!---------------------------------------------------------------------
-      !
-      ALLOCATE( ze3divh(jpi,jpj,jpkm1) )   ! jpkm1 -> avoid lbc_lnk on jpk that is not defined
+      REAL(wp) ::  ztransp, zfac, ztemp, zsp0, zsqrt, zbreiv16_w
+      REAL(wp) ::  zdep_u, zdep_v, zkh_u, zkh_v, zda_u, zda_v, sdtrp
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   zk_t, zk_u, zk_v, zu0_sd, zv0_sd ! 2D workspace
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ze3divh, zInt_w                  ! 3D workspace
+      !!---------------------------------------------------------------------
+      !
+      ALLOCATE( ze3divh(jpi,jpj,jpkm1) ) ! jpkm1 -> avoid lbc_lnk on jpk that is not defined
+      ALLOCATE( zInt_w(jpi,jpj,jpk) )
       ALLOCATE( zk_t(jpi,jpj), zk_u(jpi,jpj), zk_v(jpi,jpj), zu0_sd(jpi,jpj), zv0_sd(jpi,jpj) )
+      zk_t    (:,:) = 0._wp
+      zk_u    (:,:) = 0._wp
+      zk_v    (:,:) = 0._wp
+      zu0_sd  (:,:) = 0._wp
+      zv0_sd  (:,:) = 0._wp
+      ze3divh (:,:,:) = 0._wp
+
       !
       ! select parameterization for the calculation of vertical Stokes drift
       ! exp. wave number at t-point
-      IF( ll_st_bv_li ) THEN   ! (Eq. (19) in Breivik et al. (2014) )
+      IF( ln_breivikFV_2016 ) THEN
+      ! Assumptions :  ut0sd and vt0sd are surface Stokes drift at T-points
+      !                sdtrp is the norm of Stokes transport
+      !
+         zfac = 0.166666666667_wp
+         DO_2D( 1, 1, 1, 1 ) ! In the deep-water limit we have ke = ||ust0||/( 6 * ||transport|| )
+            zsp0          = SQRT( ut0sd(ji,jj)*ut0sd(ji,jj) + vt0sd(ji,jj)*vt0sd(ji,jj) ) !<-- norm of Surface Stokes drift
+            tsd2d(ji,jj)  = zsp0
+            IF( cpl_tusd .AND. cpl_tvsd ) THEN  !stokes transport is provided in coupled mode
+               sdtrp      = SQRT( tusd(ji,jj)*tusd(ji,jj) + tvsd(ji,jj)*tvsd(ji,jj) )  !<-- norm of Surface Stokes drift transport
+            ELSE 
+               ! Stokes drift transport estimated from Hs and Tmean 
+               sdtrp      = 2.0_wp * rpi / 16.0_wp *                             &
+                   &        hsw(ji,jj)*hsw(ji,jj) / MAX( wmp(ji,jj), 0.0000001_wp )
+            ENDIF
+            zk_t (ji,jj)  = zfac * zsp0 / MAX ( sdtrp, 0.0000001_wp ) !<-- ke = ||ust0||/( 6 * ||transport|| )
+         END_2D
+      !# define zInt_w ze3divh
+         DO_3D( 1, 1, 1, 1, 1, jpk ) ! Compute the primitive of Breivik 2016 function at W-points
+            zfac             = - 2._wp * zk_t (ji,jj) * gdepw(ji,jj,jk,Kmm)  !<-- zfac should be negative definite
+            ztemp            = EXP ( zfac )
+            zsqrt            = SQRT( -zfac )
+            zbreiv16_w       = ztemp - SQRT(rpi)*zsqrt*ERFC(zsqrt) !Eq. 16 Breivik 2016
+            zInt_w(ji,jj,jk) = ztemp - 4._wp * zk_t (ji,jj) * gdepw(ji,jj,jk,Kmm) * zbreiv16_w
+         END_3D
+!
+         DO jk = 1, jpkm1
+            zfac = 0.166666666667_wp
+            DO_2D( 1, 1, 1, 1 ) !++ Compute the FV Breivik 2016 function at T-points
+               zsp0          = zfac / MAX(zk_t (ji,jj),0.0000001_wp)
+               ztemp         = zInt_w(ji,jj,jk) - zInt_w(ji,jj,jk+1)
+               zu0_sd(ji,jj) = ut0sd(ji,jj) * zsp0 * ztemp * tmask(ji,jj,jk)
+               zv0_sd(ji,jj) = vt0sd(ji,jj) * zsp0 * ztemp * tmask(ji,jj,jk)
+            END_2D
+            DO_2D( 1, 0, 1, 0 ) ! ++ Interpolate at U/V points
+               zfac          =  1.0_wp / e3u(ji  ,jj,jk,Kmm)
+               usd(ji,jj,jk) =  0.5_wp * zfac * ( zu0_sd(ji,jj)+zu0_sd(ji+1,jj) ) * umask(ji,jj,jk)
+               zfac          =  1.0_wp / e3v(ji  ,jj,jk,Kmm)
+               vsd(ji,jj,jk) =  0.5_wp * zfac * ( zv0_sd(ji,jj)+zv0_sd(ji,jj+1) ) * vmask(ji,jj,jk)
+            END_2D
+         ENDDO
+      !# undef zInt_w
+      !
+      ELSE
          zfac = 2.0_wp * rpi / 16.0_wp
          DO_2D( 1, 1, 1, 1 )
@@ -128,23 +193,11 @@
             zv0_sd(ji,jj) = 0.5_wp * ( vt0sd(ji,jj) + vt0sd(ji,jj+1) )
          END_2D
-      ELSE IF( ll_st_peakfr ) THEN    ! peak wave number calculated from the peak frequency received by the wave model
-         DO_2D( 1, 1, 1, 1 )
-            zk_t(ji,jj) = ( 2.0_wp * rpi * wfreq(ji,jj) ) * ( 2.0_wp * rpi * wfreq(ji,jj) ) / grav
-         END_2D
-         DO_2D( 1, 0, 1, 0 )
-            zk_u(ji,jj) = 0.5_wp * ( zk_t(ji,jj) + zk_t(ji+1,jj) )
-            zk_v(ji,jj) = 0.5_wp * ( zk_t(ji,jj) + zk_t(ji,jj+1) )
-            !
-            zu0_sd(ji,jj) = 0.5_wp * ( ut0sd(ji,jj) + ut0sd(ji+1,jj) )
-            zv0_sd(ji,jj) = 0.5_wp * ( vt0sd(ji,jj) + vt0sd(ji,jj+1) )
-         END_2D
-      ENDIF
-      !
+
       !                       !==  horizontal Stokes Drift 3D velocity  ==!
-      IF( ll_st_bv2014 ) THEN
+
          DO_3D( 0, 0, 0, 0, 1, jpkm1 )
             zdep_u = 0.5_wp * ( gdept(ji,jj,jk,Kmm) + gdept(ji+1,jj,jk,Kmm) )
             zdep_v = 0.5_wp * ( gdept(ji,jj,jk,Kmm) + gdept(ji,jj+1,jk,Kmm) )
-            !                          
+            !
             zkh_u = zk_u(ji,jj) * zdep_u     ! k * depth
             zkh_v = zk_v(ji,jj) * zdep_v
@@ -156,45 +209,4 @@
             vsd(ji,jj,jk) = zda_v * zv0_sd(ji,jj) * vmask(ji,jj,jk)
          END_3D
-      ELSE IF( ll_st_li2017 .OR. ll_st_peakfr ) THEN
-         ALLOCATE( zstokes_psi_u_top(jpi,jpj), zstokes_psi_v_top(jpi,jpj) )
-         DO_2D( 1, 0, 1, 0 )
-            zstokes_psi_u_top(ji,jj) = 0._wp
-            zstokes_psi_v_top(ji,jj) = 0._wp
-         END_2D
-         zsqrtpi = SQRT(rpi)
-         z_two_thirds = 2.0_wp / 3.0_wp
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )       ! exp. wave number & Stokes drift velocity at u- & v-points
-            zbot_u = ( gdepw(ji,jj,jk+1,Kmm) + gdepw(ji+1,jj,jk+1,Kmm) )  ! 2 * bottom depth
-            zbot_v = ( gdepw(ji,jj,jk+1,Kmm) + gdepw(ji,jj+1,jk+1,Kmm) )  ! 2 * bottom depth
-            zkb_u  = zk_u(ji,jj) * zbot_u                             ! 2 * k * bottom depth
-            zkb_v  = zk_v(ji,jj) * zbot_v                             ! 2 * k * bottom depth
-            !
-            zke3_u = MAX(1.e-8_wp, 2.0_wp * zk_u(ji,jj) * e3u(ji,jj,jk,Kmm))     ! 2k * thickness
-            zke3_v = MAX(1.e-8_wp, 2.0_wp * zk_v(ji,jj) * e3v(ji,jj,jk,Kmm))     ! 2k * thickness
-
-            ! Depth attenuation .... do u component first..
-            zdepth      = zkb_u
-            zsqrt_depth = SQRT(zdepth)
-            zexp_depth  = EXP(-zdepth)
-            zstokes_psi_u_bot = 1.0_wp - zexp_depth  &
-                 &              - z_two_thirds * ( zsqrtpi*zsqrt_depth*zdepth*ERFC(zsqrt_depth) &
-                 &              + 1.0_wp - (1.0_wp + zdepth)*zexp_depth )
-            zda_u                    = ( zstokes_psi_u_bot - zstokes_psi_u_top(ji,jj) ) / zke3_u
-            zstokes_psi_u_top(ji,jj) =   zstokes_psi_u_bot
-
-            !         ... and then v component
-            zdepth      =zkb_v
-            zsqrt_depth = SQRT(zdepth)
-            zexp_depth  = EXP(-zdepth)
-            zstokes_psi_v_bot = 1.0_wp - zexp_depth  &
-                 &              - z_two_thirds * ( zsqrtpi*zsqrt_depth*zdepth*ERFC(zsqrt_depth) &
-                 &              + 1.0_wp - (1.0_wp + zdepth)*zexp_depth )
-            zda_v                    = ( zstokes_psi_v_bot - zstokes_psi_v_top(ji,jj) ) / zke3_v
-            zstokes_psi_v_top(ji,jj) =   zstokes_psi_v_bot
-            !
-            usd(ji,jj,jk) = zda_u * zu0_sd(ji,jj) * umask(ji,jj,jk)
-            vsd(ji,jj,jk) = zda_v * zv0_sd(ji,jj) * vmask(ji,jj,jk)
-         END_3D
-         DEALLOCATE( zstokes_psi_u_top, zstokes_psi_v_top )
       ENDIF
 
@@ -235,63 +247,28 @@
       CALL iom_put( "vstokes",  vsd  )
       CALL iom_put( "wstokes",  wsd  )
-      !
-      DEALLOCATE( ze3divh )
+!      !
+      DEALLOCATE( ze3divh, zInt_w )
       DEALLOCATE( zk_t, zk_u, zk_v, zu0_sd, zv0_sd )
       !
    END SUBROUTINE sbc_stokes
-
-
-   SUBROUTINE sbc_wstress( )
-      !!---------------------------------------------------------------------
-      !!                     ***  ROUTINE sbc_wstress  ***
-      !!
-      !! ** Purpose :   Updates the ocean momentum modified by waves
-      !!
-      !! ** Method  : - Calculate u,v components of stress depending on stress
-      !!                model 
-      !!              - Calculate the stress module
-      !!              - The wind module is not modified by waves 
-      !! ** action  
-      !!---------------------------------------------------------------------
-      INTEGER  ::   jj, ji   ! dummy loop argument
-      !
-      IF( ln_tauwoc ) THEN
-         utau(:,:) = utau(:,:)*tauoc_wave(:,:)
-         vtau(:,:) = vtau(:,:)*tauoc_wave(:,:)
-         taum(:,:) = taum(:,:)*tauoc_wave(:,:)
-      ENDIF
-      !
-      IF( ln_tauw ) THEN
-         DO_2D( 1, 0, 1, 0 )
-            ! Stress components at u- & v-points
-            utau(ji,jj) = 0.5_wp * ( tauw_x(ji,jj) + tauw_x(ji+1,jj) )
-            vtau(ji,jj) = 0.5_wp * ( tauw_y(ji,jj) + tauw_y(ji,jj+1) )
-            !
-            ! Stress module at t points
-            taum(ji,jj) = SQRT( tauw_x(ji,jj)*tauw_x(ji,jj) + tauw_y(ji,jj)*tauw_y(ji,jj) )
-         END_2D
-         CALL lbc_lnk_multi( 'sbcwave', utau(:,:), 'U', -1.0_wp , vtau(:,:), 'V', -1.0_wp , taum(:,:) , 'T', -1.0_wp )
-      ENDIF
-      !
-   END SUBROUTINE sbc_wstress
-
-
+!
+!
    SUBROUTINE sbc_wave( kt, Kmm )
       !!---------------------------------------------------------------------
       !!                     ***  ROUTINE sbc_wave  ***
       !!
-      !! ** Purpose :   read wave parameters from wave model  in netcdf files.
-      !!
-      !! ** Method  : - Read namelist namsbc_wave
-      !!              - Read Cd_n10 fields in netcdf files 
-      !!              - Read stokes drift 2d in netcdf files 
-      !!              - Read wave number in netcdf files 
-      !!              - Compute 3d stokes drift using Breivik et al.,2014
-      !!                formulation
-      !! ** action  
+      !! ** Purpose :   read wave parameters from wave model in netcdf files
+      !!                or from a coupled wave mdoel
+      !!
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in   ) ::   kt   ! ocean time step
       INTEGER, INTENT(in   ) ::   Kmm  ! ocean time index
       !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_wave : update the read waves fields'
+         WRITE(numout,*) '~~~~~~~~ '
+      ENDIF
       !
       IF( ln_cdgw .AND. .NOT. cpl_wdrag ) THEN     !==  Neutral drag coefficient  ==!
@@ -300,40 +277,44 @@
       ENDIF
 
-      IF( ln_tauwoc .AND. .NOT. cpl_tauwoc ) THEN  !==  Wave induced stress  ==!
-         CALL fld_read( kt, nn_fsbc, sf_tauwoc )         ! read wave norm stress from external forcing
-         tauoc_wave(:,:) = sf_tauwoc(1)%fnow(:,:,1) * tmask(:,:,1)
-      ENDIF
-
-      IF( ln_tauw .AND. .NOT. cpl_tauw ) THEN      !==  Wave induced stress  ==!
-         CALL fld_read( kt, nn_fsbc, sf_tauw )           ! read ocean stress components from external forcing (T grid)
-         tauw_x(:,:) = sf_tauw(1)%fnow(:,:,1) * tmask(:,:,1)
-         tauw_y(:,:) = sf_tauw(2)%fnow(:,:,1) * tmask(:,:,1)
-      ENDIF
-
-      IF( ln_sdw )  THEN                           !==  Computation of the 3d Stokes Drift  ==! 
+      IF( ln_tauoc .AND. .NOT. cpl_wstrf ) THEN    !==  Wave induced stress  ==!
+         CALL fld_read( kt, nn_fsbc, sf_tauoc )          ! read stress reduction factor due to wave from external forcing
+         tauoc_wave(:,:) = sf_tauoc(1)%fnow(:,:,1) * tmask(:,:,1)
+      ELSEIF ( ln_taw .AND. cpl_taw ) THEN
+         IF (kt < 1) THEN ! The first fields gave by OASIS have very high erroneous values ....
+            twox(:,:)=0._wp
+            twoy(:,:)=0._wp
+            tawx(:,:)=0._wp
+            tawy(:,:)=0._wp
+            tauoc_wavex(:,:) = 1._wp
+            tauoc_wavey(:,:) = 1._wp
+         ELSE
+            tauoc_wavex(:,:) = abs(twox(:,:)/tawx(:,:))
+            tauoc_wavey(:,:) = abs(twoy(:,:)/tawy(:,:))
+         ENDIF
+      ENDIF
+
+      IF ( ln_phioc .and. cpl_phioc .and.  kt == nit000 ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_wave : PHIOC from wave model'
+         WRITE(numout,*) '~~~~~~~~ '
+      ENDIF
+
+      IF( ln_sdw .AND. .NOT. cpl_sdrftx)  THEN       !==  Computation of the 3d Stokes Drift  ==! 
          !
          IF( jpfld > 0 ) THEN                            ! Read from file only if the field is not coupled
             CALL fld_read( kt, nn_fsbc, sf_sd )          ! read wave parameters from external forcing
+            !                                            ! NB: test case mode, not read as jpfld=0
             IF( jp_hsw > 0 )   hsw  (:,:) = sf_sd(jp_hsw)%fnow(:,:,1) * tmask(:,:,1)  ! significant wave height
             IF( jp_wmp > 0 )   wmp  (:,:) = sf_sd(jp_wmp)%fnow(:,:,1) * tmask(:,:,1)  ! wave mean period
-            IF( jp_wfr > 0 )   wfreq(:,:) = sf_sd(jp_wfr)%fnow(:,:,1) * tmask(:,:,1)  ! Peak wave frequency
             IF( jp_usd > 0 )   ut0sd(:,:) = sf_sd(jp_usd)%fnow(:,:,1) * tmask(:,:,1)  ! 2D zonal Stokes Drift at T point
             IF( jp_vsd > 0 )   vt0sd(:,:) = sf_sd(jp_vsd)%fnow(:,:,1) * tmask(:,:,1)  ! 2D meridional Stokes Drift at T point
          ENDIF
          !
-         ! Read also wave number if needed, so that it is available in coupling routines
-         IF( ln_zdfswm .AND. .NOT.cpl_wnum ) THEN
-            CALL fld_read( kt, nn_fsbc, sf_wn )          ! read wave parameters from external forcing
-            wnum(:,:) = sf_wn(1)%fnow(:,:,1) * tmask(:,:,1)
-         ENDIF
-           
-         ! Calculate only if required fields have been read
-         ! In coupled wave model-NEMO case the call is done after coupling
+         IF( jpfld == 4 .OR. ln_wave_test )   &
+            &      CALL sbc_stokes( Kmm )                 ! Calculate only if all required fields are read
+            !                                            ! or in wave test case
+         !  !                                            ! In coupled case the call is done after (in sbc_cpl)
+      ENDIF
          !
-         IF( ( ll_st_bv_li   .AND. jp_hsw>0 .AND. jp_wmp>0 .AND. jp_usd>0 .AND. jp_vsd>0 ) .OR. &
-           & ( ll_st_peakfr  .AND. jp_wfr>0 .AND. jp_usd>0 .AND. jp_vsd>0                ) ) CALL sbc_stokes( Kmm )
-         !
-      ENDIF
-      !
    END SUBROUTINE sbc_wave
 
@@ -343,12 +324,9 @@
       !!                     ***  ROUTINE sbc_wave_init  ***
       !!
-      !! ** Purpose :   read wave parameters from wave model  in netcdf files.
+      !! ** Purpose :   Initialisation fo surface waves
       !!
       !! ** Method  : - Read namelist namsbc_wave
-      !!              - Read Cd_n10 fields in netcdf files 
-      !!              - Read stokes drift 2d in netcdf files 
-      !!              - Read wave number in netcdf files 
-      !!              - Compute 3d stokes drift using Breivik et al.,2014
-      !!                formulation
+      !!              - create the structure used to read required wave fields
+      !!                (its size depends on namelist options)
       !! ** action  
       !!---------------------------------------------------------------------
@@ -357,129 +335,185 @@
       !!
       CHARACTER(len=100)     ::  cn_dir                            ! Root directory for location of drag coefficient files
-      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) ::   slf_i, slf_j     ! array of namelist informations on the fields to read
+      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) ::   slf_i            ! array of namelist informations on the fields to read
       TYPE(FLD_N)            ::  sn_cdg, sn_usd, sn_vsd,  &
-                             &   sn_hsw, sn_wmp, sn_wfr, sn_wnum, &
-                             &   sn_tauwoc, sn_tauwx, sn_tauwy     ! informations about the fields to be read
-      !
-      NAMELIST/namsbc_wave/  sn_cdg, cn_dir, sn_usd, sn_vsd, sn_hsw, sn_wmp, sn_wfr, &
-                             sn_wnum, sn_tauwoc, sn_tauwx, sn_tauwy
-      !!---------------------------------------------------------------------
+                             &   sn_hsw, sn_wmp, sn_wnum, sn_tauoc    ! informations about the fields to be read
+      !
+      NAMELIST/namsbc_wave/ cn_dir, sn_cdg, sn_usd, sn_vsd, sn_hsw, sn_wmp, sn_wnum, sn_tauoc,   &
+         &                  ln_cdgw, ln_sdw, ln_tauoc, ln_stcor, ln_charn, ln_taw, ln_phioc,     &
+         &                  ln_wave_test, ln_bern_srfc, ln_breivikFV_2016, ln_vortex_force, ln_stshear
+      !!---------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_wave_init : surface waves in the system'
+         WRITE(numout,*) '~~~~~~~~~~~~~ '
+      ENDIF
       !
       READ  ( numnam_ref, namsbc_wave, IOSTAT = ios, ERR = 901)
-901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_wave in reference namelist' )
-         
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_wave in reference namelist')
+
       READ  ( numnam_cfg, namsbc_wave, IOSTAT = ios, ERR = 902 )
 902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_wave in configuration namelist' )
       IF(lwm) WRITE ( numond, namsbc_wave )
       !
-      IF( ln_cdgw ) THEN
-         IF( .NOT. cpl_wdrag ) THEN
-            ALLOCATE( sf_cd(1), STAT=ierror )               !* allocate and fill sf_wave with sn_cdg
-            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+      IF(lwp) THEN
+         WRITE(numout,*) '   Namelist namsbc_wave'
+         WRITE(numout,*) '      Stokes drift                                  ln_sdw = ', ln_sdw
+         WRITE(numout,*) '      Breivik 2016                       ln_breivikFV_2016 = ', ln_breivikFV_2016
+         WRITE(numout,*) '      Stokes Coriolis & tracer advection terms    ln_stcor = ', ln_stcor
+         WRITE(numout,*) '      Vortex Force                         ln_vortex_force = ', ln_vortex_force
+         WRITE(numout,*) '      Bernouilli Head Pressure                ln_bern_srfc = ', ln_bern_srfc
+         WRITE(numout,*) '      wave modified ocean stress                  ln_tauoc = ', ln_tauoc
+         WRITE(numout,*) '      neutral drag coefficient (CORE bulk only)    ln_cdgw = ', ln_cdgw
+         WRITE(numout,*) '      charnock coefficient                        ln_charn = ', ln_charn
+         WRITE(numout,*) '      Stress modificated by wave                    ln_taw = ', ln_taw
+         WRITE(numout,*) '      TKE flux from wave                          ln_phioc = ', ln_phioc
+         WRITE(numout,*) '      Surface shear with Stokes drift           ln_stshear = ', ln_stshear
+         WRITE(numout,*) '      Test with constant wave fields          ln_wave_test = ', ln_wave_test
+      ENDIF
+
+      !                                ! option check
+      IF( .NOT.( ln_cdgw .OR. ln_sdw .OR. ln_tauoc .OR. ln_stcor .OR. ln_charn) )   &
+         &     CALL ctl_warn( 'Ask for wave coupling but ln_cdgw=F, ln_sdw=F, ln_tauoc=F, ln_stcor=F')
+      IF( ln_cdgw .AND. ln_blk )   &
+         &     CALL ctl_stop( 'drag coefficient read from wave model NOT available yet with aerobulk package')
+      IF( ln_stcor .AND. .NOT.ln_sdw )   &
+         &     CALL ctl_stop( 'Stokes-Coriolis term calculated only if activated Stokes Drift ln_sdw=T')
+
+      !                             !==  Allocate wave arrays  ==!
+      ALLOCATE( ut0sd (jpi,jpj)    , vt0sd (jpi,jpj) )
+      ALLOCATE( hsw   (jpi,jpj)    , wmp   (jpi,jpj) )
+      ALLOCATE( wnum  (jpi,jpj) )
+      ALLOCATE( tsd2d (jpi,jpj)    , div_sd(jpi,jpj)    , bhd_wave(jpi,jpj)     )
+      ALLOCATE( usd   (jpi,jpj,jpk), vsd   (jpi,jpj,jpk), wsd     (jpi,jpj,jpk) )
+      ALLOCATE( tusd  (jpi,jpj)    , tvsd  (jpi,jpj)    , ZMX     (jpi,jpj,jpk) )
+      usd   (:,:,:) = 0._wp
+      vsd   (:,:,:) = 0._wp
+      wsd   (:,:,:) = 0._wp
+      hsw     (:,:) = 0._wp
+      wmp     (:,:) = 0._wp
+      ut0sd   (:,:) = 0._wp
+      vt0sd   (:,:) = 0._wp
+      tusd    (:,:) = 0._wp
+      tvsd    (:,:) = 0._wp
+      bhd_wave(:,:) = 0._wp
+      ZMX   (:,:,:) = 0._wp
+!
+      IF( ln_wave_test ) THEN       !==  Wave TEST case  ==!   set uniform waves fields
+         jpfld    = 0                   ! No field read
+         ln_cdgw  = .FALSE.             ! No neutral wave drag input
+         ln_tauoc = .FALSE.             ! No wave induced drag reduction factor
+         ut0sd(:,:) = 0.13_wp * tmask(:,:,1)   ! m/s
+         vt0sd(:,:) = 0.00_wp                  ! m/s
+         hsw  (:,:) = 2.80_wp                  ! meters
+         wmp  (:,:) = 8.00_wp                  ! seconds
+         !
+      ELSE                          !==  create the structure associated with fields to be read  ==!
+         IF( ln_cdgw ) THEN                       ! wave drag
+            IF( .NOT. cpl_wdrag ) THEN
+               ALLOCATE( sf_cd(1), STAT=ierror )               !* allocate and fill sf_wave with sn_cdg
+               IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+               !
+                                      ALLOCATE( sf_cd(1)%fnow(jpi,jpj,1)   )
+               IF( sn_cdg%ln_tint )   ALLOCATE( sf_cd(1)%fdta(jpi,jpj,1,2) )
+               CALL fld_fill( sf_cd, (/ sn_cdg /), cn_dir, 'sbc_wave_init', 'Wave module ', 'namsbc_wave' )
+            ENDIF
+            ALLOCATE( cdn_wave(jpi,jpj) )
+            cdn_wave(:,:) = 0._wp
+         ENDIF
+         IF( ln_charn ) THEN                     ! wave drag
+            IF( .NOT. cpl_charn ) THEN
+               CALL ctl_stop( 'STOP', 'Charnock based wind stress can be used in coupled mode only' )
+            ENDIF
+            ALLOCATE( charn(jpi,jpj) )
+            charn(:,:) = 0._wp
+         ENDIF
+         IF( ln_taw ) THEN                     ! wind stress
+            IF( .NOT. cpl_taw ) THEN
+               CALL ctl_stop( 'STOP', 'wind stress from wave model can be used in coupled mode only, use ln_cdgw instead' )
+            ENDIF
+            ALLOCATE( tawx(jpi,jpj) )
+            ALLOCATE( tawy(jpi,jpj) )
+            ALLOCATE( twox(jpi,jpj) )
+            ALLOCATE( twoy(jpi,jpj) )
+            ALLOCATE( tauoc_wavex(jpi,jpj) )
+            ALLOCATE( tauoc_wavey(jpi,jpj) )
+            tawx(:,:) = 0._wp
+            tawy(:,:) = 0._wp
+            twox(:,:) = 0._wp
+            twoy(:,:) = 0._wp
+            tauoc_wavex(:,:) = 1._wp
+            tauoc_wavey(:,:) = 1._wp
+         ENDIF
+
+         IF( ln_phioc ) THEN                     ! TKE flux
+            IF( .NOT. cpl_phioc ) THEN
+                CALL ctl_stop( 'STOP', 'phioc can be used in coupled mode only' )
+            ENDIF
+            ALLOCATE( phioc(jpi,jpj) )
+            phioc(:,:) = 0._wp
+         ENDIF
+
+         IF( ln_tauoc ) THEN                    ! normalized wave stress into the ocean
+            IF( .NOT. cpl_wstrf ) THEN
+               ALLOCATE( sf_tauoc(1), STAT=ierror )           !* allocate and fill sf_wave with sn_tauoc
+               IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_tauoc structure' )
+               !
+                                       ALLOCATE( sf_tauoc(1)%fnow(jpi,jpj,1)   )
+               IF( sn_tauoc%ln_tint )  ALLOCATE( sf_tauoc(1)%fdta(jpi,jpj,1,2) )
+               CALL fld_fill( sf_tauoc, (/ sn_tauoc /), cn_dir, 'sbc_wave_init', 'Wave module', 'namsbc_wave' )
+            ENDIF
+            ALLOCATE( tauoc_wave(jpi,jpj) )
+            tauoc_wave(:,:) = 0._wp
+         ENDIF
+
+         IF( ln_sdw ) THEN                      ! Stokes drift
+            ! 1. Find out how many fields have to be read from file if not coupled
+            jpfld=0
+            jp_usd=0   ;   jp_vsd=0   ;   jp_hsw=0   ;   jp_wmp=0
+            IF( .NOT. cpl_sdrftx ) THEN
+               jpfld  = jpfld + 1
+               jp_usd = jpfld
+            ENDIF
+            IF( .NOT. cpl_sdrfty ) THEN
+               jpfld  = jpfld + 1
+               jp_vsd = jpfld
+            ENDIF
+            IF( .NOT. cpl_hsig ) THEN
+               jpfld  = jpfld + 1
+               jp_hsw = jpfld
+            ENDIF
+            IF( .NOT. cpl_wper ) THEN
+               jpfld  = jpfld + 1
+               jp_wmp = jpfld
+            ENDIF
+            ! 2. Read from file only the non-coupled fields 
+            IF( jpfld > 0 ) THEN
+               ALLOCATE( slf_i(jpfld) )
+               IF( jp_usd > 0 )   slf_i(jp_usd) = sn_usd
+               IF( jp_vsd > 0 )   slf_i(jp_vsd) = sn_vsd
+               IF( jp_hsw > 0 )   slf_i(jp_hsw) = sn_hsw
+               IF( jp_wmp > 0 )   slf_i(jp_wmp) = sn_wmp
+               ALLOCATE( sf_sd(jpfld), STAT=ierror )   !* allocate and fill sf_sd with stokes drift
+               IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+               !
+               DO ifpr= 1, jpfld
+                  ALLOCATE( sf_sd(ifpr)%fnow(jpi,jpj,1) )
+                  IF( slf_i(ifpr)%ln_tint )   ALLOCATE( sf_sd(ifpr)%fdta(jpi,jpj,1,2) )
+               END DO
+               !
+               CALL fld_fill( sf_sd, slf_i, cn_dir, 'sbc_wave_init', 'Wave module ', 'namsbc_wave' )
+            ENDIF
             !
-                                   ALLOCATE( sf_cd(1)%fnow(jpi,jpj,1)   )
-            IF( sn_cdg%ln_tint )   ALLOCATE( sf_cd(1)%fdta(jpi,jpj,1,2) )
-            CALL fld_fill( sf_cd, (/ sn_cdg /), cn_dir, 'sbc_wave_init', 'Wave module ', 'namsbc_wave' )
-         ENDIF
-         ALLOCATE( cdn_wave(jpi,jpj) )
-      ENDIF
-
-      IF( ln_tauwoc ) THEN
-         IF( .NOT. cpl_tauwoc ) THEN
-            ALLOCATE( sf_tauwoc(1), STAT=ierror )           !* allocate and fill sf_wave with sn_tauwoc
-            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+            ! 3. Wave number (only needed for Qiao parametrisation, ln_zdfqiao=T)
+            IF( .NOT. cpl_wnum ) THEN
+               ALLOCATE( sf_wn(1), STAT=ierror )           !* allocate and fill sf_wave with sn_wnum
+               IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wn structure' )
+                                      ALLOCATE( sf_wn(1)%fnow(jpi,jpj,1)   )
+               IF( sn_wnum%ln_tint )  ALLOCATE( sf_wn(1)%fdta(jpi,jpj,1,2) )
+               CALL fld_fill( sf_wn, (/ sn_wnum /), cn_dir, 'sbc_wave', 'Wave module', 'namsbc_wave' )
+            ENDIF
             !
-                                     ALLOCATE( sf_tauwoc(1)%fnow(jpi,jpj,1)   )
-            IF( sn_tauwoc%ln_tint )  ALLOCATE( sf_tauwoc(1)%fdta(jpi,jpj,1,2) )
-            CALL fld_fill( sf_tauwoc, (/ sn_tauwoc /), cn_dir, 'sbc_wave_init', 'Wave module', 'namsbc_wave' )
-         ENDIF
-         ALLOCATE( tauoc_wave(jpi,jpj) )
-      ENDIF
-
-      IF( ln_tauw ) THEN
-         IF( .NOT. cpl_tauw ) THEN
-            ALLOCATE( sf_tauw(2), STAT=ierror )           !* allocate and fill sf_wave with sn_tauwx/y
-            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_tauw structure' )
-            !
-            ALLOCATE( slf_j(2) )
-            slf_j(1) = sn_tauwx
-            slf_j(2) = sn_tauwy
-                                    ALLOCATE( sf_tauw(1)%fnow(jpi,jpj,1)   )
-                                    ALLOCATE( sf_tauw(2)%fnow(jpi,jpj,1)   )
-            IF( slf_j(1)%ln_tint )  ALLOCATE( sf_tauw(1)%fdta(jpi,jpj,1,2) )
-            IF( slf_j(2)%ln_tint )  ALLOCATE( sf_tauw(2)%fdta(jpi,jpj,1,2) )
-            CALL fld_fill( sf_tauw, (/ slf_j /), cn_dir, 'sbc_wave_init', 'read wave input', 'namsbc_wave' )
-         ENDIF
-         ALLOCATE( tauw_x(jpi,jpj) )
-         ALLOCATE( tauw_y(jpi,jpj) )
-      ENDIF
-
-      IF( ln_sdw ) THEN   ! Find out how many fields have to be read from file if not coupled
-         jpfld=0
-         jp_usd=0   ;   jp_vsd=0   ;   jp_hsw=0   ;   jp_wmp=0   ;   jp_wfr=0
-         IF( .NOT. cpl_sdrftx ) THEN
-            jpfld  = jpfld + 1
-            jp_usd = jpfld
-         ENDIF
-         IF( .NOT. cpl_sdrfty ) THEN
-            jpfld  = jpfld + 1
-            jp_vsd = jpfld
-         ENDIF
-         IF( .NOT. cpl_hsig  .AND. ll_st_bv_li  ) THEN
-            jpfld  = jpfld + 1
-            jp_hsw = jpfld
-         ENDIF
-         IF( .NOT. cpl_wper  .AND. ll_st_bv_li  ) THEN
-            jpfld  = jpfld + 1
-            jp_wmp = jpfld
-         ENDIF
-         IF( .NOT. cpl_wfreq .AND. ll_st_peakfr ) THEN
-            jpfld  = jpfld + 1
-            jp_wfr = jpfld
-         ENDIF
-
-         ! Read from file only the non-coupled fields 
-         IF( jpfld > 0 ) THEN
-            ALLOCATE( slf_i(jpfld) )
-            IF( jp_usd > 0 )   slf_i(jp_usd) = sn_usd
-            IF( jp_vsd > 0 )   slf_i(jp_vsd) = sn_vsd
-            IF( jp_hsw > 0 )   slf_i(jp_hsw) = sn_hsw
-            IF( jp_wmp > 0 )   slf_i(jp_wmp) = sn_wmp
-            IF( jp_wfr > 0 )   slf_i(jp_wfr) = sn_wfr
-
-            ALLOCATE( sf_sd(jpfld), STAT=ierror )   !* allocate and fill sf_sd with stokes drift
-            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
-            !
-            DO ifpr= 1, jpfld
-               ALLOCATE( sf_sd(ifpr)%fnow(jpi,jpj,1) )
-               IF( slf_i(ifpr)%ln_tint )   ALLOCATE( sf_sd(ifpr)%fdta(jpi,jpj,1,2) )
-            END DO
-            !
-            CALL fld_fill( sf_sd, slf_i, cn_dir, 'sbc_wave_init', 'Wave module ', 'namsbc_wave' )
-         ENDIF
-         ALLOCATE( usd  (jpi,jpj,jpk), vsd  (jpi,jpj,jpk), wsd(jpi,jpj,jpk) )
-         ALLOCATE( hsw  (jpi,jpj)    , wmp  (jpi,jpj)     )
-         ALLOCATE( wfreq(jpi,jpj) )
-         ALLOCATE( ut0sd(jpi,jpj)    , vt0sd(jpi,jpj)     )
-         ALLOCATE( div_sd(jpi,jpj) )
-         ALLOCATE( tsd2d (jpi,jpj) )
-
-         ut0sd(:,:) = 0._wp
-         vt0sd(:,:) = 0._wp
-         hsw(:,:) = 0._wp
-         wmp(:,:) = 0._wp
-
-         usd(:,:,:) = 0._wp
-         vsd(:,:,:) = 0._wp
-         wsd(:,:,:) = 0._wp
-         ! Wave number needed only if ln_zdfswm=T
-         IF( .NOT. cpl_wnum ) THEN
-            ALLOCATE( sf_wn(1), STAT=ierror )           !* allocate and fill sf_wave with sn_wnum
-            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable toallocate sf_wave structure' )
-                                   ALLOCATE( sf_wn(1)%fnow(jpi,jpj,1)   )
-            IF( sn_wnum%ln_tint )  ALLOCATE( sf_wn(1)%fdta(jpi,jpj,1,2) )
-            CALL fld_fill( sf_wn, (/ sn_wnum /), cn_dir, 'sbc_wave', 'Wave module', 'namsbc_wave' )
-         ENDIF
-         ALLOCATE( wnum(jpi,jpj) )
+         ENDIF
+         !
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/eosbn2.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/eosbn2.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/eosbn2.F90	(revision 14055)
@@ -39,4 +39,5 @@
    !!----------------------------------------------------------------------
    USE dom_oce        ! ocean space and time domain
+   USE domutl, ONLY : is_tile
    USE phycst         ! physical constants
    USE stopar         ! Stochastic T/S fluctuations
@@ -55,5 +56,5 @@
    !                  !! * Interface
    INTERFACE eos
-      MODULE PROCEDURE eos_insitu, eos_insitu_pot, eos_insitu_2d
+      MODULE PROCEDURE eos_insitu, eos_insitu_pot, eos_insitu_2d, eos_insitu_pot_2d
    END INTERFACE
    !
@@ -189,4 +190,14 @@
 
    SUBROUTINE eos_insitu( pts, prd, pdep )
+      !!
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                      ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prd   ! in situ density            [-]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pdep  ! depth                      [m]
+      !!
+      CALL eos_insitu_t( pts, is_tile(pts), prd, is_tile(prd), pdep, is_tile(pdep) )
+   END SUBROUTINE eos_insitu
+
+   SUBROUTINE eos_insitu_t( pts, ktts, prd, ktrd, pdep, ktdep )
       !!----------------------------------------------------------------------
       !!                   ***  ROUTINE eos_insitu  ***
@@ -222,8 +233,9 @@
       !!                TEOS-10 Manual, 2010
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
-      !                                                               ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd   ! in situ density            [-]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep  ! depth                      [m]
+      INTEGER                                 , INTENT(in   ) ::   ktts, ktrd, ktdep
+      REAL(wp), DIMENSION(A2D_T(ktts) ,JPK,JPTS), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                                  ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(A2D_T(ktrd) ,JPK     ), INTENT(  out) ::   prd   ! in situ density            [-]
+      REAL(wp), DIMENSION(A2D_T(ktdep),JPK     ), INTENT(in   ) ::   pdep  ! depth                      [m]
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -238,5 +250,5 @@
       CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
          !
-         DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             !
             zh  = pdep(ji,jj,jk) * r1_Z0                                  ! depth
@@ -274,5 +286,5 @@
       CASE( np_seos )                !==  simplified EOS  ==!
          !
-         DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             zt  = pts  (ji,jj,jk,jp_tem) - 10._wp
             zs  = pts  (ji,jj,jk,jp_sal) - 35._wp
@@ -293,8 +305,20 @@
       IF( ln_timing )   CALL timing_stop('eos-insitu')
       !
-   END SUBROUTINE eos_insitu
+   END SUBROUTINE eos_insitu_t
 
 
    SUBROUTINE eos_insitu_pot( pts, prd, prhop, pdep )
+      !!
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      !                                                       ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prd    ! in situ density            [-]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pdep   ! depth                      [m]
+      !!
+      CALL eos_insitu_pot_t( pts, is_tile(pts), prd, is_tile(prd), prhop, is_tile(prhop), pdep, is_tile(pdep) )
+   END SUBROUTINE eos_insitu_pot
+
+
+   SUBROUTINE eos_insitu_pot_t( pts, ktts, prd, ktrd, prhop, ktrhop, pdep, ktdep )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE eos_insitu_pot  ***
@@ -309,9 +333,10 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
-      !                                                                ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd    ! in situ density            [-]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep   ! depth                      [m]
+      INTEGER                                  , INTENT(in   ) ::   ktts, ktrd, ktrhop, ktdep
+      REAL(wp), DIMENSION(A2D_T(ktts)  ,JPK,JPTS), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      !                                                                    ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(A2D_T(ktrd)  ,JPK     ), INTENT(  out) ::   prd    ! in situ density            [-]
+      REAL(wp), DIMENSION(A2D_T(ktrhop),JPK     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      REAL(wp), DIMENSION(A2D_T(ktdep) ,JPK     ), INTENT(in   ) ::   pdep   ! depth                      [m]
       !
       INTEGER  ::   ji, jj, jk, jsmp             ! dummy loop indices
@@ -338,5 +363,5 @@
             END DO
             !
-            DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+            DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
                !
                ! compute density (2*nn_sto_eos) times:
@@ -388,5 +413,5 @@
          ! Non-stochastic equation of state
          ELSE
-            DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+            DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
                !
                zh  = pdep(ji,jj,jk) * r1_Z0                                  ! depth
@@ -426,5 +451,5 @@
       CASE( np_seos )                !==  simplified EOS  ==!
          !
-         DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             zt  = pts  (ji,jj,jk,jp_tem) - 10._wp
             zs  = pts  (ji,jj,jk,jp_sal) - 35._wp
@@ -444,12 +469,24 @@
       END SELECT
       !
-      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-pot: ', tab3d_2=prhop, clinfo2=' pot : ', kdim=jpk )
+      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-pot: ', &
+         &                                  tab3d_2=prhop, clinfo2=' pot : ', kdim=jpk )
       !
       IF( ln_timing )   CALL timing_stop('eos-pot')
       !
-   END SUBROUTINE eos_insitu_pot
+   END SUBROUTINE eos_insitu_pot_t
 
 
    SUBROUTINE eos_insitu_2d( pts, pdep, prd )
+      !!
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                    ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pdep  ! depth                      [m]
+      REAL(wp), DIMENSION(:,:)  , INTENT(  out) ::   prd   ! in situ density
+      !!
+      CALL eos_insitu_2d_t( pts, is_tile(pts), pdep, is_tile(pdep), prd, is_tile(prd) )
+   END SUBROUTINE eos_insitu_2d
+
+
+   SUBROUTINE eos_insitu_2d_t( pts, ktts, pdep, ktdep, prd, ktrd )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE eos_insitu_2d  ***
@@ -462,8 +499,9 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
-      !                                                           ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(in   ) ::   pdep  ! depth                      [m]
-      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(  out) ::   prd   ! in situ density
+      INTEGER                            , INTENT(in   ) ::   ktts, ktdep, ktrd
+      REAL(wp), DIMENSION(A2D_T(ktts),JPTS), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                             ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(A2D_T(ktdep)    ), INTENT(in   ) ::   pdep  ! depth                      [m]
+      REAL(wp), DIMENSION(A2D_T(ktrd)     ), INTENT(  out) ::   prd   ! in situ density
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -480,5 +518,5 @@
       CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
          !
-         DO_2D( 1, 1, 1, 1 )
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
             !
             zh  = pdep(ji,jj) * r1_Z0                                  ! depth
@@ -515,5 +553,5 @@
       CASE( np_seos )                !==  simplified EOS  ==!
          !
-         DO_2D( 1, 1, 1, 1 )
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
             !
             zt    = pts  (ji,jj,jp_tem)  - 10._wp
@@ -535,8 +573,91 @@
       IF( ln_timing )   CALL timing_stop('eos2d')
       !
-   END SUBROUTINE eos_insitu_2d
+   END SUBROUTINE eos_insitu_2d_t
+
+
+   SUBROUTINE eos_insitu_pot_2d( pts, prhop )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE eos_insitu_pot  ***
+      !!
+      !! ** Purpose :   Compute the in situ density (ratio rho/rho0) and the
+      !!      potential volumic mass (Kg/m3) from potential temperature and
+      !!      salinity fields using an equation of state selected in the
+      !!     namelist.
+      !!
+      !! ** Action  :
+      !!              - prhop, the potential volumic mass (Kg/m3)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      !                                                                ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(jpi,jpj     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      !
+      INTEGER  ::   ji, jj, jk, jsmp             ! dummy loop indices
+      INTEGER  ::   jdof
+      REAL(wp) ::   zt , zh , zstemp, zs , ztm   ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3      !   -      -
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: zn0_sto, zn_sto, zsign    ! local vectors
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('eos-pot')
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+            DO_2D( 1, 1, 1, 1 )
+               !
+               zt  = pts (ji,jj,jp_tem) * r1_T0                           ! temperature
+               zs  = SQRT( ABS( pts(ji,jj,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+               ztm = tmask(ji,jj,1)                                         ! tmask
+               !
+               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
+                  !
+               !
+               prhop(ji,jj) = zn0 * ztm                           ! potential density referenced at the surface
+               !
+            END_2D
+
+      CASE( np_seos )                !==  simplified EOS  ==!
+         !
+         DO_2D( 1, 1, 1, 1 )
+            zt  = pts  (ji,jj,jp_tem) - 10._wp
+            zs  = pts  (ji,jj,jp_sal) - 35._wp
+            ztm = tmask(ji,jj,1)
+            !                                                     ! potential density referenced at the surface
+            zn =  - rn_a0 * ( 1._wp + 0.5_wp*rn_lambda1*zt ) * zt   &
+               &  + rn_b0 * ( 1._wp - 0.5_wp*rn_lambda2*zs ) * zs   &
+               &  - rn_nu * zt * zs
+            prhop(ji,jj) = ( rho0 + zn ) * ztm
+            !
+         END_2D
+         !
+      END SELECT
+      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab2d_1=prhop, clinfo1=' pot: ', kdim=1 )
+      !
+      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab2d_1=prhop, clinfo1=' eos-pot: ' )
+      !
+      IF( ln_timing )   CALL timing_stop('eos-pot')
+      !
+   END SUBROUTINE eos_insitu_pot_2d
 
 
    SUBROUTINE rab_3d( pts, pab, Kmm )
+      !!
+      INTEGER                     , INTENT(in   ) ::   Kmm   ! time level index
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts   ! pot. temperature & salinity
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
+      !!
+      CALL rab_3d_t( pts, is_tile(pts), pab, is_tile(pab), Kmm )
+   END SUBROUTINE rab_3d
+
+
+   SUBROUTINE rab_3d_t( pts, ktts, pab, ktab, Kmm )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE rab_3d  ***
@@ -548,7 +669,8 @@
       !! ** Action  : - pab     : thermal/haline expansion ratio at T-points
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   ) ::   Kmm   ! time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! pot. temperature & salinity
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
+      INTEGER                                , INTENT(in   ) ::   Kmm   ! time level index
+      INTEGER                                , INTENT(in   ) ::   ktts, ktab
+      REAL(wp), DIMENSION(A2D_T(ktts),JPK,JPTS), INTENT(in   ) ::   pts   ! pot. temperature & salinity
+      REAL(wp), DIMENSION(A2D_T(ktab),JPK,JPTS), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -563,5 +685,5 @@
       CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
          !
-         DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             !
             zh  = gdept(ji,jj,jk,Kmm) * r1_Z0                                ! depth
@@ -616,5 +738,5 @@
       CASE( np_seos )                  !==  simplified EOS  ==!
          !
-         DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             zt  = pts (ji,jj,jk,jp_tem) - 10._wp   ! pot. temperature anomaly (t-T0)
             zs  = pts (ji,jj,jk,jp_sal) - 35._wp   ! abs. salinity anomaly (s-S0)
@@ -641,8 +763,19 @@
       IF( ln_timing )   CALL timing_stop('rab_3d')
       !
-   END SUBROUTINE rab_3d
+   END SUBROUTINE rab_3d_t
 
 
    SUBROUTINE rab_2d( pts, pdep, pab, Kmm )
+      !!
+      INTEGER                   , INTENT(in   ) ::   Kmm   ! time level index
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pts    ! pot. temperature & salinity
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pdep   ! depth                  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pab    ! thermal/haline expansion ratio
+      !!
+      CALL rab_2d_t(pts, is_tile(pts), pdep, is_tile(pdep), pab, is_tile(pab), Kmm)
+   END SUBROUTINE rab_2d
+
+
+   SUBROUTINE rab_2d_t( pts, ktts, pdep, ktdep, pab, ktab, Kmm )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE rab_2d  ***
@@ -652,8 +785,9 @@
       !! ** Action  : - pab     : thermal/haline expansion ratio at T-points
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   ) ::   Kmm   ! time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpts)    , INTENT(in   ) ::   pts    ! pot. temperature & salinity
-      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(in   ) ::   pdep   ! depth                  [m]
-      REAL(wp), DIMENSION(jpi,jpj,jpts)    , INTENT(  out) ::   pab    ! thermal/haline expansion ratio
+      INTEGER                            , INTENT(in   ) ::   Kmm   ! time level index
+      INTEGER                            , INTENT(in   ) ::   ktts, ktdep, ktab
+      REAL(wp), DIMENSION(A2D_T(ktts),JPTS), INTENT(in   ) ::   pts    ! pot. temperature & salinity
+      REAL(wp), DIMENSION(A2D_T(ktdep)    ), INTENT(in   ) ::   pdep   ! depth                  [m]
+      REAL(wp), DIMENSION(A2D_T(ktab),JPTS), INTENT(  out) ::   pab    ! thermal/haline expansion ratio
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -670,5 +804,5 @@
       CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
          !
-         DO_2D( 1, 1, 1, 1 )
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
             !
             zh  = pdep(ji,jj) * r1_Z0                                  ! depth
@@ -723,5 +857,5 @@
       CASE( np_seos )                  !==  simplified EOS  ==!
          !
-         DO_2D( 1, 1, 1, 1 )
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
             !
             zt    = pts  (ji,jj,jp_tem) - 10._wp   ! pot. temperature anomaly (t-T0)
@@ -748,5 +882,5 @@
       IF( ln_timing )   CALL timing_stop('rab_2d')
       !
-   END SUBROUTINE rab_2d
+   END SUBROUTINE rab_2d_t
 
 
@@ -849,4 +983,15 @@
 
    SUBROUTINE bn2( pts, pab, pn2, Kmm )
+      !!
+      INTEGER                              , INTENT(in   ) ::  Kmm   ! time level index
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celsius,psu]
+      REAL(wp), DIMENSION(:,:,:,:)         , INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-1,psu-1]
+      REAL(wp), DIMENSION(:,:,:)           , INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
+      !!
+      CALL bn2_t( pts, pab, is_tile(pab), pn2, is_tile(pn2), Kmm )
+   END SUBROUTINE bn2
+
+
+   SUBROUTINE bn2_t( pts, pab, ktab, pn2, ktn2, Kmm )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE bn2  ***
@@ -862,8 +1007,9 @@
       !!
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   ) ::   Kmm   ! time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celsius,psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-1,psu-1]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
+      INTEGER                                , INTENT(in   ) ::  Kmm   ! time level index
+      INTEGER                                , INTENT(in   ) ::  ktab, ktn2
+      REAL(wp), DIMENSION(jpi,jpj,  jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celsius,psu]
+      REAL(wp), DIMENSION(A2D_T(ktab),JPK,JPTS), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-1,psu-1]
+      REAL(wp), DIMENSION(A2D_T(ktn2),JPK     ), INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
       !
       INTEGER  ::   ji, jj, jk      ! dummy loop indices
@@ -873,5 +1019,5 @@
       IF( ln_timing )   CALL timing_start('bn2')
       !
-      DO_3D( 1, 1, 1, 1, 2, jpkm1 )      ! interior points only (2=< jk =< jpkm1 ); surface and bottom value set to zero one for all in istate.F90
+      DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 2, jpkm1 )      ! interior points only (2=< jk =< jpkm1 ); surface and bottom value set to zero one for all in istate.F90
          zrw =   ( gdepw(ji,jj,jk  ,Kmm) - gdept(ji,jj,jk,Kmm) )   &
             &  / ( gdept(ji,jj,jk-1,Kmm) - gdept(ji,jj,jk,Kmm) ) 
@@ -889,5 +1035,5 @@
       IF( ln_timing )   CALL timing_stop('bn2')
       !
-   END SUBROUTINE bn2
+   END SUBROUTINE bn2_t
 
 
@@ -949,5 +1095,15 @@
 
 
-   SUBROUTINE  eos_fzp_2d( psal, ptf, pdep )
+   SUBROUTINE eos_fzp_2d( psal, ptf, pdep )
+      !!
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   )           ::   psal   ! salinity   [psu]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
+      REAL(wp), DIMENSION(:,:)    , INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
+      !!
+      CALL eos_fzp_2d_t( psal, ptf, is_tile(ptf), pdep )
+   END SUBROUTINE eos_fzp_2d
+
+
+   SUBROUTINE  eos_fzp_2d_t( psal, ptf, kttf, pdep )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE eos_fzp  ***
@@ -961,7 +1117,8 @@
       !! Reference  :   UNESCO tech. papers in the marine science no. 28. 1978
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   )           ::   psal   ! salinity   [psu]
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
+      INTEGER                       , INTENT(in   )           ::   kttf
+      REAL(wp), DIMENSION(jpi,jpj)  , INTENT(in   )           ::   psal   ! salinity   [psu]
+      REAL(wp), DIMENSION(jpi,jpj)  , INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
+      REAL(wp), DIMENSION(A2D_T(kttf)), INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
       !
       INTEGER  ::   ji, jj          ! dummy loop indices
@@ -996,5 +1153,5 @@
       END SELECT      
       !
-  END SUBROUTINE eos_fzp_2d
+  END SUBROUTINE eos_fzp_2d_t
 
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv.F90	(revision 14055)
@@ -18,4 +18,6 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
+   ! TEMP: [tiling] This change not necessary after extended haloes development
+   USE domain, ONLY : dom_tile
    USE domvvl         ! variable vertical scale factors
    USE sbcwave        ! wave module
@@ -23,5 +25,7 @@
    USE traadv_cen     ! centered scheme            (tra_adv_cen  routine)
    USE traadv_fct     ! FCT      scheme            (tra_adv_fct  routine)
+   USE traadv_fct_lf  ! FCT      scheme            (tra_adv_fct  routine - loop fusion version)
    USE traadv_mus     ! MUSCL    scheme            (tra_adv_mus  routine)
+   USE traadv_mus_lf  ! MUSCL    scheme            (tra_adv_mus  routine - loop fusion version)
    USE traadv_ubs     ! UBS      scheme            (tra_adv_ubs  routine)
    USE traadv_qck     ! QUICKEST scheme            (tra_adv_qck  routine)
@@ -65,5 +69,7 @@
    INTEGER, PARAMETER ::   np_UBS     = 4   ! 3rd order Upstream Biased Scheme
    INTEGER, PARAMETER ::   np_QCK     = 5   ! QUICK scheme
-   
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
 #  include "domzgr_substitute.h90"
    !!----------------------------------------------------------------------
@@ -86,88 +92,151 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts            ! active tracers and RHS of tracer equation
       !
-      INTEGER ::   jk   ! dummy loop index
-      REAL(wp), DIMENSION(jpi,jpj,jpk)        :: zuu, zvv, zww   ! 3D workspace
-      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds
+      INTEGER ::   ji, jj, jk   ! dummy loop index
+      ! TEMP: [tiling] This change not necessary and can be A2D(nn_hls) if using XIOS (subdomain support)
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE, SAVE :: zuu, zvv, zww   ! 3D workspace
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: ztrdt, ztrds
+      ! TEMP: [tiling] This change not necessary after extra haloes development
+      LOGICAL :: lskip
       !!----------------------------------------------------------------------
       !
       IF( ln_timing )   CALL timing_start('tra_adv')
       !
-      !                                         !==  effective transport  ==!
-      zuu(:,:,jpk) = 0._wp
-      zvv(:,:,jpk) = 0._wp
-      zww(:,:,jpk) = 0._wp
-      IF( ln_wave .AND. ln_sdw )  THEN
-         DO jk = 1, jpkm1                                                       ! eulerian transport + Stokes Drift
-            zuu(:,:,jk) =   &
-               &  e2u  (:,:) * e3u(:,:,jk,Kmm) * ( uu(:,:,jk,Kmm) + usd(:,:,jk) )
-            zvv(:,:,jk) =   & 
-               &  e1v  (:,:) * e3v(:,:,jk,Kmm) * ( vv(:,:,jk,Kmm) + vsd(:,:,jk) )
-            zww(:,:,jk) =   & 
-               &  e1e2t(:,:)                 * ( ww(:,:,jk) + wsd(:,:,jk) )
-         END DO
-      ELSE
-         DO jk = 1, jpkm1
-            zuu(:,:,jk) = e2u  (:,:) * e3u(:,:,jk,Kmm) * uu(:,:,jk,Kmm)               ! eulerian transport only
-            zvv(:,:,jk) = e1v  (:,:) * e3v(:,:,jk,Kmm) * vv(:,:,jk,Kmm)
-            zww(:,:,jk) = e1e2t(:,:)                 * ww(:,:,jk)
-         END DO
-      ENDIF
-      !
-      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN                                ! add z-tilde and/or vvl corrections
-         zuu(:,:,:) = zuu(:,:,:) + un_td(:,:,:)
-         zvv(:,:,:) = zvv(:,:,:) + vn_td(:,:,:)
-      ENDIF
-      !
-      zuu(:,:,jpk) = 0._wp                                                      ! no transport trough the bottom
-      zvv(:,:,jpk) = 0._wp
-      zww(:,:,jpk) = 0._wp
-      !
-      IF( ln_ldfeiv .AND. .NOT. ln_traldf_triad )   &
-         &              CALL ldf_eiv_trp( kt, nit000, zuu, zvv, zww, 'TRA', Kmm, Krhs )   ! add the eiv transport (if necessary)
-      !
-      IF( ln_mle    )   CALL tra_mle_trp( kt, nit000, zuu, zvv, zww, 'TRA', Kmm       )   ! add the mle transport (if necessary)
-      !
-      CALL iom_put( "uocetr_eff", zuu )                                        ! output effective transport      
-      CALL iom_put( "vocetr_eff", zvv )
-      CALL iom_put( "wocetr_eff", zww )
-      !
-!!gm ???
-      CALL dia_ptr( kt, Kmm, zvv )                                    ! diagnose the effective MSF 
-!!gm ???
-      !
-
-      IF( l_trdtra )   THEN                    !* Save ta and sa trends
-         ALLOCATE( ztrdt(jpi,jpj,jpk), ztrds(jpi,jpj,jpk) )
-         ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
-         ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs)
-      ENDIF
-      !
-      SELECT CASE ( nadv )                      !==  compute advection trend and add it to general trend  ==!
-      !
-      CASE ( np_CEN )                                 ! Centered scheme : 2nd / 4th order
-         CALL tra_adv_cen    ( kt, nit000, 'TRA',         zuu, zvv, zww, Kmm, pts, jpts, Krhs, nn_cen_h, nn_cen_v )
-      CASE ( np_FCT )                                 ! FCT scheme      : 2nd / 4th order
-         CALL tra_adv_fct    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, nn_fct_h, nn_fct_v )
-      CASE ( np_MUS )                                 ! MUSCL
-         CALL tra_adv_mus    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, ln_mus_ups ) 
-      CASE ( np_UBS )                                 ! UBS
-         CALL tra_adv_ubs    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, nn_ubs_v   )
-      CASE ( np_QCK )                                 ! QUICKEST
-         CALL tra_adv_qck    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs )
-      !
-      END SELECT
-      !
-      IF( l_trdtra )   THEN                      ! save the advective trends for further diagnostics
-         DO jk = 1, jpkm1
-            ztrdt(:,:,jk) = pts(:,:,jk,jp_tem,Krhs) - ztrdt(:,:,jk)
-            ztrds(:,:,jk) = pts(:,:,jk,jp_sal,Krhs) - ztrds(:,:,jk)
-         END DO
-         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_totad, ztrdt )
-         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_totad, ztrds )
-         DEALLOCATE( ztrdt, ztrds )
+      lskip = .FALSE.
+
+      ! TEMP: [tiling] These changes not necessary if using XIOS (subdomain support)
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         ALLOCATE( zuu(jpi,jpj,jpk), zvv(jpi,jpj,jpk), zww(jpi,jpj,jpk) )
+      ENDIF
+
+      ! TEMP: [tiling] These changes not necessary after extra haloes development (lbc_lnk removed from tra_adv_*) and if XIOS has subdomain support (ldf_eiv_dia)
+      IF( nadv /= np_CEN .OR. (nadv == np_CEN .AND. nn_cen_h == 4) .OR. ln_ldfeiv_dia )  THEN
+         IF( ln_tile ) THEN
+            IF( ntile == 1 ) THEN
+               CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )
+            ELSE
+               lskip = .TRUE.
+            ENDIF
+         ENDIF
+      ENDIF
+      IF( .NOT. lskip ) THEN
+         !                                         !==  effective transport  ==!
+         IF( ln_wave .AND. ln_sdw )  THEN
+            DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
+               zuu(ji,jj,jk) = e2u  (ji,jj) * e3u(ji,jj,jk,Kmm) * ( uu(ji,jj,jk,Kmm) + usd(ji,jj,jk) )
+               zvv(ji,jj,jk) = e1v  (ji,jj) * e3v(ji,jj,jk,Kmm) * ( vv(ji,jj,jk,Kmm) + vsd(ji,jj,jk) )
+               zww(ji,jj,jk) = e1e2t(ji,jj)                     * ( ww(ji,jj,jk)     + wsd(ji,jj,jk) )
+            END_3D
+         ELSE
+            DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
+               zuu(ji,jj,jk) = e2u  (ji,jj) * e3u(ji,jj,jk,Kmm) * uu(ji,jj,jk,Kmm)               ! eulerian transport only
+               zvv(ji,jj,jk) = e1v  (ji,jj) * e3v(ji,jj,jk,Kmm) * vv(ji,jj,jk,Kmm)
+               zww(ji,jj,jk) = e1e2t(ji,jj)                     * ww(ji,jj,jk)
+            END_3D
+         ENDIF
+         !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN                                ! add z-tilde and/or vvl corrections
+            DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
+               zuu(ji,jj,jk) = zuu(ji,jj,jk) + un_td(ji,jj,jk)
+               zvv(ji,jj,jk) = zvv(ji,jj,jk) + vn_td(ji,jj,jk)
+            END_3D
+         ENDIF
+         !
+         DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
+            zuu(ji,jj,jpk) = 0._wp                                                      ! no transport trough the bottom
+            zvv(ji,jj,jpk) = 0._wp
+            zww(ji,jj,jpk) = 0._wp
+         END_2D
+         !
+         ! TEMP: [tiling] These changes not necessary if using XIOS (subdomain support)
+         IF( ln_ldfeiv .AND. .NOT. ln_traldf_triad )   &
+            &              CALL ldf_eiv_trp( kt, nit000, zuu(A2D(nn_hls),:), zvv(A2D(nn_hls),:), zww(A2D(nn_hls),:), &
+            &                                'TRA', Kmm, Krhs )   ! add the eiv transport (if necessary)
+         !
+         IF( ln_mle    )   CALL tra_mle_trp( kt, nit000, zuu(A2D(nn_hls),:), zvv(A2D(nn_hls),:), zww(A2D(nn_hls),:), &
+            &                                'TRA', Kmm       )   ! add the mle transport (if necessary)
+         !
+         ! TEMP: [tiling] This change not necessary if using XIOS (subdomain support)
+         IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+            CALL iom_put( "uocetr_eff", zuu )                                        ! output effective transport
+            CALL iom_put( "vocetr_eff", zvv )
+            CALL iom_put( "wocetr_eff", zww )
+         ENDIF
+         !
+   !!gm ???
+         ! TEMP: [tiling] This change not necessary if using XIOS (subdomain support)
+         CALL dia_ptr( kt, Kmm, zvv(A2D(nn_hls),:) )                                    ! diagnose the effective MSF
+   !!gm ???
+         !
+
+         IF( l_trdtra )   THEN                    !* Save ta and sa trends
+            ALLOCATE( ztrdt(jpi,jpj,jpk), ztrds(jpi,jpj,jpk) )
+            ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
+            ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs)
+         ENDIF
+         !
+         ! NOTE: [tiling-comms-merge] These lbc_lnk calls are still needed (pts in the zco case because zps_hde is not called in step, zuu/zvv/zww in all cases, I think because DO loop bounds need to be updated in DYN as done in TRA)
+         SELECT CASE ( nadv )                      !==  compute advection trend and add it to general trend  ==!
+         !
+         CASE ( np_CEN )                                 ! Centered scheme : 2nd / 4th order
+            IF (nn_hls.EQ.2) CALL lbc_lnk( 'traadv', pts(:,:,:,:,Kmm), 'T', 1. )
+            CALL tra_adv_cen    ( kt, nit000, 'TRA',         zuu, zvv, zww, Kmm, pts, jpts, Krhs, nn_cen_h, nn_cen_v )
+         CASE ( np_FCT )                                 ! FCT scheme      : 2nd / 4th order
+            IF (nn_hls.EQ.2) THEN
+               CALL lbc_lnk_multi( 'traadv', pts(:,:,:,:,Kbb), 'T', 1., pts(:,:,:,:,Kmm), 'T', 1.)
+               CALL lbc_lnk_multi( 'traadv', zuu(:,:,:), 'U', -1., zvv(:,:,:), 'V', -1., zww(:,:,:), 'W', 1.)
+#if defined key_loop_fusion
+               CALL tra_adv_fct_lf ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, nn_fct_h, nn_fct_v )
+#else
+               CALL tra_adv_fct    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, nn_fct_h, nn_fct_v )
+#endif
+            ELSE
+               CALL tra_adv_fct    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, nn_fct_h, nn_fct_v )
+            END IF
+         CASE ( np_MUS )                                 ! MUSCL
+            ! NOTE: [tiling-comms-merge] I added this lbc_lnk as it did not validate against the trunk when using ln_zco
+            IF (nn_hls.EQ.2) THEN 
+                CALL lbc_lnk( 'traadv', pts(:,:,:,:,Kbb), 'T', 1.)
+#if defined key_loop_fusion
+                CALL tra_adv_mus_lf ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, ln_mus_ups ) 
+#else
+                CALL tra_adv_mus    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, ln_mus_ups ) 
+#endif
+            ELSE
+                CALL tra_adv_mus    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, ln_mus_ups ) 
+            END IF
+         CASE ( np_UBS )                                 ! UBS
+            IF (nn_hls.EQ.2) CALL lbc_lnk( 'traadv', pts(:,:,:,:,Kbb), 'T', 1.)
+            CALL tra_adv_ubs    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs, nn_ubs_v   )
+         CASE ( np_QCK )                                 ! QUICKEST
+            IF (nn_hls.EQ.2) THEN
+               CALL lbc_lnk_multi( 'traadv', zuu(:,:,:), 'U', -1., zvv(:,:,:), 'V', -1.)
+               CALL lbc_lnk( 'traadv', pts(:,:,:,:,Kbb), 'T', 1.)
+            END IF
+            CALL tra_adv_qck    ( kt, nit000, 'TRA', rDt, zuu, zvv, zww, Kbb, Kmm, pts, jpts, Krhs )
+         !
+         END SELECT
+         !
+         IF( l_trdtra )   THEN                      ! save the advective trends for further diagnostics
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = pts(:,:,jk,jp_tem,Krhs) - ztrdt(:,:,jk)
+               ztrds(:,:,jk) = pts(:,:,jk,jp_sal,Krhs) - ztrds(:,:,jk)
+            END DO
+            CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_totad, ztrdt )
+            CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_totad, ztrds )
+            DEALLOCATE( ztrdt, ztrds )
+         ENDIF
+
+         ! TEMP: [tiling] This change not necessary after extra haloes development (lbc_lnk removed from tra_adv_*) and if XIOS has subdomain support (ldf_eiv_dia)
+         IF( ln_tile .AND. ntile == 0 ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 1 )
+
       ENDIF
       !                                              ! print mean trends (used for debugging)
-      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' adv  - Ta: ', mask1=tmask,               &
+      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' adv  - Ta: ', mask1=tmask, &
          &                                  tab3d_2=pts(:,:,:,jp_sal,Krhs), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+
+      ! TEMP: [tiling] This change not necessary if using XIOS (subdomain support)
+      IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only for the full domain
+         DEALLOCATE( zuu, zvv, zww )
+      ENDIF
       !
       IF( ln_timing )   CALL timing_stop( 'tra_adv' )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_cen.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_cen.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_cen.F90	(revision 14055)
@@ -71,4 +71,5 @@
       INTEGER                                  , INTENT(in   ) ::   kn_cen_h        ! =2/4 (2nd or 4th order scheme)
       INTEGER                                  , INTENT(in   ) ::   kn_cen_v        ! =2/4 (2nd or 4th order scheme)
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU, pV, pW      ! 3 ocean volume flux components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
@@ -78,20 +79,22 @@
       REAL(wp) ::   zC2t_u, zC4t_u   ! local scalars
       REAL(wp) ::   zC2t_v, zC4t_v   !   -      -
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwx, zwy, zwz, ztu, ztv, ztw
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwx, zwy, zwz, ztu, ztv, ztw
       !!----------------------------------------------------------------------
       !
-      IF( kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_adv_cen : centered advection scheme on ', cdtype, ' order h/v =', kn_cen_h,'/', kn_cen_v
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~ '
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_adv_cen : centered advection scheme on ', cdtype, ' order h/v =', kn_cen_h,'/', kn_cen_v
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~ '
+         ENDIF
+         !                          ! set local switches
+         l_trd = .FALSE.
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )       l_trd = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )    l_ptr = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+            &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
       ENDIF
-      !                          ! set local switches
-      l_trd = .FALSE.
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )       l_trd = .TRUE.
-      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )    l_ptr = .TRUE. 
-      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
-         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
       !
       !                    
@@ -112,11 +115,11 @@
             ztu(:,:,jpk) = 0._wp                   ! Bottom value : flux set to zero
             ztv(:,:,jpk) = 0._wp
-            DO_3D( 0, 0, 0, 0, 1, jpkm1 )          ! masked gradient
+            DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )          ! masked gradient
                ztu(ji,jj,jk) = ( pt(ji+1,jj  ,jk,jn,Kmm) - pt(ji,jj,jk,jn,Kmm) ) * umask(ji,jj,jk)
                ztv(ji,jj,jk) = ( pt(ji  ,jj+1,jk,jn,Kmm) - pt(ji,jj,jk,jn,Kmm) ) * vmask(ji,jj,jk)
             END_3D
-            CALL lbc_lnk_multi( 'traadv_cen', ztu, 'U', -1.0_wp , ztv, 'V', -1.0_wp )   ! Lateral boundary cond.
+            IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_cen', ztu, 'U', -1.0_wp , ztv, 'V', -1.0_wp )   ! Lateral boundary cond.
             !
-            DO_3D( 0, 0, 0, 0, 1, jpkm1 )           ! Horizontal advective fluxes
+            DO_3D( nn_hls-1, 0, nn_hls-1, 0, 1, jpkm1 )           ! Horizontal advective fluxes
                zC2t_u = pt(ji,jj,jk,jn,Kmm) + pt(ji+1,jj  ,jk,jn,Kmm)   ! C2 interpolation of T at u- & v-points (x2)
                zC2t_v = pt(ji,jj,jk,jn,Kmm) + pt(ji  ,jj+1,jk,jn,Kmm)
@@ -128,5 +131,5 @@
                zwy(ji,jj,jk) =  0.5_wp * pV(ji,jj,jk) * zC4t_v
             END_3D
-            CALL lbc_lnk_multi( 'traadv_cen', zwx, 'U', -1. , zwy, 'V', -1. )
+            IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_cen', zwx, 'U', -1. , zwy, 'V', -1. )
             !
          CASE DEFAULT
@@ -155,5 +158,7 @@
                END_2D
             ELSE                                   ! no ice-shelf cavities (only ocean surface)
-               zwz(:,:,1) = pW(:,:,1) * pt(:,:,1,jn,Kmm)
+               DO_2D( 1, 1, 1, 1 )
+                  zwz(ji,jj,1) = pW(ji,jj,1) * pt(ji,jj,1,jn,Kmm)
+               END_2D
             ENDIF
          ENDIF
@@ -171,6 +176,6 @@
             CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_yad, zwy, pV, pt(:,:,:,jn,Kmm) )
             CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_zad, zwz, pW, pt(:,:,:,jn,Kmm) )
-         END IF
-         !                                 ! "Poleward" heat and salt transports 
+         ENDIF
+         !                                 ! "Poleward" heat and salt transports
          IF( l_ptr )   CALL dia_ptr_hst( jn, 'adv', zwy(:,:,:) )
          !                                 !  heat and salt transport
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_fct.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_fct.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_fct.F90	(revision 14055)
@@ -34,4 +34,6 @@
    PUBLIC   tra_adv_fct        ! called by traadv.F90
    PUBLIC   interp_4th_cpt     ! called by traadv_cen.F90
+   PUBLIC   tridia_solver      ! called by traadv_fct_lf.F90
+   PUBLIC   nonosc             ! called by traadv_fct_lf.F90 - key_agrif
 
    LOGICAL  ::   l_trd   ! flag to compute trends
@@ -79,12 +81,14 @@
       INTEGER                                  , INTENT(in   ) ::   kn_fct_v        ! order of the FCT scheme (=2 or 4)
       REAL(wp)                                 , INTENT(in   ) ::   p2dt            ! tracer time-step
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
+      ! NOTE: [tiling-comms-merge] These were changed to INTENT(inout) but they are not modified, so it is reverted
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU, pV, pW      ! 3 ocean volume flux components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
       !
-      INTEGER  ::   ji, jj, jk, jn                           ! dummy loop indices  
+      INTEGER  ::   ji, jj, jk, jn                           ! dummy loop indices
       REAL(wp) ::   ztra                                     ! local scalar
       REAL(wp) ::   zfp_ui, zfp_vj, zfp_wk, zC2t_u, zC4t_u   !   -      -
       REAL(wp) ::   zfm_ui, zfm_vj, zfm_wk, zC2t_v, zC4t_v   !   -      -
-      REAL(wp), DIMENSION(jpi,jpj,jpk)        ::   zwi, zwx, zwy, zwz, ztu, ztv, zltu, zltv, ztw
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk)        ::   zwi, zwx, zwy, zwz, ztu, ztv, zltu, zltv, ztw
       REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdx, ztrdy, ztrdz, zptry
       REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   zwinf, zwdia, zwsup
@@ -92,9 +96,23 @@
       !!----------------------------------------------------------------------
       !
-      IF( kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_adv_fct : FCT advection scheme on ', cdtype
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_adv_fct : FCT advection scheme on ', cdtype
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+         ENDIF
+         ! NOTE: [tiling-comms-merge] Bug fix- move array zeroing out of this IF block
+         !
+         l_trd = .FALSE.            ! set local switches
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         ll_zAimp = .FALSE.
+         IF( ( cdtype == 'TRA' .AND. l_trdtra  ) .OR. ( cdtype =='TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) ) )    l_ptr = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR.  &
+            &                         iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
+         !
       ENDIF
+
       !! -- init to 0
       zwi(:,:,:) = 0._wp
@@ -108,36 +126,22 @@
       ztw(:,:,:) = 0._wp
       !
-      l_trd = .FALSE.            ! set local switches
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      ll_zAimp = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra  ) .OR. ( cdtype =='TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
-      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) ) )    l_ptr = .TRUE. 
-      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR.  &
-         &                         iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
-      !
       IF( l_trd .OR. l_hst )  THEN
-         ALLOCATE( ztrdx(jpi,jpj,jpk), ztrdy(jpi,jpj,jpk), ztrdz(jpi,jpj,jpk) )
+         ALLOCATE( ztrdx(A2D(nn_hls),jpk), ztrdy(A2D(nn_hls),jpk), ztrdz(A2D(nn_hls),jpk) )
          ztrdx(:,:,:) = 0._wp   ;    ztrdy(:,:,:) = 0._wp   ;   ztrdz(:,:,:) = 0._wp
       ENDIF
       !
-      IF( l_ptr ) THEN  
-         ALLOCATE( zptry(jpi,jpj,jpk) )
+      IF( l_ptr ) THEN
+         ALLOCATE( zptry(A2D(nn_hls),jpk) )
          zptry(:,:,:) = 0._wp
       ENDIF
-      !                          ! surface & bottom value : flux set to zero one for all
-      zwz(:,:, 1 ) = 0._wp            
-      zwx(:,:,jpk) = 0._wp   ;   zwy(:,:,jpk) = 0._wp    ;    zwz(:,:,jpk) = 0._wp
-      !
-      zwi(:,:,:) = 0._wp        
       !
       ! If adaptive vertical advection, check if it is needed on this PE at this time
       IF( ln_zad_Aimp ) THEN
-         IF( MAXVAL( ABS( wi(:,:,:) ) ) > 0._wp ) ll_zAimp = .TRUE.
+         IF( MAXVAL( ABS( wi(A2D(nn_hls),:) ) ) > 0._wp ) ll_zAimp = .TRUE.
       END IF
       ! If active adaptive vertical advection, build tridiagonal matrix
       IF( ll_zAimp ) THEN
-         ALLOCATE(zwdia(jpi,jpj,jpk), zwinf(jpi,jpj,jpk),zwsup(jpi,jpj,jpk))
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         ALLOCATE(zwdia(A2D(nn_hls),jpk), zwinf(A2D(nn_hls),jpk), zwsup(A2D(nn_hls),jpk))
+         DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 1, jpkm1 )
             zwdia(ji,jj,jk) =  1._wp + p2dt * ( MAX( wi(ji,jj,jk) , 0._wp ) - MIN( wi(ji,jj,jk+1) , 0._wp ) )   &
             &                               / e3t(ji,jj,jk,Krhs)
@@ -151,5 +155,5 @@
          !        !==  upstream advection with initial mass fluxes & intermediate update  ==!
          !                    !* upstream tracer flux in the i and j direction 
-         DO_3D( 1, 0, 1, 0, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )
             ! upstream scheme
             zfp_ui = pU(ji,jj,jk) + ABS( pU(ji,jj,jk) )
@@ -178,5 +182,5 @@
          ENDIF
          !               
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )   !* trend and after field with monotonic scheme
+         DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 1, jpkm1 )   !* trend and after field with monotonic scheme
             !                               ! total intermediate advective trends
             ztra = - (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
@@ -194,5 +198,5 @@
             !
             ztw(:,:,1) = 0._wp ; ztw(:,:,jpk) = 0._wp ;
-            DO_3D( 0, 0, 0, 0, 2, jpkm1 )       ! Interior value ( multiplied by wmask)
+            DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 2, jpkm1 )       ! Interior value ( multiplied by wmask)
                zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
                zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
@@ -206,5 +210,5 @@
             !
          END IF
-         !                
+         !
          IF( l_trd .OR. l_hst )  THEN             ! trend diagnostics (contribution of upstream fluxes)
             ztrdx(:,:,:) = zwx(:,:,:)   ;   ztrdy(:,:,:) = zwy(:,:,:)   ;   ztrdz(:,:,:) = zwz(:,:,:)
@@ -218,5 +222,5 @@
          !
          CASE(  2  )                   !- 2nd order centered
-            DO_3D( 1, 0, 1, 0, 1, jpkm1 )
+            DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )
                zwx(ji,jj,jk) = 0.5_wp * pU(ji,jj,jk) * ( pt(ji,jj,jk,jn,Kmm) + pt(ji+1,jj,jk,jn,Kmm) ) - zwx(ji,jj,jk)
                zwy(ji,jj,jk) = 0.5_wp * pV(ji,jj,jk) * ( pt(ji,jj,jk,jn,Kmm) + pt(ji,jj+1,jk,jn,Kmm) ) - zwy(ji,jj,jk)
@@ -238,20 +242,23 @@
             CALL lbc_lnk_multi( 'traadv_fct', zltu, 'T', 1.0_wp , zltv, 'T', 1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
             !
-            DO_3D( 1, 0, 1, 0, 1, jpkm1 )    ! Horizontal advective fluxes
+            DO_3D( 1, 0, 1, 0, 1, jpkm1 )
                zC2t_u = pt(ji,jj,jk,jn,Kmm) + pt(ji+1,jj  ,jk,jn,Kmm)   ! 2 x C2 interpolation of T at u- & v-points
                zC2t_v = pt(ji,jj,jk,jn,Kmm) + pt(ji  ,jj+1,jk,jn,Kmm)
-               !                                                        ! C4 minus upstream advective fluxes 
+               !                                                        ! C4 minus upstream advective fluxes
                zwx(ji,jj,jk) =  0.5_wp * pU(ji,jj,jk) * ( zC2t_u + zltu(ji,jj,jk) - zltu(ji+1,jj,jk) ) - zwx(ji,jj,jk)
                zwy(ji,jj,jk) =  0.5_wp * pV(ji,jj,jk) * ( zC2t_v + zltv(ji,jj,jk) - zltv(ji,jj+1,jk) ) - zwy(ji,jj,jk)
             END_3D
+            IF (nn_hls.EQ.2) CALL lbc_lnk_multi( 'traadv_fct', zwx, 'U', -1.0_wp, zwy, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
             !
          CASE(  41 )                   !- 4th order centered       ==>>   !!gm coding attempt   need to be tested
             ztu(:,:,jpk) = 0._wp             ! Bottom value : flux set to zero
             ztv(:,:,jpk) = 0._wp
-            DO_3D( 1, 0, 1, 0, 1, jpkm1 )    ! 1st derivative (gradient)
+            DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )    ! 1st derivative (gradient)
                ztu(ji,jj,jk) = ( pt(ji+1,jj  ,jk,jn,Kmm) - pt(ji,jj,jk,jn,Kmm) ) * umask(ji,jj,jk)
                ztv(ji,jj,jk) = ( pt(ji  ,jj+1,jk,jn,Kmm) - pt(ji,jj,jk,jn,Kmm) ) * vmask(ji,jj,jk)
             END_3D
-            CALL lbc_lnk_multi( 'traadv_fct', ztu, 'U', -1.0_wp , ztv, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
+            IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_fct', ztu, 'U', -1.0_wp , ztv, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
+            !
+            IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_fct', ztu, 'U', -1.0_wp , ztv, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
             !
             DO_3D( 0, 0, 0, 0, 1, jpkm1 )    ! Horizontal advective fluxes
@@ -265,4 +272,5 @@
                zwy(ji,jj,jk) =  0.5_wp * pV(ji,jj,jk) * zC4t_v - zwy(ji,jj,jk)
             END_3D
+            IF (nn_hls.EQ.2) CALL lbc_lnk_multi( 'traadv_fct', zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
             !
          END SELECT
@@ -271,5 +279,5 @@
          !
          CASE(  2  )                   !- 2nd order centered
-            DO_3D( 0, 0, 0, 0, 2, jpkm1 )
+            DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 2, jpkm1 )
                zwz(ji,jj,jk) =  (  pW(ji,jj,jk) * 0.5_wp * ( pt(ji,jj,jk,jn,Kmm) + pt(ji,jj,jk-1,jn,Kmm) )   &
                   &              - zwz(ji,jj,jk)  ) * wmask(ji,jj,jk)
@@ -278,5 +286,5 @@
          CASE(  4  )                   !- 4th order COMPACT
             CALL interp_4th_cpt( pt(:,:,:,jn,Kmm) , ztw )   ! zwt = COMPACT interpolation of T at w-point
-            DO_3D( 0, 0, 0, 0, 2, jpkm1 )
+            DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 2, jpkm1 )
                zwz(ji,jj,jk) = ( pW(ji,jj,jk) * ztw(ji,jj,jk) - zwz(ji,jj,jk) ) * wmask(ji,jj,jk)
             END_3D
@@ -286,24 +294,34 @@
             zwz(:,:,1) = 0._wp   ! only ocean surface as interior zwz values have been w-masked
          ENDIF
-         !         
+         !
+         IF (nn_hls.EQ.1) THEN
+            CALL lbc_lnk_multi( 'traadv_fct', zwi, 'T', 1.0_wp, zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp, zwz, 'T', 1.0_wp )
+         ELSE
+            CALL lbc_lnk( 'traadv_fct', zwi, 'T', 1.0_wp)
+         END IF
+         !
+         IF (nn_hls.EQ.1) THEN
+            CALL lbc_lnk_multi( 'traadv_fct', zwi, 'T', 1.0_wp, zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp, zwz, 'T', 1.0_wp )
+         ELSE
+            CALL lbc_lnk( 'traadv_fct', zwi, 'T', 1.0_wp)
+         END IF
+         !
          IF ( ll_zAimp ) THEN
-            DO_3D( 0, 0, 0, 0, 1, jpkm1 )    !* trend and after field with monotonic scheme
+            DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 1, jpkm1 )    !* trend and after field with monotonic scheme
                !                                                ! total intermediate advective trends
                ztra = - (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
                   &      + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
                   &      + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) ) * r1_e1e2t(ji,jj)
-               ztw(ji,jj,jk)  = zwi(ji,jj,jk) + p2dt * ztra / e3t(ji,jj,jk,Krhs) * tmask(ji,jj,jk)
+               ztw(ji,jj,jk) = zwi(ji,jj,jk) + p2dt * ztra / e3t(ji,jj,jk,Krhs) * tmask(ji,jj,jk)
             END_3D
             !
             CALL tridia_solver( zwdia, zwsup, zwinf, ztw, ztw , 0 )
             !
-            DO_3D( 0, 0, 0, 0, 2, jpkm1 )       ! Interior value ( multiplied by wmask)
+            DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 2, jpkm1 )       ! Interior value ( multiplied by wmask)
                zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
                zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
-               zwz(ji,jj,jk) =  zwz(ji,jj,jk) + 0.5 * e1e2t(ji,jj) * ( zfp_wk * ztw(ji,jj,jk) + zfm_wk * ztw(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+               zwz(ji,jj,jk) = zwz(ji,jj,jk) + 0.5 * e1e2t(ji,jj) * ( zfp_wk * ztw(ji,jj,jk) + zfm_wk * ztw(ji,jj,jk-1) ) * wmask(ji,jj,jk)
             END_3D
          END IF
-         !
-         CALL lbc_lnk_multi( 'traadv_fct', zwi, 'T', 1.0_wp, zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp,  zwz, 'W',  1.0_wp )
          !
          !        !==  monotonicity algorithm  ==!
@@ -334,8 +352,9 @@
                   &                                        * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
             END_3D
-         END IF         
-         !
+         END IF
+         ! NOTE: [tiling-comms-merge] I tested this
+         ! NOT TESTED - NEED l_trd OR l_hst TRUE
          IF( l_trd .OR. l_hst ) THEN   ! trend diagnostics // heat/salt transport
-            ztrdx(:,:,:) = ztrdx(:,:,:) + zwx(:,:,:)  ! <<< add anti-diffusive fluxes 
+            ztrdx(:,:,:) = ztrdx(:,:,:) + zwx(:,:,:)  ! <<< add anti-diffusive fluxes
             ztrdy(:,:,:) = ztrdy(:,:,:) + zwy(:,:,:)  !     to upstream fluxes
             ztrdz(:,:,:) = ztrdz(:,:,:) + zwz(:,:,:)  !
@@ -350,4 +369,6 @@
             !
          ENDIF
+         ! NOTE: [tiling-comms-merge] I tested this
+         ! NOT TESTED - NEED l_ptr TRUE
          IF( l_ptr ) THEN              ! "Poleward" transports
             zptry(:,:,:) = zptry(:,:,:) + zwy(:,:,:)  ! <<< add anti-diffusive fluxes
@@ -360,5 +381,5 @@
          DEALLOCATE( zwdia, zwinf, zwsup )
       ENDIF
-      IF( l_trd .OR. l_hst ) THEN 
+      IF( l_trd .OR. l_hst ) THEN
          DEALLOCATE( ztrdx, ztrdy, ztrdz )
       ENDIF
@@ -383,8 +404,9 @@
       !!       in-space based differencing for fluid
       !!----------------------------------------------------------------------
-      INTEGER                          , INTENT(in   ) ::   Kmm             ! time level index 
-      REAL(wp)                         , INTENT(in   ) ::   p2dt            ! tracer time-step
-      REAL(wp), DIMENSION (jpi,jpj,jpk), INTENT(in   ) ::   pbef, paft      ! before & after field
-      REAL(wp), DIMENSION (jpi,jpj,jpk), INTENT(inout) ::   paa, pbb, pcc   ! monotonic fluxes in the 3 directions
+      INTEGER                         , INTENT(in   ) ::   Kmm             ! time level index
+      REAL(wp)                        , INTENT(in   ) ::   p2dt            ! tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pbef            ! before field
+      REAL(wp), DIMENSION(A2D(nn_hls)    ,jpk), INTENT(in   ) ::   paft            ! after field
+      REAL(wp), DIMENSION(A2D(nn_hls)    ,jpk), INTENT(inout) ::   paa, pbb, pcc   ! monotonic fluxes in the 3 directions
       !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
@@ -392,5 +414,5 @@
       REAL(dp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn    ! local scalars
       REAL(dp) ::   zau, zbu, zcu, zav, zbv, zcv, zup, zdo            !   -      -
-      REAL(dp), DIMENSION(jpi,jpj,jpk) :: zbetup, zbetdo, zbup, zbdo
+      REAL(dp), DIMENSION(A2D(nn_hls),jpk) :: zbetup, zbetdo, zbup, zbdo
       !!----------------------------------------------------------------------
       !
@@ -402,12 +424,14 @@
       ! --------------------
       ! max/min of pbef & paft with large negative/positive value (-/+zbig) inside land
-      zbup = MAX( pbef * tmask - zbig * ( 1._wp - tmask ),   &
-         &        paft * tmask - zbig * ( 1._wp - tmask )  )
-      zbdo = MIN( pbef * tmask + zbig * ( 1._wp - tmask ),   &
-         &        paft * tmask + zbig * ( 1._wp - tmask )  )
+      DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpk )
+         zbup(ji,jj,jk) = MAX( pbef(ji,jj,jk) * tmask(ji,jj,jk) - zbig * ( 1._wp - tmask(ji,jj,jk) ),   &
+            &                  paft(ji,jj,jk) * tmask(ji,jj,jk) - zbig * ( 1._wp - tmask(ji,jj,jk) )  )
+         zbdo(ji,jj,jk) = MIN( pbef(ji,jj,jk) * tmask(ji,jj,jk) + zbig * ( 1._wp - tmask(ji,jj,jk) ),   &
+            &                  paft(ji,jj,jk) * tmask(ji,jj,jk) + zbig * ( 1._wp - tmask(ji,jj,jk) )  )
+      END_3D
 
       DO jk = 1, jpkm1
          ikm1 = MAX(jk-1,1)
-         DO_2D( 0, 0, 0, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
 
             ! search maximum in neighbourhood
@@ -439,9 +463,9 @@
          END_2D
       END DO
-      CALL lbc_lnk_multi( 'traadv_fct', zbetup, 'T', 1.0_wp , zbetdo, 'T', 1.0_wp )   ! lateral boundary cond. (unchanged sign)
+      IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_fct', zbetup, 'T', 1.0_wp , zbetdo, 'T', 1.0_wp )   ! lateral boundary cond. (unchanged sign)
 
       ! 3. monotonic flux in the i & j direction (paa & pbb)
       ! ----------------------------------------
-      DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+      DO_3D( 1, 0, 1, 0, 1, jpkm1 )
          zau = MIN( 1._wp, zbetdo(ji,jj,jk), zbetup(ji+1,jj,jk) )
          zbu = MIN( 1._wp, zbetup(ji,jj,jk), zbetdo(ji+1,jj,jk) )
@@ -461,5 +485,4 @@
          pcc(ji,jj,jk+1) = pcc(ji,jj,jk+1) * ( zc * za + ( 1._wp - zc) * zb )
       END_3D
-      CALL lbc_lnk_multi( 'traadv_fct', paa, 'U', -1.0_wp , pbb, 'V', -1.0_wp )   ! lateral boundary condition (changed sign)
       !
    END SUBROUTINE nonosc
@@ -537,14 +560,14 @@
       !!----------------------------------------------------------------------
       REAL(wp),DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pt_in    ! field at t-point
-      REAL(wp),DIMENSION(jpi,jpj,jpk), INTENT(  out) ::   pt_out   ! field interpolated at w-point
+      REAL(wp),DIMENSION(A2D(nn_hls)    ,jpk), INTENT(  out) ::   pt_out   ! field interpolated at w-point
       !
       INTEGER ::   ji, jj, jk   ! dummy loop integers
       INTEGER ::   ikt, ikb     ! local integers
-      REAL(wp),DIMENSION(jpi,jpj,jpk) :: zwd, zwi, zws, zwrm, zwt
+      REAL(wp),DIMENSION(A2D(nn_hls),jpk) :: zwd, zwi, zws, zwrm, zwt
       !!----------------------------------------------------------------------
       !
       !                      !==  build the three diagonal matrix & the RHS  ==!
       !
-      DO_3D( 0, 0, 0, 0, 3, jpkm1 )    ! interior (from jk=3 to jpk-1)
+      DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 3, jpkm1 )    ! interior (from jk=3 to jpk-1)
          zwd (ji,jj,jk) = 3._wp * wmask(ji,jj,jk) + 1._wp                 !       diagonal
          zwi (ji,jj,jk) =         wmask(ji,jj,jk)                         ! lower diagonal
@@ -565,5 +588,5 @@
       END IF
       !
-      DO_2D( 0, 0, 0, 0 )              ! 2nd order centered at top & bottom
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )              ! 2nd order centered at top & bottom
          ikt = mikt(ji,jj) + 1            ! w-point below the 1st  wet point
          ikb = MAX(mbkt(ji,jj), 2)        !     -   above the last wet point
@@ -582,22 +605,22 @@
       !                       !==  tridiagonal solver  ==!
       !
-      DO_2D( 0, 0, 0, 0 )           !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )           !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1
          zwt(ji,jj,2) = zwd(ji,jj,2)
       END_2D
-      DO_3D( 0, 0, 0, 0, 3, jpkm1 )
+      DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 3, jpkm1 )
          zwt(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) /zwt(ji,jj,jk-1)
       END_3D
       !
-      DO_2D( 0, 0, 0, 0 )           !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )           !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
          pt_out(ji,jj,2) = zwrm(ji,jj,2)
       END_2D
-      DO_3D( 0, 0, 0, 0, 3, jpkm1 )
+      DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 3, jpkm1 )
          pt_out(ji,jj,jk) = zwrm(ji,jj,jk) - zwi(ji,jj,jk) / zwt(ji,jj,jk-1) *pt_out(ji,jj,jk-1)             
       END_3D
 
-      DO_2D( 0, 0, 0, 0 )           !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )           !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk
          pt_out(ji,jj,jpkm1) = pt_out(ji,jj,jpkm1) / zwt(ji,jj,jpkm1)
       END_2D
-      DO_3DS( 0, 0, 0, 0, jpk-2, 2, -1 )
+      DO_3DS( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, jpk-2, 2, -1 )
          pt_out(ji,jj,jk) = ( pt_out(ji,jj,jk) - zws(ji,jj,jk) * pt_out(ji,jj,jk+1) ) / zwt(ji,jj,jk)
       END_3D
@@ -626,34 +649,34 @@
       !!        The 3d array zwt is used as a work space array.
       !!----------------------------------------------------------------------
-      REAL(wp),DIMENSION(:,:,:), INTENT(in   ) ::   pD, pU, PL    ! 3-diagonal matrix
-      REAL(wp),DIMENSION(:,:,:), INTENT(in   ) ::   pRHS          ! Right-Hand-Side
-      REAL(wp),DIMENSION(:,:,:), INTENT(  out) ::   pt_out        !!gm field at level=F(klev)
-      INTEGER                  , INTENT(in   ) ::   klev          ! =1 pt_out at w-level 
-      !                                                           ! =0 pt at t-level
+      REAL(wp),DIMENSION(A2D(nn_hls),jpk), INTENT(in   ) ::   pD, pU, PL    ! 3-diagonal matrix
+      REAL(wp),DIMENSION(A2D(nn_hls),jpk), INTENT(in   ) ::   pRHS          ! Right-Hand-Side
+      REAL(wp),DIMENSION(A2D(nn_hls),jpk), INTENT(  out) ::   pt_out        !!gm field at level=F(klev)
+      INTEGER                    , INTENT(in   ) ::   klev          ! =1 pt_out at w-level
+      !                                                             ! =0 pt at t-level
       INTEGER ::   ji, jj, jk   ! dummy loop integers
       INTEGER ::   kstart       ! local indices
-      REAL(wp),DIMENSION(jpi,jpj,jpk) ::   zwt   ! 3D work array
+      REAL(wp),DIMENSION(A2D(nn_hls),jpk) ::   zwt   ! 3D work array
       !!----------------------------------------------------------------------
       !
       kstart =  1  + klev
       !
-      DO_2D( 0, 0, 0, 0 )                         !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )                         !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1
          zwt(ji,jj,kstart) = pD(ji,jj,kstart)
       END_2D
-      DO_3D( 0, 0, 0, 0, kstart+1, jpkm1 )
+      DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, kstart+1, jpkm1 )
          zwt(ji,jj,jk) = pD(ji,jj,jk) - pL(ji,jj,jk) * pU(ji,jj,jk-1) /zwt(ji,jj,jk-1)
       END_3D
       !
-      DO_2D( 0, 0, 0, 0 )                        !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )                        !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
          pt_out(ji,jj,kstart) = pRHS(ji,jj,kstart)
       END_2D
-      DO_3D( 0, 0, 0, 0, kstart+1, jpkm1 )
+      DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, kstart+1, jpkm1 )
          pt_out(ji,jj,jk) = pRHS(ji,jj,jk) - pL(ji,jj,jk) / zwt(ji,jj,jk-1) *pt_out(ji,jj,jk-1)             
       END_3D
 
-      DO_2D( 0, 0, 0, 0 )                       !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk
+      DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )                       !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk
          pt_out(ji,jj,jpkm1) = pt_out(ji,jj,jpkm1) / zwt(ji,jj,jpkm1)
       END_2D
-      DO_3DS( 0, 0, 0, 0, jpk-2, kstart, -1 )
+      DO_3DS( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, jpk-2, kstart, -1 )
          pt_out(ji,jj,jk) = ( pt_out(ji,jj,jk) - pU(ji,jj,jk) * pt_out(ji,jj,jk+1) ) / zwt(ji,jj,jk)
       END_3D
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_fct_lf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_fct_lf.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_fct_lf.F90	(revision 14055)
@@ -0,0 +1,553 @@
+MODULE traadv_fct_lf
+   !!==============================================================================
+   !!                       ***  MODULE  traadv_fct  ***
+   !! Ocean  tracers:  horizontal & vertical advective trend (2nd/4th order Flux Corrected Transport method)
+   !!==============================================================================
+   !! History :  3.7  !  2015-09  (L. Debreu, G. Madec)  original code (inspired from traadv_tvd.F90)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  tra_adv_fct-lf : update the tracer trend with a 3D advective trends using a 2nd or 4th order FCT scheme
+   !!                   with sub-time-stepping in the vertical direction - loop fusion version
+   !!  nonosc_lf      : compute monotonic tracer fluxes by a non-oscillatory algorithm - loop fusion version 
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! tracers trends
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   USE phycst  , ONLY : rho0_rcp
+   USE zdf_oce , ONLY : ln_zad_Aimp
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! 
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link) 
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+   USE traadv_fct
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_fct_lf     ! called by traadv.F90
+
+   LOGICAL  ::   l_trd   ! flag to compute trends
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat/salt transport
+   REAL(wp) ::   r1_6 = 1._wp / 6._wp   ! =1/6
+
+   !                                        ! tridiag solver associated indices:
+   INTEGER, PARAMETER ::   np_NH   = 0   ! Neumann homogeneous boundary condition
+   INTEGER, PARAMETER ::   np_CEN2 = 1   ! 2nd order centered  boundary condition
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+#  include "domzgr_substitute.h90"
+
+#define tracer_flux_i(out,zfp,zfm,ji,jj,jk) \
+        zfp = pU(ji,jj,jk) + ABS( pU(ji,jj,jk) ) ; \
+        zfm = pU(ji,jj,jk) - ABS( pU(ji,jj,jk) ) ; \
+        out = 0.5 * ( zfp * pt(ji,jj,jk,jn,Kbb) + zfm * pt(ji+1,jj,jk,jn,Kbb) )
+
+#define tracer_flux_j(out,zfp,zfm,ji,jj,jk) \
+        zfp = pV(ji,jj,jk) + ABS( pV(ji,jj,jk) ) ; \
+        zfm = pV(ji,jj,jk) - ABS( pV(ji,jj,jk) ) ; \
+        out = 0.5 * ( zfp * pt(ji,jj,jk,jn,Kbb) + zfm * pt(ji,jj+1,jk,jn,Kbb) )
+
+#define search_in_neighbour(out,OP,vec,ji,jj,jk) \
+        out = OP(vec(ji,jj,jk),vec(ji-1,jj,jk),vec(ji+1,jj,jk), \
+        vec(ji,jj-1,jk),vec(ji,jj+1,jk),vec(ji,jj,MAX(jk-1,1)),vec(ji,jj,jk+1))
+
+#define pos_part_of_flux(ji,jj,jk,out) \
+        out = MAX(0.,paa_in(ji-1,jj,jk)) - MIN(0.,paa_in(ji,jj,jk)) \
+        + MAX(0.,pbb_in(ji,jj-1,jk)) - MIN(0.,pbb_in(ji,jj,jk)) \
+        + MAX(0.,pcc_in(ji,jj,jk+1)) - MIN(0.,pcc_in(ji,jj,jk)) 
+
+#define neg_part_of_flux(ji,jj,jk,out) \
+        out = MAX( 0.,paa_in(ji,jj,jk) ) - MIN( 0., paa_in(ji-1,jj,jk)) \
+        + MAX( 0.,pbb_in(ji,jj,jk) ) - MIN( 0., pbb_in(ji,jj-1,jk)) \
+        + MAX( 0.,pcc_in(ji,jj,jk) ) - MIN( 0., pcc_in(ji,jj,jk+1))
+
+#define beta_terms(bt,betup,betdo,up,pos,do,neg,ji,jj,jk) \
+        bt = e1e2t(ji,jj) * e3t(ji,jj,jk,Kmm) / p2dt ; \
+        betup = ( up            - paft(ji,jj,jk) ) / ( pos + zrtrn ) * bt ; \
+        betdo = ( paft(ji,jj,jk) - do            ) / ( neg + zrtrn ) * bt
+
+#define monotonic_flux(a,b,c,betup_p1,betdo_p1,vec,vec_in,jk) \
+        a = MIN( 1._wp, zbetdo(ji,jj), betup_p1 ) ; \
+        b = MIN( 1._wp, zbetup(ji,jj), betdo_p1 ) ; \
+        c = ( 0.5_wp  + SIGN( 0.5_wp , vec_in(ji,jj,jk) ) ) ; \
+        vec(ji,jj,jk) = vec_in(ji,jj,jk) * ( c * a + ( 1._wp - c) * b )
+
+#define monotonic_flux_k(a,b,c,betup,betdo,vec,vec_in,jk) \
+        a = MIN( 1._wp, betdo, zbetup_ptr(ji,jj) ) ; \
+        b = MIN( 1._wp, betup, zbetdo_ptr(ji,jj) ) ; \
+        c = ( 0.5 + SIGN( 0.5_wp , vec_in(ji,jj,jk) ) ) ; \
+        vec(ji,jj,jk) = vec_in(ji,jj,jk) * ( c * a + ( 1._wp - c) * b )
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: traadv_fct.F90 13660 2020-10-22 10:47:32Z francesca $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_fct_lf( kt, kit000, cdtype, p2dt, pU, pV, pW,       &
+      &                    Kbb, Kmm, pt, kjpt, Krhs, kn_fct_h, kn_fct_v )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_fct  ***
+      !! 
+      !! **  Purpose :   Compute the now trend due to total advection of tracers
+      !!               and add it to the general trend of tracer equations
+      !!
+      !! **  Method  : - 2nd or 4th FCT scheme on the horizontal direction
+      !!               (choice through the value of kn_fct)
+      !!               - on the vertical the 4th order is a compact scheme 
+      !!               - corrected flux (monotonic correction) 
+      !!
+      !! ** Action : - update pt(:,:,:,:,Krhs)  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostics (l_trdtra=T)
+      !!             - poleward advective heat and salt transport (ln_diaptr=T)
+      !!----------------------------------------------------------------------
+      INTEGER                                  , INTENT(in   ) ::   kt              ! ocean time-step index
+      INTEGER                                  , INTENT(in   ) ::   Kbb, Kmm, Krhs  ! ocean time level indices
+      INTEGER                                  , INTENT(in   ) ::   kit000          ! first time step index
+      CHARACTER(len=3)                         , INTENT(in   ) ::   cdtype          ! =TRA or TRC (tracer indicator)
+      INTEGER                                  , INTENT(in   ) ::   kjpt            ! number of tracers
+      INTEGER                                  , INTENT(in   ) ::   kn_fct_h        ! order of the FCT scheme (=2 or 4)
+      INTEGER                                  , INTENT(in   ) ::   kn_fct_v        ! order of the FCT scheme (=2 or 4)
+      REAL(wp)                                 , INTENT(in   ) ::   p2dt            ! tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(inout) ::   pU, pV, pW      ! 3 ocean volume flux components
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
+      !
+      INTEGER  ::   ji, jj, jk, jn                           ! dummy loop indices  
+      REAL(wp) ::   ztra                                     ! local scalar
+      REAL(wp) ::   zwx_im1, zfp_ui, zfp_ui_m1, zfp_vj, zfp_vj_m1, zfp_wk, zC2t_u, zC4t_u   !   -      -
+      REAL(wp) ::   zwy_jm1, zfm_ui, zfm_ui_m1, zfm_vj, zfm_vj_m1, zfm_wk, zC2t_v, zC4t_v   !   -      -
+      REAL(wp) ::   ztu_im1, ztu_ip1, ztv_jm1, ztv_jp1  
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        ::   zwi, zwx_3d, zwy_3d, zwz, ztw, zltu_3d, zltv_3d, ztu, ztv
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdx, ztrdy, ztrdz, zptry
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   zwinf, zwdia, zwsup
+      LOGICAL  ::   ll_zAimp                                 ! flag to apply adaptive implicit vertical advection
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv_fct_lf : FCT advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !! -- init to 0
+      zwx_3d(:,:,:) = 0._wp
+      zwy_3d(:,:,:) = 0._wp
+      zwz(:,:,:) = 0._wp
+      zwi(:,:,:) = 0._wp
+      !
+      l_trd = .FALSE.            ! set local switches
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      ll_zAimp = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra  ) .OR. ( cdtype =='TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) ) )    l_ptr = .TRUE. 
+      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR.  &
+         &                         iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
+      !
+      IF( l_trd .OR. l_hst )  THEN
+         ALLOCATE( ztrdx(jpi,jpj,jpk), ztrdy(jpi,jpj,jpk), ztrdz(jpi,jpj,jpk) )
+         ztrdx(:,:,:) = 0._wp   ;    ztrdy(:,:,:) = 0._wp   ;   ztrdz(:,:,:) = 0._wp
+      ENDIF
+      !
+      IF( l_ptr ) THEN  
+         ALLOCATE( zptry(jpi,jpj,jpk) )
+         zptry(:,:,:) = 0._wp
+      ENDIF
+      !
+      ! If adaptive vertical advection, check if it is needed on this PE at this time
+      IF( ln_zad_Aimp ) THEN
+         IF( MAXVAL( ABS( wi(:,:,:) ) ) > 0._wp ) ll_zAimp = .TRUE.
+      END IF
+      ! If active adaptive vertical advection, build tridiagonal matrix
+      IF( ll_zAimp ) THEN
+         ALLOCATE(zwdia(jpi,jpj,jpk), zwinf(jpi,jpj,jpk),zwsup(jpi,jpj,jpk))
+         DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+            zwdia(ji,jj,jk) =  1._wp + p2dt * ( MAX( wi(ji,jj,jk) , 0._wp ) - MIN( wi(ji,jj,jk+1) , 0._wp ) )   &
+            &                               / e3t(ji,jj,jk,Krhs)
+            zwinf(ji,jj,jk) =  p2dt * MIN( wi(ji,jj,jk  ) , 0._wp ) / e3t(ji,jj,jk,Krhs)
+            zwsup(ji,jj,jk) = -p2dt * MAX( wi(ji,jj,jk+1) , 0._wp ) / e3t(ji,jj,jk,Krhs)
+         END_3D
+      END IF
+      !
+      DO jn = 1, kjpt            !==  loop over the tracers  ==!
+         !
+         !        !==  upstream advection with initial mass fluxes & intermediate update  ==!
+         !                               !* upstream tracer flux in the k direction *!
+         DO_3D( 1, 1, 1, 1, 2, jpkm1 )      ! Interior value ( multiplied by wmask)
+            zfp_wk = pW(ji,jj,jk) + ABS( pW(ji,jj,jk) )
+            zfm_wk = pW(ji,jj,jk) - ABS( pW(ji,jj,jk) )
+            zwz(ji,jj,jk) = 0.5 * ( zfp_wk * pt(ji,jj,jk,jn,Kbb) + zfm_wk * pt(ji,jj,jk-1,jn,Kbb) ) * wmask(ji,jj,jk)
+         END_3D
+         IF( ln_linssh ) THEN               ! top ocean value (only in linear free surface as zwz has been w-masked)
+            IF( ln_isfcav ) THEN                        ! top of the ice-shelf cavities and at the ocean surface
+               DO_2D( 1, 1, 1, 1 )
+                  zwz(ji,jj, mikt(ji,jj) ) = pW(ji,jj,mikt(ji,jj)) * pt(ji,jj,mikt(ji,jj),jn,Kbb)   ! linear free surface 
+               END_2D
+            ELSE                                        ! no cavities: only at the ocean surface
+               DO_2D( 1, 1, 1, 1 )
+                  zwz(ji,jj,1) = pW(ji,jj,1) * pt(ji,jj,1,jn,Kbb)
+               END_2D
+            ENDIF
+         ENDIF
+         !               
+         !                    !* upstream tracer flux in the i and j direction 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj-1
+               tracer_flux_i(zwx_3d(1,jj,jk),zfp_ui,zfm_ui,1,jj,jk)
+               tracer_flux_j(zwy_3d(1,jj,jk),zfp_vj,zfm_vj,1,jj,jk)
+            END DO
+            DO ji = 1, jpi-1
+               tracer_flux_i(zwx_3d(ji,1,jk),zfp_ui,zfm_ui,ji,1,jk)
+               tracer_flux_j(zwy_3d(ji,1,jk),zfp_vj,zfm_vj,ji,1,jk)
+            END DO
+            DO_2D( 1, 1, 1, 1 )
+               tracer_flux_i(zwx_3d(ji,jj,jk),zfp_ui,zfm_ui,ji,jj,jk)
+               tracer_flux_i(zwx_im1,zfp_ui_m1,zfm_ui_m1,ji-1,jj,jk)
+               tracer_flux_j(zwy_3d(ji,jj,jk),zfp_vj,zfm_vj,ji,jj,jk)
+               tracer_flux_j(zwy_jm1,zfp_vj_m1,zfm_vj_m1,ji,jj-1,jk)
+               ztra = - ( zwx_3d(ji,jj,jk) - zwx_im1 + zwy_3d(ji,jj,jk) - zwy_jm1 + zwz(ji,jj,jk) - zwz(ji,jj,jk+1) ) * r1_e1e2t(ji,jj)
+               !                               ! update and guess with monotonic sheme
+               pt(ji,jj,jk,jn,Krhs) =                   pt(ji,jj,jk,jn,Krhs) +       ztra   &
+                  &                                  / e3t(ji,jj,jk,Kmm ) * tmask(ji,jj,jk)
+               zwi(ji,jj,jk)    = ( e3t(ji,jj,jk,Kbb) * pt(ji,jj,jk,jn,Kbb) + p2dt * ztra ) &
+                  &                                  / e3t(ji,jj,jk,Krhs) * tmask(ji,jj,jk)
+            END_2D
+         END DO
+         
+         IF ( ll_zAimp ) THEN
+            CALL tridia_solver( zwdia, zwsup, zwinf, zwi, zwi , 0 )
+            !
+            ztw(:,:,1) = 0._wp ; ztw(:,:,jpk) = 0._wp ;
+            DO_3D( 1, 1, 1, 1, 2, jpkm1 )       ! Interior value ( multiplied by wmask)
+               zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
+               zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
+               ztw(ji,jj,jk) =  0.5 * e1e2t(ji,jj) * ( zfp_wk * zwi(ji,jj,jk) + zfm_wk * zwi(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+               zwz(ji,jj,jk) = zwz(ji,jj,jk) + ztw(ji,jj,jk) ! update vertical fluxes
+            END_3D
+            DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+               pt(ji,jj,jk,jn,Krhs) = pt(ji,jj,jk,jn,Krhs) - ( ztw(ji,jj,jk) - ztw(ji  ,jj  ,jk+1) ) &
+                  &                                        * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
+            END_3D
+            !
+         END IF
+         !                
+         IF( l_trd .OR. l_hst )  THEN             ! trend diagnostics (contribution of upstream fluxes)
+            ztrdx(:,:,:) = zwx_3d(:,:,:)   ;   ztrdy(:,:,:) = zwy_3d(:,:,:)   ;   ztrdz(:,:,:) = zwz(:,:,:)
+         END IF
+         !                             ! "Poleward" heat and salt transports (contribution of upstream fluxes)
+         IF( l_ptr )   zptry(:,:,:) = zwy_3d(:,:,:) 
+         !
+         !        !==  anti-diffusive flux : high order minus low order  ==!
+         !
+         SELECT CASE( kn_fct_h )    !* horizontal anti-diffusive fluxes
+         !
+         CASE(  2  )                   !- 2nd order centered
+            DO_3D( 2, 1, 2, 1, 1, jpkm1 )
+               zwx_3d(ji,jj,jk) = 0.5_wp * pU(ji,jj,jk) * ( pt(ji,jj,jk,jn,Kmm) + pt(ji+1,jj,jk,jn,Kmm) ) - zwx_3d(ji,jj,jk)
+               zwy_3d(ji,jj,jk) = 0.5_wp * pV(ji,jj,jk) * ( pt(ji,jj,jk,jn,Kmm) + pt(ji,jj+1,jk,jn,Kmm) ) - zwy_3d(ji,jj,jk)
+            END_3D
+            !
+         CASE(  4  )                   !- 4th order centered
+            zltu_3d(:,:,jpk) = 0._wp            ! Bottom value : flux set to zero
+            zltv_3d(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1                 ! Laplacian
+               DO_2D( 1, 0, 1, 0 )                 ! 1st derivative (gradient)
+                  ztu(ji,jj,jk) = ( pt(ji+1,jj  ,jk,jn,Kmm) - pt(ji,jj,jk,jn,Kmm) ) * umask(ji,jj,jk)
+                  ztv(ji,jj,jk) = ( pt(ji  ,jj+1,jk,jn,Kmm) - pt(ji,jj,jk,jn,Kmm) ) * vmask(ji,jj,jk)
+               END_2D
+               DO_2D( 0, 0, 0, 0 )                 ! 2nd derivative * 1/ 6
+                  zltu_3d(ji,jj,jk) = (  ztu(ji,jj,jk) + ztu(ji-1,jj,jk)  ) * r1_6
+                  zltv_3d(ji,jj,jk) = (  ztv(ji,jj,jk) + ztv(ji,jj-1,jk)  ) * r1_6
+               END_2D
+            END DO
+            CALL lbc_lnk_multi( 'traadv_fct', zltu_3d, 'T', 1.0_wp , zltv_3d, 'T', 1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
+!            !
+            DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )
+               zC2t_u = pt(ji,jj,jk,jn,Kmm) + pt(ji+1,jj  ,jk,jn,Kmm)   ! 2 x C2 interpolation of T at u- & v-points
+               zC2t_v = pt(ji,jj,jk,jn,Kmm) + pt(ji  ,jj+1,jk,jn,Kmm)
+               !                                                        ! C4 minus upstream advective fluxes 
+               zwx_3d(ji,jj,jk) =  0.5_wp * pU(ji,jj,jk) * ( zC2t_u + zltu_3d(ji,jj,jk) - zltu_3d(ji+1,jj,jk) ) - zwx_3d(ji,jj,jk)
+               zwy_3d(ji,jj,jk) =  0.5_wp * pV(ji,jj,jk) * ( zC2t_v + zltv_3d(ji,jj,jk) - zltv_3d(ji,jj+1,jk) ) - zwy_3d(ji,jj,jk)
+            END_3D
+            !
+            CALL lbc_lnk_multi( 'traadv_fct', zwx_3d, 'U', -1.0_wp , zwy_3d, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
+         CASE(  41 )                   !- 4th order centered       ==>>   !!gm coding attempt   need to be tested
+            DO_3D( 0, 0, 0, 0, 1, jpkm1 )    ! Horizontal advective fluxes
+               ztu_im1 = ( pt(ji  ,jj  ,jk,jn,Kmm) - pt(ji-1,jj,jk,jn,Kmm) ) * umask(ji-1,jj,jk)
+               ztu_ip1 = ( pt(ji+2,jj  ,jk,jn,Kmm) - pt(ji+1,jj,jk,jn,Kmm) ) * umask(ji+1,jj,jk)
+
+               ztv_jm1 = ( pt(ji,jj  ,jk,jn,Kmm) - pt(ji,jj-1,jk,jn,Kmm) ) * vmask(ji,jj-1,jk)
+               ztv_jp1 = ( pt(ji,jj+2,jk,jn,Kmm) - pt(ji,jj+1,jk,jn,Kmm) ) * vmask(ji,jj+1,jk)
+
+               zC2t_u = pt(ji,jj,jk,jn,Kmm) + pt(ji+1,jj  ,jk,jn,Kmm)   ! 2 x C2 interpolation of T at u- & v-points (x2)
+               zC2t_v = pt(ji,jj,jk,jn,Kmm) + pt(ji  ,jj+1,jk,jn,Kmm)
+               !                                                  ! C4 interpolation of T at u- & v-points (x2)
+               zC4t_u =  zC2t_u + r1_6 * ( ztu_im1 - ztu_ip1 )
+               zC4t_v =  zC2t_v + r1_6 * ( ztv_jm1 - ztv_jp1 )
+               !                                                  ! C4 minus upstream advective fluxes 
+               zwx_3d(ji,jj,jk) =  0.5_wp * pU(ji,jj,jk) * zC4t_u - zwx_3d(ji,jj,jk)
+               zwy_3d(ji,jj,jk) =  0.5_wp * pV(ji,jj,jk) * zC4t_v - zwy_3d(ji,jj,jk)
+            END_3D
+            CALL lbc_lnk_multi( 'traadv_fct', zwx_3d, 'U', -1.0_wp , zwy_3d, 'V', -1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
+            !
+         END SELECT
+         !                      
+         SELECT CASE( kn_fct_v )    !* vertical anti-diffusive fluxes (w-masked interior values)
+         !
+         CASE(  2  )                   !- 2nd order centered
+            DO_3D( 1, 1, 1, 1, 2, jpkm1 )
+               zwz(ji,jj,jk) =  (  pW(ji,jj,jk) * 0.5_wp * ( pt(ji,jj,jk,jn,Kmm) + pt(ji,jj,jk-1,jn,Kmm) )   &
+                  &              - zwz(ji,jj,jk)  ) * wmask(ji,jj,jk)
+            END_3D
+            !
+         CASE(  4  )                   !- 4th order COMPACT
+            CALL interp_4th_cpt( pt(:,:,:,jn,Kmm) , ztw )   ! zwt = COMPACT interpolation of T at w-point
+            DO_3D( 1, 1, 1, 1, 2, jpkm1 )
+               zwz(ji,jj,jk) = ( pW(ji,jj,jk) * ztw(ji,jj,jk) - zwz(ji,jj,jk) ) * wmask(ji,jj,jk)
+            END_3D
+            !
+         END SELECT
+         IF( ln_linssh ) THEN    ! top ocean value: high order = upstream  ==>>  zwz=0
+            zwz(:,:,1) = 0._wp   ! only ocean surface as interior zwz values have been w-masked
+         ENDIF
+         !         
+         CALL lbc_lnk( 'traadv_fct', zwi, 'T', 1.0_wp)
+         !
+         IF ( ll_zAimp ) THEN
+            DO_3D( 1, 1, 1, 1, 1, jpkm1 )    !* trend and after field with monotonic scheme
+               !                                                ! total intermediate advective trends
+               ztra = - (  zwx_3d(ji,jj,jk) - zwx_3d(ji-1,jj  ,jk  )   &
+                  &      + zwy_3d(ji,jj,jk) - zwy_3d(ji  ,jj-1,jk  )   &
+                  &      + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) ) * r1_e1e2t(ji,jj)
+               ztw(ji,jj,jk) = zwi(ji,jj,jk) + p2dt * ztra / e3t(ji,jj,jk,Krhs) * tmask(ji,jj,jk)
+            END_3D
+            !
+            CALL tridia_solver( zwdia, zwsup, zwinf, ztw, ztw , 0 )
+            !
+            DO_3D( 1, 1, 1, 1, 2, jpkm1 )       ! Interior value ( multiplied by wmask)
+               zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
+               zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
+               zwz(ji,jj,jk) = zwz(ji,jj,jk) + 0.5 * e1e2t(ji,jj) * ( zfp_wk * ztw(ji,jj,jk) + zfm_wk * ztw(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+            END_3D
+         END IF
+         !
+         !        !==  monotonicity algorithm  ==!
+         !
+#if defined key_agrif
+         CALL nonosc( Kmm, pt(:,:,:,jn,Kbb), zwx_3d, zwy_3d, zwz, zwi, p2dt )
+#else
+         CALL nonosc_lf( Kmm, pt(:,:,:,jn,Kbb), zwx_3d, zwy_3d, zwz, zwi, p2dt )
+#endif
+         !
+         !        !==  final trend with corrected fluxes  ==!
+         !
+         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+            ztra = - (  zwx_3d(ji,jj,jk) - zwx_3d(ji-1,jj  ,jk  )   &
+               &      + zwy_3d(ji,jj,jk) - zwy_3d(ji  ,jj-1,jk  )   &
+               &      + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) ) * r1_e1e2t(ji,jj)
+            pt(ji,jj,jk,jn,Krhs) = pt(ji,jj,jk,jn,Krhs) + ztra / e3t(ji,jj,jk,Kmm)
+            zwi(ji,jj,jk) = zwi(ji,jj,jk) + p2dt * ztra / e3t(ji,jj,jk,Krhs) * tmask(ji,jj,jk)
+         END_3D
+         !
+         IF ( ll_zAimp ) THEN
+            !
+            ztw(:,:,1) = 0._wp ; ztw(:,:,jpk) = 0._wp
+            DO_3D( 0, 0, 0, 0, 2, jpkm1 )      ! Interior value ( multiplied by wmask)
+               zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
+               zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
+               ztw(ji,jj,jk) = - 0.5 * e1e2t(ji,jj) * ( zfp_wk * zwi(ji,jj,jk) + zfm_wk * zwi(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+               zwz(ji,jj,jk) = zwz(ji,jj,jk) + ztw(ji,jj,jk) ! Update vertical fluxes for trend diagnostic
+            END_3D
+            DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+               pt(ji,jj,jk,jn,Krhs) = pt(ji,jj,jk,jn,Krhs) - ( ztw(ji,jj,jk) - ztw(ji  ,jj  ,jk+1) ) &
+                  &                                        * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
+            END_3D
+         END IF         
+         ! NOT TESTED - NEED l_trd OR l_hst TRUE 
+         IF( l_trd .OR. l_hst ) THEN   ! trend diagnostics // heat/salt transport
+            ztrdx(:,:,:) = ztrdx(:,:,:) + zwx_3d(:,:,:)  ! <<< add anti-diffusive fluxes 
+            ztrdy(:,:,:) = ztrdy(:,:,:) + zwy_3d(:,:,:)  !     to upstream fluxes
+            ztrdz(:,:,:) = ztrdz(:,:,:) + zwz(:,:,:)  !
+            !
+            IF( l_trd ) THEN              ! trend diagnostics
+               CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_xad, ztrdx, pU, pt(:,:,:,jn,Kmm) )
+               CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_yad, ztrdy, pV, pt(:,:,:,jn,Kmm) )
+               CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_zad, ztrdz, pW, pt(:,:,:,jn,Kmm) )
+            ENDIF
+            !                             ! heat/salt transport
+            IF( l_hst )   CALL dia_ar5_hst( jn, 'adv', ztrdx(:,:,:), ztrdy(:,:,:) )
+            !
+         ENDIF
+         ! NOT TESTED - NEED l_ptr TRUE 
+         IF( l_ptr ) THEN              ! "Poleward" transports
+            zptry(:,:,:) = zptry(:,:,:) + zwy_3d(:,:,:)  ! <<< add anti-diffusive fluxes
+            CALL dia_ptr_hst( jn, 'adv', zptry(:,:,:) )
+         ENDIF
+         !
+      END DO                     ! end of tracer loop
+      !
+      IF ( ll_zAimp ) THEN
+         DEALLOCATE( zwdia, zwinf, zwsup )
+      ENDIF
+      IF( l_trd .OR. l_hst ) THEN 
+         DEALLOCATE( ztrdx, ztrdy, ztrdz )
+      ENDIF
+      IF( l_ptr ) THEN 
+         DEALLOCATE( zptry )
+      ENDIF
+      !
+   END SUBROUTINE tra_adv_fct_lf
+
+   SUBROUTINE nonosc_lf( Kmm, pbef, paa, pbb, pcc, paft, p2dt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE nonosc  ***
+      !!     
+      !! **  Purpose :   compute monotonic tracer fluxes from the upstream 
+      !!       scheme and the before field by a nonoscillatory algorithm 
+      !!
+      !! **  Method  :   ... ???
+      !!       warning : pbef and paft must be masked, but the boundaries
+      !!       conditions on the fluxes are not necessary zalezak (1979)
+      !!       drange (1995) multi-dimensional forward-in-time and upstream-
+      !!       in-space based differencing for fluid
+      !!----------------------------------------------------------------------
+      INTEGER                          , INTENT(in   ) ::   Kmm             ! time level index 
+      REAL(wp)                         , INTENT(in   ) ::   p2dt            ! tracer time-step
+      REAL(wp), DIMENSION (jpi,jpj,jpk), INTENT(in   ) ::   pbef, paft      ! before & after field
+      REAL(wp), DIMENSION (jpi,jpj,jpk), INTENT(inout) ::   paa, pbb, pcc   ! monotonic fluxes in the 3 directions
+      REAL(wp), DIMENSION (jpi,jpj,jpk) ::   paa_in, pbb_in, pcc_in   ! monotonic fluxes in the 3 directions
+      !
+      REAL(dp), DIMENSION (jpi,jpj,jpk) :: zbup, zbdo
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(dp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn    ! local scalars
+      REAL(dp) ::   zau, zbu, zcu, zav, zbv, zcv, zup, zdo            !   -      -
+      REAL(dp) ::   zbt_ip1, zpos_ip1, zneg_ip1, zup_ip1, zdo_ip1, zbetup_ip1, zbetdo_ip1 
+      REAL(dp) ::   zbt_jp1, zpos_jp1, zneg_jp1, zup_jp1, zdo_jp1, zbetup_jp1, zbetdo_jp1
+      REAL(dp), TARGET, DIMENSION(jpi,jpj) :: zbetup_buf, zbetdo_buf, zbetup_ptr_buf, zbetdo_ptr_buf
+      REAL(dp), POINTER, DIMENSION(:,:) :: tmp, zbetup, zbetdo, zbetup_ptr, zbetdo_ptr
+      !!----------------------------------------------------------------------
+      !
+      zbig  = 1.e+40_dp
+      zrtrn = 1.e-15_dp
+
+      paa_in(:,:,:) = paa(:,:,:)
+      pbb_in(:,:,:) = pbb(:,:,:)
+      pcc_in(:,:,:) = pcc(:,:,:)
+      ! Search local extrema
+      ! --------------------
+      ! max/min of pbef & paft with large negative/positive value (-/+zbig) inside land
+      zbup = MAX( pbef * tmask - zbig * ( 1._wp - tmask ),   &
+         &        paft * tmask - zbig * ( 1._wp - tmask )  )
+      zbdo = MIN( pbef * tmask + zbig * ( 1._wp - tmask ),   &
+         &        paft * tmask + zbig * ( 1._wp - tmask )  )
+
+      zbetup => zbetup_buf
+      zbetdo => zbetdo_buf
+      zbetup_ptr => zbetup_ptr_buf
+      zbetdo_ptr => zbetdo_ptr_buf
+
+      DO_2D( 1, 0, 1, 0 )
+
+        ! search maximum in neighbourhood
+        search_in_neighbour(zup,MAX,zbup,ji,jj,1)
+        search_in_neighbour(zup_ip1,MAX,zbup,ji+1,jj,1)
+        search_in_neighbour(zup_jp1,MAX,zbup,ji,jj+1,1)
+
+        ! search minimum in neighbourhood
+        search_in_neighbour(zdo,MIN,zbdo,ji,jj,1)
+        search_in_neighbour(zdo_ip1,MIN,zbdo,ji+1,jj,1)
+        search_in_neighbour(zdo_jp1,MIN,zbdo,ji,jj+1,1)
+
+        ! positive part of the flux
+        pos_part_of_flux(ji,jj,1,zpos)
+        pos_part_of_flux(ji+1,jj,1,zpos_ip1)
+        pos_part_of_flux(ji,jj+1,1,zpos_jp1)
+
+        ! negative part of the flux
+        neg_part_of_flux(ji,jj,1,zneg)
+        neg_part_of_flux(ji+1,jj,1,zneg_ip1)
+        neg_part_of_flux(ji,jj+1,1,zneg_jp1)
+
+        ! up & down beta terms
+        beta_terms(zbt,zbetup(ji,jj),zbetdo(ji,jj),zup,zpos,zdo,zneg,ji,jj,1)
+        beta_terms(zbt_ip1,zbetup_ip1,zbetdo_ip1,zup_ip1,zpos_ip1,zdo_ip1,zneg_ip1,ji+1,jj,1)
+        beta_terms(zbt_jp1,zbetup_jp1,zbetdo_jp1,zup_jp1,zpos_jp1,zdo_jp1,zneg_jp1,ji,jj+1,1)
+
+        ! 3. monotonic flux in the i & j (paa & pbb)
+        ! ----------------------------------------
+        monotonic_flux(zau,zbu,zcu,zbetup_ip1,zbetdo_ip1,paa,paa_in,1)
+        monotonic_flux(zav,zbv,zcv,zbetup_jp1,zbetdo_jp1,pbb,pbb_in,1)
+
+      END_2D
+      tmp => zbetup_ptr
+      zbetup_ptr => zbetup
+      zbetup => tmp
+
+      tmp => zbetdo_ptr
+      zbetdo_ptr => zbetdo
+      zbetdo => tmp
+
+      DO jk = 2, jpk-1
+         DO_2D( 1, 0, 1, 0 )
+
+            ! search maximum in neighbourhood
+            search_in_neighbour(zup,MAX,zbup,ji,jj,jk)
+            search_in_neighbour(zup_ip1,MAX,zbup,ji+1,jj,jk)
+            search_in_neighbour(zup_jp1,MAX,zbup,ji,jj+1,jk)
+
+            ! search minimum in neighbourhood
+            search_in_neighbour(zdo,MIN,zbdo,ji,jj,jk)
+            search_in_neighbour(zdo_ip1,MIN,zbdo,ji+1,jj,jk)
+            search_in_neighbour(zdo_jp1,MIN,zbdo,ji,jj+1,jk)
+
+            ! positive part of the flux
+            pos_part_of_flux(ji,jj,jk,zpos)
+            pos_part_of_flux(ji+1,jj,jk,zpos_ip1)
+            pos_part_of_flux(ji,jj+1,jk,zpos_jp1)
+
+            ! negative part of the flux
+            neg_part_of_flux(ji,jj,jk,zneg)
+            neg_part_of_flux(ji+1,jj,jk,zneg_ip1)
+            neg_part_of_flux(ji,jj+1,jk,zneg_jp1)
+
+            ! up & down beta terms
+            beta_terms(zbt,zbetup(ji,jj),zbetdo(ji,jj),zup,zpos,zdo,zneg,ji,jj,jk)
+            beta_terms(zbt_ip1,zbetup_ip1,zbetdo_ip1,zup_ip1,zpos_ip1,zdo_ip1,zneg_ip1,ji+1,jj,jk)
+            beta_terms(zbt_jp1,zbetup_jp1,zbetdo_jp1,zup_jp1,zpos_jp1,zdo_jp1,zneg_jp1,ji,jj+1,jk)
+
+            ! 3. monotonic flux in the i & j (paa & pbb)
+            ! ----------------------------------------
+            monotonic_flux(zau,zbu,zcu,zbetup_ip1,zbetdo_ip1,paa,paa_in,jk)
+            monotonic_flux(zav,zbv,zcv,zbetup_jp1,zbetdo_jp1,pbb,pbb_in,jk)
+
+            ! monotonic flux in the k direction, i.e. pcc
+            ! -------------------------------------------
+            monotonic_flux_k(za,zb,zc,zbetup(ji,jj),zbetdo(ji,jj),pcc,pcc_in,jk)
+         END_2D
+         tmp => zbetup_ptr
+         zbetup_ptr => zbetup
+         zbetup => tmp
+
+         tmp => zbetdo_ptr
+         zbetdo_ptr => zbetdo
+         zbetdo => tmp
+      END DO
+      !
+      DO_2D( 1, 0, 1, 0 )
+        ! monotonic flux in the k direction, i.e. pcc
+        ! -------------------------------------------
+        monotonic_flux_k(za,zb,zc,0._dp,0._dp,pcc,pcc_in,jpk)
+      END_2D
+   END SUBROUTINE nonosc_lf
+
+END MODULE traadv_fct_lf
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_mus.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_mus.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_mus.F90	(revision 14055)
@@ -81,4 +81,5 @@
       LOGICAL                                  , INTENT(in   ) ::   ld_msc_ups      ! use upstream scheme within muscl
       REAL(wp)                                 , INTENT(in   ) ::   p2dt            ! tracer time-step
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU, pV, pW      ! 3 ocean volume flux components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
@@ -88,40 +89,42 @@
       REAL(wp) ::   zu, z0u, zzwx, zw , zalpha   ! local scalars
       REAL(wp) ::   zv, z0v, zzwy, z0w           !   -      -
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwx, zslpx   ! 3D workspace
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwy, zslpy   ! -      - 
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwx, zslpx   ! 3D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwy, zslpy   ! -      -
       !!----------------------------------------------------------------------
       !
-      IF( kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_adv : MUSCL advection scheme on ', cdtype
-         IF(lwp) WRITE(numout,*) '        : mixed up-stream           ', ld_msc_ups
-         IF(lwp) WRITE(numout,*) '~~~~~~~'
-         IF(lwp) WRITE(numout,*)
-         !
-         ! Upstream / MUSCL scheme indicator
-         !
-         ALLOCATE( xind(jpi,jpj,jpk), STAT=ierr )
-         xind(:,:,:) = 1._wp              ! set equal to 1 where up-stream is not needed
-         !
-         IF( ld_msc_ups ) THEN            ! define the upstream indicator (if asked)
-            ALLOCATE( upsmsk(jpi,jpj), STAT=ierr )
-            upsmsk(:,:) = 0._wp                             ! not upstream by default
-            !
-            DO jk = 1, jpkm1
-               xind(:,:,jk) = 1._wp                              &                 ! =>1 where up-stream is not needed
-                  &         - MAX ( rnfmsk(:,:) * rnfmsk_z(jk),  &                 ! =>0 near runoff mouths (& closed sea outflows)
-                  &                 upsmsk(:,:)                ) * tmask(:,:,jk)   ! =>0 in some user defined area
-            END DO
-         ENDIF 
-         !
-      ENDIF 
-      !      
-      l_trd = .FALSE.
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
-      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )   l_ptr = .TRUE. 
-      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
-         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_adv : MUSCL advection scheme on ', cdtype
+            IF(lwp) WRITE(numout,*) '        : mixed up-stream           ', ld_msc_ups
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+            IF(lwp) WRITE(numout,*)
+            !
+            ! Upstream / MUSCL scheme indicator
+            !
+            ALLOCATE( xind(jpi,jpj,jpk), STAT=ierr )
+            xind(:,:,:) = 1._wp              ! set equal to 1 where up-stream is not needed
+            !
+            IF( ld_msc_ups ) THEN            ! define the upstream indicator (if asked)
+               ALLOCATE( upsmsk(jpi,jpj), STAT=ierr )
+               upsmsk(:,:) = 0._wp                             ! not upstream by default
+               !
+               DO jk = 1, jpkm1
+                  xind(:,:,jk) = 1._wp                              &                 ! =>1 where up-stream is not needed
+                     &         - MAX ( rnfmsk(:,:) * rnfmsk_z(jk),  &                 ! =>0 near runoff mouths (& closed sea outflows)
+                     &                 upsmsk(:,:)                ) * tmask(:,:,jk)   ! =>0 in some user defined area
+               END DO
+            ENDIF
+            !
+         ENDIF
+         !
+         l_trd = .FALSE.
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )   l_ptr = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+            &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
+      ENDIF
       !
       DO jn = 1, kjpt            !==  loop over the tracers  ==!
@@ -132,14 +135,14 @@
          zwx(:,:,jpk) = 0._wp                   ! bottom values
          zwy(:,:,jpk) = 0._wp  
-         DO_3D( 1, 0, 1, 0, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )
             zwx(ji,jj,jk) = umask(ji,jj,jk) * ( pt(ji+1,jj,jk,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
             zwy(ji,jj,jk) = vmask(ji,jj,jk) * ( pt(ji,jj+1,jk,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
          END_3D
          ! lateral boundary conditions   (changed sign)
-         CALL lbc_lnk_multi( 'traadv_mus', zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp )
+         IF ( nn_hls.EQ.1 ) CALL lbc_lnk_multi( 'traadv_mus', zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp )
          !                                !-- Slopes of tracer
          zslpx(:,:,jpk) = 0._wp                 ! bottom values
          zslpy(:,:,jpk) = 0._wp
-         DO_3D( 0, 1, 0, 1, 1, jpkm1 )
+         DO_3D( nn_hls-1, 1, nn_hls-1, 1, 1, jpkm1 )
             zslpx(ji,jj,jk) =                       ( zwx(ji,jj,jk) + zwx(ji-1,jj  ,jk) )   &
                &            * ( 0.25 + SIGN( 0.25_wp, zwx(ji,jj,jk) * zwx(ji-1,jj  ,jk) ) )
@@ -148,5 +151,5 @@
          END_3D
          !
-         DO_3D( 0, 1, 0, 1, 1, jpkm1 )    !-- Slopes limitation
+         DO_3D( nn_hls-1, 1, nn_hls-1, 1, 1, jpkm1 )    !-- Slopes limitation
             zslpx(ji,jj,jk) = SIGN( 1.0_wp, zslpx(ji,jj,jk) ) * MIN(    ABS( zslpx(ji  ,jj,jk) ),   &
                &                                                     2.*ABS( zwx  (ji-1,jj,jk) ),   &
@@ -157,5 +160,5 @@
          END_3D
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )    !-- MUSCL horizontal advective fluxes
+         DO_3D( nn_hls-1, 0, nn_hls-1, 0, 1, jpkm1 )    !-- MUSCL horizontal advective fluxes
             ! MUSCL fluxes
             z0u = SIGN( 0.5_wp, pU(ji,jj,jk) )
@@ -173,5 +176,5 @@
             zwy(ji,jj,jk) = pV(ji,jj,jk) * ( zalpha * zzwx + (1.-zalpha) * zzwy )
          END_3D
-         CALL lbc_lnk_multi( 'traadv_mus', zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp )   ! lateral boundary conditions   (changed sign)
+         IF ( nn_hls.EQ.1 ) CALL lbc_lnk_multi( 'traadv_mus', zwx, 'U', -1.0_wp , zwy, 'V', -1.0_wp )   ! lateral boundary conditions   (changed sign)
          !
          DO_3D( 0, 0, 0, 0, 1, jpkm1 )    !-- Tracer advective trend
@@ -195,7 +198,7 @@
          zwx(:,:, 1 ) = 0._wp                   ! surface & bottom boundary conditions
          zwx(:,:,jpk) = 0._wp
-         DO jk = 2, jpkm1                       ! interior values
-            zwx(:,:,jk) = tmask(:,:,jk) * ( pt(:,:,jk-1,jn,Kbb) - pt(:,:,jk,jn,Kbb) )
-         END DO
+         DO_3D( 1, 1, 1, 1, 2, jpkm1 )                ! interior values
+            zwx(ji,jj,jk) = tmask(ji,jj,jk) * ( pt(ji,jj,jk-1,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
+         END_3D
          !                                !-- Slopes of tracer
          zslpx(:,:,1) = 0._wp                   ! surface values
@@ -223,5 +226,7 @@
                END_2D
             ELSE                                      ! no cavities: only at the ocean surface
-               zwx(:,:,1) = pW(:,:,1) * pt(:,:,1,jn,Kbb)
+               DO_2D( 1, 1, 1, 1 )
+                  zwx(ji,jj,1) = pW(ji,jj,1) * pt(ji,jj,1,jn,Kbb)
+               END_2D
             ENDIF
          ENDIF
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_mus_lf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_mus_lf.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_mus_lf.F90	(revision 14055)
@@ -0,0 +1,289 @@
+MODULE traadv_mus_lf
+   !!======================================================================
+   !!                       ***  MODULE  traadv_mus  ***
+   !! Ocean  tracers:  horizontal & vertical advective trend
+   !!======================================================================
+   !! History :       !  2000-06  (A.Estublier)  for passive tracers
+   !!                 !  2001-08  (E.Durand, G.Madec)  adapted for T & S
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  F90: Free form and module
+   !!            3.2  !  2010-05  (C. Ethe, G. Madec)  merge TRC-TRA + switch from velocity to transport
+   !!            3.4  !  2012-06  (P. Oddo, M. Vichi) include the upstream where needed
+   !!            3.7  !  2015-09  (G. Madec) add the ice-shelf cavities boundary condition
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_adv_mus   : update the tracer trend with the horizontal
+   !!                   and vertical advection trends using MUSCL scheme
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE dom_oce        ! ocean space and time domain
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! tracers trends manager
+   USE sbcrnf         ! river runoffs
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+
+   !
+   USE iom            ! XIOS library
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_mus_lf   ! routine called by traadv.F90
+   
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   upsmsk   !: mixed upstream/centered scheme near some straits
+   !                                                           !  and in closed seas (orca 2 and 1 configurations)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xind     !: mixed upstream/centered index
+   
+   LOGICAL  ::   l_trd   ! flag to compute trends
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat/salt transport
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+#  include "domzgr_substitute.h90"
+
+#define initial_slop_i(out, ji) \
+        out = umask(ji,jj,jk) * ( pt(ji+1,jj,jk,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
+
+#define initial_slop_j(out, jj) \
+        out = vmask(ji,jj,jk) * ( pt(ji,jj+1,jk,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
+
+#define initial_slop_k(out, jk) \
+        out = tmask(ji,jj,jk) * ( pt(ji,jj,jk-1,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
+
+#define tracer_slop(out, zzw, zzwm1) \
+        out = ( zzw + zzwm1 ) * ( 0.25 + SIGN( 0.25_wp, zzw * zzwm1 ) )
+
+#define limitation_slop(out, zzslp, zzwm1, zzw) \
+        out = SIGN( 1.0_wp, zzslp ) * MIN( ABS( zzslp ), 2.*ABS( zzwm1 ), 2.*ABS( zzw ) )
+
+#define vertical_adv_flux_i(out, jk, slp, slp1) \
+        z0u = SIGN( 0.5_wp, pU(ji,jj,jk) ) ; \
+        zalpha = 0.5 - z0u ; \
+        zu  = z0u - 0.5 * pU(ji,jj,jk) * p2dt * r1_e1e2u(ji,jj) / e3u(ji,jj,jk,Kmm) ; \
+        zzwx = pt(ji+1,jj,jk,jn,Kbb) + xind(ji,jj,jk) * zu * slp1 ; \
+        zzwy = pt(ji  ,jj,jk,jn,Kbb) + xind(ji,jj,jk) * zu * slp ; \
+        out = pU(ji,jj,jk) * ( zalpha * zzwx + (1.-zalpha) * zzwy )
+
+#define vertical_adv_flux_j(out, jk, slp, slp1) \
+        z0v = SIGN( 0.5_wp, pV(ji,jj,jk) ) ; \
+        zalpha = 0.5 - z0v ; \
+        zv  = z0v - 0.5 * pV(ji,jj,jk) * p2dt * r1_e1e2v(ji,jj) / e3v(ji,jj,jk,Kmm) ; \
+        zzwx = pt(ji,jj+1,jk,jn,Kbb) + xind(ji,jj,jk) * zv * slp1 ; \
+        zzwy = pt(ji,jj  ,jk,jn,Kbb) + xind(ji,jj,jk) * zv * slp ; \
+        out = pV(ji,jj,jk) * ( zalpha * zzwx + (1.-zalpha) * zzwy )
+
+#define vertical_adv_flux(out, jk, slp, slp1) \
+        z0w = SIGN( 0.5_wp, pW(ji,jj,jk+1) ) ; \
+        zalpha = 0.5 + z0w ; \
+        zw  = z0w - 0.5 * pW(ji,jj,jk+1) * p2dt * r1_e1e2t(ji,jj) / e3w(ji,jj,jk+1,Kmm) ; \
+        zzwx = pt(ji,jj,jk+1,jn,Kbb) + xind(ji,jj,jk) * zw * slp1 ; \
+        zzwy = pt(ji,jj,jk  ,jn,Kbb) + xind(ji,jj,jk) * zw * slp ; \
+        out = pW(ji,jj,jk+1) * ( zalpha * zzwx + (1.-zalpha) * zzwy ) * wmask(ji,jj,jk) 
+
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: traadv_mus.F90 13619 2020-10-16 08:41:21Z francesca $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_mus_lf( kt, kit000, cdtype, p2dt, pU, pV, pW,             &
+      &                    Kbb, Kmm, pt, kjpt, Krhs, ld_msc_ups )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE tra_adv_mus  ***
+      !!
+      !! ** Purpose :   Compute the now trend due to total advection of tracers
+      !!              using a MUSCL scheme (Monotone Upstream-centered Scheme for
+      !!              Conservation Laws) and add it to the general tracer trend.
+      !!
+      !! ** Method  : MUSCL scheme plus centered scheme at ocean boundaries
+      !!              ld_msc_ups=T : 
+      !!
+      !! ** Action : - update pt(:,:,:,:,Krhs)  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostcs (l_trdtra=T)
+      !!             - poleward advective heat and salt transport (ln_diaptr=T)
+      !!
+      !! References : Estubier, A., and M. Levy, Notes Techn. Pole de Modelisation
+      !!              IPSL, Sept. 2000 (http://www.lodyc.jussieu.fr/opa)
+      !!----------------------------------------------------------------------
+      INTEGER                                  , INTENT(in   ) ::   kt              ! ocean time-step index
+      INTEGER                                  , INTENT(in   ) ::   Kbb, Kmm, Krhs  ! ocean time level indices
+      INTEGER                                  , INTENT(in   ) ::   kit000          ! first time step index
+      CHARACTER(len=3)                         , INTENT(in   ) ::   cdtype          ! =TRA or TRC (tracer indicator)
+      INTEGER                                  , INTENT(in   ) ::   kjpt            ! number of tracers
+      LOGICAL                                  , INTENT(in   ) ::   ld_msc_ups      ! use upstream scheme within muscl
+      REAL(wp)                                 , INTENT(in   ) ::   p2dt            ! tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU, pV, pW      ! 3 ocean volume flux components
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::   ierr             ! local integer
+      REAL(wp) ::   zu, z0u, zw , zalpha   ! local scalars
+      REAL(wp) ::   zv, z0v, z0w           !   -      -
+      REAL(wp) ::   zzwx, zzwxm1, zzwxp1, zzwy, zzwym1, zzwyp1
+      REAL(wp) ::   zzslpx, zzslpxp1, zzslpy, zzslpyp1
+      REAL(wp), TARGET, DIMENSION(jpi,jpj) :: zzwz_buf, zzwzp1_buf, zzwzp2_buf
+      REAL(wp), TARGET, DIMENSION(jpi,jpj) :: zzslpz_buf, zzslpzp1_buf
+      REAL(wp), POINTER, DIMENSION(:,:)    :: tmp, zzwz_ptr, zzwzp1_ptr, zzwzp2_ptr
+      REAL(wp), POINTER, DIMENSION(:,:)    :: zzslpz_ptr, zzslpzp1_ptr 
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwz, zwx, zwy   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv : MUSCL advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '        : mixed up-stream           ', ld_msc_ups
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+         IF(lwp) WRITE(numout,*)
+         !
+         ! Upstream / MUSCL scheme indicator
+         !
+         ALLOCATE( xind(jpi,jpj,jpk), STAT=ierr )
+         xind(:,:,:) = 1._wp              ! set equal to 1 where up-stream is not needed
+         !
+         IF( ld_msc_ups ) THEN            ! define the upstream indicator (if asked)
+            ALLOCATE( upsmsk(jpi,jpj), STAT=ierr )
+            upsmsk(:,:) = 0._wp                             ! not upstream by default
+            !
+            DO jk = 1, jpkm1
+               xind(:,:,jk) = 1._wp                              &                 ! =>1 where up-stream is not needed
+                  &         - MAX ( rnfmsk(:,:) * rnfmsk_z(jk),  &                 ! =>0 near runoff mouths (& closed sea outflows)
+                  &                 upsmsk(:,:)                ) * tmask(:,:,jk)   ! =>0 in some user defined area
+            END DO
+         ENDIF 
+         !
+      ENDIF 
+      !      
+      l_trd = .FALSE.
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )   l_ptr = .TRUE. 
+      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
+      !
+         zzwz_ptr => zzwz_buf
+         zzwzp1_ptr => zzwzp1_buf
+         zzwzp2_ptr => zzwzp2_buf
+         zzslpz_ptr => zzslpz_buf
+         zzslpzp1_ptr => zzslpzp1_buf
+         !
+      DO jn = 1, kjpt            !==  loop over the tracers  ==!
+         !
+         zwx(:,:,jpk) = 0._wp                   ! bottom values
+         zwy(:,:,jpk) = 0._wp
+         zwz(:,:, 1 ) = 0._wp                   ! surface & bottom boundary conditions
+         zwz(:,:,jpk) = 0._wp
+         !                          !* Horizontal advective fluxes
+         !
+         !!----------------------------------------------------------------------
+         DO_3D( 1, 0, 1, 0, 1, jpkm1 )
+            !-- first guess of the slopes
+            initial_slop_i(zzwxm1, ji-1)
+            initial_slop_i(zzwx, ji)
+            initial_slop_i(zzwxp1, ji+1)
+
+            initial_slop_j(zzwym1, jj-1)
+            initial_slop_j(zzwy, jj)
+            initial_slop_j(zzwyp1, jj+1)
+            !-- Slopes of tracer
+            tracer_slop(zzslpx, zzwx, zzwxm1) 
+            tracer_slop(zzslpxp1, zzwxp1, zzwx) 
+            tracer_slop(zzslpy, zzwy, zzwym1) 
+            tracer_slop(zzslpyp1, zzwyp1, zzwy) 
+            !-- Slopes limitation
+            limitation_slop(zzslpx, zzslpx, zzwxm1, zzwx)
+            limitation_slop(zzslpxp1, zzslpxp1, zzwx, zzwxp1)
+            limitation_slop(zzslpy, zzslpy, zzwym1, zzwy)
+            limitation_slop(zzslpyp1, zzslpyp1, zzwy, zzwyp1)
+            !-- MUSCL horizontal advective fluxes
+            vertical_adv_flux_i(zwx(ji,jj,jk), jk, zzslpx, zzslpxp1) 
+            vertical_adv_flux_j(zwy(ji,jj,jk), jk, zzslpy, zzslpyp1) 
+         END_3D
+         !
+         DO_3D( 0, 0, 0, 0, 1, jpkm1 )    !-- Tracer advective trend
+            pt(ji,jj,jk,jn,Krhs) = pt(ji,jj,jk,jn,Krhs) - ( zwx(ji,jj,jk) - zwx(ji-1,jj,jk)       &
+            &                                     + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  ) )     &
+            &                                     * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
+         END_3D
+         !                          !* Vertical advective fluxes
+         DO_2D( 0, 0, 0, 0 ) 
+            !-- first guess of the slopes
+            initial_slop_k(zzwz_ptr(ji,jj), 2)
+            initial_slop_k(zzwzp1_ptr(ji,jj), 3)
+            !-- Slopes of tracer
+            tracer_slop(zzslpz_ptr(ji,jj), zzwz_ptr(ji,jj), zzwzp1_ptr(ji,jj))
+            !-- Slopes limitation
+            limitation_slop(zzslpz_ptr(ji,jj), zzslpz_ptr(ji,jj), zzwzp1_ptr(ji,jj), zzwz_ptr(ji,jj))
+            !-- vertical advective flux
+            vertical_adv_flux(zwz(ji,jj,2), 1, 0, zzslpz_ptr(ji,jj))
+         END_2D
+         
+         DO jk = 2, jpk-3    
+            DO_2D( 0, 0, 0, 0 )
+               !-- first guess of the slopes
+               initial_slop_k(zzwzp2_ptr(ji,jj), jk+2)
+               !-- Slopes of tracer
+               tracer_slop(zzslpzp1_ptr(ji,jj), zzwzp1_ptr(ji,jj), zzwzp2_ptr(ji,jj))
+               !-- Slopes limitation
+               limitation_slop(zzslpzp1_ptr(ji,jj), zzslpzp1_ptr(ji,jj), zzwzp2_ptr(ji,jj), zzwzp1_ptr(ji,jj))
+               !-- vertical advective flux
+               vertical_adv_flux(zwz(ji,jj,jk+1), jk, zzslpz_ptr(ji,jj), zzslpzp1_ptr(ji,jj))
+            END_2D
+            tmp => zzwzp1_ptr
+            zzwzp1_ptr => zzwzp2_ptr
+            zzwzp2_ptr => tmp
+
+            tmp => zzslpz_ptr
+            zzslpz_ptr => zzslpzp1_ptr
+            zzslpzp1_ptr => tmp 
+         END DO
+         DO_2D( 0, 0, 0, 0 ) 
+            !-- Slopes of tracer
+            tracer_slop(zzslpzp1_ptr(ji,jj), zzwzp1_ptr(ji,jj), 0)
+            !-- Slopes limitation
+            limitation_slop(zzslpzp1_ptr(ji,jj), zzslpzp1_ptr(ji,jj), 0, zzwzp1_ptr(ji,jj))
+            !-- vertical advective flux
+            vertical_adv_flux(zwz(ji,jj,jpk-1), jpk-2, zzslpz_ptr(ji,jj), zzslpzp1_ptr(ji,jj))
+         END_2D
+
+         IF( ln_linssh ) THEN                   ! top values, linear free surface only
+            IF( ln_isfcav ) THEN                      ! ice-shelf cavities (top of the ocean)
+               DO_2D( 1, 1, 1, 1 )
+                  zwz(ji,jj, mikt(ji,jj) ) = pW(ji,jj,mikt(ji,jj)) * pt(ji,jj,mikt(ji,jj),jn,Kbb)
+               END_2D
+            ELSE                                      ! no cavities: only at the ocean surface
+               zwz(:,:,1) = pW(:,:,1) * pt(:,:,1,jn,Kbb)
+            ENDIF
+         ENDIF
+         !
+         DO_3D( 0, 0, 0, 0, 1, jpkm1 )     !-- vertical advective trend
+            pt(ji,jj,jk,jn,Krhs) =  pt(ji,jj,jk,jn,Krhs) - ( zwz(ji,jj,jk) - zwz(ji,jj,jk+1) )   &
+               &                                      * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
+         END_3D
+         !                                ! trend horizontal diagnostics
+         IF( l_trd )  THEN
+            CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_xad, zwx, pU, pt(:,:,:,jn,Kbb) )
+            CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_yad, zwy, pV, pt(:,:,:,jn,Kbb) )
+         END IF
+         !                                 ! "Poleward" heat and salt transports 
+         IF( l_ptr )  CALL dia_ptr_hst( jn, 'adv', zwy(:,:,:) )
+         !                                 !  heat transport
+         IF( l_hst )  CALL dia_ar5_hst( jn, 'adv', zwx(:,:,:), zwy(:,:,:) )
+         !
+         !                                ! send vertical trends for diagnostic
+         IF( l_trd )  CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_zad, zwz, pW, pt(:,:,:,jn,Kbb) )
+         !
+      END DO                     ! end of tracer loop
+      !
+   END SUBROUTINE tra_adv_mus_lf
+
+   !!======================================================================
+END MODULE traadv_mus_lf
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_qck.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_qck.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_qck.F90	(revision 14055)
@@ -91,20 +91,23 @@
       INTEGER                                  , INTENT(in   ) ::   kjpt            ! number of tracers
       REAL(wp)                                 , INTENT(in   ) ::   p2dt            ! tracer time-step
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
+      ! NOTE: [tiling-comms-merge] These were changed to INTENT(inout) but they are not modified, so it is reverted
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU, pV, pW      ! 3 ocean volume transport components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
       !!----------------------------------------------------------------------
       !
-      IF( kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_adv_qck : 3rd order quickest advection scheme on ', cdtype
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
-         IF(lwp) WRITE(numout,*)
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_adv_qck : 3rd order quickest advection scheme on ', cdtype
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+            IF(lwp) WRITE(numout,*)
+         ENDIF
+         !
+         l_trd = .FALSE.
+         l_ptr = .FALSE.
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )   l_trd = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) ) ) l_ptr = .TRUE.
       ENDIF
-      !
-      l_trd = .FALSE.
-      l_ptr = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )   l_trd = .TRUE.
-      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) ) ) l_ptr = .TRUE. 
-      !
       !
       !        ! horizontal fluxes are computed with the QUICKEST + ULTIMATE scheme
@@ -127,4 +130,5 @@
       INTEGER                                  , INTENT(in   ) ::   kjpt       ! number of tracers
       REAL(wp)                                 , INTENT(in   ) ::   p2dt       ! tracer time-step
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU        ! i-velocity components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! active tracers and RHS of tracer equation
@@ -132,5 +136,5 @@
       INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
       REAL(wp) ::   ztra, zbtr, zdir, zdx, zmsk   ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwx, zfu, zfc, zfd
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwx, zfu, zfc, zfd
       !----------------------------------------------------------------------
       !
@@ -142,19 +146,19 @@
          !
 !!gm why not using a SHIFT instruction...
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )     !--- Computation of the ustream and downstream value of the tracer and the mask
+         DO_3D( 0, 0, nn_hls-1, nn_hls-1, 1, jpkm1 )     !--- Computation of the ustream and downstream value of the tracer and the mask
             zfc(ji,jj,jk) = pt(ji-1,jj,jk,jn,Kbb)        ! Upstream   in the x-direction for the tracer
             zfd(ji,jj,jk) = pt(ji+1,jj,jk,jn,Kbb)        ! Downstream in the x-direction for the tracer
          END_3D
-         CALL lbc_lnk_multi( 'traadv_qck', zfc(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp )   ! Lateral boundary conditions 
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_qck', zfc(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp )   ! Lateral boundary conditions
          
          !
          ! Horizontal advective fluxes
          ! ---------------------------
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( 0, 0, nn_hls-1, 0, 1, jpkm1 )
             zdir = 0.5 + SIGN( 0.5_wp, pU(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0 
             zfu(ji,jj,jk) = zdir * zfc(ji,jj,jk ) + ( 1. - zdir ) * zfd(ji+1,jj,jk)  ! FU in the x-direction for T 
          END_3D
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( 0, 0, nn_hls-1, 0, 1, jpkm1 )
             zdir = 0.5 + SIGN( 0.5_wp, pU(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0 
             zdx = ( zdir * e1t(ji,jj) + ( 1. - zdir ) * e1t(ji+1,jj) ) * e2u(ji,jj) * e3u(ji,jj,jk,Kmm)
@@ -164,5 +168,5 @@
          END_3D
          !--- Lateral boundary conditions 
-         CALL lbc_lnk_multi( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp, zfc(:,:,:), 'T', 1.0_wp,  zwx(:,:,:), 'T', 1.0_wp )
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp, zfc(:,:,:), 'T', 1.0_wp,  zwx(:,:,:), 'T', 1.0_wp )
 
          !--- QUICKEST scheme
@@ -170,24 +174,19 @@
          !
          ! Mask at the T-points in the x-direction (mask=0 or mask=1)
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( 0, 0, nn_hls-1, nn_hls-1, 1, jpkm1 )
             zfu(ji,jj,jk) = tmask(ji-1,jj,jk) + tmask(ji,jj,jk) + tmask(ji+1,jj,jk) - 2.
          END_3D
-         CALL lbc_lnk( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp )      ! Lateral boundary conditions 
+         IF (nn_hls.EQ.1) CALL lbc_lnk( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp )      ! Lateral boundary conditions
 
          !
          ! Tracer flux on the x-direction
-         DO jk = 1, jpkm1  
-            !
-            DO_2D( 0, 0, 0, 0 )
-               zdir = 0.5 + SIGN( 0.5_wp, pU(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0 
-               !--- If the second ustream point is a land point
-               !--- the flux is computed by the 1st order UPWIND scheme
-               zmsk = zdir * zfu(ji,jj,jk) + ( 1. - zdir ) * zfu(ji+1,jj,jk)
-               zwx(ji,jj,jk) = zmsk * zwx(ji,jj,jk) + ( 1. - zmsk ) * zfc(ji,jj,jk)
-               zwx(ji,jj,jk) = zwx(ji,jj,jk) * pU(ji,jj,jk)
-            END_2D
-         END DO
-         !
-         CALL lbc_lnk( 'traadv_qck', zwx(:,:,:), 'T', 1.0_wp ) ! Lateral boundary conditions
+         DO_3D( 0, 0, 1, 0, 1, jpkm1 )
+            zdir = 0.5 + SIGN( 0.5_wp, pU(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0
+            !--- If the second ustream point is a land point
+            !--- the flux is computed by the 1st order UPWIND scheme
+            zmsk = zdir * zfu(ji,jj,jk) + ( 1. - zdir ) * zfu(ji+1,jj,jk)
+            zwx(ji,jj,jk) = zmsk * zwx(ji,jj,jk) + ( 1. - zmsk ) * zfc(ji,jj,jk)
+            zwx(ji,jj,jk) = zwx(ji,jj,jk) * pU(ji,jj,jk)
+         END_3D
          !
          ! Computation of the trend
@@ -216,4 +215,5 @@
       INTEGER                                  , INTENT(in   ) ::   kjpt       ! number of tracers
       REAL(wp)                                 , INTENT(in   ) ::   p2dt       ! tracer time-step
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pV        ! j-velocity components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! active tracers and RHS of tracer equation
@@ -221,5 +221,5 @@
       INTEGER  :: ji, jj, jk, jn                ! dummy loop indices
       REAL(wp) :: ztra, zbtr, zdir, zdx, zmsk   ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwy, zfu, zfc, zfd   ! 3D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwy, zfu, zfc, zfd   ! 3D workspace
       !----------------------------------------------------------------------
       !
@@ -233,5 +233,5 @@
             !                                             
             !--- Computation of the ustream and downstream value of the tracer and the mask
-            DO_2D( 0, 0, 0, 0 )
+            DO_2D( nn_hls-1, nn_hls-1, 0, 0 )
                ! Upstream in the x-direction for the tracer
                zfc(ji,jj,jk) = pt(ji,jj-1,jk,jn,Kbb)
@@ -240,6 +240,5 @@
             END_2D
          END DO
-         CALL lbc_lnk_multi( 'traadv_qck', zfc(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp )   ! Lateral boundary conditions 
-
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_qck', zfc(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp )   ! Lateral boundary conditions
          
          !
@@ -247,10 +246,10 @@
          ! ---------------------------
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls-1, 0, 0, 0, 1, jpkm1 )
             zdir = 0.5 + SIGN( 0.5_wp, pV(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0 
             zfu(ji,jj,jk) = zdir * zfc(ji,jj,jk ) + ( 1. - zdir ) * zfd(ji,jj+1,jk)  ! FU in the x-direction for T 
          END_3D
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls-1, 0, 0, 0, 1, jpkm1 )
             zdir = 0.5 + SIGN( 0.5_wp, pV(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0 
             zdx = ( zdir * e2t(ji,jj) + ( 1. - zdir ) * e2t(ji,jj+1) ) * e1v(ji,jj) * e3v(ji,jj,jk,Kmm)
@@ -261,5 +260,5 @@
 
          !--- Lateral boundary conditions 
-         CALL lbc_lnk_multi( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp, zfc(:,:,:), 'T', 1.0_wp, zwy(:,:,:), 'T', 1.0_wp )
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp , zfd(:,:,:), 'T', 1.0_wp, zfc(:,:,:), 'T', 1.0_wp, zwy(:,:,:), 'T', 1.0_wp )
 
          !--- QUICKEST scheme
@@ -267,23 +266,18 @@
          !
          ! Mask at the T-points in the x-direction (mask=0 or mask=1)
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls-1, nn_hls-1, 0, 0, 1, jpkm1 )
             zfu(ji,jj,jk) = tmask(ji,jj-1,jk) + tmask(ji,jj,jk) + tmask(ji,jj+1,jk) - 2.
          END_3D
-         CALL lbc_lnk( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp )    !--- Lateral boundary conditions 
+         IF (nn_hls.EQ.1) CALL lbc_lnk( 'traadv_qck', zfu(:,:,:), 'T', 1.0_wp )    !--- Lateral boundary conditions
          !
          ! Tracer flux on the x-direction
-         DO jk = 1, jpkm1  
-            !
-            DO_2D( 0, 0, 0, 0 )
-               zdir = 0.5 + SIGN( 0.5_wp, pV(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0 
-               !--- If the second ustream point is a land point
-               !--- the flux is computed by the 1st order UPWIND scheme
-               zmsk = zdir * zfu(ji,jj,jk) + ( 1. - zdir ) * zfu(ji,jj+1,jk)
-               zwy(ji,jj,jk) = zmsk * zwy(ji,jj,jk) + ( 1. - zmsk ) * zfc(ji,jj,jk)
-               zwy(ji,jj,jk) = zwy(ji,jj,jk) * pV(ji,jj,jk)
-            END_2D
-         END DO
-         !
-         CALL lbc_lnk( 'traadv_qck', zwy(:,:,:), 'T', 1.0_wp ) ! Lateral boundary conditions
+         DO_3D( 1, 0, 0, 0, 1, jpkm1 )
+            zdir = 0.5 + SIGN( 0.5_wp, pV(ji,jj,jk) )   ! if pU > 0 : zdir = 1 otherwise zdir = 0
+            !--- If the second ustream point is a land point
+            !--- the flux is computed by the 1st order UPWIND scheme
+            zmsk = zdir * zfu(ji,jj,jk) + ( 1. - zdir ) * zfu(ji,jj+1,jk)
+            zwy(ji,jj,jk) = zmsk * zwy(ji,jj,jk) + ( 1. - zmsk ) * zfc(ji,jj,jk)
+            zwy(ji,jj,jk) = zwy(ji,jj,jk) * pV(ji,jj,jk)
+         END_3D
          !
          ! Computation of the trend
@@ -313,9 +307,10 @@
       CHARACTER(len=3)                         , INTENT(in   ) ::   cdtype   ! =TRA or TRC (tracer indicator)
       INTEGER                                  , INTENT(in   ) ::   kjpt     ! number of tracers
-      REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pW      ! vertical velocity 
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
+      REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pW      ! vertical velocity
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! active tracers and RHS of tracer equation
       !
       INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwz   ! 3D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwz   ! 3D workspace
       !!----------------------------------------------------------------------
       !
@@ -332,9 +327,11 @@
          IF( ln_linssh ) THEN                !* top value   (only in linear free surf. as zwz is multiplied by wmask)
             IF( ln_isfcav ) THEN                  ! ice-shelf cavities (top of the ocean)
-               DO_2D( 1, 1, 1, 1 )
+               DO_2D( 0, 0, 0, 0 )
                   zwz(ji,jj, mikt(ji,jj) ) = pW(ji,jj,mikt(ji,jj)) * pt(ji,jj,mikt(ji,jj),jn,Kmm)   ! linear free surface 
                END_2D
             ELSE                                   ! no ocean cavities (only ocean surface)
-               zwz(:,:,1) = pW(:,:,1) * pt(:,:,1,jn,Kmm)
+               DO_2D( 0, 0, 0, 0 )
+                  zwz(ji,jj,1) = pW(ji,jj,1) * pt(ji,jj,1,jn,Kmm)
+               END_2D
             ENDIF
          ENDIF
@@ -359,8 +356,8 @@
       !! ** Method :   
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pfu   ! second upwind point
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pfd   ! first douwning point
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pfc   ! the central point (or the first upwind point)
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   puc   ! input as Courant number ; output as flux
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(in   ) ::   pfu   ! second upwind point
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(in   ) ::   pfd   ! first douwning point
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(in   ) ::   pfc   ! the central point (or the first upwind point)
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   puc   ! input as Courant number ; output as flux
       !!
       INTEGER  ::  ji, jj, jk               ! dummy loop indices 
@@ -369,5 +366,5 @@
       !----------------------------------------------------------------------
       !
-      DO_3D( 1, 1, 1, 1, 1, jpkm1 )
+      DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
          zc     = puc(ji,jj,jk)                         ! Courant number
          zcurv  = pfd(ji,jj,jk) + pfu(ji,jj,jk) - 2. * pfc(ji,jj,jk)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_ubs.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_ubs.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traadv_ubs.F90	(revision 14055)
@@ -92,4 +92,5 @@
       INTEGER                                  , INTENT(in   ) ::   kn_ubs_v        ! number of tracers
       REAL(wp)                                 , INTENT(in   ) ::   p2dt            ! tracer time-step
+      ! TEMP: [tiling] This can be A2D(nn_hls) if using XIOS (subdomain support)
       REAL(wp), DIMENSION(jpi,jpj,jpk         ), INTENT(in   ) ::   pU, pV, pW      ! 3 ocean volume transport components
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt,jpt), INTENT(inout) ::   pt              ! tracers and RHS of tracer equation
@@ -99,25 +100,26 @@
       REAL(wp) ::   zfp_ui, zfm_ui, zcenut, ztak, zfp_wk, zfm_wk   !   -      -
       REAL(wp) ::   zfp_vj, zfm_vj, zcenvt, zeeu, zeev, z_hdivn    !   -      -
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ztu, ztv, zltu, zltv, zti, ztw   ! 3D workspace
-      !!----------------------------------------------------------------------
-      !
-      IF( kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_adv_ubs :  horizontal UBS advection scheme on ', cdtype
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   ztu, ztv, zltu, zltv, zti, ztw     ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_adv_ubs :  horizontal UBS advection scheme on ', cdtype
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+         ENDIF
+         !
+         l_trd = .FALSE.
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )   l_ptr = .TRUE.
+         IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+            &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
       ENDIF
-      !
-      l_trd = .FALSE.
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
-      IF(   cdtype == 'TRA' .AND. ( iom_use( 'sophtadv' ) .OR. iom_use( 'sophtadv' ) )  )   l_ptr = .TRUE. 
-      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
-         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
       !
       ztw (:,:, 1 ) = 0._wp      ! surface & bottom value : set to zero for all tracers
       zltu(:,:,jpk) = 0._wp   ;   zltv(:,:,jpk) = 0._wp
       ztw (:,:,jpk) = 0._wp   ;   zti (:,:,jpk) = 0._wp
-      !
       !                                                          ! ===========
       DO jn = 1, kjpt                                            ! tracer loop
@@ -125,5 +127,5 @@
          !                                              
          DO jk = 1, jpkm1                !==  horizontal laplacian of before tracer ==!
-            DO_2D( 1, 0, 1, 0 )                   ! First derivative (masked gradient)
+            DO_2D( nn_hls, nn_hls-1, nn_hls, nn_hls-1 )                   ! First derivative (masked gradient)
                zeeu = e2_e1u(ji,jj) * e3u(ji,jj,jk,Kmm) * umask(ji,jj,jk)
                zeev = e1_e2v(ji,jj) * e3v(ji,jj,jk,Kmm) * vmask(ji,jj,jk)
@@ -131,5 +133,5 @@
                ztv(ji,jj,jk) = zeev * ( pt(ji  ,jj+1,jk,jn,Kbb) - pt(ji,jj,jk,jn,Kbb) )
             END_2D
-            DO_2D( 0, 0, 0, 0 )                   ! Second derivative (divergence)
+            DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )                   ! Second derivative (divergence)
                zcoef = 1._wp / ( 6._wp * e3t(ji,jj,jk,Kmm) )
                zltu(ji,jj,jk) = (  ztu(ji,jj,jk) - ztu(ji-1,jj,jk)  ) * zcoef
@@ -138,5 +140,5 @@
             !                                    
          END DO         
-         CALL lbc_lnk( 'traadv_ubs', zltu, 'T', 1.0_wp )   ;    CALL lbc_lnk( 'traadv_ubs', zltv, 'T', 1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'traadv_ubs', zltu, 'T', 1.0_wp, zltv, 'T', 1.0_wp )   ! Lateral boundary cond. (unchanged sgn)
          !    
          DO_3D( 1, 0, 1, 0, 1, jpkm1 )   !==  Horizontal advective fluxes  ==!     (UBS)
@@ -153,5 +155,7 @@
          END_3D
          !
-         zltu(:,:,:) = pt(:,:,:,jn,Krhs)      ! store the initial trends before its update
+         DO_3D( 1, 1, 1, 1, 1, jpk )
+            zltu(ji,jj,jk) = pt(ji,jj,jk,jn,Krhs)      ! store the initial trends before its update
+         END_3D
          !
          DO jk = 1, jpkm1        !==  add the horizontal advective trend  ==!
@@ -165,7 +169,8 @@
          END DO
          !
-         zltu(:,:,:) = pt(:,:,:,jn,Krhs) - zltu(:,:,:)    ! Horizontal advective trend used in vertical 2nd order FCT case
-         !                                                ! and/or in trend diagnostic (l_trd=T) 
-         !                
+         DO_3D( 1, 1, 1, 1, 1, jpk )
+            zltu(ji,jj,jk) = pt(ji,jj,jk,jn,Krhs) - zltu(ji,jj,jk)  ! Horizontal advective trend used in vertical 2nd order FCT case
+         END_3D                                                     ! and/or in trend diagnostic (l_trd=T)
+         !
          IF( l_trd ) THEN                  ! trend diagnostics
              CALL trd_tra( kt, Kmm, Krhs, cdtype, jn, jptra_xad, ztu, pU, pt(:,:,:,jn,Kmm) )
@@ -185,5 +190,9 @@
          CASE(  2  )                   ! 2nd order FCT 
             !         
-            IF( l_trd )   zltv(:,:,:) = pt(:,:,:,jn,Krhs)          ! store pt(:,:,:,:,Krhs) if trend diag.
+            IF( l_trd ) THEN
+               DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+                  zltv(ji,jj,jk) = pt(ji,jj,jk,jn,Krhs)          ! store pt(:,:,:,:,Krhs) if trend diag.
+               END_3D
+            ENDIF
             !
             !                               !*  upstream advection with initial mass fluxes & intermediate update  ==!
@@ -199,5 +208,7 @@
                   END_2D
                ELSE                                   ! no cavities: only at the ocean surface
-                  ztw(:,:,1) = pW(:,:,1) * pt(:,:,1,jn,Kbb)
+                  DO_2D( 1, 1, 1, 1 )
+                     ztw(ji,jj,1) = pW(ji,jj,1) * pt(ji,jj,1,jn,Kbb)
+                  END_2D
                ENDIF
             ENDIF
@@ -209,5 +220,4 @@
                zti(ji,jj,jk)    = ( pt(ji,jj,jk,jn,Kbb) + p2dt * ( ztak + zltu(ji,jj,jk) ) ) * tmask(ji,jj,jk)
             END_3D
-            CALL lbc_lnk( 'traadv_ubs', zti, 'T', 1.0_wp )      ! Lateral boundary conditions on zti, zsi   (unchanged sign)
             !
             !                          !*  anti-diffusive flux : high order minus low order
@@ -226,5 +236,9 @@
                ztw(ji,jj,jk) = pW(ji,jj,jk) * ztw(ji,jj,jk) * wmask(ji,jj,jk)
             END_3D
-            IF( ln_linssh )   ztw(:,:, 1 ) = pW(:,:,1) * pt(:,:,1,jn,Kmm)     !!gm ISF & 4th COMPACT doesn't work
+            IF( ln_linssh ) THEN
+               DO_2D( 1, 1, 1, 1 )
+                  ztw(ji,jj,1) = pW(ji,jj,1) * pt(ji,jj,1,jn,Kmm)     !!gm ISF & 4th COMPACT doesn't work
+               END_2D
+            ENDIF
             !
          END SELECT
@@ -262,14 +276,14 @@
       !!       in-space based differencing for fluid
       !!----------------------------------------------------------------------
-      INTEGER , INTENT(in   )                          ::   Kmm    ! time level index
-      REAL(wp), INTENT(in   )                          ::   p2dt   ! tracer time-step
-      REAL(wp),                DIMENSION (jpi,jpj,jpk) ::   pbef   ! before field
-      REAL(wp), INTENT(inout), DIMENSION (jpi,jpj,jpk) ::   paft   ! after field
-      REAL(wp), INTENT(inout), DIMENSION (jpi,jpj,jpk) ::   pcc    ! monotonic flux in the k direction
+      INTEGER , INTENT(in   )                         ::   Kmm    ! time level index
+      REAL(wp), INTENT(in   )                         ::   p2dt   ! tracer time-step
+      REAL(wp),                DIMENSION(jpi,jpj,jpk) ::   pbef   ! before field
+      REAL(wp), INTENT(inout), DIMENSION(A2D(nn_hls)    ,jpk) ::   paft   ! after field
+      REAL(wp), INTENT(inout), DIMENSION(A2D(nn_hls)    ,jpk) ::   pcc    ! monotonic flux in the k direction
       !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
       INTEGER  ::   ikm1         ! local integer
       REAL(wp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn   ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zbetup, zbetdo     ! 3D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zbetup, zbetdo         ! 3D workspace
       !!----------------------------------------------------------------------
       !
@@ -281,6 +295,8 @@
       ! --------------------
       !                    ! large negative value (-zbig) inside land
-      pbef(:,:,:) = pbef(:,:,:) * tmask(:,:,:) - zbig * ( 1.e0 - tmask(:,:,:) )
-      paft(:,:,:) = paft(:,:,:) * tmask(:,:,:) - zbig * ( 1.e0 - tmask(:,:,:) )
+      DO_3D( 0, 0, 0, 0, 1, jpk )
+         pbef(ji,jj,jk) = pbef(ji,jj,jk) * tmask(ji,jj,jk) - zbig * ( 1.e0 - tmask(ji,jj,jk) )
+         paft(ji,jj,jk) = paft(ji,jj,jk) * tmask(ji,jj,jk) - zbig * ( 1.e0 - tmask(ji,jj,jk) )
+      END_3D
       !
       DO jk = 1, jpkm1     ! search maximum in neighbourhood
@@ -293,6 +309,8 @@
       END DO
       !                    ! large positive value (+zbig) inside land
-      pbef(:,:,:) = pbef(:,:,:) * tmask(:,:,:) + zbig * ( 1.e0 - tmask(:,:,:) )
-      paft(:,:,:) = paft(:,:,:) * tmask(:,:,:) + zbig * ( 1.e0 - tmask(:,:,:) )
+      DO_3D( 0, 0, 0, 0, 1, jpk )
+         pbef(ji,jj,jk) = pbef(ji,jj,jk) * tmask(ji,jj,jk) + zbig * ( 1.e0 - tmask(ji,jj,jk) )
+         paft(ji,jj,jk) = paft(ji,jj,jk) * tmask(ji,jj,jk) + zbig * ( 1.e0 - tmask(ji,jj,jk) )
+      END_3D
       !
       DO jk = 1, jpkm1     ! search minimum in neighbourhood
@@ -305,6 +323,8 @@
       END DO
       !                    ! restore masked values to zero
-      pbef(:,:,:) = pbef(:,:,:) * tmask(:,:,:)
-      paft(:,:,:) = paft(:,:,:) * tmask(:,:,:)
+      DO_3D( 0, 0, 0, 0, 1, jpk )
+         pbef(ji,jj,jk) = pbef(ji,jj,jk) * tmask(ji,jj,jk)
+         paft(ji,jj,jk) = paft(ji,jj,jk) * tmask(ji,jj,jk)
+      END_3D
       !
       ! Positive and negative part of fluxes and beta terms
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traatf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traatf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traatf.F90	(revision 14055)
@@ -117,6 +117,6 @@
       IF( l_trdtra )   THEN                    
          ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
-         ztrdt(:,:,jpk) = 0._wp
-         ztrds(:,:,jpk) = 0._wp
+         ztrdt(:,:,:) = 0._wp
+         ztrds(:,:,:) = 0._wp
          IF( ln_traldf_iso ) THEN              ! diagnose the "pure" Kz diffusive trend 
             CALL trd_tra( kt, Kmm, Kaa, 'TRA', jp_tem, jptra_zdfp, ztrdt )
@@ -156,8 +156,6 @@
          ENDIF
          !
-         CALL lbc_lnk_multi( 'traatf', pts(:,:,:,jp_tem,Kbb) , 'T', 1.0_wp, pts(:,:,:,jp_sal,Kbb) , 'T', 1.0_wp, &
-                  &                    pts(:,:,:,jp_tem,Kmm) , 'T', 1.0_wp, pts(:,:,:,jp_sal,Kmm) , 'T', 1.0_wp, &
-                  &                    pts(:,:,:,jp_tem,Kaa), 'T', 1.0_wp, pts(:,:,:,jp_sal,Kaa), 'T', 1.0_wp  )
-         !
+         CALL lbc_lnk_multi( 'traatf',  pts(:,:,:,jp_tem,Kmm) , 'T', 1.0_wp, pts(:,:,:,jp_sal,Kmm) , 'T', 1.0_wp ) 
+
       ENDIF     
       !
@@ -210,5 +208,5 @@
       DO jn = 1, kjpt
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             ztn = pt(ji,jj,jk,jn,Kmm)                                    
             ztd = pt(ji,jj,jk,jn,Kaa) - 2._wp * ztn + pt(ji,jj,jk,jn,Kbb)  ! time laplacian on tracers
@@ -275,5 +273,5 @@
       zfact2 = zfact1 * r1_rho0
       DO jn = 1, kjpt      
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             ze3t_b = e3t(ji,jj,jk,Kbb)
             ze3t_n = e3t(ji,jj,jk,Kmm)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traatf_qco.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traatf_qco.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traatf_qco.F90	(revision 14055)
@@ -149,8 +149,6 @@
          ENDIF
          !
-         CALL lbc_lnk_multi( 'traatfqco', pts(:,:,:,jp_tem,Kbb) , 'T', 1., pts(:,:,:,jp_sal,Kbb) , 'T', 1., &
-                  &                    pts(:,:,:,jp_tem,Kmm) , 'T', 1., pts(:,:,:,jp_sal,Kmm) , 'T', 1., &
-                  &                    pts(:,:,:,jp_tem,Kaa), 'T', 1., pts(:,:,:,jp_sal,Kaa), 'T', 1.  )
-         !
+         CALL lbc_lnk_multi( 'traatfqco', pts(:,:,:,jp_tem,Kmm) , 'T', 1., pts(:,:,:,jp_sal,Kmm) , 'T', 1. )
+
       ENDIF
       !
@@ -203,5 +201,5 @@
       DO jn = 1, kjpt
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             ztn = pt(ji,jj,jk,jn,Kmm)
             ztd = pt(ji,jj,jk,jn,Kaa) - 2._wp * ztn + pt(ji,jj,jk,jn,Kbb)  ! time laplacian on tracers
@@ -268,5 +266,5 @@
       zfact2 = zfact1 * r1_rho0
       DO jn = 1, kjpt
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpkm1 )
             ze3t_b = e3t(ji,jj,jk,Kbb)
             ze3t_n = e3t(ji,jj,jk,Kmm)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trabbc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trabbc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trabbc.F90	(revision 14055)
@@ -80,5 +80,5 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts        ! active tracers and RHS of tracer equation
       !
-      INTEGER  ::   ji, jj    ! dummy loop indices
+      INTEGER  ::   ji, jj, jk    ! dummy loop indices
       REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt   ! 3D workspace
       !!----------------------------------------------------------------------
@@ -86,5 +86,5 @@
       IF( ln_timing )   CALL timing_start('tra_bbc')
       !
-      IF( l_trdtra )   THEN         ! Save the input temperature trend
+      IF( l_trdtra ) THEN           ! Save the input temperature trend
          ALLOCATE( ztrdt(jpi,jpj,jpk) )
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
@@ -96,6 +96,4 @@
       END_2D
       !
-      CALL lbc_lnk( 'trabbc', pts(:,:,:,jp_tem,Krhs) , 'T', 1.0_wp )
-      !
       IF( l_trdtra ) THEN        ! Send the trend for diagnostics
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs) - ztrdt(:,:,:)
@@ -104,5 +102,7 @@
       ENDIF
       !
-      CALL iom_put ( "hfgeou" , rho0_rcp * qgh_trd0(:,:) )
+      IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only for the full domain
+         CALL iom_put ( "hfgeou" , rho0_rcp * qgh_trd0(:,:) )
+      ENDIF
       IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' bbc  - Ta: ', mask1=tmask, clinfo3='tra-ta' )
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trabbl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trabbl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trabbl.F90	(revision 14055)
@@ -106,4 +106,5 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts             ! active tracers and RHS of tracer equation
       !
+      INTEGER  ::   ji, jj, jk   ! Dummy loop indices
       REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds
       !!----------------------------------------------------------------------
@@ -112,5 +113,5 @@
       !
       IF( l_trdtra )   THEN                         !* Save the T-S input trends
-         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ALLOCATE( ztrdt(jpi,jpj,jpk), ztrds(jpi,jpj,jpk) )
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
          ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs)
@@ -125,8 +126,8 @@
          CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' bbl_ldf  - Ta: ', mask1=tmask, &
             &          tab3d_2=pts(:,:,:,jp_sal,Krhs), clinfo2=           ' Sa: ', mask2=tmask, clinfo3='tra' )
-         ! lateral boundary conditions ; just need for outputs
-         CALL lbc_lnk_multi( 'trabbl', ahu_bbl, 'U', 1.0_wp , ahv_bbl, 'V', 1.0_wp )
-         CALL iom_put( "ahu_bbl", ahu_bbl )   ! bbl diffusive flux i-coef
-         CALL iom_put( "ahv_bbl", ahv_bbl )   ! bbl diffusive flux j-coef
+         IF( ntile == 0 .OR. ntile == nijtile ) THEN                       ! Do only on the last tile
+            CALL iom_put( "ahu_bbl", ahu_bbl )   ! bbl diffusive flux i-coef
+            CALL iom_put( "ahv_bbl", ahv_bbl )   ! bbl diffusive flux j-coef
+         ENDIF
          !
       ENDIF
@@ -136,10 +137,13 @@
          CALL tra_bbl_adv( pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs), jpts, Kmm )
          IF(sn_cfctl%l_prtctl)   &
-         CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' bbl_adv  - Ta: ', mask1=tmask,   &
+         CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' bbl_adv  - Ta: ', mask1=tmask, &
             &          tab3d_2=pts(:,:,:,jp_sal,Krhs), clinfo2=           ' Sa: ', mask2=tmask, clinfo3='tra' )
-         ! lateral boundary conditions ; just need for outputs
-         CALL lbc_lnk_multi( 'trabbl', utr_bbl, 'U', 1.0_wp , vtr_bbl, 'V', 1.0_wp )
-         CALL iom_put( "uoce_bbl", utr_bbl )  ! bbl i-transport
-         CALL iom_put( "voce_bbl", vtr_bbl )  ! bbl j-transport
+         IF( ntile == 0 .OR. ntile == nijtile ) THEN                       ! Do only on the last tile
+            ! lateral boundary conditions ; just need for outputs
+            ! NOTE: [tiling-comms-merge] The diagnostic results change along the north fold if this is removed
+            CALL lbc_lnk_multi( 'trabbl', utr_bbl, 'U', 1.0_wp , vtr_bbl, 'V', 1.0_wp )
+            CALL iom_put( "uoce_bbl", utr_bbl )  ! bbl i-transport
+            CALL iom_put( "voce_bbl", vtr_bbl )  ! bbl j-transport
+         ENDIF
          !
       ENDIF
@@ -187,5 +191,5 @@
       INTEGER  ::   ik           ! local integers
       REAL(wp) ::   zbtr         ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj) ::   zptb   ! workspace
+      REAL(wp), DIMENSION(A2D(nn_hls)) ::   zptb   ! workspace
       !!----------------------------------------------------------------------
       !
@@ -235,62 +239,63 @@
       INTEGER  ::   iis , iid , ijs , ijd    ! local integers
       INTEGER  ::   ikus, ikud, ikvs, ikvd   !   -       -
+      INTEGER  ::   isi, isj                 !   -       -
       REAL(wp) ::   zbtr, ztra               ! local scalars
       REAL(wp) ::   zu_bbl, zv_bbl           !   -      -
       !!----------------------------------------------------------------------
       !
+      IF( ntsi == Nis0 ) THEN ; isi = 1 ; ELSE ; isi = 0 ; ENDIF    ! Avoid double-counting when using tiling
+      IF( ntsj == Njs0 ) THEN ; isj = 1 ; ELSE ; isj = 0 ; ENDIF
       !                                                          ! ===========
       DO jn = 1, kjpt                                            ! tracer loop
          !                                                       ! ===========
-         DO jj = 1, jpjm1
-            DO ji = 1, jpim1            ! CAUTION start from i=1 to update i=2 when cyclic east-west
-               IF( utr_bbl(ji,jj) /= 0.e0 ) THEN            ! non-zero i-direction bbl advection
-                  ! down-slope i/k-indices (deep)      &   up-slope i/k indices (shelf)
-                  iid  = ji + MAX( 0, mgrhu(ji,jj) )   ;   iis  = ji + 1 - MAX( 0, mgrhu(ji,jj) )
-                  ikud = mbku_d(ji,jj)                 ;   ikus = mbku(ji,jj)
-                  zu_bbl = ABS( utr_bbl(ji,jj) )
-                  !
-                  !                                               ! up  -slope T-point (shelf bottom point)
-                  zbtr = r1_e1e2t(iis,jj) / e3t(iis,jj,ikus,Kmm)
-                  ztra = zu_bbl * ( pt(iid,jj,ikus,jn) - pt(iis,jj,ikus,jn) ) * zbtr
-                  pt_rhs(iis,jj,ikus,jn) = pt_rhs(iis,jj,ikus,jn) + ztra
-                  !
-                  DO jk = ikus, ikud-1                            ! down-slope upper to down T-point (deep column)
-                     zbtr = r1_e1e2t(iid,jj) / e3t(iid,jj,jk,Kmm)
-                     ztra = zu_bbl * ( pt(iid,jj,jk+1,jn) - pt(iid,jj,jk,jn) ) * zbtr
-                     pt_rhs(iid,jj,jk,jn) = pt_rhs(iid,jj,jk,jn) + ztra
-                  END DO
-                  !
-                  zbtr = r1_e1e2t(iid,jj) / e3t(iid,jj,ikud,Kmm)
-                  ztra = zu_bbl * ( pt(iis,jj,ikus,jn) - pt(iid,jj,ikud,jn) ) * zbtr
-                  pt_rhs(iid,jj,ikud,jn) = pt_rhs(iid,jj,ikud,jn) + ztra
-               ENDIF
-               !
-               IF( vtr_bbl(ji,jj) /= 0.e0 ) THEN            ! non-zero j-direction bbl advection
-                  ! down-slope j/k-indices (deep)        &   up-slope j/k indices (shelf)
-                  ijd  = jj + MAX( 0, mgrhv(ji,jj) )     ;   ijs  = jj + 1 - MAX( 0, mgrhv(ji,jj) )
-                  ikvd = mbkv_d(ji,jj)                   ;   ikvs = mbkv(ji,jj)
-                  zv_bbl = ABS( vtr_bbl(ji,jj) )
-                  !
-                  ! up  -slope T-point (shelf bottom point)
-                  zbtr = r1_e1e2t(ji,ijs) / e3t(ji,ijs,ikvs,Kmm)
-                  ztra = zv_bbl * ( pt(ji,ijd,ikvs,jn) - pt(ji,ijs,ikvs,jn) ) * zbtr
-                  pt_rhs(ji,ijs,ikvs,jn) = pt_rhs(ji,ijs,ikvs,jn) + ztra
-                  !
-                  DO jk = ikvs, ikvd-1                            ! down-slope upper to down T-point (deep column)
-                     zbtr = r1_e1e2t(ji,ijd) / e3t(ji,ijd,jk,Kmm)
-                     ztra = zv_bbl * ( pt(ji,ijd,jk+1,jn) - pt(ji,ijd,jk,jn) ) * zbtr
-                     pt_rhs(ji,ijd,jk,jn) = pt_rhs(ji,ijd,jk,jn)  + ztra
-                  END DO
-                  !                                               ! down-slope T-point (deep bottom point)
-                  zbtr = r1_e1e2t(ji,ijd) / e3t(ji,ijd,ikvd,Kmm)
-                  ztra = zv_bbl * ( pt(ji,ijs,ikvs,jn) - pt(ji,ijd,ikvd,jn) ) * zbtr
-                  pt_rhs(ji,ijd,ikvd,jn) = pt_rhs(ji,ijd,ikvd,jn) + ztra
-               ENDIF
-            END DO
+         ! NOTE: [tiling-comms-merge] Bug fix- correct order of indices
+         DO_2D( isj, 0, isi, 0 )            ! CAUTION start from i=1 to update i=2 when cyclic east-west
+            IF( utr_bbl(ji,jj) /= 0.e0 ) THEN            ! non-zero i-direction bbl advection
+               ! down-slope i/k-indices (deep)      &   up-slope i/k indices (shelf)
+               iid  = ji + MAX( 0, mgrhu(ji,jj) )   ;   iis  = ji + 1 - MAX( 0, mgrhu(ji,jj) )
+               ikud = mbku_d(ji,jj)                 ;   ikus = mbku(ji,jj)
+               zu_bbl = ABS( utr_bbl(ji,jj) )
+               !
+               !                                               ! up  -slope T-point (shelf bottom point)
+               zbtr = r1_e1e2t(iis,jj) / e3t(iis,jj,ikus,Kmm)
+               ztra = zu_bbl * ( pt(iid,jj,ikus,jn) - pt(iis,jj,ikus,jn) ) * zbtr
+               pt_rhs(iis,jj,ikus,jn) = pt_rhs(iis,jj,ikus,jn) + ztra
+               !
+               DO jk = ikus, ikud-1                            ! down-slope upper to down T-point (deep column)
+                  zbtr = r1_e1e2t(iid,jj) / e3t(iid,jj,jk,Kmm)
+                  ztra = zu_bbl * ( pt(iid,jj,jk+1,jn) - pt(iid,jj,jk,jn) ) * zbtr
+                  pt_rhs(iid,jj,jk,jn) = pt_rhs(iid,jj,jk,jn) + ztra
+               END DO
+               !
+               zbtr = r1_e1e2t(iid,jj) / e3t(iid,jj,ikud,Kmm)
+               ztra = zu_bbl * ( pt(iis,jj,ikus,jn) - pt(iid,jj,ikud,jn) ) * zbtr
+               pt_rhs(iid,jj,ikud,jn) = pt_rhs(iid,jj,ikud,jn) + ztra
+            ENDIF
             !
-         END DO
-         !                                                  ! ===========
-      END DO                                                ! end tracer
-      !                                                     ! ===========
+            IF( vtr_bbl(ji,jj) /= 0.e0 ) THEN            ! non-zero j-direction bbl advection
+               ! down-slope j/k-indices (deep)        &   up-slope j/k indices (shelf)
+               ijd  = jj + MAX( 0, mgrhv(ji,jj) )     ;   ijs  = jj + 1 - MAX( 0, mgrhv(ji,jj) )
+               ikvd = mbkv_d(ji,jj)                   ;   ikvs = mbkv(ji,jj)
+               zv_bbl = ABS( vtr_bbl(ji,jj) )
+               !
+               ! up  -slope T-point (shelf bottom point)
+               zbtr = r1_e1e2t(ji,ijs) / e3t(ji,ijs,ikvs,Kmm)
+               ztra = zv_bbl * ( pt(ji,ijd,ikvs,jn) - pt(ji,ijs,ikvs,jn) ) * zbtr
+               pt_rhs(ji,ijs,ikvs,jn) = pt_rhs(ji,ijs,ikvs,jn) + ztra
+               !
+               DO jk = ikvs, ikvd-1                            ! down-slope upper to down T-point (deep column)
+                  zbtr = r1_e1e2t(ji,ijd) / e3t(ji,ijd,jk,Kmm)
+                  ztra = zv_bbl * ( pt(ji,ijd,jk+1,jn) - pt(ji,ijd,jk,jn) ) * zbtr
+                  pt_rhs(ji,ijd,jk,jn) = pt_rhs(ji,ijd,jk,jn)  + ztra
+               END DO
+               !                                               ! down-slope T-point (deep bottom point)
+               zbtr = r1_e1e2t(ji,ijd) / e3t(ji,ijd,ikvd,Kmm)
+               ztra = zv_bbl * ( pt(ji,ijs,ikvs,jn) - pt(ji,ijd,ikvd,jn) ) * zbtr
+               pt_rhs(ji,ijd,ikvd,jn) = pt_rhs(ji,ijd,ikvd,jn) + ztra
+            ENDIF
+         END_2D
+         !                                                       ! ===========
+      END DO                                                     ! end tracer
+      !                                                          ! ===========
    END SUBROUTINE tra_bbl_adv
 
@@ -333,12 +338,14 @@
       REAL(wp) ::   za, zb, zgdrho            ! local scalars
       REAL(wp) ::   zsign, zsigna, zgbbl      !   -      -
-      REAL(wp), DIMENSION(jpi,jpj,jpts)   :: zts, zab         ! 3D workspace
-      REAL(wp), DIMENSION(jpi,jpj)        :: zub, zvb, zdep   ! 2D workspace
-      !!----------------------------------------------------------------------
-      !
-      IF( kt == kit000 )  THEN
-         IF(lwp)  WRITE(numout,*)
-         IF(lwp)  WRITE(numout,*) 'trabbl:bbl : Compute bbl velocities and diffusive coefficients in ', cdtype
-         IF(lwp)  WRITE(numout,*) '~~~~~~~~~~'
+      REAL(wp), DIMENSION(A2D(nn_hls),jpts)   :: zts, zab         ! 3D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls))        :: zub, zvb, zdep   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 )  THEN
+            IF(lwp)  WRITE(numout,*)
+            IF(lwp)  WRITE(numout,*) 'trabbl:bbl : Compute bbl velocities and diffusive coefficients in ', cdtype
+            IF(lwp)  WRITE(numout,*) '~~~~~~~~~~'
+         ENDIF
       ENDIF
       !                                        !* bottom variables (T, S, alpha, beta, depth, velocity)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tradmp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tradmp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tradmp.F90	(revision 14055)
@@ -95,5 +95,5 @@
       !
       INTEGER ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts)     ::  zts_dta
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk,jpts)     ::  zts_dta
       REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE ::  ztrdts
       !!----------------------------------------------------------------------
@@ -102,6 +102,6 @@
       !
       IF( l_trdtra )   THEN                    !* Save ta and sa trends
-         ALLOCATE( ztrdts(jpi,jpj,jpk,jpts) ) 
-         ztrdts(:,:,:,:) = pts(:,:,:,:,Krhs) 
+         ALLOCATE( ztrdts(jpi,jpj,jpk,jpts) )
+         ztrdts(:,:,:,:) = pts(:,:,:,:,Krhs)
       ENDIF
       !                           !==  input T-S data at kt  ==!
@@ -144,5 +144,5 @@
          CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_dmp, ztrdts(:,:,:,jp_tem) )
          CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_dmp, ztrdts(:,:,:,jp_sal) )
-         DEALLOCATE( ztrdts ) 
+         DEALLOCATE( ztrdts )
       ENDIF
       !                           ! Control print
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traisf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traisf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traisf.F90	(revision 14055)
@@ -11,4 +11,5 @@
    !!----------------------------------------------------------------------
    USE isf_oce                                     ! Ice shelf variables
+   USE par_oce , ONLY : nijtile, ntile, ntsi, ntei, ntsj, ntej
    USE dom_oce                                     ! ocean space domain variables
    USE isfutils, ONLY : debug                      ! debug option
@@ -46,8 +47,10 @@
       IF( ln_timing )   CALL timing_start('tra_isf')
       !
-      IF( kt == nit000 ) THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_isf : Ice shelf heat fluxes'
-         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == nit000 ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_isf : Ice shelf heat fluxes'
+            IF(lwp) WRITE(numout,*) '~~~~~~~ '
+         ENDIF
       ENDIF
       !
@@ -76,6 +79,8 @@
       !
       IF ( ln_isfdebug ) THEN
-         CALL debug('tra_isf: pts(:,:,:,:,Krhs) T', pts(:,:,:,1,Krhs))
-         CALL debug('tra_isf: pts(:,:,:,:,Krhs) S', pts(:,:,:,2,Krhs))
+         IF( ntile == 0 .OR. ntile == nijtile ) THEN                       ! Do only for the full domain
+            CALL debug('tra_isf: pts(:,:,:,:,Krhs) T', pts(:,:,:,1,Krhs))
+            CALL debug('tra_isf: pts(:,:,:,:,Krhs) S', pts(:,:,:,2,Krhs))
+         ENDIF
       END IF
       !
@@ -101,12 +106,14 @@
       INTEGER                      :: ji,jj,jk  ! loop index   
       INTEGER                      :: ikt, ikb  ! top and bottom level of the tbl
-      REAL(wp), DIMENSION(jpi,jpj) :: ztc       ! total ice shelf tracer trend
+      REAL(wp), DIMENSION(A2D(nn_hls))     :: ztc       ! total ice shelf tracer trend
       !!----------------------------------------------------------------------
       !
       ! compute 2d total trend due to isf
-      ztc(:,:) = 0.5_wp * ( ptsc(:,:,jp_tem) + ptsc_b(:,:,jp_tem) ) / phtbl(:,:)
+      DO_2D( 0, 0, 0, 0 )
+         ztc(ji,jj) = 0.5_wp * ( ptsc(ji,jj,jp_tem) + ptsc_b(ji,jj,jp_tem) ) / phtbl(ji,jj)
+      END_2D
       !
       ! update pts(:,:,:,:,Krhs)
-      DO_2D( 1, 1, 1, 1 )
+      DO_2D( 0, 0, 0, 0 )
          !
          ikt = ktop(ji,jj)
@@ -137,13 +144,11 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) :: ptsc
       !!----------------------------------------------------------------------
-      INTEGER :: jk
+      INTEGER :: ji, jj, jk
       !!----------------------------------------------------------------------
       !
-      DO jk = 1,jpk
-         ptsa(:,:,jk,jp_tem) =   &
-            &  ptsa(:,:,jk,jp_tem) + ptsc(:,:,jk,jp_tem) * r1_e1e2t(:,:) / e3t(:,:,jk,Kmm)
-         ptsa(:,:,jk,jp_sal) =   &
-            &  ptsa(:,:,jk,jp_sal) + ptsc(:,:,jk,jp_sal) * r1_e1e2t(:,:) / e3t(:,:,jk,Kmm)
-      END DO
+      DO_3D( 0, 0, 0, 0, 1, jpk )
+         ptsa(ji,jj,jk,jp_tem) = ptsa(ji,jj,jk,jp_tem) + ptsc(ji,jj,jk,jp_tem) * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
+         ptsa(ji,jj,jk,jp_sal) = ptsa(ji,jj,jk,jp_sal) + ptsc(ji,jj,jk,jp_sal) * r1_e1e2t(ji,jj) / e3t(ji,jj,jk,Kmm)
+      END_3D
       !
    END SUBROUTINE tra_isf_cpl
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf.F90	(revision 14055)
@@ -17,4 +17,6 @@
    USE oce            ! ocean dynamics and tracers
    USE dom_oce        ! ocean space and time domain
+   ! TEMP: [tiling] This change not necessary after extra haloes development (lbc_lnk removed from tra_ldf_blp, zps_hde*)
+   USE domain, ONLY : dom_tile
    USE phycst         ! physical constants
    USE ldftra         ! lateral diffusion: eddy diffusivity & EIV coeff.
@@ -37,5 +39,5 @@
    PUBLIC   tra_ldf        ! called by step.F90 
    PUBLIC   tra_ldf_init   ! called by nemogcm.F90 
-   
+
    !!----------------------------------------------------------------------
    !! NEMO/OCE 4.0 , NEMO Consortium (2018)
@@ -56,34 +58,56 @@
       !!
       REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds
+      ! TEMP: [tiling] This change not necessary after extra haloes development (lbc_lnk removed from tra_ldf_blp, zps_hde*)
+      LOGICAL :: lskip
       !!----------------------------------------------------------------------
       !
       IF( ln_timing )   CALL timing_start('tra_ldf')
       !
+      lskip = .FALSE.
+
       IF( l_trdtra )   THEN                    !* Save ta and sa trends
-         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) ) 
-         ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs) 
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
          ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs)
       ENDIF
-      !
-      SELECT CASE ( nldf_tra )                 !* compute lateral mixing trend and add it to the general trend
-      CASE ( np_lap   )                                  ! laplacian: iso-level operator
-         CALL tra_ldf_lap  ( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs),                   jpts,  1 )
-      CASE ( np_lap_i )                                  ! laplacian: standard iso-neutral operator (Madec)
-         CALL tra_ldf_iso  ( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs), jpts,  1 )
-      CASE ( np_lap_it )                                 ! laplacian: triad iso-neutral operator (griffies)
-         CALL tra_ldf_triad( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs), jpts,  1 )
-      CASE ( np_blp , np_blp_i , np_blp_it )             ! bilaplacian: iso-level & iso-neutral operators
-         CALL tra_ldf_blp  ( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs),             jpts, nldf_tra )
-      END SELECT
-      !
-      IF( l_trdtra )   THEN                    !* save the horizontal diffusive trends for further diagnostics
-         ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs) - ztrdt(:,:,:)
-         ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs) - ztrds(:,:,:)
-         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_ldf, ztrdt )
-         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_ldf, ztrds )
-         DEALLOCATE( ztrdt, ztrds ) 
+
+      ! TEMP: [tiling] These changes not necessary after extra haloes development (lbc_lnk removed from tra_ldf_blp, zps_hde*)
+      IF( nldf_tra == np_blp .OR. nldf_tra == np_blp_i .OR. nldf_tra == np_blp_it )  THEN
+         IF( ln_tile ) THEN
+            IF( ntile == 1 ) THEN
+               CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )
+            ELSE
+               lskip = .TRUE.
+            ENDIF
+         ENDIF
+      ENDIF
+      IF( .NOT. lskip ) THEN
+         !
+         SELECT CASE ( nldf_tra )                 !* compute lateral mixing trend and add it to the general trend
+         CASE ( np_lap   )                                  ! laplacian: iso-level operator
+            CALL tra_ldf_lap  ( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs),                   jpts,  1 )
+         CASE ( np_lap_i )                                  ! laplacian: standard iso-neutral operator (Madec)
+            CALL tra_ldf_iso  ( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs), jpts,  1 )
+         CASE ( np_lap_it )                                 ! laplacian: triad iso-neutral operator (griffies)
+            CALL tra_ldf_triad( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs), jpts,  1 )
+         CASE ( np_blp , np_blp_i , np_blp_it )             ! bilaplacian: iso-level & iso-neutral operators
+            ! NOTE: [tiling-comms-merge] This lbc_lnk is still needed in the zco case, because zps_hde is not called in step
+            IF(nn_hls.EQ.2) CALL lbc_lnk( 'tra_ldf', pts(:,:,:,:,Kbb), 'T',1.)
+            CALL tra_ldf_blp  ( kt, Kmm, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, pts(:,:,:,:,Kbb), pts(:,:,:,:,Krhs),             jpts, nldf_tra )
+         END SELECT
+         !
+         IF( l_trdtra )   THEN                    !* save the horizontal diffusive trends for further diagnostics
+            ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs) - ztrdt(:,:,:)
+            ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs) - ztrds(:,:,:)
+            CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_ldf, ztrdt )
+            CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_ldf, ztrds )
+            DEALLOCATE( ztrdt, ztrds )
+         ENDIF
+
+         ! TEMP: [tiling] This change not necessary after extra haloes development (lbc_lnk removed from tra_ldf_blp, zps_hde*)
+         IF( ln_tile .AND. ntile == 0 ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 1 )
       ENDIF
       !                                        !* print mean trends (used for debugging)
-      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' ldf  - Ta: ', mask1=tmask,               &
+      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab3d_1=pts(:,:,:,jp_tem,Krhs), clinfo1=' ldf  - Ta: ', mask1=tmask, &
          &                                  tab3d_2=pts(:,:,:,jp_sal,Krhs), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_iso.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_iso.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_iso.F90	(revision 14055)
@@ -19,4 +19,5 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
+   USE domutl, ONLY : is_tile
    USE trc_oce        ! share passive tracers/Ocean variables
    USE zdf_oce        ! ocean vertical physics
@@ -49,7 +50,30 @@
 CONTAINS
 
-  SUBROUTINE tra_ldf_iso( kt, Kmm, kit000, cdtype, pahu, pahv,                    &
-      &                                            pgu , pgv    ,   pgui, pgvi,   &
-      &                                       pt , pt2 , pt_rhs , kjpt  , kpass )
+   SUBROUTINE tra_ldf_iso( kt, Kmm, kit000, cdtype, pahu, pahv,             &
+      &                                             pgu , pgv , pgui, pgvi, &
+      &                                             pt, pt2, pt_rhs, kjpt, kpass )
+      !!
+      INTEGER                     , INTENT(in   ) ::   kt         ! ocean time-step index
+      INTEGER                     , INTENT(in   ) ::   kit000     ! first time step index
+      CHARACTER(len=3)            , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      INTEGER                     , INTENT(in   ) ::   kjpt       ! number of tracers
+      INTEGER                     , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      INTEGER                     , INTENT(in   ) ::   Kmm        ! ocean time level index
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pt         ! tracer (kpass=1) or laplacian of tracer (kpass=2)
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pt2        ! tracer (only used in kpass=2)
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pt_rhs     ! tracer trend
+      !!
+      CALL tra_ldf_iso_t( kt, Kmm, kit000, cdtype, pahu, pahv, is_tile(pahu),                             &
+         &                                         pgu , pgv , is_tile(pgu) , pgui, pgvi, is_tile(pgui),  &
+         &                                         pt, is_tile(pt), pt2, is_tile(pt2), pt_rhs, is_tile(pt_rhs), kjpt, kpass )
+   END SUBROUTINE tra_ldf_iso
+
+
+  SUBROUTINE tra_ldf_iso_t( kt, Kmm, kit000, cdtype, pahu, pahv, ktah,                    &
+      &                                              pgu , pgv , ktg , pgui, pgvi, ktgi,  &
+      &                                              pt, ktt, pt2, ktt2, pt_rhs, ktt_rhs, kjpt, kpass )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE tra_ldf_iso  ***
@@ -92,16 +116,17 @@
       !! ** Action :   Update pt_rhs arrays with the before rotated diffusion
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   ) ::   kt         ! ocean time-step index
-      INTEGER                              , INTENT(in   ) ::   kit000     ! first time step index
-      CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
-      INTEGER                              , INTENT(in   ) ::   kjpt       ! number of tracers
-      INTEGER                              , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
-      INTEGER                              , INTENT(in   ) ::   Kmm        ! ocean time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
-      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   pt         ! tracer (kpass=1) or laplacian of tracer (kpass=2)
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   pt2        ! tracer (only used in kpass=2)
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pt_rhs     ! tracer trend
+      INTEGER                                   , INTENT(in   ) ::   kt         ! ocean time-step index
+      INTEGER                                   , INTENT(in   ) ::   kit000     ! first time step index
+      CHARACTER(len=3)                          , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      INTEGER                                   , INTENT(in   ) ::   kjpt       ! number of tracers
+      INTEGER                                   , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      INTEGER                                   , INTENT(in   ) ::   Kmm        ! ocean time level index
+      INTEGER                                   , INTENT(in   ) ::   ktah, ktg, ktgi, ktt, ktt2, ktt_rhs
+      REAL(wp), DIMENSION(A2D_T(ktah)   ,JPK)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      REAL(wp), DIMENSION(A2D_T(ktg)        ,KJPT), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(A2D_T(ktgi)       ,KJPT), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
+      REAL(wp), DIMENSION(A2D_T(ktt)    ,JPK,KJPT), INTENT(in   ) ::   pt         ! tracer (kpass=1) or laplacian of tracer (kpass=2)
+      REAL(wp), DIMENSION(A2D_T(ktt2)   ,JPK,KJPT), INTENT(in   ) ::   pt2        ! tracer (only used in kpass=2)
+      REAL(wp), DIMENSION(A2D_T(ktt_rhs),JPK,KJPT), INTENT(inout) ::   pt_rhs     ! tracer trend
       !
       INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
@@ -111,22 +136,28 @@
       REAL(wp) ::  zmskv, zahv_w, zabe2, zcof2, zcoef4   !   -      -
       REAL(wp) ::  zcoef0, ze3w_2, zsign                 !   -      -
-      REAL(wp), DIMENSION(jpi,jpj)     ::   zdkt, zdk1t, z2d
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdit, zdjt, zftu, zftv, ztfw 
+      REAL(wp), DIMENSION(A2D(nn_hls))     ::   zdkt, zdk1t, z2d
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zdit, zdjt, zftu, zftv, ztfw
       !!----------------------------------------------------------------------
       !
       IF( kpass == 1 .AND. kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_ldf_iso : rotated laplacian diffusion operator on ', cdtype
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
-         !
-         akz     (:,:,:) = 0._wp      
-         ah_wslp2(:,:,:) = 0._wp
+         IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_ldf_iso : rotated laplacian diffusion operator on ', cdtype
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+         ENDIF
+         !
+         DO_3D( 0, 0, 0, 0, 1, jpk )
+            akz     (ji,jj,jk) = 0._wp
+            ah_wslp2(ji,jj,jk) = 0._wp
+         END_3D
       ENDIF
-      !   
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      IF( cdtype == 'TRA' .AND. ( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) )     l_ptr = .TRUE. 
-      IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
-         &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )   l_hst = .TRUE.
+      !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                           ! Do only on the first tile
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         IF( cdtype == 'TRA' .AND. ( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) )     l_ptr = .TRUE.
+         IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+            &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )   l_hst = .TRUE.
+      ENDIF
       !
       !
@@ -167,5 +198,5 @@
             !
             IF( ln_traldf_blp ) THEN                ! bilaplacian operator
-               DO_3D( 1, 0, 1, 0, 2, jpkm1 )
+               DO_3D( 0, 0, 0, 0, 2, jpkm1 )
                   akz(ji,jj,jk) = 16._wp   &
                      &   * ah_wslp2   (ji,jj,jk)   &
@@ -175,5 +206,5 @@
                END_3D
             ELSEIF( ln_traldf_lap ) THEN              ! laplacian operator
-               DO_3D( 1, 0, 1, 0, 2, jpkm1 )
+               DO_3D( 0, 0, 0, 0, 2, jpkm1 )
                   ze3w_2 = e3w(ji,jj,jk,Kmm) * e3w(ji,jj,jk,Kmm)
                   zcoef0 = rDt * (  akz(ji,jj,jk) + ah_wslp2(ji,jj,jk) / ze3w_2  )
@@ -183,5 +214,7 @@
            !
          ELSE                                    ! 33 flux set to zero with akz=ah_wslp2 ==>> computed in full implicit
-            akz(:,:,:) = ah_wslp2(:,:,:)      
+            DO_3D( 0, 0, 0, 0, 1, jpk )
+               akz(ji,jj,jk) = ah_wslp2(ji,jj,jk)
+            END_3D
          ENDIF
       ENDIF
@@ -195,6 +228,6 @@
          !!----------------------------------------------------------------------
 !!gm : bug.... why (x,:,:)?   (1,jpj,:) and (jpi,1,:) should be sufficient....
-         zdit (1,:,:) = 0._wp     ;     zdit (jpi,:,:) = 0._wp
-         zdjt (1,:,:) = 0._wp     ;     zdjt (jpi,:,:) = 0._wp
+         zdit (ntsi-nn_hls,:,:) = 0._wp     ;     zdit (ntei+nn_hls,:,:) = 0._wp
+         zdjt (ntsi-nn_hls,:,:) = 0._wp     ;     zdjt (ntei+nn_hls,:,:) = 0._wp
          !!end
 
@@ -223,10 +256,13 @@
          DO jk = 1, jpkm1                                 ! Horizontal slab
             !
-            !                             !== Vertical tracer gradient
-            zdk1t(:,:) = ( pt(:,:,jk,jn) - pt(:,:,jk+1,jn) ) * wmask(:,:,jk+1)     ! level jk+1
-            !
-            IF( jk == 1 ) THEN   ;   zdkt(:,:) = zdk1t(:,:)                          ! surface: zdkt(jk=1)=zdkt(jk=2)
-            ELSE                 ;   zdkt(:,:) = ( pt(:,:,jk-1,jn) - pt(:,:,jk,jn) ) * wmask(:,:,jk)
-            ENDIF
+            DO_2D( 1, 1, 1, 1 )
+               !                             !== Vertical tracer gradient
+               zdk1t(ji,jj) = ( pt(ji,jj,jk,jn) - pt(ji,jj,jk+1,jn) ) * wmask(ji,jj,jk+1)     ! level jk+1
+               !
+               IF( jk == 1 ) THEN   ;   zdkt(ji,jj) = zdk1t(ji,jj)                            ! surface: zdkt(jk=1)=zdkt(jk=2)
+               ELSE                 ;   zdkt(ji,jj) = ( pt(ji,jj,jk-1,jn) - pt(ji,jj,jk,jn) ) * wmask(ji,jj,jk)
+               ENDIF
+            END_2D
+            !
             DO_2D( 1, 0, 1, 0 )           !==  Horizontal fluxes
                zabe1 = pahu(ji,jj,jk) * e2_e1u(ji,jj) * e3u(ji,jj,jk,Kmm)
@@ -330,5 +366,5 @@
       END DO                                                      ! end tracer loop
       !
-   END SUBROUTINE tra_ldf_iso
+   END SUBROUTINE tra_ldf_iso_t
 
    !!==============================================================================
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_lap_blp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_lap_blp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_lap_blp.F90	(revision 14055)
@@ -13,4 +13,5 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
+   USE domutl, ONLY : is_tile
    USE ldftra         ! lateral physics: eddy diffusivity
    USE traldf_iso     ! iso-neutral lateral diffusion (standard operator)     (tra_ldf_iso   routine)
@@ -46,7 +47,29 @@
 CONTAINS
 
-   SUBROUTINE tra_ldf_lap( kt, Kmm, kit000, cdtype, pahu, pahv  ,               &
-      &                                             pgu , pgv   , pgui, pgvi,   &
-      &                                             pt  , pt_rhs, kjpt, kpass ) 
+   SUBROUTINE tra_ldf_lap( kt, Kmm, kit000, cdtype, pahu, pahv,             &
+      &                                             pgu , pgv , pgui, pgvi, &
+      &                                             pt, pt_rhs, kjpt, kpass )
+      !!
+      INTEGER                     , INTENT(in   ) ::   kt         ! ocean time-step index
+      INTEGER                     , INTENT(in   ) ::   kit000     ! first time step index
+      CHARACTER(len=3)            , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      INTEGER                     , INTENT(in   ) ::   kjpt       ! number of tracers
+      INTEGER                     , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      INTEGER                     , INTENT(in   ) ::   Kmm        ! ocean time level index
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pt         ! before tracer fields
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pt_rhs     ! tracer trend
+      !!
+      CALL tra_ldf_lap_t( kt, Kmm, kit000, cdtype, pahu, pahv, is_tile(pahu),                            &
+      &                                            pgu , pgv , is_tile(pgu) , pgui, pgvi, is_tile(pgui), &
+      &                                            pt, is_tile(pt), pt_rhs, is_tile(pt_rhs), kjpt, kpass )
+   END SUBROUTINE tra_ldf_lap
+
+
+   SUBROUTINE tra_ldf_lap_t( kt, Kmm, kit000, cdtype, pahu, pahv, ktah,                   &
+      &                                               pgu , pgv , ktg , pgui, pgvi, ktgi, &
+      &                                               pt, ktt, pt_rhs, ktt_rhs, kjpt, kpass )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE tra_ldf_lap  ***
@@ -72,26 +95,30 @@
       INTEGER                              , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
       INTEGER                              , INTENT(in   ) ::   Kmm        ! ocean time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
-      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   pt         ! before tracer fields
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pt_rhs     ! tracer trend 
-      !
-      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp) ::   zsign            ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ztu, ztv, zaheeu, zaheev
-      !!----------------------------------------------------------------------
-      !
-      IF( kt == nit000 .AND. lwp )  THEN
-         WRITE(numout,*)
-         WRITE(numout,*) 'tra_ldf_lap : iso-level laplacian diffusion on ', cdtype, ', pass=', kpass
-         WRITE(numout,*) '~~~~~~~~~~~ '
-      ENDIF
-      !
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      IF( cdtype == 'TRA' .AND. ( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) )     l_ptr = .TRUE.
-      IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
-         &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
+      INTEGER                              , INTENT(in   ) ::   ktah, ktg, ktgi, ktt, ktt_rhs
+      REAL(wp), DIMENSION(A2D_T(ktah),   JPK)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      REAL(wp), DIMENSION(A2D_T(ktg),        KJPT), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(A2D_T(ktgi),       KJPT), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
+      REAL(wp), DIMENSION(A2D_T(ktt),    JPK,KJPT), INTENT(in   ) ::   pt         ! before tracer fields
+      REAL(wp), DIMENSION(A2D_T(ktt_rhs),JPK,KJPT), INTENT(inout) ::   pt_rhs     ! tracer trend
+      !
+      INTEGER  ::   ji, jj, jk, jn      ! dummy loop indices
+      INTEGER  ::   isi, iei, isj, iej  ! local integers
+      REAL(wp) ::   zsign               ! local scalars
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   ztu, ztv, zaheeu, zaheev
+      !!----------------------------------------------------------------------
+      !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == nit000 .AND. lwp )  THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'tra_ldf_lap : iso-level laplacian diffusion on ', cdtype, ', pass=', kpass
+            WRITE(numout,*) '~~~~~~~~~~~ '
+         ENDIF
+         !
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         IF( cdtype == 'TRA' .AND. ( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) )     l_ptr = .TRUE.
+         IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+            &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
+      ENDIF
       !
       !                                !==  Initialization of metric arrays used for all tracers  ==!
@@ -99,5 +126,11 @@
       ELSE                    ;   zsign = -1._wp
       ENDIF
-      DO_3D( 1, 0, 1, 0, 1, jpkm1 )
+
+      IF( ntsi == Nis0 ) THEN ; isi = nn_hls - 1 ; ELSE ; isi = 0 ; ENDIF    ! Avoid double-counting when using tiling
+      IF( ntsj == Njs0 ) THEN ; isj = nn_hls - 1 ; ELSE ; isj = 0 ; ENDIF
+      IF( ntei == Nie0 ) THEN ; iei = nn_hls - 1 ; ELSE ; iei = 0 ; ENDIF
+      IF( ntej == Nje0 ) THEN ; iej = nn_hls - 1 ; ELSE ; iej = 0 ; ENDIF
+
+      DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )            !== First derivative (gradient)  ==!
          zaheeu(ji,jj,jk) = zsign * pahu(ji,jj,jk) * e2_e1u(ji,jj) * e3u(ji,jj,jk,Kmm)   !!gm   * umask(ji,jj,jk) pah masked!
          zaheev(ji,jj,jk) = zsign * pahv(ji,jj,jk) * e1_e2v(ji,jj) * e3v(ji,jj,jk,Kmm)   !!gm   * vmask(ji,jj,jk)
@@ -108,15 +141,15 @@
          !                          ! =========== !    
          !                               
-         DO_3D( 1, 0, 1, 0, 1, jpkm1 )            !== First derivative (gradient)  ==!
+         DO_3D( nn_hls, nn_hls-1, nn_hls, nn_hls-1, 1, jpkm1 )            !== First derivative (gradient)  ==!
             ztu(ji,jj,jk) = zaheeu(ji,jj,jk) * ( pt(ji+1,jj  ,jk,jn) - pt(ji,jj,jk,jn) )
             ztv(ji,jj,jk) = zaheev(ji,jj,jk) * ( pt(ji  ,jj+1,jk,jn) - pt(ji,jj,jk,jn) )
          END_3D
          IF( ln_zps ) THEN                             ! set gradient at bottom/top ocean level
-            DO_2D( 1, 0, 1, 0 )                              ! bottom
+            DO_2D( nn_hls, nn_hls-1, nn_hls, nn_hls-1 )                              ! bottom
                ztu(ji,jj,mbku(ji,jj)) = zaheeu(ji,jj,mbku(ji,jj)) * pgu(ji,jj,jn)
                ztv(ji,jj,mbkv(ji,jj)) = zaheev(ji,jj,mbkv(ji,jj)) * pgv(ji,jj,jn)
             END_2D
             IF( ln_isfcav ) THEN                             ! top in ocean cavities only
-               DO_2D( 1, 0, 1, 0 )
+               DO_2D( nn_hls, nn_hls-1, nn_hls, nn_hls-1 )
                   IF( miku(ji,jj) > 1 )   ztu(ji,jj,miku(ji,jj)) = zaheeu(ji,jj,miku(ji,jj)) * pgui(ji,jj,jn) 
                   IF( mikv(ji,jj) > 1 )   ztv(ji,jj,mikv(ji,jj)) = zaheev(ji,jj,mikv(ji,jj)) * pgvi(ji,jj,jn) 
@@ -125,5 +158,6 @@
          ENDIF
          !
-         DO_3D( 0, 0, 0, 0, 1, jpkm1 )            !== Second derivative (divergence) added to the general tracer trends  ==!
+         ! NOTE: [tiling-comms-merge] Bounds changed to avoid repeating this calculation for overlapping rows when using tiling
+         DO_3D( isj, iej, isi, iei, 1, jpkm1 )            !== Second derivative (divergence) added to the general tracer trends  ==!
             pt_rhs(ji,jj,jk,jn) = pt_rhs(ji,jj,jk,jn) + (  ztu(ji,jj,jk) - ztu(ji-1,jj,jk)     &
                &                                      +    ztv(ji,jj,jk) - ztv(ji,jj-1,jk) )   &
@@ -142,5 +176,5 @@
       !                             ! ==================
       !
-   END SUBROUTINE tra_ldf_lap
+   END SUBROUTINE tra_ldf_lap_t
    
 
@@ -173,17 +207,19 @@
       !
       INTEGER ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt) :: zlap         ! laplacian at t-point
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt) :: zglu, zglv   ! bottom GRADh of the laplacian (u- and v-points)
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt) :: zgui, zgvi   ! top    GRADh of the laplacian (u- and v-points)
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk,kjpt) :: zlap         ! laplacian at t-point
+      REAL(wp), DIMENSION(A2D(nn_hls),    kjpt) :: zglu, zglv   ! bottom GRADh of the laplacian (u- and v-points)
+      REAL(wp), DIMENSION(A2D(nn_hls),    kjpt) :: zgui, zgvi   ! top    GRADh of the laplacian (u- and v-points)
       !!---------------------------------------------------------------------
       !
-      IF( kt == kit000 .AND. lwp )  THEN
-         WRITE(numout,*)
-         SELECT CASE ( kldf )
-         CASE ( np_blp    )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-level   bilaplacian operator on ', cdtype
-         CASE ( np_blp_i  )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-neutral bilaplacian operator on ', cdtype, ' (Standard)'
-         CASE ( np_blp_it )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-neutral bilaplacian operator on ', cdtype, ' (triad)'
-         END SELECT
-         WRITE(numout,*) '~~~~~~~~~~~'
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == kit000 .AND. lwp )  THEN
+            WRITE(numout,*)
+            SELECT CASE ( kldf )
+            CASE ( np_blp    )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-level   bilaplacian operator on ', cdtype
+            CASE ( np_blp_i  )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-neutral bilaplacian operator on ', cdtype, ' (Standard)'
+            CASE ( np_blp_it )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-neutral bilaplacian operator on ', cdtype, ' (triad)'
+            END SELECT
+            WRITE(numout,*) '~~~~~~~~~~~'
+         ENDIF
       ENDIF
 
@@ -200,4 +236,5 @@
       END SELECT
       !
+      ! NOTE: [tiling-comms-merge] Needed for both nn_hls as tra_ldf_iso and tra_ldf_triad have not yet been adjusted to work with nn_hls = 2. In the zps case the lbc_lnk in zps_hde handles this, but in the zco case zlap always needs this lbc_lnk. I did try adjusting the bounds in tra_ldf_iso and tra_ldf_triad so this lbc_lnk was only needed for nn_hls = 1, but this was not correct and I did not have time to figure out why
       CALL lbc_lnk( 'traldf_lap_blp', zlap(:,:,:,:) , 'T', 1.0_wp )     ! Lateral boundary conditions (unchanged sign)
       !                                               ! Partial top/bottom cell: GRADh( zlap )  
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_triad.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_triad.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traldf_triad.F90	(revision 14055)
@@ -13,4 +13,7 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
+   ! TEMP: [tiling] This change not necessary if XIOS has subdomain support
+   USE domain, ONLY : dom_tile
+   USE domutl, ONLY : is_tile
    USE phycst         ! physical constants
    USE trc_oce        ! share passive tracers/Ocean variables
@@ -33,6 +36,4 @@
    PUBLIC   tra_ldf_triad   ! routine called by traldf.F90
 
-   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE, SAVE ::   zdkt3d   !: vertical tracer gradient at 2 levels
-
    LOGICAL  ::   l_ptr   ! flag to compute poleward transport
    LOGICAL  ::   l_hst   ! flag to compute heat transport
@@ -49,7 +50,30 @@
 CONTAINS
 
-  SUBROUTINE tra_ldf_triad( kt, Kmm, kit000, cdtype, pahu, pahv,               &
-      &                                              pgu , pgv  , pgui, pgvi , &
-      &                                         pt , pt2, pt_rhs, kjpt, kpass )
+   SUBROUTINE tra_ldf_triad( kt, Kmm, kit000, cdtype, pahu, pahv,             &
+      &                                               pgu , pgv , pgui, pgvi, &
+      &                                               pt, pt2, pt_rhs, kjpt, kpass )
+      !!
+      INTEGER                     , INTENT(in   ) ::   kt         ! ocean time-step index
+      INTEGER                     , INTENT(in   ) ::   kit000     ! first time step index
+      CHARACTER(len=3)            , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      INTEGER                     , INTENT(in   ) ::   kjpt       ! number of tracers
+      INTEGER                     , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      INTEGER                     , INTENT(in   ) ::   Kmm        ! ocean time level indices
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pgu , pgv  ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pt         ! tracer (kpass=1) or laplacian of tracer (kpass=2)
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pt2        ! tracer (only used in kpass=2)
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pt_rhs     ! tracer trend
+      !!
+      CALL tra_ldf_triad_t( kt, Kmm, kit000, cdtype, pahu, pahv, is_tile(pahu),                            &
+      &                                              pgu , pgv , is_tile(pgu) , pgui, pgvi, is_tile(pgui), &
+      &                                              pt, is_tile(pt), pt2, is_tile(pt2), pt_rhs, is_tile(pt_rhs), kjpt, kpass )
+   END SUBROUTINE tra_ldf_triad
+
+
+  SUBROUTINE tra_ldf_triad_t( kt, Kmm, kit000, cdtype, pahu, pahv, ktah,                   &
+      &                                                pgu , pgv , ktg , pgui, pgvi, ktgi, &
+      &                                                pt, ktt, pt2, ktt2, pt_rhs, ktt_rhs, kjpt, kpass )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE tra_ldf_triad  ***
@@ -77,10 +101,11 @@
       INTEGER                              , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
       INTEGER                              , INTENT(in)    ::   Kmm        ! ocean time level indices
-      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
-      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgu , pgv  ! tracer gradient at pstep levels
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   pt         ! tracer (kpass=1) or laplacian of tracer (kpass=2)
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   pt2        ! tracer (only used in kpass=2)
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pt_rhs     ! tracer trend
+      INTEGER                              , INTENT(in   ) ::   ktah, ktg, ktgi, ktt, ktt2, ktt_rhs
+      REAL(wp), DIMENSION(A2D_T(ktah),   JPK)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      REAL(wp), DIMENSION(A2D_T(ktg),        KJPT), INTENT(in   ) ::   pgu , pgv  ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(A2D_T(ktgi),       KJPT), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top   levels
+      REAL(wp), DIMENSION(A2D_T(ktt),    JPK,KJPT), INTENT(in   ) ::   pt         ! tracer (kpass=1) or laplacian of tracer (kpass=2)
+      REAL(wp), DIMENSION(A2D_T(ktt2),   JPK,KJPT), INTENT(in   ) ::   pt2        ! tracer (only used in kpass=2)
+      REAL(wp), DIMENSION(A2D_T(ktt_rhs),JPK,KJPT), INTENT(inout) ::   pt_rhs     ! tracer trend
       !
       INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
@@ -94,26 +119,25 @@
       REAL(wp) ::   ze1ur, ze2vr, ze3wr, zdxt, zdyt, zdzt
       REAL(wp) ::   zah, zah_slp, zaei_slp
-      REAL(wp), DIMENSION(jpi,jpj    ) ::   z2d                                              ! 2D workspace
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdit, zdjt, zftu, zftv, ztfw, zpsi_uw, zpsi_vw   ! 3D     -
+      REAL(wp), DIMENSION(A2D(nn_hls),0:1)     ::   zdkt3d                         ! vertical tracer gradient at 2 levels
+      REAL(wp), DIMENSION(A2D(nn_hls)        ) ::   z2d                            ! 2D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls)    ,jpk) ::   zdit, zdjt, zftu, zftv, ztfw   ! 3D     -
+      ! TEMP: [tiling] This can be A2D(nn_hls) if XIOS has subdomain support
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zpsi_uw, zpsi_vw
       !!----------------------------------------------------------------------
       !
-      IF( .NOT.ALLOCATED(zdkt3d) )  THEN
-         ALLOCATE( zdkt3d(jpi,jpj,0:1) , STAT=ierr )
-         CALL mpp_sum ( 'traldf_triad', ierr )
-         IF( ierr > 0 )   CALL ctl_stop('STOP', 'tra_ldf_triad: unable to allocate arrays')
-      ENDIF
-     !
-      IF( kpass == 1 .AND. kt == kit000 )  THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_ldf_triad : rotated laplacian diffusion operator on ', cdtype
-         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'
-      ENDIF
-      !   
-      l_hst = .FALSE.
-      l_ptr = .FALSE.
-      IF( cdtype == 'TRA' ) THEN
-         IF( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf') )      l_ptr = .TRUE. 
-         IF( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR.                   &
-         &   iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  )   l_hst = .TRUE.
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kpass == 1 .AND. kt == kit000 )  THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_ldf_triad : rotated laplacian diffusion operator on ', cdtype
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'
+         ENDIF
+         !
+         l_hst = .FALSE.
+         l_ptr = .FALSE.
+         IF( cdtype == 'TRA' ) THEN
+            IF( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf') )      l_ptr = .TRUE.
+            IF( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR.                   &
+            &   iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  )   l_hst = .TRUE.
+         ENDIF
       ENDIF
       !
@@ -128,27 +152,23 @@
       IF( kpass == 1 ) THEN         !==  first pass only  and whatever the tracer is  ==!
          !
-         akz     (:,:,:) = 0._wp      
-         ah_wslp2(:,:,:) = 0._wp
-         IF( ln_ldfeiv_dia ) THEN
-            zpsi_uw(:,:,:) = 0._wp
-            zpsi_vw(:,:,:) = 0._wp
-         ENDIF
+         DO_3D( 0, 0, 0, 0, 1, jpk )
+            akz     (ji,jj,jk) = 0._wp
+            ah_wslp2(ji,jj,jk) = 0._wp
+         END_3D
          !
          DO ip = 0, 1                            ! i-k triads
             DO kp = 0, 1
-               DO_3D( 1, 0, 1, 0, 1, jpkm1 )
-                  ze3wr = 1._wp / e3w(ji+ip,jj,jk+kp,Kmm)
-                  zbu   = e1e2u(ji,jj) * e3u(ji,jj,jk,Kmm)
-                  zah   = 0.25_wp * pahu(ji,jj,jk)
-                  zslope_skew = triadi_g(ji+ip,jj,jk,1-ip,kp)
+               DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+                  ze3wr = 1._wp / e3w(ji,jj,jk+kp,Kmm)
+                  zbu   = e1e2u(ji-ip,jj) * e3u(ji-ip,jj,jk,Kmm)
+                  zah   = 0.25_wp * pahu(ji-ip,jj,jk)
+                  zslope_skew = triadi_g(ji,jj,jk,1-ip,kp)
                   ! Subtract s-coordinate slope at t-points to give slope rel to s-surfaces (do this by *adding* gradient of depth)
-                  zslope2 = zslope_skew + ( gdept(ji+1,jj,jk,Kmm) - gdept(ji,jj,jk,Kmm) ) * r1_e1u(ji,jj) * umask(ji,jj,jk+kp)
+                  zslope2 = zslope_skew + ( gdept(ji-ip+1,jj,jk,Kmm) - gdept(ji-ip,jj,jk,Kmm) ) * r1_e1u(ji-ip,jj) * umask(ji-ip,jj,jk+kp)
                   zslope2 = zslope2 *zslope2
-                  ah_wslp2(ji+ip,jj,jk+kp) = ah_wslp2(ji+ip,jj,jk+kp) + zah * zbu * ze3wr * r1_e1e2t(ji+ip,jj) * zslope2
-                  akz     (ji+ip,jj,jk+kp) = akz     (ji+ip,jj,jk+kp) + zah * r1_e1u(ji,jj)       &
-                     &                                                      * r1_e1u(ji,jj) * umask(ji,jj,jk+kp)
+                  ah_wslp2(ji,jj,jk+kp) = ah_wslp2(ji,jj,jk+kp) + zah * zbu * ze3wr * r1_e1e2t(ji,jj) * zslope2
+                  akz     (ji,jj,jk+kp) = akz     (ji,jj,jk+kp) + zah * r1_e1u(ji-ip,jj)       &
+                     &                                                      * r1_e1u(ji-ip,jj) * umask(ji-ip,jj,jk+kp)
                      !
-                 IF( ln_ldfeiv_dia )   zpsi_uw(ji,jj,jk+kp) = zpsi_uw(ji,jj,jk+kp)   &
-                     &                                       + 0.25_wp * aeiu(ji,jj,jk) * e2u(ji,jj) * zslope_skew
                END_3D
             END DO
@@ -157,19 +177,17 @@
          DO jp = 0, 1                            ! j-k triads 
             DO kp = 0, 1
-               DO_3D( 1, 0, 1, 0, 1, jpkm1 )
-                  ze3wr = 1.0_wp / e3w(ji,jj+jp,jk+kp,Kmm)
-                  zbv   = e1e2v(ji,jj) * e3v(ji,jj,jk,Kmm)
-                  zah   = 0.25_wp * pahv(ji,jj,jk)
-                  zslope_skew = triadj_g(ji,jj+jp,jk,1-jp,kp)
+               DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+                  ze3wr = 1.0_wp / e3w(ji,jj,jk+kp,Kmm)
+                  zbv   = e1e2v(ji,jj-jp) * e3v(ji,jj-jp,jk,Kmm)
+                  zah   = 0.25_wp * pahv(ji,jj-jp,jk)
+                  zslope_skew = triadj_g(ji,jj,jk,1-jp,kp)
                   ! Subtract s-coordinate slope at t-points to give slope rel to s surfaces
                   !    (do this by *adding* gradient of depth)
-                  zslope2 = zslope_skew + ( gdept(ji,jj+1,jk,Kmm) - gdept(ji,jj,jk,Kmm) ) * r1_e2v(ji,jj) * vmask(ji,jj,jk+kp)
+                  zslope2 = zslope_skew + ( gdept(ji,jj-jp+1,jk,Kmm) - gdept(ji,jj-jp,jk,Kmm) ) * r1_e2v(ji,jj-jp) * vmask(ji,jj-jp,jk+kp)
                   zslope2 = zslope2 * zslope2
-                  ah_wslp2(ji,jj+jp,jk+kp) = ah_wslp2(ji,jj+jp,jk+kp) + zah * zbv * ze3wr * r1_e1e2t(ji,jj+jp) * zslope2
-                  akz     (ji,jj+jp,jk+kp) = akz     (ji,jj+jp,jk+kp) + zah * r1_e2v(ji,jj)     &
-                     &                                                      * r1_e2v(ji,jj) * vmask(ji,jj,jk+kp)
+                  ah_wslp2(ji,jj,jk+kp) = ah_wslp2(ji,jj,jk+kp) + zah * zbv * ze3wr * r1_e1e2t(ji,jj) * zslope2
+                  akz     (ji,jj,jk+kp) = akz     (ji,jj,jk+kp) + zah * r1_e2v(ji,jj-jp)     &
+                     &                                                      * r1_e2v(ji,jj-jp) * vmask(ji,jj-jp,jk+kp)
                   !
-                  IF( ln_ldfeiv_dia )   zpsi_vw(ji,jj,jk+kp) = zpsi_vw(ji,jj,jk+kp)   &
-                     &                                       + 0.25 * aeiv(ji,jj,jk) * e1v(ji,jj) * zslope_skew
                END_3D
             END DO
@@ -179,5 +197,5 @@
             !
             IF( ln_traldf_blp ) THEN                ! bilaplacian operator
-               DO_3D( 1, 0, 1, 0, 2, jpkm1 )
+               DO_3D( 0, 0, 0, 0, 2, jpkm1 )
                   akz(ji,jj,jk) = 16._wp           &
                      &   * ah_wslp2   (ji,jj,jk)   &
@@ -187,5 +205,5 @@
                END_3D
             ELSEIF( ln_traldf_lap ) THEN              ! laplacian operator
-               DO_3D( 1, 0, 1, 0, 2, jpkm1 )
+               DO_3D( 0, 0, 0, 0, 2, jpkm1 )
                   ze3w_2 = e3w(ji,jj,jk,Kmm) * e3w(ji,jj,jk,Kmm)
                   zcoef0 = rDt * (  akz(ji,jj,jk) + ah_wslp2(ji,jj,jk) / ze3w_2  )
@@ -195,8 +213,32 @@
            !
          ELSE                                    ! 33 flux set to zero with akz=ah_wslp2 ==>> computed in full implicit
-            akz(:,:,:) = ah_wslp2(:,:,:)      
-         ENDIF
-         !
-         IF( ln_ldfeiv_dia .AND. cdtype == 'TRA' )   CALL ldf_eiv_dia( zpsi_uw, zpsi_vw, Kmm )
+            DO_3D( 0, 0, 0, 0, 1, jpk )
+               akz(ji,jj,jk) = ah_wslp2(ji,jj,jk)
+            END_3D
+         ENDIF
+         !
+         ! TEMP: [tiling] These changes not necessary if XIOS has subdomain support
+         IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only for the full domain
+            IF( ln_ldfeiv_dia .AND. cdtype == 'TRA' ) THEN
+               IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )
+
+               zpsi_uw(:,:,:) = 0._wp
+               zpsi_vw(:,:,:) = 0._wp
+
+               DO jp = 0, 1
+                  DO kp = 0, 1
+                     DO_3D( 1, 0, 1, 0, 1, jpkm1 )
+                        zpsi_uw(ji,jj,jk+kp) = zpsi_uw(ji,jj,jk+kp) &
+                           & + 0.25_wp * aeiu(ji,jj,jk) * e2u(ji,jj) * triadi_g(ji+jp,jj,jk,1-jp,kp)
+                        zpsi_vw(ji,jj,jk+kp) = zpsi_vw(ji,jj,jk+kp) &
+                           & + 0.25_wp * aeiv(ji,jj,jk) * e1v(ji,jj) * triadj_g(ji,jj+jp,jk,1-jp,kp)
+                     END_3D
+                  END DO
+               END DO
+               CALL ldf_eiv_dia( zpsi_uw, zpsi_vw, Kmm )
+
+               IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = nijtile )
+            ENDIF
+         ENDIF
          !
       ENDIF                                  !==  end 1st pass only  ==!
@@ -234,9 +276,14 @@
          DO jk = 1, jpkm1
             !                    !==  Vertical tracer gradient at level jk and jk+1
-            zdkt3d(:,:,1) = ( pt(:,:,jk,jn) - pt(:,:,jk+1,jn) ) * tmask(:,:,jk+1)
+            DO_2D( 1, 1, 1, 1 )
+               zdkt3d(ji,jj,1) = ( pt(ji,jj,jk,jn) - pt(ji,jj,jk+1,jn) ) * tmask(ji,jj,jk+1)
+            END_2D
             !
             !                    ! surface boundary condition: zdkt3d(jk=0)=zdkt3d(jk=1)
             IF( jk == 1 ) THEN   ;   zdkt3d(:,:,0) = zdkt3d(:,:,1)
-            ELSE                 ;   zdkt3d(:,:,0) = ( pt(:,:,jk-1,jn) - pt(:,:,jk,jn) ) * tmask(:,:,jk)
+            ELSE
+               DO_2D( 1, 1, 1, 1 )
+                  zdkt3d(ji,jj,0) = ( pt(ji,jj,jk-1,jn) - pt(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
+               END_2D
             ENDIF
             !
@@ -380,5 +427,5 @@
       END DO                                                      ! end tracer loop
       !                                                           ! ===============
-   END SUBROUTINE tra_ldf_triad
+   END SUBROUTINE tra_ldf_triad_t
 
    !!==============================================================================
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tramle.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tramle.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tramle.F90	(revision 14055)
@@ -20,4 +20,8 @@
    USE lib_mpp        ! MPP library
    USE lbclnk         ! lateral boundary condition / mpp link
+
+   ! where OSMOSIS_OBL is used with integrated FK
+   USE zdf_oce, ONLY : ln_zdfosm
+   USE zdfosm, ONLY  : ln_osm_mle, hmle, dbdx_mle, dbdy_mle, mld_prof
 
    IMPLICIT NONE
@@ -79,11 +83,11 @@
       !!             Fox-Kemper and Ferrari, JPO, 38, 1166-1179, 2008
       !!----------------------------------------------------------------------
-      INTEGER                         , INTENT(in   ) ::   kt         ! ocean time-step index
-      INTEGER                         , INTENT(in   ) ::   kit000     ! first time step index
-      INTEGER                         , INTENT(in   ) ::   Kmm        ! ocean time level index
-      CHARACTER(len=3)                , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pu         ! in : 3 ocean transport components
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pv         ! out: same 3  transport components
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pw         !   increased by the MLE induced transport
+      INTEGER                     , INTENT(in   ) ::   kt         ! ocean time-step index
+      INTEGER                     , INTENT(in   ) ::   kit000     ! first time step index
+      INTEGER                     , INTENT(in   ) ::   Kmm        ! ocean time level index
+      CHARACTER(len=3)            , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   pu         ! in : 3 ocean transport components
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   pv         ! out: same 3  transport components
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk), INTENT(inout) ::   pw         !   increased by the MLE induced transport
       !
       INTEGER  ::   ji, jj, jk          ! dummy loop indices
@@ -91,95 +95,147 @@
       REAL(wp) ::   zcuw, zmuw, zc      ! local scalar
       REAL(wp) ::   zcvw, zmvw          !   -      -
-      INTEGER , DIMENSION(jpi,jpj)     :: inml_mle
-      REAL(wp), DIMENSION(jpi,jpj)     :: zpsim_u, zpsim_v, zmld, zbm, zhu, zhv, zn2, zLf_NH, zLf_MH
-      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpsi_uw, zpsi_vw
-      !!----------------------------------------------------------------------
-      !
-      !                                      !==  MLD used for MLE  ==!
-      !                                                ! compute from the 10m density to deal with the diurnal cycle
-      inml_mle(:,:) = mbkt(:,:) + 1                    ! init. to number of ocean w-level (T-level + 1)
-      IF ( nla10 > 0 ) THEN                            ! avoid case where first level is thicker than 10m
-         DO_3DS( 1, 1, 1, 1, jpkm1, nlb10, -1 )        ! from the bottom to nlb10 (10m)
-            IF( rhop(ji,jj,jk) > rhop(ji,jj,nla10) + rn_rho_c_mle )   inml_mle(ji,jj) = jk      ! Mixed layer
+      INTEGER , DIMENSION(A2D(nn_hls))     :: inml_mle
+      REAL(wp), DIMENSION(A2D(nn_hls))     :: zpsim_u, zpsim_v, zmld, zbm, zhu, zhv, zn2, zLf_MH
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) :: zpsi_uw, zpsi_vw
+      ! TEMP: [tiling] These changes not necessary if using XIOS (subdomain support)
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE, SAVE :: zLf_NH
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE, SAVE :: zpsiu_mle, zpsiv_mle
+      !!----------------------------------------------------------------------
+      !
+      !
+      IF(ln_osm_mle.and.ln_zdfosm) THEN
+         ikmax = MIN( MAXVAL( mld_prof(:,:) ), jpkm1 )                  ! max level of the computation
+         !
+         !
+         SELECT CASE( nn_mld_uv )                         ! MLD at u- & v-pts
+         CASE ( 0 )                                               != min of the 2 neighbour MLDs
+            DO_2D( 1, 0, 1, 0 )
+               zhu(ji,jj) = MIN( hmle(ji+1,jj), hmle(ji,jj) )
+               zhv(ji,jj) = MIN( hmle(ji,jj+1), hmle(ji,jj) )
+            END_2D
+         CASE ( 1 )                                               != average of the 2 neighbour MLDs
+            DO_2D( 1, 0, 1, 0 )
+               zhu(ji,jj) = MAX( hmle(ji+1,jj), hmle(ji,jj) )
+               zhv(ji,jj) = MAX( hmle(ji,jj+1), hmle(ji,jj) )
+            END_2D
+         CASE ( 2 )                                               != max of the 2 neighbour MLDs
+            DO_2D( 1, 0, 1, 0 )
+               zhu(ji,jj) = MAX( hmle(ji+1,jj), hmle(ji,jj) )
+               zhv(ji,jj) = MAX( hmle(ji,jj+1), hmle(ji,jj) )
+            END_2D
+         END SELECT
+         IF( nn_mle == 0 ) THEN           ! Fox-Kemper et al. 2010 formulation
+            DO_2D( 1, 0, 1, 0 )
+               zpsim_u(ji,jj) = rn_ce * zhu(ji,jj) * zhu(ji,jj)  * e2u(ji,jj)                                            &
+                    &           * dbdx_mle(ji,jj) * MIN( 111.e3_wp , e1u(ji,jj) )   &
+                    &           / (  MAX( rn_lf * rfu(ji,jj) , SQRT( rb_c * zhu(ji,jj) ) )   )
+               !
+               zpsim_v(ji,jj) = rn_ce * zhv(ji,jj) * zhv(ji,jj)  * e1v(ji,jj)                                            &
+                    &           * dbdy_mle(ji,jj)  * MIN( 111.e3_wp , e2v(ji,jj) )   &
+                    &           / (  MAX( rn_lf * rfv(ji,jj) , SQRT( rb_c * zhv(ji,jj) ) )   )
+            END_2D
+            !
+         ELSEIF( nn_mle == 1 ) THEN       ! New formulation (Lf = 5km fo/ff with fo=Coriolis parameter at latitude rn_lat)
+            DO_2D( 1, 0, 1, 0 )
+               zpsim_u(ji,jj) = rc_f *   zhu(ji,jj)   * zhu(ji,jj)   * e2u(ji,jj)               &
+                    &                  * dbdx_mle(ji,jj) * MIN( 111.e3_wp , e1u(ji,jj) )
+               !
+               zpsim_v(ji,jj) = rc_f *   zhv(ji,jj)   * zhv(ji,jj)   * e1v(ji,jj)               &
+                    &                  * dbdy_mle(ji,jj) * MIN( 111.e3_wp , e2v(ji,jj) )
+            END_2D
+         ENDIF
+
+      ELSE !do not use osn_mle
+         !                                      !==  MLD used for MLE  ==!
+         !                                                ! compute from the 10m density to deal with the diurnal cycle
+         DO_2D( 1, 1, 1, 1 )
+            inml_mle(ji,jj) = mbkt(ji,jj) + 1                    ! init. to number of ocean w-level (T-level + 1)
+         END_2D
+         IF ( nla10 > 0 ) THEN                            ! avoid case where first level is thicker than 10m
+           DO_3DS( 1, 1, 1, 1, jpkm1, nlb10, -1 )        ! from the bottom to nlb10 (10m)
+              IF( rhop(ji,jj,jk) > rhop(ji,jj,nla10) + rn_rho_c_mle )   inml_mle(ji,jj) = jk      ! Mixed layer
+           END_3D
+         ENDIF
+         ikmax = MIN( MAXVAL( inml_mle(:,:) ), jpkm1 )                  ! max level of the computation
+         !
+         !
+         zmld(:,:) = 0._wp                      !==   Horizontal shape of the MLE  ==!
+         zbm (:,:) = 0._wp
+         zn2 (:,:) = 0._wp
+         DO_3D( 1, 1, 1, 1, 1, ikmax )                    ! MLD and mean buoyancy and N2 over the mixed layer
+            zc = e3t(ji,jj,jk,Kmm) * REAL( MIN( MAX( 0, inml_mle(ji,jj)-jk ) , 1  )  )    ! zc being 0 outside the ML t-points
+            zmld(ji,jj) = zmld(ji,jj) + zc
+            zbm (ji,jj) = zbm (ji,jj) + zc * (rho0 - rhop(ji,jj,jk) ) * r1_rho0
+            zn2 (ji,jj) = zn2 (ji,jj) + zc * (rn2(ji,jj,jk)+rn2(ji,jj,jk+1))*0.5_wp
          END_3D
-      ENDIF
-      ikmax = MIN( MAXVAL( inml_mle(:,:) ), jpkm1 )                  ! max level of the computation
-      !
-      !
-      zmld(:,:) = 0._wp                      !==   Horizontal shape of the MLE  ==!
-      zbm (:,:) = 0._wp
-      zn2 (:,:) = 0._wp
-      DO_3D( 1, 1, 1, 1, 1, ikmax )                    ! MLD and mean buoyancy and N2 over the mixed layer
-         zc = e3t(ji,jj,jk,Kmm) * REAL( MIN( MAX( 0, inml_mle(ji,jj)-jk ) , 1  )  )    ! zc being 0 outside the ML t-points
-         zmld(ji,jj) = zmld(ji,jj) + zc
-         zbm (ji,jj) = zbm (ji,jj) + zc * (rho0 - rhop(ji,jj,jk) ) * r1_rho0
-         zn2 (ji,jj) = zn2 (ji,jj) + zc * (rn2(ji,jj,jk)+rn2(ji,jj,jk+1))*0.5_wp
-      END_3D
-
-      SELECT CASE( nn_mld_uv )                         ! MLD at u- & v-pts
-      CASE ( 0 )                                               != min of the 2 neighbour MLDs
-         DO_2D( 1, 0, 1, 0 )
-            zhu(ji,jj) = MIN( zmld(ji+1,jj), zmld(ji,jj) )
-            zhv(ji,jj) = MIN( zmld(ji,jj+1), zmld(ji,jj) )
+   
+         SELECT CASE( nn_mld_uv )                         ! MLD at u- & v-pts
+         CASE ( 0 )                                               != min of the 2 neighbour MLDs
+            DO_2D( 1, 0, 1, 0 )
+               zhu(ji,jj) = MIN( zmld(ji+1,jj), zmld(ji,jj) )
+               zhv(ji,jj) = MIN( zmld(ji,jj+1), zmld(ji,jj) )
+            END_2D
+         CASE ( 1 )                                               != average of the 2 neighbour MLDs
+            DO_2D( 1, 0, 1, 0 )
+               zhu(ji,jj) = ( zmld(ji+1,jj) + zmld(ji,jj) ) * 0.5_wp
+               zhv(ji,jj) = ( zmld(ji,jj+1) + zmld(ji,jj) ) * 0.5_wp
+            END_2D
+         CASE ( 2 )                                               != max of the 2 neighbour MLDs
+            DO_2D( 1, 0, 1, 0 )
+               zhu(ji,jj) = MAX( zmld(ji+1,jj), zmld(ji,jj) )
+               zhv(ji,jj) = MAX( zmld(ji,jj+1), zmld(ji,jj) )
+            END_2D
+         END SELECT
+         !                                                ! convert density into buoyancy
+         DO_2D( 1, 1, 1, 1 )
+            zbm(ji,jj) = + grav * zbm(ji,jj) / MAX( e3t(ji,jj,1,Kmm), zmld(ji,jj) )
          END_2D
-      CASE ( 1 )                                               != average of the 2 neighbour MLDs
-         DO_2D( 1, 0, 1, 0 )
-            zhu(ji,jj) = ( zmld(ji+1,jj) + zmld(ji,jj) ) * 0.5_wp
-            zhv(ji,jj) = ( zmld(ji,jj+1) + zmld(ji,jj) ) * 0.5_wp
-         END_2D
-      CASE ( 2 )                                               != max of the 2 neighbour MLDs
-         DO_2D( 1, 0, 1, 0 )
-            zhu(ji,jj) = MAX( zmld(ji+1,jj), zmld(ji,jj) )
-            zhv(ji,jj) = MAX( zmld(ji,jj+1), zmld(ji,jj) )
-         END_2D
-      END SELECT
-      !                                                ! convert density into buoyancy
-      zbm(:,:) = + grav * zbm(:,:) / MAX( e3t(:,:,1,Kmm), zmld(:,:) )
-      !
-      !
-      !                                      !==  Magnitude of the MLE stream function  ==!
-      !
-      !                 di[bm]  Ds
-      ! Psi = Ce  H^2 ---------------- e2u  mu(z)   where fu Lf = MAX( fu*rn_fl , (Db H)^1/2 )
-      !                  e1u   Lf fu                      and the e2u for the "transport"
-      !                                                      (not *e3u as divided by e3u at the end)
-      !
-      IF( nn_mle == 0 ) THEN           ! Fox-Kemper et al. 2010 formulation
-         DO_2D( 1, 0, 1, 0 )
-            zpsim_u(ji,jj) = rn_ce * zhu(ji,jj) * zhu(ji,jj)  * e2_e1u(ji,jj)                                            &
-               &           * ( zbm(ji+1,jj) - zbm(ji,jj) ) * MIN( 111.e3_wp , e1u(ji,jj) )   &
-               &           / (  MAX( rn_lf * rfu(ji,jj) , SQRT( rb_c * zhu(ji,jj) ) )   )
+         !
+         !
+         !                                      !==  Magnitude of the MLE stream function  ==!
+         !
+         !                 di[bm]  Ds
+         ! Psi = Ce  H^2 ---------------- e2u  mu(z)   where fu Lf = MAX( fu*rn_fl , (Db H)^1/2 )
+         !                  e1u   Lf fu                      and the e2u for the "transport"
+         !                                                      (not *e3u as divided by e3u at the end)
+         !
+         IF( nn_mle == 0 ) THEN           ! Fox-Kemper et al. 2010 formulation
+            DO_2D( 1, 0, 1, 0 )
+               zpsim_u(ji,jj) = rn_ce * zhu(ji,jj) * zhu(ji,jj)  * e2_e1u(ji,jj)                                            &
+                    &           * ( zbm(ji+1,jj) - zbm(ji,jj) ) * MIN( 111.e3_wp , e1u(ji,jj) )   &
+                    &           / (  MAX( rn_lf * rfu(ji,jj) , SQRT( rb_c * zhu(ji,jj) ) )   )
                !
-            zpsim_v(ji,jj) = rn_ce * zhv(ji,jj) * zhv(ji,jj)  * e1_e2v(ji,jj)                                            &
-               &           * ( zbm(ji,jj+1) - zbm(ji,jj) ) * MIN( 111.e3_wp , e2v(ji,jj) )   &
-               &           / (  MAX( rn_lf * rfv(ji,jj) , SQRT( rb_c * zhv(ji,jj) ) )   )
-         END_2D
-         !
-      ELSEIF( nn_mle == 1 ) THEN       ! New formulation (Lf = 5km fo/ff with fo=Coriolis parameter at latitude rn_lat)
-         DO_2D( 1, 0, 1, 0 )
-            zpsim_u(ji,jj) = rc_f *   zhu(ji,jj)   * zhu(ji,jj)   * e2_e1u(ji,jj)               &
-               &                  * ( zbm(ji+1,jj) - zbm(ji,jj) ) * MIN( 111.e3_wp , e1u(ji,jj) )
+               zpsim_v(ji,jj) = rn_ce * zhv(ji,jj) * zhv(ji,jj)  * e1_e2v(ji,jj)                                            &
+                    &           * ( zbm(ji,jj+1) - zbm(ji,jj) ) * MIN( 111.e3_wp , e2v(ji,jj) )   &
+                    &           / (  MAX( rn_lf * rfv(ji,jj) , SQRT( rb_c * zhv(ji,jj) ) )   )
+            END_2D
+            !
+         ELSEIF( nn_mle == 1 ) THEN       ! New formulation (Lf = 5km fo/ff with fo=Coriolis parameter at latitude rn_lat)
+            DO_2D( 1, 0, 1, 0 )
+               zpsim_u(ji,jj) = rc_f *   zhu(ji,jj)   * zhu(ji,jj)   * e2_e1u(ji,jj)               &
+                    &                  * ( zbm(ji+1,jj) - zbm(ji,jj) ) * MIN( 111.e3_wp , e1u(ji,jj) )
                !
-            zpsim_v(ji,jj) = rc_f *   zhv(ji,jj)   * zhv(ji,jj)   * e1_e2v(ji,jj)               &
-               &                  * ( zbm(ji,jj+1) - zbm(ji,jj) ) * MIN( 111.e3_wp , e2v(ji,jj) )
-         END_2D
-      ENDIF
-      !
-      IF( nn_conv == 1 ) THEN              ! No MLE in case of convection
-         DO_2D( 1, 0, 1, 0 )
-            IF( MIN( zn2(ji,jj) , zn2(ji+1,jj) ) < 0._wp )   zpsim_u(ji,jj) = 0._wp
-            IF( MIN( zn2(ji,jj) , zn2(ji,jj+1) ) < 0._wp )   zpsim_v(ji,jj) = 0._wp
-         END_2D
-      ENDIF
-      !
-      !                                      !==  structure function value at uw- and vw-points  ==!
-      DO_2D( 1, 0, 1, 0 )
-         zhu(ji,jj) = 1._wp / zhu(ji,jj)                   ! hu --> 1/hu
-         zhv(ji,jj) = 1._wp / zhv(ji,jj)
-      END_2D
-      !
-      zpsi_uw(:,:,:) = 0._wp
-      zpsi_vw(:,:,:) = 0._wp
-      !
+               zpsim_v(ji,jj) = rc_f *   zhv(ji,jj)   * zhv(ji,jj)   * e1_e2v(ji,jj)               &
+                    &                  * ( zbm(ji,jj+1) - zbm(ji,jj) ) * MIN( 111.e3_wp , e2v(ji,jj) )
+            END_2D
+         ENDIF
+         !
+         IF( nn_conv == 1 ) THEN              ! No MLE in case of convection
+            DO_2D( 1, 0, 1, 0 )
+               IF( MIN( zn2(ji,jj) , zn2(ji+1,jj) ) < 0._wp )   zpsim_u(ji,jj) = 0._wp
+               IF( MIN( zn2(ji,jj) , zn2(ji,jj+1) ) < 0._wp )   zpsim_v(ji,jj) = 0._wp
+            END_2D
+         ENDIF
+         !
+      ENDIF  ! end of ln_osm_mle conditional
+    !                                      !==  structure function value at uw- and vw-points  ==!
+    DO_2D( 1, 0, 1, 0 )
+       zhu(ji,jj) = 1._wp / MAX(zhu(ji,jj), rsmall)                   ! hu --> 1/hu
+       zhv(ji,jj) = 1._wp / MAX(zhv(ji,jj), rsmall) 
+    END_2D
+    !
+    zpsi_uw(:,:,:) = 0._wp
+    zpsi_vw(:,:,:) = 0._wp
+    !
       DO_3D( 1, 0, 1, 0, 2, ikmax )                ! start from 2 : surface value = 0
          zcuw = 1._wp - ( gdepw(ji+1,jj,jk,Kmm) + gdepw(ji,jj,jk,Kmm) ) * zhu(ji,jj)
@@ -206,20 +262,36 @@
       END DO
 
+      ! TEMP: [tiling] These changes not necessary if using XIOS (subdomain support)
       IF( cdtype == 'TRA') THEN              !==  outputs  ==!
-         !
-         zLf_NH(:,:) = SQRT( rb_c * zmld(:,:) ) * r1_ft(:,:)      ! Lf = N H / f
-         CALL iom_put( "Lf_NHpf" , zLf_NH  )    ! Lf = N H / f
+         IF( ntile == 0 .OR. ntile == 1 ) THEN                             ! Do only on the first tile
+            ALLOCATE( zLf_NH(jpi,jpj), zpsiu_mle(jpi,jpj,jpk), zpsiv_mle(jpi,jpj,jpk) )
+            zpsiu_mle(:,:,:) = 0._wp ; zpsiv_mle(:,:,:) = 0._wp
+         ENDIF
+         !
+         IF (ln_osm_mle.and.ln_zdfosm) THEN
+            DO_2D( 0, 0, 0, 0 )
+               zLf_NH(ji,jj) = SQRT( rb_c * hmle(ji,jj) ) * r1_ft(ji,jj)      ! Lf = N H / f
+            END_2D
+         ELSE
+            DO_2D( 0, 0, 0, 0 )
+               zLf_NH(ji,jj) = SQRT( rb_c * zmld(ji,jj) ) * r1_ft(ji,jj)      ! Lf = N H / f
+            END_2D
+         ENDIF
          !
          ! divide by cross distance to give streamfunction with dimensions m^2/s
-         DO jk = 1, ikmax+1
-            zpsi_uw(:,:,jk) = zpsi_uw(:,:,jk) * r1_e2u(:,:)
-            zpsi_vw(:,:,jk) = zpsi_vw(:,:,jk) * r1_e1v(:,:)
-         END DO
-         CALL iom_put( "psiu_mle", zpsi_uw )    ! i-mle streamfunction
-         CALL iom_put( "psiv_mle", zpsi_vw )    ! j-mle streamfunction
+         DO_3D( 0, 0, 0, 0, 1, ikmax+1 )
+            zpsiu_mle(ji,jj,jk) = zpsi_uw(ji,jj,jk) * r1_e2u(ji,jj)
+            zpsiv_mle(ji,jj,jk) = zpsi_vw(ji,jj,jk) * r1_e1v(ji,jj)
+         END_3D
+
+         IF( ntile == 0 .OR. ntile == nijtile ) THEN                       ! Do only on the last tile
+            CALL iom_put( "Lf_NHpf" , zLf_NH  )    ! Lf = N H / f
+            CALL iom_put( "psiu_mle", zpsiu_mle )    ! i-mle streamfunction
+            CALL iom_put( "psiv_mle", zpsiv_mle )    ! j-mle streamfunction
+            DEALLOCATE( zLf_NH, zpsiu_mle, zpsiv_mle )
+         ENDIF
       ENDIF
       !
    END SUBROUTINE tra_mle_trp
-
 
    SUBROUTINE tra_mle_init
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tranpc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tranpc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/tranpc.F90	(revision 14055)
@@ -17,4 +17,6 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
+   ! TEMP: [tiling] This change not necessary after extra haloes development (lbc_lnk removed)
+   USE domain, ONLY : dom_tile
    USE phycst         ! physical constants
    USE zdf_oce        ! ocean vertical physics
@@ -32,4 +34,6 @@
 
    PUBLIC   tra_npc    ! routine called by step.F90
+
+   INTEGER  ::   nnpcc        ! number of statically instable water column
 
    !! * Substitutions
@@ -64,5 +68,4 @@
       !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      INTEGER  ::   inpcc        ! number of statically instable water column
       INTEGER  ::   jiter, ikbot, ikp, ikup, ikdown, ilayer, ik_low   ! local integers
       LOGICAL  ::   l_bottom_reached, l_column_treated
@@ -70,12 +73,13 @@
       REAL(wp) ::   zsa, zbeta, zsum_sali, zsum_beta, zbw, zrw, z1_rDt
       REAL(wp), PARAMETER ::   zn2_zero = 1.e-14_wp             ! acceptance criteria for neutrality (N2==0)
-      REAL(wp), DIMENSION(        jpk     )   ::   zvn2         ! vertical profile of N2 at 1 given point...
-      REAL(wp), DIMENSION(        jpk,jpts)   ::   zvts, zvab   ! vertical profile of T & S , and  alpha & betaat 1 given point
-      REAL(wp), DIMENSION(jpi,jpj,jpk     )   ::   zn2          ! N^2 
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts)   ::   zab          ! alpha and beta
+      REAL(wp), DIMENSION(    jpk     )   ::   zvn2             ! vertical profile of N2 at 1 given point...
+      REAL(wp), DIMENSION(    jpk,jpts)   ::   zvts, zvab       ! vertical profile of T & S , and  alpha & betaat 1 given point
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk     )   ::   zn2              ! N^2
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk,jpts)   ::   zab              ! alpha and beta
       REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds ! 3D workspace
       !
       LOGICAL, PARAMETER :: l_LB_debug = .FALSE. ! set to true if you want to follow what is
       INTEGER :: ilc1, jlc1, klc1, nncpu         ! actually happening in a water column at point "ilc1, jlc1"
+      INTEGER :: isi, isj, iei, iej
       LOGICAL :: lp_monitor_point = .FALSE.      ! in CPU domain "nncpu"
       !!----------------------------------------------------------------------
@@ -87,5 +91,5 @@
          IF( l_trdtra )   THEN                    !* Save initial after fields
             ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
-            ztrdt(:,:,:) = pts(:,:,:,jp_tem,Kaa) 
+            ztrdt(:,:,:) = pts(:,:,:,jp_tem,Kaa)
             ztrds(:,:,:) = pts(:,:,:,jp_sal,Kaa)
          ENDIF
@@ -101,7 +105,13 @@
          CALL bn2    ( pts(:,:,:,:,Kaa), zab, zn2, Kmm )    ! after Brunt-Vaisala  (given on W-points)
          !
-         inpcc = 0
-         !
-         DO_2D( 0, 0, 0, 0 )                                ! interior column only
+         IF( ntile == 0 .OR. ntile == 1 ) nnpcc = 0         ! Do only on the first tile
+         !
+         IF( ntsi == Nis0 ) THEN ; isi = nn_hls ; ELSE ; isi = 0 ; ENDIF    ! Avoid double-counting when using tiling
+         IF( ntsj == Njs0 ) THEN ; isj = nn_hls ; ELSE ; isj = 0 ; ENDIF
+         IF( ntei == Nie0 ) THEN ; iei = nn_hls ; ELSE ; iei = 0 ; ENDIF
+         IF( ntej == Nje0 ) THEN ; iej = nn_hls ; ELSE ; iej = 0 ; ENDIF
+         !
+         ! NOTE: [tiling-comms-merge] Bounds changed to avoid repeating this calculation for overlapping rows when using tiling
+         DO_2D( isj, iej, isi, iei )                        ! interior column only
             !
             IF( tmask(ji,jj,2) == 1 ) THEN      ! At least 2 ocean points
@@ -160,5 +170,5 @@
                         ENDIF
                         !
-                        IF( jiter == 1 )   inpcc = inpcc + 1 
+                        IF( jiter == 1 )   nnpcc = nnpcc + 1
                         !
                         IF( lp_monitor_point )   WRITE(numout, *) 'Negative N2 at ikp =',ikp,' for layer #', ilayer
@@ -310,9 +320,9 @@
          ENDIF
          !
-         CALL lbc_lnk_multi( 'tranpc', pts(:,:,:,jp_tem,Kaa), 'T', 1.0_wp, pts(:,:,:,jp_sal,Kaa), 'T', 1.0_wp )
-         !
-         IF( lwp .AND. l_LB_debug ) THEN
-            WRITE(numout,*) 'Exiting tra_npc , kt = ',kt,', => numb. of statically instable water-columns: ', inpcc
-            WRITE(numout,*)
+         IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only for the full domain
+            IF( lwp .AND. l_LB_debug ) THEN
+               WRITE(numout,*) 'Exiting tra_npc , kt = ',kt,', => numb. of statically instable water-columns: ', nnpcc
+               WRITE(numout,*)
+            ENDIF
          ENDIF
          !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traqsr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traqsr.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/traqsr.F90	(revision 14055)
@@ -22,4 +22,5 @@
    USE phycst         ! physical constants
    USE dom_oce        ! ocean space and time domain
+   USE domain, ONLY : dom_tile
    USE sbc_oce        ! surface boundary condition: ocean
    USE trc_oce        ! share SMS/Ocean variables
@@ -107,5 +108,5 @@
       !
       INTEGER  ::   ji, jj, jk               ! dummy loop indices
-      INTEGER  ::   irgb                     ! local integers
+      INTEGER  ::   irgb, isi, iei, isj, iej ! local integers
       REAL(wp) ::   zchl, zcoef, z1_2        ! local scalars
       REAL(wp) ::   zc0 , zc1 , zc2 , zc3    !    -         -
@@ -120,12 +121,14 @@
       IF( ln_timing )   CALL timing_start('tra_qsr')
       !
-      IF( kt == nit000 ) THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_qsr : penetration of the surface solar radiation'
-         IF(lwp) WRITE(numout,*) '~~~~~~~'
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == nit000 ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_qsr : penetration of the surface solar radiation'
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+         ENDIF
       ENDIF
       !
       IF( l_trdtra ) THEN      ! trends diagnostic: save the input temperature trend
-         ALLOCATE( ztrdt(jpi,jpj,jpk) ) 
+         ALLOCATE( ztrdt(jpi,jpj,jpk) )
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
       ENDIF
@@ -134,16 +137,28 @@
       !                         !  before qsr induced heat content  !
       !                         !-----------------------------------!
+      ! NOTE: [tiling-comms-merge] Many DO loop bounds changed (probably more than necessary) to avoid changing results when using tiling. Some bounds were also adjusted to account for those changed in tra_atf
+      IF( ntsi == Nis0 ) THEN ; isi = nn_hls ; ELSE ; isi = 0 ; ENDIF    ! Avoid double-counting when using tiling
+      IF( ntsj == Njs0 ) THEN ; isj = nn_hls ; ELSE ; isj = 0 ; ENDIF
+      IF( ntei == Nie0 ) THEN ; iei = nn_hls ; ELSE ; iei = 0 ; ENDIF
+      IF( ntej == Nje0 ) THEN ; iej = nn_hls ; ELSE ; iej = 0 ; ENDIF
+
       IF( kt == nit000 ) THEN          !==  1st time step  ==!
          IF( ln_rstart .AND. iom_varid( numror, 'qsr_hc_b', ldstop = .FALSE. ) > 0  .AND. .NOT.l_1st_euler ) THEN    ! read in restart
-            IF(lwp) WRITE(numout,*) '          nit000-1 qsr tracer content forcing field read in the restart file'
             z1_2 = 0.5_wp
-            CALL iom_get( numror, jpdom_auto, 'qsr_hc_b', qsr_hc_b, ldxios = lrxios )   ! before heat content trend due to Qsr flux
+            IF( ntile == 0 .OR. ntile == 1 )  THEN                        ! Do only on the first tile
+               IF(lwp) WRITE(numout,*) '          nit000-1 qsr tracer content forcing field read in the restart file'
+               CALL iom_get( numror, jpdom_auto, 'qsr_hc_b', qsr_hc_b )   ! before heat content trend due to Qsr flux
+            ENDIF
          ELSE                                           ! No restart or restart not found: Euler forward time stepping
             z1_2 = 1._wp
-            qsr_hc_b(:,:,:) = 0._wp
+            DO_3D( isj, iej, isi, iei, 1, jpk )
+               qsr_hc_b(ji,jj,jk) = 0._wp
+            END_3D
          ENDIF
       ELSE                             !==  Swap of qsr heat content  ==!
          z1_2 = 0.5_wp
-         qsr_hc_b(:,:,:) = qsr_hc(:,:,:)
+         DO_3D( isj, iej, isi, iei, 1, jpk )
+            qsr_hc_b(ji,jj,jk) = qsr_hc(ji,jj,jk)
+         END_3D
       ENDIF
       !
@@ -154,16 +169,20 @@
       CASE( np_BIO )                   !==  bio-model fluxes  ==!
          !
-         DO jk = 1, nksr
-            qsr_hc(:,:,jk) = r1_rho0_rcp * ( etot3(:,:,jk) - etot3(:,:,jk+1) )
-         END DO
+         DO_3D( isj, iej, isi, iei, 1, nksr )
+            qsr_hc(ji,jj,jk) = r1_rho0_rcp * ( etot3(ji,jj,jk) - etot3(ji,jj,jk+1) )
+         END_3D
          !
       CASE( np_RGB , np_RGBc )         !==  R-G-B fluxes  ==!
          !
-         ALLOCATE( ze0 (jpi,jpj)           , ze1 (jpi,jpj) ,   &
-            &      ze2 (jpi,jpj)           , ze3 (jpi,jpj) ,   &
-            &      ztmp3d(jpi,jpj,nksr + 1)                     )
+         ALLOCATE( ze0 (A2D(nn_hls))           , ze1 (A2D(nn_hls)) ,   &
+            &      ze2 (A2D(nn_hls))           , ze3 (A2D(nn_hls)) ,   &
+            &      ztmp3d(A2D(nn_hls),nksr + 1)                     )
          !
          IF( nqsr == np_RGBc ) THEN          !*  Variable Chlorophyll
-            CALL fld_read( kt, 1, sf_chl )         ! Read Chl data and provides it at the current time step
+            IF( ntile == 0 .OR. ntile == 1 )  THEN                                         ! Do only for the full domain
+               IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )            ! Use full domain
+               CALL fld_read( kt, 1, sf_chl )         ! Read Chl data and provides it at the current time step
+               IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 1 )            ! Revert to tile domain
+            ENDIF
             !
             ! Separation in R-G-B depending on the surface Chl
@@ -172,5 +191,5 @@
             ! most expensive calculations)
             !
-            DO_2D( 0, 0, 0, 0 )
+            DO_2D( isj, iej, isi, iei )
                        ! zlogc = log(zchl)
                zlogc = LOG ( MIN( 10. , MAX( 0.03, sf_chl(1)%fnow(ji,jj,1) ) ) )     
@@ -191,5 +210,5 @@
             
 !
-            DO_3D( 0, 0, 0, 0, 1, nksr + 1 )
+            DO_3D( isj, iej, isi, iei, 1, nksr + 1 )
                ! zchl    = ALOG( ze0(ji,jj) )
                zlogc = ze0(ji,jj)
@@ -216,10 +235,10 @@
             zlui = 41 + 20.*LOG10(zchl) + 1.e-15
             DO jk = 1, nksr + 1
-               ztmp3d(:,:,jk) = zlui 
+               ztmp3d(:,:,jk) = zlui
             END DO
          ENDIF
          !
          zcoef  = ( 1. - rn_abs ) / 3._wp    !* surface equi-partition in R-G-B
-         DO_2D( 0, 0, 0, 0 )
+         DO_2D( isj, iej, isi, iei )
             ze0(ji,jj) = rn_abs * qsr(ji,jj)
             ze1(ji,jj) = zcoef  * qsr(ji,jj)
@@ -232,5 +251,5 @@
          !
          !                                    !* interior equi-partition in R-G-B depending on vertical profile of Chl
-         DO_3D( 0, 0, 0, 0, 2, nksr + 1 )
+         DO_3D( isj, iej, isi, iei, 2, nksr + 1 )
             ze3t = e3t(ji,jj,jk-1,Kmm)
             irgb = NINT( ztmp3d(ji,jj,jk) )
@@ -246,5 +265,5 @@
          END_3D
          !
-         DO_3D( 0, 0, 0, 0, 1, nksr )          !* now qsr induced heat content
+         DO_3D( isj, iej, isi, iei, 1, nksr )          !* now qsr induced heat content
             qsr_hc(ji,jj,jk) = r1_rho0_rcp * ( ztmp3d(ji,jj,jk) - ztmp3d(ji,jj,jk+1) )
          END_3D
@@ -256,5 +275,5 @@
          zz0 =        rn_abs   * r1_rho0_rcp      ! surface equi-partition in 2-bands
          zz1 = ( 1. - rn_abs ) * r1_rho0_rcp
-         DO_3D( 0, 0, 0, 0, 1, nksr )             ! solar heat absorbed at T-point in the top 400m 
+         DO_3D( isj, iej, isi, iei, 1, nksr )          !* now qsr induced heat content
             zc0 = zz0 * EXP( -gdepw(ji,jj,jk  ,Kmm)*xsi0r ) + zz1 * EXP( -gdepw(ji,jj,jk  ,Kmm)*xsi1r )
             zc1 = zz0 * EXP( -gdepw(ji,jj,jk+1,Kmm)*xsi0r ) + zz1 * EXP( -gdepw(ji,jj,jk+1,Kmm)*xsi1r )
@@ -274,26 +293,28 @@
       !
       ! sea-ice: store the 1st ocean level attenuation coefficient
-      DO_2D( 0, 0, 0, 0 )
+      DO_2D( isj, iej, isi, iei )
          IF( qsr(ji,jj) /= 0._wp ) THEN   ;   fraqsr_1lev(ji,jj) = qsr_hc(ji,jj,1) / ( r1_rho0_rcp * qsr(ji,jj) )
          ELSE                             ;   fraqsr_1lev(ji,jj) = 1._wp
          ENDIF
       END_2D
-      CALL lbc_lnk( 'traqsr', fraqsr_1lev(:,:), 'T', 1._wp )
-      !
-      IF( iom_use('qsr3d') ) THEN      ! output the shortwave Radiation distribution
-         ALLOCATE( zetot(jpi,jpj,jpk) )
-         zetot(:,:,nksr+1:jpk) = 0._wp     ! below ~400m set to zero
-         DO jk = nksr, 1, -1
-            zetot(:,:,jk) = zetot(:,:,jk+1) + qsr_hc(:,:,jk) * rho0_rcp
-         END DO         
-         CALL iom_put( 'qsr3d', zetot )   ! 3D distribution of shortwave Radiation
-         DEALLOCATE( zetot ) 
-      ENDIF
-      !
-      IF( lrst_oce ) THEN     ! write in the ocean restart file
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'qsr_hc_b'   , qsr_hc     , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'fraqsr_1lev', fraqsr_1lev, ldxios = lwxios ) 
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      !
+      ! TEMP: [tiling] This change not necessary and working array can use A2D(nn_hls) if using XIOS (subdomain support)
+      IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only for the full domain
+         IF( iom_use('qsr3d') ) THEN      ! output the shortwave Radiation distribution
+            ALLOCATE( zetot(jpi,jpj,jpk) )
+            zetot(:,:,nksr+1:jpk) = 0._wp     ! below ~400m set to zero
+            DO jk = nksr, 1, -1
+               zetot(:,:,jk) = zetot(:,:,jk+1) + qsr_hc(:,:,jk) * rho0_rcp
+            END DO
+            CALL iom_put( 'qsr3d', zetot )   ! 3D distribution of shortwave Radiation
+            DEALLOCATE( zetot )
+         ENDIF
+      ENDIF
+      !
+      IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+         IF( lrst_oce ) THEN     ! write in the ocean restart file
+            CALL iom_rstput( kt, nitrst, numrow, 'qsr_hc_b'   , qsr_hc      )
+            CALL iom_rstput( kt, nitrst, numrow, 'fraqsr_1lev', fraqsr_1lev )
+         ENDIF
       ENDIF
       !
@@ -301,5 +322,5 @@
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs) - ztrdt(:,:,:)
          CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_qsr, ztrdt )
-         DEALLOCATE( ztrdt ) 
+         DEALLOCATE( ztrdt )
       ENDIF
       !                       ! print mean trends (used for debugging)
@@ -431,14 +452,9 @@
       ! 1st ocean level attenuation coefficient (used in sbcssm)
       IF( iom_varid( numror, 'fraqsr_1lev', ldstop = .FALSE. ) > 0 ) THEN
-         CALL iom_get( numror, jpdom_auto, 'fraqsr_1lev'  , fraqsr_1lev, ldxios = lrxios  )
+         CALL iom_get( numror, jpdom_auto, 'fraqsr_1lev'  , fraqsr_1lev  )
       ELSE
          fraqsr_1lev(:,:) = 1._wp   ! default : no penetration
       ENDIF
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('qsr_hc_b')
-         CALL iom_set_rstw_var_active('fraqsr_1lev')
-      ENDIF
-      !
    END SUBROUTINE tra_qsr_init
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trasbc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trasbc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trasbc.F90	(revision 14055)
@@ -76,7 +76,7 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts        ! active tracers and RHS of tracer equation
       !
-      INTEGER  ::   ji, jj, jk, jn              ! dummy loop indices  
-      INTEGER  ::   ikt, ikb                    ! local integers
-      REAL(wp) ::   zfact, z1_e3t, zdep, ztim   ! local scalar
+      INTEGER  ::   ji, jj, jk, jn               ! dummy loop indices
+      INTEGER  ::   ikt, ikb, isi, iei, isj, iej ! local integers
+      REAL(wp) ::   zfact, z1_e3t, zdep, ztim    ! local scalar
       REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  ztrdt, ztrds
       !!----------------------------------------------------------------------
@@ -84,20 +84,30 @@
       IF( ln_timing )   CALL timing_start('tra_sbc')
       !
-      IF( kt == nit000 ) THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_sbc : TRAcer Surface Boundary Condition'
-         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == nit000 ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_sbc : TRAcer Surface Boundary Condition'
+            IF(lwp) WRITE(numout,*) '~~~~~~~ '
+         ENDIF
       ENDIF
       !
       IF( l_trdtra ) THEN                    !* Save ta and sa trends
-         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) ) 
+         ALLOCATE( ztrdt(jpi,jpj,jpk), ztrds(jpi,jpj,jpk) )
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs)
          ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs)
       ENDIF
       !
+      ! NOTE: [tiling-comms-merge] Many DO loop bounds changed to avoid changing results when using tiling. Some bounds were also adjusted to account for those changed in tra_atf
+      IF( ntsi == Nis0 ) THEN ; isi = nn_hls ; ELSE ; isi = 0 ; ENDIF    ! Avoid double-counting when using tiling
+      IF( ntsj == Njs0 ) THEN ; isj = nn_hls ; ELSE ; isj = 0 ; ENDIF
+      IF( ntei == Nie0 ) THEN ; iei = nn_hls ; ELSE ; iei = 0 ; ENDIF
+      IF( ntej == Nje0 ) THEN ; iej = nn_hls ; ELSE ; iej = 0 ; ENDIF
+
 !!gm  This should be moved into sbcmod.F90 module ? (especially now that ln_traqsr is read in namsbc namelist)
       IF( .NOT.ln_traqsr ) THEN     ! no solar radiation penetration
-         qns(:,:) = qns(:,:) + qsr(:,:)      ! total heat flux in qns
-         qsr(:,:) = 0._wp                     ! qsr set to zero
+         DO_2D( isj, iej, isi, iei )
+            qns(ji,jj) = qns(ji,jj) + qsr(ji,jj)      ! total heat flux in qns
+            qsr(ji,jj) = 0._wp                        ! qsr set to zero
+         END_2D
       ENDIF
 
@@ -109,34 +119,43 @@
          IF( ln_rstart .AND.    &               ! Restart: read in restart file
               & iom_varid( numror, 'sbc_hc_b', ldstop = .FALSE. ) > 0 ) THEN
-            IF(lwp) WRITE(numout,*) '          nit000-1 sbc tracer content field read in the restart file'
             zfact = 0.5_wp
-            sbc_tsc(:,:,:) = 0._wp
-            CALL iom_get( numror, jpdom_auto, 'sbc_hc_b', sbc_tsc_b(:,:,jp_tem), ldxios = lrxios )   ! before heat content sbc trend
-            CALL iom_get( numror, jpdom_auto, 'sbc_sc_b', sbc_tsc_b(:,:,jp_sal), ldxios = lrxios )   ! before salt content sbc trend
+            IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+               IF(lwp) WRITE(numout,*) '          nit000-1 sbc tracer content field read in the restart file'
+               sbc_tsc(:,:,:) = 0._wp
+               CALL iom_get( numror, jpdom_auto, 'sbc_hc_b', sbc_tsc_b(:,:,jp_tem) )   ! before heat content sbc trend
+               CALL iom_get( numror, jpdom_auto, 'sbc_sc_b', sbc_tsc_b(:,:,jp_sal) )   ! before salt content sbc trend
+            ENDIF
          ELSE                                   ! No restart or restart not found: Euler forward time stepping
             zfact = 1._wp
-            sbc_tsc(:,:,:) = 0._wp
-            sbc_tsc_b(:,:,:) = 0._wp
+            DO_2D( isj, iej, isi, iei )
+               sbc_tsc(ji,jj,:) = 0._wp
+               sbc_tsc_b(ji,jj,:) = 0._wp
+            END_2D
          ENDIF
       ELSE                                !* other time-steps: swap of forcing fields
          zfact = 0.5_wp
-         sbc_tsc_b(:,:,:) = sbc_tsc(:,:,:)
+         DO_2D( isj, iej, isi, iei )
+            sbc_tsc_b(ji,jj,:) = sbc_tsc(ji,jj,:)
+         END_2D
       ENDIF
       !                             !==  Now sbc tracer content fields  ==!
-      DO_2D( 0, 1, 0, 0 )
+      DO_2D( isj, iej, isi, iei )
          sbc_tsc(ji,jj,jp_tem) = r1_rho0_rcp * qns(ji,jj)   ! non solar heat flux
          sbc_tsc(ji,jj,jp_sal) = r1_rho0     * sfx(ji,jj)   ! salt flux due to freezing/melting
       END_2D
       IF( ln_linssh ) THEN                !* linear free surface  
-         DO_2D( 0, 1, 0, 0 )                    !==>> add concentration/dilution effect due to constant volume cell
+         DO_2D( isj, iej, isi, iei )                    !==>> add concentration/dilution effect due to constant volume cell
             sbc_tsc(ji,jj,jp_tem) = sbc_tsc(ji,jj,jp_tem) + r1_rho0 * emp(ji,jj) * pts(ji,jj,1,jp_tem,Kmm)
             sbc_tsc(ji,jj,jp_sal) = sbc_tsc(ji,jj,jp_sal) + r1_rho0 * emp(ji,jj) * pts(ji,jj,1,jp_sal,Kmm)
          END_2D                                 !==>> output c./d. term
-         IF( iom_use('emp_x_sst') )   CALL iom_put( "emp_x_sst", emp (:,:) * pts(:,:,1,jp_tem,Kmm) )
-         IF( iom_use('emp_x_sss') )   CALL iom_put( "emp_x_sss", emp (:,:) * pts(:,:,1,jp_sal,Kmm) )
+         IF( ntile == 0 .OR. ntile == nijtile )  THEN             ! Do only on the last tile
+            IF( iom_use('emp_x_sst') )   CALL iom_put( "emp_x_sst", emp (:,:) * pts(:,:,1,jp_tem,Kmm) )
+            IF( iom_use('emp_x_sss') )   CALL iom_put( "emp_x_sss", emp (:,:) * pts(:,:,1,jp_sal,Kmm) )
+         ENDIF
       ENDIF
       !
       DO jn = 1, jpts               !==  update tracer trend  ==!
-         DO_2D( 0, 1, 0, 0 )
+         ! NOTE: [tiling-comms-merge] This looped over nn_hls, which changes the results when using tiling
+         DO_2D( 0, 0, 0, 0 )
             pts(ji,jj,1,jn,Krhs) = pts(ji,jj,1,jn,Krhs) + zfact * ( sbc_tsc_b(ji,jj,jn) + sbc_tsc(ji,jj,jn) )    &
                &                                                / e3t(ji,jj,1,Kmm)
@@ -144,9 +163,9 @@
       END DO
       !                  
-      IF( lrst_oce ) THEN           !==  write sbc_tsc in the ocean restart file  ==!
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'sbc_hc_b', sbc_tsc(:,:,jp_tem), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'sbc_sc_b', sbc_tsc(:,:,jp_sal), ldxios = lwxios )
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+         IF( lrst_oce ) THEN           !==  write sbc_tsc in the ocean restart file  ==!
+            CALL iom_rstput( kt, nitrst, numrow, 'sbc_hc_b', sbc_tsc(:,:,jp_tem) )
+            CALL iom_rstput( kt, nitrst, numrow, 'sbc_sc_b', sbc_tsc(:,:,jp_sal) )
+         ENDIF
       ENDIF
       !
@@ -157,5 +176,5 @@
       IF( ln_rnf ) THEN         ! input of heat and salt due to river runoff 
          zfact = 0.5_wp
-         DO_2D( 0, 1, 0, 0 )
+         DO_2D( 0, 0, 0, 0 )
             IF( rnf(ji,jj) /= 0._wp ) THEN
                zdep = zfact / h_rnf(ji,jj)
@@ -170,6 +189,8 @@
       ENDIF
 
-      IF( iom_use('rnf_x_sst') )   CALL iom_put( "rnf_x_sst", rnf*pts(:,:,1,jp_tem,Kmm) )   ! runoff term on sst
-      IF( iom_use('rnf_x_sss') )   CALL iom_put( "rnf_x_sss", rnf*pts(:,:,1,jp_sal,Kmm) )   ! runoff term on sss
+      IF( ntile == 0 .OR. ntile == nijtile )  THEN                ! Do only on the last tile
+         IF( iom_use('rnf_x_sst') )   CALL iom_put( "rnf_x_sst", rnf*pts(:,:,1,jp_tem,Kmm) )   ! runoff term on sst
+         IF( iom_use('rnf_x_sss') )   CALL iom_put( "rnf_x_sss", rnf*pts(:,:,1,jp_sal,Kmm) )   ! runoff term on sss
+      ENDIF
 
 #if defined key_asminc
@@ -182,5 +203,5 @@
       	 !
          IF( ln_linssh ) THEN 
-            DO_2D( 0, 1, 0, 0 )
+            DO_2D( 0, 0, 0, 0 )
                ztim = ssh_iau(ji,jj) / e3t(ji,jj,1,Kmm)
                pts(ji,jj,1,jp_tem,Krhs) = pts(ji,jj,1,jp_tem,Krhs) + pts(ji,jj,1,jp_tem,Kmm) * ztim
@@ -188,5 +209,5 @@
             END_2D
          ELSE
-            DO_2D( 0, 1, 0, 0 )
+            DO_2D( 0, 0, 0, 0 )
                ztim = ssh_iau(ji,jj) / ( ht(ji,jj) + 1. - ssmask(ji, jj) )
                pts(ji,jj,:,jp_tem,Krhs) = pts(ji,jj,:,jp_tem,Krhs) + pts(ji,jj,:,jp_tem,Kmm) * ztim
@@ -204,5 +225,5 @@
          CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_nsr, ztrdt )
          CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_nsr, ztrds )
-         DEALLOCATE( ztrdt , ztrds ) 
+         DEALLOCATE( ztrdt , ztrds )
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trazdf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trazdf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/trazdf.F90	(revision 14055)
@@ -13,8 +13,9 @@
    !!----------------------------------------------------------------------
    USE oce            ! ocean dynamics and tracers variables
-   USE dom_oce        ! ocean space and time domain variables 
+   USE dom_oce        ! ocean space and time domain variables
    USE domvvl         ! variable volume
    USE phycst         ! physical constant
    USE zdf_oce        ! ocean vertical physics variables
+   USE zdfmfc         ! Mass FLux Convection 
    USE sbc_oce        ! surface boundary condition: ocean
    USE ldftra         ! lateral diffusion: eddy diffusivity
@@ -55,5 +56,5 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts                 ! active tracers and RHS of tracer equation
       !
-      INTEGER  ::   jk   ! Dummy loop indices
+      INTEGER  ::   ji, jj, jk   ! Dummy loop indices
       REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds   ! 3D workspace
       !!---------------------------------------------------------------------
@@ -62,11 +63,13 @@
       !
       IF( kt == nit000 )  THEN
-         IF(lwp)WRITE(numout,*)
-         IF(lwp)WRITE(numout,*) 'tra_zdf : implicit vertical mixing on T & S'
-         IF(lwp)WRITE(numout,*) '~~~~~~~ '
+         IF( ntile == 0 .OR. ntile == 1 )  THEN                   ! Do only on the first tile
+            IF(lwp)WRITE(numout,*)
+            IF(lwp)WRITE(numout,*) 'tra_zdf : implicit vertical mixing on T & S'
+            IF(lwp)WRITE(numout,*) '~~~~~~~ '
+         ENDIF
       ENDIF
       !
       IF( l_trdtra )   THEN                  !* Save ta and sa trends
-         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ALLOCATE( ztrdt(jpi,jpj,jpk), ztrds(jpi,jpj,jpk) )
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Kaa)
          ztrds(:,:,:) = pts(:,:,:,jp_sal,Kaa)
@@ -80,9 +83,9 @@
       ! JMM avoid negative salinities near river outlet ! Ugly fix
       ! JMM : restore negative salinities to small salinities:
-      WHERE( pts(:,:,:,jp_sal,Kaa) < 0._wp )   pts(:,:,:,jp_sal,Kaa) = 0.1_wp
+      WHERE( pts(A2D(0),:,jp_sal,Kaa) < 0._wp )   pts(A2D(0),:,jp_sal,Kaa) = 0.1_wp
 !!gm
 
       IF( l_trdtra )   THEN                      ! save the vertical diffusive trends for further diagnostics
-         DO jk = 1, jpkm1
+         DO jk = 1, jpk
             ztrdt(:,:,jk) = (   (  pts(:,:,jk,jp_tem,Kaa)*e3t(:,:,jk,Kaa)     &
                &                 - pts(:,:,jk,jp_tem,Kbb)*e3t(:,:,jk,Kbb)  )  &
@@ -94,4 +97,5 @@
                &          - ztrds(:,:,jk)
          END DO
+         ! NOTE: [tiling-comms-merge] The diagnostic results change along the north fold if this is removed
 !!gm this should be moved in trdtra.F90 and done on all trends
          CALL lbc_lnk_multi( 'trazdf', ztrdt, 'T', 1.0_wp , ztrds, 'T', 1.0_wp )
@@ -140,5 +144,5 @@
       INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
       REAL(wp) ::  zrhs, zzwi, zzws ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zwi, zwt, zwd, zws
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::  zwi, zwt, zwd, zws
       !!---------------------------------------------------------------------
       !
@@ -154,6 +158,12 @@
             !
             ! vertical mixing coef.: avt for temperature, avs for salinity and passive tracers
-            IF( cdtype == 'TRA' .AND. jn == jp_tem ) THEN   ;   zwt(:,:,2:jpk) = avt(:,:,2:jpk)
-            ELSE                                            ;   zwt(:,:,2:jpk) = avs(:,:,2:jpk)
+            IF( cdtype == 'TRA' .AND. jn == jp_tem ) THEN
+               DO_3D( 1, 1, 1, 1, 2, jpk )
+                  zwt(ji,jj,jk) = avt(ji,jj,jk)
+               END_3D
+            ELSE
+               DO_3D( 1, 1, 1, 1, 2, jpk )
+                  zwt(ji,jj,jk) = avs(ji,jj,jk)
+               END_3D
             ENDIF
             zwt(:,:,1) = 0._wp
@@ -189,4 +199,9 @@
             ENDIF
             !
+            ! Modification of diagonal to add MF scheme
+            IF ( ln_zdfmfc ) THEN
+               CALL diag_mfc( zwi, zwd, zws, p2dt, Kaa )
+            END IF
+            !
             !! Matrix inversion from the first level
             !!----------------------------------------------------------------------
@@ -217,10 +232,15 @@
          ENDIF 
          !         
+         ! Modification of rhs to add MF scheme
+         IF ( ln_zdfmfc ) THEN
+            CALL rhs_mfc( pt(:,:,:,jn,Krhs), jn )
+         END IF
+         !
          DO_2D( 0, 0, 0, 0 )         !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
             pt(ji,jj,1,jn,Kaa) =        e3t(ji,jj,1,Kbb) * pt(ji,jj,1,jn,Kbb)    &
-               &               + p2dt * e3t(ji,jj,1,Kmm) * pt(ji,jj,1,jn,Krhs)
+               &               + p2dt * e3t(ji,jj,1,Kmm) * pt(ji,jj,1,jn,Krhs) 
          END_2D
          DO_3D( 0, 0, 0, 0, 2, jpkm1 )
-            zrhs =        e3t(ji,jj,jk,Kbb) * pt(ji,jj,jk,jn,Kbb)    & 
+            zrhs =        e3t(ji,jj,jk,Kbb) * pt(ji,jj,jk,jn,Kbb)    &
                & + p2dt * e3t(ji,jj,jk,Kmm) * pt(ji,jj,jk,jn,Krhs)   ! zrhs=right hand side
             pt(ji,jj,jk,jn,Kaa) = zrhs - zwi(ji,jj,jk) / zwt(ji,jj,jk-1) * pt(ji,jj,jk-1,jn,Kaa)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/zpshde.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/zpshde.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRA/zpshde.F90	(revision 14055)
@@ -17,4 +17,5 @@
    USE oce             ! ocean: dynamics and tracers variables
    USE dom_oce         ! domain: ocean variables
+   USE domutl, ONLY : is_tile
    USE phycst          ! physical constants
    USE eosbn2          ! ocean equation of state
@@ -40,6 +41,27 @@
 CONTAINS
 
-   SUBROUTINE zps_hde( kt, Kmm, kjpt, pta, pgtu, pgtv,   &
-      &                          prd, pgru, pgrv    )
+   SUBROUTINE zps_hde( kt, Kmm, kjpt, pta, pgtu, pgtv,  &
+      &                               prd, pgru, pgrv )
+      !!
+      INTEGER                     , INTENT(in   )           ::  kt          ! ocean time-step index
+      INTEGER                     , INTENT(in   )           ::  Kmm         ! ocean time level index
+      INTEGER                     , INTENT(in   )           ::  kjpt        ! number of tracers
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout)           ::  pta         ! 4D tracers fields
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out)           ::  pgtu, pgtv  ! hor. grad. of ptra at u- & v-pts
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout), OPTIONAL ::  prd         ! 3D density anomaly fields
+      REAL(wp), DIMENSION(:,:)    , INTENT(  out), OPTIONAL ::  pgru, pgrv  ! hor. grad of prd at u- & v-pts (bottom)
+      !
+      INTEGER :: itrd, itgr
+      !!
+      IF( PRESENT(prd)  ) THEN ; itrd = is_tile(prd)  ; ELSE ; itrd = 0 ; ENDIF
+      IF( PRESENT(pgru) ) THEN ; itgr = is_tile(pgru) ; ELSE ; itgr = 0 ; ENDIF
+
+      CALL zps_hde_t( kt, Kmm, kjpt, pta, is_tile(pta), pgtu, pgtv, is_tile(pgtu), &
+         &                           prd, itrd,         pgru, pgrv, itgr )
+   END SUBROUTINE zps_hde
+
+
+   SUBROUTINE zps_hde_t( kt, Kmm, kjpt, pta, ktta, pgtu, pgtv, ktgt,   &
+      &                                 prd, ktrd, pgru, pgrv, ktgr )
       !!----------------------------------------------------------------------
       !!                     ***  ROUTINE zps_hde  ***
@@ -85,20 +107,26 @@
       !!              - pgru, pgrv: horizontal gradient of rho (if present) at u- & v-points
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   )           ::  kt          ! ocean time-step index
-      INTEGER                              , INTENT(in   )           ::  Kmm         ! ocean time level index
-      INTEGER                              , INTENT(in   )           ::  kjpt        ! number of tracers
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   )           ::  pta         ! 4D tracers fields
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(  out)           ::  pgtu, pgtv  ! hor. grad. of ptra at u- & v-pts 
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ), OPTIONAL ::  prd         ! 3D density anomaly fields
-      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgru, pgrv  ! hor. grad of prd at u- & v-pts (bottom)
+      INTEGER                                , INTENT(in   )           ::  kt          ! ocean time-step index
+      INTEGER                                , INTENT(in   )           ::  Kmm         ! ocean time level index
+      INTEGER                                , INTENT(in   )           ::  kjpt        ! number of tracers
+      INTEGER                                , INTENT(in   )           ::  ktta, ktgt, ktrd, ktgr
+      REAL(wp), DIMENSION(A2D_T(ktta),JPK,KJPT), INTENT(inout)           ::  pta         ! 4D tracers fields
+      REAL(wp), DIMENSION(A2D_T(ktgt)    ,KJPT), INTENT(  out)           ::  pgtu, pgtv  ! hor. grad. of ptra at u- & v-pts
+      REAL(wp), DIMENSION(A2D_T(ktrd),JPK     ), INTENT(inout), OPTIONAL ::  prd         ! 3D density anomaly fields
+      REAL(wp), DIMENSION(A2D_T(ktgr)         ), INTENT(  out), OPTIONAL ::  pgru, pgrv  ! hor. grad of prd at u- & v-pts (bottom)
       !
       INTEGER  ::   ji, jj, jn                  ! Dummy loop indices
       INTEGER  ::   iku, ikv, ikum1, ikvm1      ! partial step level (ocean bottom level) at u- and v-points
       REAL(wp) ::   ze3wu, ze3wv, zmaxu, zmaxv  ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj)      ::   zri, zrj, zhi, zhj   ! NB: 3rd dim=1 to use eos
-      REAL(wp), DIMENSION(jpi,jpj,kjpt) ::   zti, ztj             ! 
+      REAL(wp), DIMENSION(A2D(nn_hls))      ::   zri, zrj, zhi, zhj   ! NB: 3rd dim=1 to use eos
+      REAL(wp), DIMENSION(A2D(nn_hls),kjpt) ::   zti, ztj             !
       !!----------------------------------------------------------------------
       !
       IF( ln_timing )   CALL timing_start( 'zps_hde')
+      ! NOTE: [tiling-comms-merge] Some lbc_lnks in tra_adv and tra_ldf can be taken out in the zps case, because this lbc_lnk is called when zps_hde is called in the stp routine. In the zco case they are still needed.
+      IF (nn_hls.EQ.2) THEN
+         CALL lbc_lnk( 'zpshde', pta, 'T', 1.0_wp)
+         IF(PRESENT(prd)) CALL lbc_lnk( 'zpshde', prd, 'T', 1.0_wp)
+      END IF
       !
       pgtu(:,:,:) = 0._wp   ;   zti (:,:,:) = 0._wp   ;   zhi (:,:) = 0._wp
@@ -107,5 +135,5 @@
       DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!
          !
-         DO_2D( 1, 0, 1, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )              ! Gradient of density at the last level
             iku = mbku(ji,jj)   ;   ikum1 = MAX( iku - 1 , 1 )    ! last and before last ocean level at u- & v-points
             ikv = mbkv(ji,jj)   ;   ikvm1 = MAX( ikv - 1 , 1 )    ! if level first is a p-step, ik.m1=1
@@ -146,10 +174,10 @@
       END DO
       !
-      CALL lbc_lnk_multi( 'zpshde', pgtu(:,:,:), 'U', -1.0_wp , pgtv(:,:,:), 'V', -1.0_wp )   ! Lateral boundary cond.
+      IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'zpshde', pgtu(:,:,:), 'U', -1.0_wp , pgtv(:,:,:), 'V', -1.0_wp )   ! Lateral boundary cond.
       !                
       IF( PRESENT( prd ) ) THEN    !==  horizontal derivative of density anomalies (rd)  ==!    (optional part)
          pgru(:,:) = 0._wp
          pgrv(:,:) = 0._wp                ! depth of the partial step level
-         DO_2D( 1, 0, 1, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
             iku = mbku(ji,jj)
             ikv = mbkv(ji,jj)
@@ -167,5 +195,5 @@
          CALL eos( ztj, zhj, zrj )        ! at the partial step depth output in  zri, zrj 
          !
-         DO_2D( 1, 0, 1, 0 )              ! Gradient of density at the last level
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )              ! Gradient of density at the last level
             iku = mbku(ji,jj)
             ikv = mbkv(ji,jj)
@@ -179,5 +207,5 @@
             ENDIF
          END_2D
-         CALL lbc_lnk_multi( 'zpshde', pgru , 'U', -1.0_wp , pgrv , 'V', -1.0_wp )   ! Lateral boundary conditions
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'zpshde', pgru , 'U', -1.0_wp , pgrv , 'V', -1.0_wp )   ! Lateral boundary conditions
          !
       END IF
@@ -185,9 +213,33 @@
       IF( ln_timing )   CALL timing_stop( 'zps_hde')
       !
-   END SUBROUTINE zps_hde
+   END SUBROUTINE zps_hde_t
 
 
    SUBROUTINE zps_hde_isf( kt, Kmm, kjpt, pta, pgtu, pgtv, pgtui, pgtvi,  &
-      &                          prd, pgru, pgrv, pgrui, pgrvi )
+      &                                   prd, pgru, pgrv, pgrui, pgrvi )
+      !!
+      INTEGER                     , INTENT(in   )           ::  kt           ! ocean time-step index
+      INTEGER                     , INTENT(in   )           ::  Kmm          ! ocean time level index
+      INTEGER                     , INTENT(in   )           ::  kjpt         ! number of tracers
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout)           ::  pta          ! 4D tracers fields
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out)           ::  pgtu, pgtv   ! hor. grad. of ptra at u- & v-pts
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out)           ::  pgtui, pgtvi ! hor. grad. of stra at u- & v-pts (ISF)
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout), OPTIONAL ::  prd          ! 3D density anomaly fields
+      REAL(wp), DIMENSION(:,:)    , INTENT(  out), OPTIONAL ::  pgru, pgrv   ! hor. grad of prd at u- & v-pts (bottom)
+      REAL(wp), DIMENSION(:,:)    , INTENT(  out), OPTIONAL ::  pgrui, pgrvi ! hor. grad of prd at u- & v-pts (top)
+      !
+      INTEGER :: itrd, itgr, itgri
+      !!
+      IF( PRESENT(prd)   ) THEN ; itrd  = is_tile(prd)   ; ELSE ; itrd  = 0 ; ENDIF
+      IF( PRESENT(pgru)  ) THEN ; itgr  = is_tile(pgru)  ; ELSE ; itgr  = 0 ; ENDIF
+      IF( PRESENT(pgrui) ) THEN ; itgri = is_tile(pgrui) ; ELSE ; itgri = 0 ; ENDIF
+
+      CALL zps_hde_isf_t( kt, Kmm, kjpt, pta, is_tile(pta), pgtu, pgtv, is_tile(pgtu), pgtui, pgtvi, is_tile(pgtui),  &
+      &                                  prd, itrd,         pgru, pgrv, itgr,          pgrui, pgrvi, itgri )
+   END SUBROUTINE zps_hde_isf
+
+
+   SUBROUTINE zps_hde_isf_t( kt, Kmm, kjpt, pta, ktta, pgtu, pgtv, ktgt, pgtui, pgtvi, ktgti,  &
+      &                                     prd, ktrd, pgru, pgrv, ktgr, pgrui, pgrvi, ktgri )
       !!----------------------------------------------------------------------
       !!                     ***  ROUTINE zps_hde_isf  ***
@@ -236,23 +288,29 @@
       !!              - pgru, pgrv, pgrui, pgtvi: horizontal gradient of rho (if present) at u- & v-points
       !!----------------------------------------------------------------------
-      INTEGER                              , INTENT(in   )           ::  kt           ! ocean time-step index
-      INTEGER                              , INTENT(in   )           ::  Kmm          ! ocean time level index
-      INTEGER                              , INTENT(in   )           ::  kjpt         ! number of tracers
-      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   )           ::  pta          ! 4D tracers fields
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(  out)           ::  pgtu, pgtv   ! hor. grad. of ptra at u- & v-pts 
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(  out)           ::  pgtui, pgtvi ! hor. grad. of stra at u- & v-pts (ISF)
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ), OPTIONAL ::  prd          ! 3D density anomaly fields
-      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgru, pgrv   ! hor. grad of prd at u- & v-pts (bottom)
-      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgrui, pgrvi ! hor. grad of prd at u- & v-pts (top)
+      INTEGER                                , INTENT(in   )           ::  kt           ! ocean time-step index
+      INTEGER                                , INTENT(in   )           ::  Kmm          ! ocean time level index
+      INTEGER                                , INTENT(in   )           ::  kjpt         ! number of tracers
+      INTEGER                                , INTENT(in   )           ::  ktta, ktgt, ktgti, ktrd, ktgr, ktgri
+      REAL(wp), DIMENSION(A2D_T(ktta),JPK,KJPT), INTENT(inout)           ::  pta          ! 4D tracers fields
+      REAL(wp), DIMENSION(A2D_T(ktgt)    ,KJPT), INTENT(  out)           ::  pgtu, pgtv   ! hor. grad. of ptra at u- & v-pts
+      REAL(wp), DIMENSION(A2D_T(ktgti)   ,KJPT), INTENT(  out)           ::  pgtui, pgtvi ! hor. grad. of stra at u- & v-pts (ISF)
+      REAL(wp), DIMENSION(A2D_T(ktrd),JPK     ), INTENT(inout), OPTIONAL ::  prd          ! 3D density anomaly fields
+      REAL(wp), DIMENSION(A2D_T(ktgr)         ), INTENT(  out), OPTIONAL ::  pgru, pgrv   ! hor. grad of prd at u- & v-pts (bottom)
+      REAL(wp), DIMENSION(A2D_T(ktgri)        ), INTENT(  out), OPTIONAL ::  pgrui, pgrvi ! hor. grad of prd at u- & v-pts (top)
       !
       INTEGER  ::   ji, jj, jn      ! Dummy loop indices
       INTEGER  ::   iku, ikv, ikum1, ikvm1,ikup1, ikvp1   ! partial step level (ocean bottom level) at u- and v-points
       REAL(wp) ::  ze3wu, ze3wv, zmaxu, zmaxv             ! temporary scalars
-      REAL(wp), DIMENSION(jpi,jpj)      ::  zri, zrj, zhi, zhj   ! NB: 3rd dim=1 to use eos
-      REAL(wp), DIMENSION(jpi,jpj,kjpt) ::  zti, ztj             ! 
+      REAL(wp), DIMENSION(A2D(nn_hls))      ::  zri, zrj, zhi, zhj   ! NB: 3rd dim=1 to use eos
+      REAL(wp), DIMENSION(A2D(nn_hls),kjpt) ::  zti, ztj             !
       !!----------------------------------------------------------------------
       !
       IF( ln_timing )   CALL timing_start( 'zps_hde_isf')
       !
+      IF (nn_hls.EQ.2) THEN
+         CALL lbc_lnk( 'zpshde', pta, 'T', 1.0_wp)
+         IF (PRESENT(prd)) CALL lbc_lnk( 'zpshde', prd, 'T', 1.0_wp)
+      END IF
+
       pgtu (:,:,:) = 0._wp   ;   pgtv (:,:,:) =0._wp
       pgtui(:,:,:) = 0._wp   ;   pgtvi(:,:,:) =0._wp
@@ -262,5 +320,5 @@
       DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!
          !
-         DO_2D( 1, 0, 1, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
 
             iku = mbku(ji,jj); ikum1 = MAX( iku - 1 , 1 )    ! last and before last ocean level at u- & v-points
@@ -302,5 +360,5 @@
       END DO
       !
-      CALL lbc_lnk_multi( 'zpshde', pgtu(:,:,:), 'U', -1.0_wp , pgtv(:,:,:), 'V', -1.0_wp )   ! Lateral boundary cond.
+      IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'zpshde', pgtu(:,:,:), 'U', -1.0_wp , pgtv(:,:,:), 'V', -1.0_wp )   ! Lateral boundary cond.
 
       ! horizontal derivative of density anomalies (rd)
@@ -308,5 +366,5 @@
          pgru(:,:)=0.0_wp   ; pgrv(:,:)=0.0_wp ; 
          !
-         DO_2D( 1, 0, 1, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
 
             iku = mbku(ji,jj)
@@ -329,5 +387,5 @@
          CALL eos( ztj, zhj, zrj )
 
-         DO_2D( 1, 0, 1, 0 )            ! Gradient of density at the last level
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
             iku = mbku(ji,jj)
             ikv = mbkv(ji,jj)
@@ -344,5 +402,5 @@
          END_2D
 
-         CALL lbc_lnk_multi( 'zpshde', pgru , 'U', -1.0_wp , pgrv , 'V', -1.0_wp )   ! Lateral boundary conditions
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'zpshde', pgru , 'U', -1.0_wp , pgrv , 'V', -1.0_wp )   ! Lateral boundary conditions
          !
       END IF
@@ -351,5 +409,5 @@
       !
       DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!            !
-         DO_2D( 1, 0, 1, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
             iku = miku(ji,jj); ikup1 = miku(ji,jj) + 1
             ikv = mikv(ji,jj); ikvp1 = mikv(ji,jj) + 1
@@ -395,10 +453,10 @@
          !
       END DO
-      CALL lbc_lnk_multi( 'zpshde', pgtui(:,:,:), 'U', -1.0_wp , pgtvi(:,:,:), 'V', -1.0_wp )   ! Lateral boundary cond.
+      IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'zpshde', pgtui(:,:,:), 'U', -1.0_wp , pgtvi(:,:,:), 'V', -1.0_wp )   ! Lateral boundary cond.
 
       IF( PRESENT( prd ) ) THEN    !==  horizontal derivative of density anomalies (rd)  ==!    (optional part)
          !
          pgrui(:,:)  =0.0_wp; pgrvi(:,:)  =0.0_wp;
-         DO_2D( 1, 0, 1, 0 )
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
 
             iku = miku(ji,jj)
@@ -420,5 +478,5 @@
          CALL eos( ztj, zhj, zrj )        ! at the partial step depth output in  zri, zrj 
          !
-         DO_2D( 1, 0, 1, 0 )              ! Gradient of density at the last level
+         DO_2D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1 )
             iku = miku(ji,jj) 
             ikv = mikv(ji,jj) 
@@ -434,5 +492,5 @@
 
          END_2D
-         CALL lbc_lnk_multi( 'zpshde', pgrui, 'U', -1.0_wp , pgrvi, 'V', -1.0_wp )   ! Lateral boundary conditions
+         IF (nn_hls.EQ.1) CALL lbc_lnk_multi( 'zpshde', pgrui, 'U', -1.0_wp , pgrvi, 'V', -1.0_wp )   ! Lateral boundary conditions
          !
       END IF  
@@ -440,5 +498,5 @@
       IF( ln_timing )   CALL timing_stop( 'zps_hde_isf')
       !
-   END SUBROUTINE zps_hde_isf
+   END SUBROUTINE zps_hde_isf_t
 
    !!======================================================================
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRD/trd_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRD/trd_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRD/trd_oce.F90	(revision 14055)
@@ -33,5 +33,5 @@
 # endif
    !                                                  !!!* Active tracers trends indexes
-   INTEGER, PUBLIC, PARAMETER ::   jptot_tra  = 20     !: Total trend nb: change it when adding/removing one indice below
+   INTEGER, PUBLIC, PARAMETER ::   jptot_tra  = 21     !: Total trend nb: change it when adding/removing one indice below
    !                               ===============     !  
    INTEGER, PUBLIC, PARAMETER ::   jptra_xad  =  1     !: x- horizontal advection
@@ -46,4 +46,5 @@
    INTEGER, PUBLIC, PARAMETER ::   jptra_bbc  = 10     !: Bottom Boundary Condition (geoth. heating) 
    INTEGER, PUBLIC, PARAMETER ::   jptra_bbl  = 11     !: Bottom Boundary Layer (diffusive and/or advective)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_osm  = 21     !: Non-local terms from OSMOSIS OBL model
    INTEGER, PUBLIC, PARAMETER ::   jptra_npc  = 12     !: non-penetrative convection treatment
    INTEGER, PUBLIC, PARAMETER ::   jptra_dmp  = 13     !: internal restoring (damping)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRD/trdini.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRD/trdini.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/TRD/trdini.F90	(revision 14055)
@@ -11,4 +11,5 @@
    !!----------------------------------------------------------------------
    USE dom_oce        ! ocean domain
+   USE domain, ONLY : dom_tile
    USE trd_oce        ! trends: ocean variables
    USE trdken         ! trends: 3D kinetic   energy
@@ -88,5 +89,11 @@
       !
 !      IF( .NOT.ln_linssh .AND. ( l_trdtra .OR. l_trddyn ) )  CALL ctl_stop( 'trend diagnostics with variable volume not validated' )
-      
+
+      IF( ln_tile .AND. ( l_trdtra .OR. l_trddyn ) ) THEN
+         CALL ctl_warn('Tiling is not yet implemented for the trends diagnostics; ln_tile is forced to FALSE')
+         ln_tile = .FALSE.
+         CALL dom_tile( ntsi, ntsj, ntei, ntej )
+      ENDIF
+
 !!gm  : Potential BUG : 3D output only for vector invariant form!  add a ctl_stop or code the flux form case
 !!gm  : bug/pb for vertical advection of tracer in vvl case: add T.dt[eta] in the output... 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/USR/usrdef_nam.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/USR/usrdef_nam.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/USR/usrdef_nam.F90	(revision 14055)
@@ -70,5 +70,5 @@
       kk_cfg = nn_GYRE
       !
-      kpi = 30 * nn_GYRE + 2       !                     
+      kpi = 30 * nn_GYRE + 2       !
       kpj = 20 * nn_GYRE + 2
 #if defined key_agrif
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdf_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdf_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdf_oce.F90	(revision 14055)
@@ -40,4 +40,5 @@
    LOGICAL , PUBLIC ::   ln_zdfswm   !: surface  wave-induced mixing flag
    LOGICAL , PUBLIC ::   ln_zdfiwm   !: internal wave-induced mixing flag
+   LOGICAL , PUBLIC ::   ln_zdfmfc   !: convection: eddy diffusivity Mass Flux Convection
    !                             ! coefficients 
    REAL(wp), PUBLIC ::   rn_avm0     !: vertical eddy viscosity (m2/s)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfgls.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfgls.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfgls.F90	(revision 14055)
@@ -1057,11 +1057,4 @@
       CALL gls_rst( nit000, 'READ' )      ! (en, avt_k, avm_k, hmxl_n)
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('en')
-         CALL iom_set_rstw_var_active('avt_k')
-         CALL iom_set_rstw_var_active('avm_k')
-         CALL iom_set_rstw_var_active('hmxl_n')
-      ENDIF
-      !
    END SUBROUTINE zdf_gls_init
 
@@ -1097,8 +1090,8 @@
             !
             IF( MIN( id1, id2, id3, id4 ) > 0 ) THEN        ! all required arrays exist
-               CALL iom_get( numror, jpdom_auto, 'en'    , en    , ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'avt_k' , avt_k , ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'avm_k' , avm_k , ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'hmxl_n', hmxl_n, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'en'    , en     )
+               CALL iom_get( numror, jpdom_auto, 'avt_k' , avt_k  )
+               CALL iom_get( numror, jpdom_auto, 'avm_k' , avm_k  )
+               CALL iom_get( numror, jpdom_auto, 'hmxl_n', hmxl_n )
             ELSE                        
                IF(lwp) WRITE(numout,*)
@@ -1119,10 +1112,8 @@
          !                                   ! -------------------
          IF(lwp) WRITE(numout,*) '---- gls-rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context         )
-         CALL iom_rstput( kt, nitrst, numrow, 'en'    , en    , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'avt_k' , avt_k , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'avm_k' , avm_k , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'hmxl_n', hmxl_n, ldxios = lwxios )
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'en'    , en     )
+         CALL iom_rstput( kt, nitrst, numrow, 'avt_k' , avt_k  )
+         CALL iom_rstput( kt, nitrst, numrow, 'avm_k' , avm_k  )
+         CALL iom_rstput( kt, nitrst, numrow, 'hmxl_n', hmxl_n )
          !
       ENDIF
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfmfc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfmfc.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfmfc.F90	(revision 14055)
@@ -0,0 +1,475 @@
+ MODULE zdfmfc
+   !!======================================================================
+   !!                       ***  MODULE  zdfmfc  ***
+   !! Ocean physics: Mass-Flux scheme parameterization of Convection:
+   !!                Non-local transport for the convective ocean boundary
+   !!                layer. Subgrid-scale large eddies are represented by a
+   !!                mass-flux contribution (ln_zdfmfc = .TRUE.)
+   !!======================================================================
+   !! History : NEMO  !
+   !!            3.6  !  2016-06  (H. Giordani, R. Bourdallé-Badie)  Original code
+   !!            4.2  !  2020-12  (H. Giordani, R. Bourdallé-Badie)  adapt to NEM04.2
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   tra_mfc       : Compute the Mass Flux and trends of T/S
+   !!   diag_mfc      : Modify diagonal of trazdf Matrix
+   !!   rhs_mfc       : Modify RHS of trazdf Matrix
+   !!   zdf_mfc_init  : initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   !
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE domvvl         ! ocean space and time domain : variable volume layer
+   USE domzgr
+   USE zdf_oce        ! ocean vertical physics
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE phycst         ! physical constants
+   USE eosbn2         ! equation of state (eos routine)
+   USE zdfmxl         ! mixed layer
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! MPP manager
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE timing         ! Timing
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_mfc         ! routine called in step module
+   PUBLIC   diag_mfc        ! routine called in trazdf module
+   PUBLIC   rhs_mfc         ! routine called in trazdf module
+   PUBLIC   zdf_mfc_init    ! routine called in nemo module
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::  edmfa, edmfb, edmfc   !: diagonal term of the matrix.
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  edmftra               !: y term for matrix inversion
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::  edmfm               !: y term for matrix inversion
+   !
+   !! ** Namelist  namzdf_edmf  **
+   REAL(wp) ::   rn_cemf           ! entrain of T/S
+   REAL(wp) ::   rn_cwmf           ! detrain of T/S
+   REAL(wp) ::   rn_cent           ! entrain of the convective mass flux
+   REAL(wp) ::   rn_cdet           ! detrain of the convective mass flux
+   REAL(wp) ::   rn_cap            ! Factor of computation for convective area (negative => area constant)
+   REAL(wp) ::   App_max           ! Maximum of the convective area
+   LOGICAL, PUBLIC, SAVE  ::   ln_edmfuv         !: EDMF flag for velocity  !
+   !
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.2 , NEMO Consortium (2018)
+   !! $Id: zdfmfc.F90 13783 2020-20-02 15:30:22Z rbourdal $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_mfc_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION zdf_edmf_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( edmfa(jpi,jpj,jpk) , edmfb(jpi,jpj,jpk) , edmfc(jpi,jpj,jpk)      &
+         &      , edmftra(jpi,jpj,jpk,2), edmfm(jpi,jpj,jpk) ,  STAT= zdf_mfc_alloc )
+         !
+      IF( lk_mpp             )   CALL mpp_sum ( 'zdfmfc', zdf_mfc_alloc )
+      IF( zdf_mfc_alloc /= 0 )   CALL ctl_warn('zdf_mfc_alloc: failed to allocate arrays')
+   END FUNCTION zdf_mfc_alloc
+
+
+   SUBROUTINE tra_mfc( kt, Kmm, pts, Krhs )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_mfc  ***
+      !!
+      !! ** Purpose :      Compute a mass flux, depending on surface flux, over
+      !!            the instable part of the water column.
+      !!
+      !! ** Method  :     Compute surface instability and mix tracers until stable level
+      !!           
+      !!
+      !! ** Action  :      Compute convection plume and (ta,sa)-trends for trazdf (EDMF scheme)
+      !!
+      !! References :      
+      !!                   Giordani, Bourdallé-Badie and Madec JAMES 2020
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER                                  , INTENT(in)    :: Kmm, Krhs ! time level indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts       ! active tracers and RHS of tracer equation
+      REAL(wp), DIMENSION(jpi,jpj,jpk,2) ::   ztsp         ! T/S of the plume
+      REAL(wp), DIMENSION(jpi,jpj,jpk,2) ::   ztse         ! T/S at W point
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zrwp          !
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zrwp2         !
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zapp          !
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zedmf         !
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zepsT, zepsW  !
+      !
+      REAL(wp), DIMENSION(jpi,jpj) :: zustar, zustar2   !
+      REAL(wp), DIMENSION(jpi,jpj) :: zuws, zvws, zsws, zfnet          !
+      REAL(wp), DIMENSION(jpi,jpj) :: zfbuo, zrautbm1, zrautb, zraupl
+      REAL(wp), DIMENSION(jpi,jpj) :: zwpsurf            !
+      REAL(wp), DIMENSION(jpi,jpj) :: zop0 , zsp0 !
+      REAL(wp), DIMENSION(jpi,jpj) :: zrwp_0, zrwp2_0  !
+      REAL(wp), DIMENSION(jpi,jpj) :: zapp0           !
+      REAL(wp), DIMENSION(jpi,jpj) :: zphp, zph, zphpm1, zphm1, zNHydro
+      REAL(wp), DIMENSION(jpi,jpj) :: zhcmo          !
+      !
+      REAL(wp), DIMENSION(jpi,jpj,jpk)   ::   zn2    ! N^2
+      REAL(wp), DIMENSION(jpi,jpj,2  ) ::   zab, zabm1, zabp ! alpha and beta
+     
+      REAL(wp), PARAMETER :: zepsilon = 1.e-30                 ! local small value
+
+      REAL(wp) :: zrho, zrhop
+      REAL(wp) :: zcnh, znum, zden, zcoef1, zcoef2
+      REAL(wp) :: zca, zcb, zcd, zrw, zxl, zcdet, zctre
+      REAL(wp) :: zaw, zbw, zxw
+      REAL(wp) :: alpha
+     !
+      INTEGER, INTENT(in   )    ::   kt   ! ocean time-step index      !
+      !
+      INTEGER  ::   ji, jj, jk  ! dummy  loop arguments   
+      !
+      !------------------------------------------------------------------
+      ! Initialisation of coefficients
+      !------------------------------------------------------------------
+      zca          = 1._wp
+      zcb          = 1._wp
+      zcd          = 1._wp
+
+      !------------------------------------------------------------------
+      ! Surface boundary condition
+      !------------------------------------------------------------------
+      ! surface Stress
+      !--------------------
+      zuws(:,:) = utau(:,:) * r1_rho0 
+      zvws(:,:) = vtau(:,:) * r1_rho0 
+      zustar2(:,:) = SQRT(zuws(:,:)*zuws(:,:)+zvws(:,:)*zvws(:,:))
+      zustar(:,:)  = SQRT(zustar2(:,:))
+
+      ! Heat Flux
+      !--------------------
+      zfnet(:,:) = qns(:,:) + qsr(:,:)
+      zfnet(:,:) = zfnet(:,:) / (rho0 * rcp)
+
+      ! Water Flux
+      !---------------------
+      zsws(:,:) = emp(:,:)
+
+      !-------------------------------------------
+      ! Initialisation of prognostic variables
+      !-------------------------------------------
+      zrwp (:,:,:) =  0._wp ; zrwp2(:,:,:) =  0._wp ; zedmf(:,:,:) =  0._wp
+      zph  (:,:)   =  0._wp ; zphm1(:,:)   =  0._wp ; zphpm1(:,:)  =  0._wp
+      ztsp(:,:,:,:)=  0._wp
+
+      ! Tracers inside plume (ztsp) and environment (ztse)
+      ztsp(:,:,1,jp_tem) = pts(:,:,1,jp_tem,Kmm) * tmask(:,:,1)
+      ztsp(:,:,1,jp_sal) = pts(:,:,1,jp_sal,Kmm) * tmask(:,:,1)
+      ztse(:,:,1,jp_tem) = pts(:,:,1,jp_tem,Kmm) * tmask(:,:,1)
+      ztse(:,:,1,jp_sal) = pts(:,:,1,jp_sal,Kmm) * tmask(:,:,1)
+
+      CALL eos( ztse(:,:,1,:) ,  zrautb(:,:) )
+      CALL eos( ztsp(:,:,1,:) ,  zraupl(:,:) )
+
+      !-------------------------------------------
+      ! Boundary Condition of Mass Flux (plume velo.; convective area, entrain/detrain)
+      !-------------------------------------------
+      zhcmo(:,:) = e3t(:,:,1,Kmm)
+      zfbuo(:,:)   = 0._wp
+      WHERE ( ABS(zrautb(:,:)) > 1.e-20 ) zfbuo(:,:)   =   &
+         &      grav * ( 2.e-4_wp *zfnet(:,:) - 7.6E-4_wp*pts(:,:,1,jp_sal,Kmm)*zsws(:,:)/zrautb(:,:)) * zhcmo(:,:)
+
+      zedmf(:,:,1) = -0.065_wp*(ABS(zfbuo(:,:)))**(1._wp/3._wp)*SIGN(1.,zfbuo(:,:))
+      zedmf(:,:,1) = MAX(0., zedmf(:,:,1))
+
+      zwpsurf(:,:) = 2._wp/3._wp*zustar(:,:) + 2._wp/3._wp*ABS(zfbuo(:,:))**(1._wp/3._wp)
+      zwpsurf(:,:) = MAX(1.e-5_wp,zwpsurf(:,:))
+      zwpsurf(:,:) = MIN(1.,zwpsurf(:,:))
+
+      zapp(:,:,:)  = App_max
+      WHERE(zwpsurf .NE. 0.) zapp(:,:,1)   = MIN(MAX(0.,zedmf(:,:,1)/zwpsurf(:,:)), App_max)
+
+      zedmf(:,:,1) = 0._wp 
+      zrwp (:,:,1) = 0._wp 
+      zrwp2(:,:,1) = 0._wp
+      zepsT(:,:,:) = 0.001_wp
+      zepsW(:,:,:) = 0.001_wp
+
+
+      !--------------------------------------------------------------
+      ! Compute plume properties 
+      ! In the same loop on vert. levels computation of:
+      !    - Vertical velocity: zWp
+      !    - Convective Area: zAp
+      !    - Tracers properties inside the plume (if necessary): ztp
+      !---------------------------------------------------------------
+
+      DO jk= 2, jpk
+
+         ! Compute the buoyancy acceleration on T-points at jk-1
+         zrautbm1(:,:) = zrautb(:,:)
+         CALL eos( pts (:,:,jk  ,:,Kmm) ,  zrautb(:,:)   )
+         CALL eos( ztsp(:,:,jk-1,:    ) ,  zraupl(:,:)   )
+
+         zphm1(:,:)  = zphm1(:,:)  + grav * zrautbm1(:,:) * e3t(:,:,jk-1, Kmm)
+         zphpm1(:,:) = zphpm1(:,:) + grav * zraupl(:,:)   * e3t(:,:,jk-1, Kmm)
+         zph(:,:)    = zphm1(:,:)  + grav * zrautb(:,:)   * e3t(:,:,jk  , Kmm)
+         zph(:,:)    = MAX( zph(:,:), zepsilon)
+
+         WHERE(zrautbm1 .NE. 0.) zfbuo(:,:)  =  grav * (zraupl(:,:) - zrautbm1(:,:)) / zrautbm1(:,:)
+
+         DO_2D( 0, 0, 0, 0 )
+
+            ! Compute Environment of Plume. Interpolation T/S (before time step) on W-points
+            zrw              =  (gdept(ji,jj,jk,Kmm) - gdepw(ji,jj,jk,Kmm)) &
+               &              / (gdept(ji,jj,jk,Kmm) - gdept(ji,jj,jk-1,Kmm))
+            ztse(ji,jj,jk,:) = (pts(ji,jj,jk,:,Kmm) * zrw + pts(ji,jj,jk-1,:,Kmm)*(1._wp - zrw) )*tmask(ji,jj,jk)
+
+            !---------------------------------------------------------------
+            ! Compute the vertical velocity on W-points
+            !---------------------------------------------------------------
+
+            ! Non-hydrostatic pressure terms in the wp2 equation
+            zcnh = 0.2_wp 
+            znum = 0.5_wp  + zcnh - &
+                   (zcnh*grav*zraupl(ji,jj)/zph(ji,jj)+zcb*zepsW(ji,jj,jk-1)) &
+                   *e3t(ji,jj,jk-1,Kmm)*0.5_wp   
+            zden = 0.5_wp + zcnh + &
+                   (zcnh*grav*zraupl(ji,jj)/zph(ji,jj)+zcb*zepsW(ji,jj,jk-1)) &
+                   *e3t(ji,jj,jk-1,Kmm)*0.5_wp   
+
+            zcoef1 = zca*e3t(ji,jj,jk-1,Kmm) / zden
+            zcoef2 = znum/zden
+
+            ! compute wp2 
+            zrwp2(ji,jj,jk) = zcoef1*zfbuo(ji,jj) &
+                            + zcoef2*zrwp2(ji,jj,jk-1)
+            zrwp2(ji,jj,jk) = MAX ( zrwp2(ji,jj,jk)*wmask(ji,jj,jk) , 0.)
+            zrwp (ji,jj,jk) = SQRT( zrwp2(ji,jj,jk) )
+
+            !----------------------------------------------------------------------------------
+            ! Compute convective area on W-point
+            ! Compute vertical profil of the convective area with mass conservation hypothesis
+            ! If rn_cap negative => constant value on the water column.
+            !----------------------------------------------------------------------------------
+            IF( rn_cap .GT. 0. ) THEN
+
+               zxw = MAX(zrwp(ji,jj,jk-1), zrwp(ji,jj,jk) )
+               IF( zxw > 0. ) THEN
+
+                  zxl = (zrwp(ji,jj,jk-1)-zrwp(ji,jj,jk))/(e3t(ji,jj,jk-1,Kmm)*zxw)
+                  IF (zxl .LT. 0._wp) THEN
+                     zctre  = -1.*rn_cap*zxl 
+                     zcdet  =  0._wp
+                  ELSE
+                     zctre  =  0._wp
+                     zcdet  =  rn_cap*zxl 
+                  END IF
+                     zapp(ji,jj,jk) = zapp(ji,jj,jk-1)*     &
+                     &                (1._wp + (zxl + zctre - zcdet )*e3t(ji,jj,jk-1,Kmm))
+                  ELSE
+                     zapp(ji,jj,jk) = App_max
+                  END IF
+                  zapp(ji,jj,jk) = MIN( MAX(zapp(ji,jj,jk),0.), App_max)
+               ELSE
+                  zapp(ji,jj,jk) = -1. * rn_cap
+               END IF
+
+            ! Compute Mass Flux on W-point
+            zedmf(ji,jj,jk)   = -zapp(ji,jj,jk) * zrwp(ji,jj,jk)* wmask(ji,jj,jk)
+
+            ! Compute Entrainment coefficient
+            IF(rn_cemf .GT. 0.) THEN
+               zxw = 0.5_wp*(zrwp(ji,jj,jk-1)+ zrwp(ji,jj,jk) )
+               zepsT(ji,jj,jk)  =  0.01_wp
+               IF( zxw > 0.  ) THEN
+                  zepsT(ji,jj,jk)  =  zepsT(ji,jj,jk) +                       &
+                                   &  ABS( zrwp(ji,jj,jk-1)-zrwp(ji,jj,jk) )  &
+                                   &  / ( e3t(ji,jj,jk-1,Kmm) * zxw )
+                  zepsT(ji,jj,jk)  = zepsT(ji,jj,jk) * rn_cemf * wmask(ji,jj,jk)
+               ENDIF
+            ELSE
+               zepsT(ji,jj,jk)  = -rn_cemf
+            ENDIF
+
+            ! Compute the detrend coef for velocity (on W-point and not T-points, bug ???)
+            IF(rn_cwmf .GT. 0.) THEN
+               zepsW(ji,jj,jk)  =  rn_cwmf * zepsT(ji,jj,jk)
+            ELSE
+               zepsW(ji,jj,jk)  = -rn_cwmf
+            ENDIF
+
+            !---------------------------------------------------------------
+            ! Compute the plume properties on T-points
+            !---------------------------------------------------------------
+            IF(zrwp (ji,jj,jk) .LT. 1.e-12_wp .AND. zrwp (ji,jj,jk-1) .LT. 1.e-12_wp) THEN
+               ztsp(ji,jj,jk-1,jp_tem) = pts(ji,jj,jk-1,jp_tem,Kmm)
+               ztsp(ji,jj,jk-1,jp_sal) = pts(ji,jj,jk-1,jp_sal,Kmm)
+            ENDIF
+
+            zcoef1 =  (1._wp-zepsT(ji,jj,jk)*(1._wp-zrw)*e3w(ji,jj,jk,Kmm)*wmask(ji,jj,jk ) ) &
+            &       / (1._wp+zepsT(ji,jj,jk)*zrw*e3w(ji,jj,jk,Kmm)*wmask(ji,jj,jk) )
+            !
+            zcoef2 =  zepsT(ji,jj,jk)*e3w(ji,jj,jk,Kmm)*wmask(ji,jj,jk)                       &
+            &       / (1._wp+zepsT(ji,jj,jk)*zrw*e3w(ji,jj,jk,Kmm)*wmask(ji,jj,jk))
+            !
+            ztsp(ji,jj,jk,jp_tem) = (zcoef1 * ztsp(ji,jj,jk-1,jp_tem) +  &
+            &                        zcoef2 * ztse(ji,jj,jk  ,jp_tem) )*tmask(ji,jj,jk)
+            ztsp(ji,jj,jk,jp_sal) = (zcoef1 * ztsp(ji,jj,jk-1,jp_sal) +  &
+            &                        zcoef2 * ztse(ji,jj,jk  ,jp_sal) )*tmask(ji,jj,jk)
+
+         END_2D 
+      END DO ! end of loop on jpk
+
+      ! Compute Mass Flux on T-point
+      DO jk=1,jpk-1
+         edmfm(:,:,jk) = (zedmf(:,:,jk+1)  + zedmf(:,:,jk) )*0.5_wp
+      END DO
+      edmfm(:,:,jpk) = zedmf(:,:,jpk) 
+
+      ! Save variable (on T point)
+      CALL iom_put( "mf_Tp" , ztsp(:,:,:,jp_tem) )  ! Save plume temperature
+      CALL iom_put( "mf_Sp" , ztsp(:,:,:,jp_sal) )  ! Save plume salinity
+      CALL iom_put( "mf_mf" , edmfm(:,:,:)       )  ! Save Mass Flux
+      ! Save variable (on W point)
+      CALL iom_put( "mf_wp" , zrwp (:,:,:)       )  ! Save convective velocity in the plume
+      CALL iom_put( "mf_app", zapp (:,:,:)       )  ! Save convective area
+
+      !=================================================================================
+      !  Computation of a tridiagonal matrix and right hand side terms of the linear system
+      !=================================================================================
+      edmfa(:,:,:)     = 0._wp
+      edmfb(:,:,:)     = 0._wp
+      edmfc(:,:,:)     = 0._wp
+      edmftra(:,:,:,:) = 0._wp
+
+      !---------------------------------------------------------------
+      ! Diagonal terms 
+      !---------------------------------------------------------------
+      DO jk=1,jpk-1
+         edmfa(:,:,jk) =  0._wp
+         edmfb(:,:,jk) = -edmfm(:,:,jk  ) / e3w(:,:,jk+1,Kmm)
+         edmfc(:,:,jk) =  edmfm(:,:,jk+1) / e3w(:,:,jk+1,Kmm)
+      END DO
+      edmfa(:,:,jpk)   = -edmfm(:,:,jpk-1) / e3w(:,:,jpk,Kmm)
+      edmfb(:,:,jpk)   =  edmfm(:,:,jpk  ) / e3w(:,:,jpk,Kmm)
+      edmfc(:,:,jpk)   =  0._wp
+
+      !---------------------------------------------------------------
+      ! right hand side term for Temperature
+      !---------------------------------------------------------------
+      DO jk=1,jpk-1
+        edmftra(:,:,jk,1) = - edmfm(:,:,jk  ) * ztsp(:,:,jk  ,jp_tem) / e3w(:,:,jk+1,Kmm) &
+                          & + edmfm(:,:,jk+1) * ztsp(:,:,jk+1,jp_tem) / e3w(:,:,jk+1,Kmm)
+      END DO
+      edmftra(:,:,jpk,1) = - edmfm(:,:,jpk-1) * ztsp(:,:,jpk-1,jp_tem) / e3w(:,:,jpk,Kmm) &
+                         & + edmfm(:,:,jpk  ) * ztsp(:,:,jpk  ,jp_tem) / e3w(:,:,jpk,Kmm)
+                        
+      !---------------------------------------------------------------
+      ! Right hand side term for Salinity
+      !---------------------------------------------------------------
+      DO jk=1,jpk-1
+         edmftra(:,:,jk,2) =  - edmfm(:,:,jk  ) * ztsp(:,:,jk  ,jp_sal) / e3w(:,:,jk+1,Kmm) &
+                           &  + edmfm(:,:,jk+1) * ztsp(:,:,jk+1,jp_sal) / e3w(:,:,jk+1,Kmm)
+      END DO
+      edmftra(:,:,jpk,2) = - edmfm(:,:,jpk-1) * ztsp(:,:,jpk-1,jp_sal) / e3w(:,:,jpk,Kmm) &
+                         & + edmfm(:,:,jpk  ) * ztsp(:,:,jpk  ,jp_sal) / e3w(:,:,jpk,Kmm)
+      !
+      !
+      CALL lbc_lnk_multi( 'zdfmfc', edmfm,'T',1., edmfa,'T',1., edmfb,'T',1., edmfc,'T',1., edmftra(:,:,:,jp_tem),'T',1., edmftra(:,:,:,jp_sal),'T',1.)
+      !
+   END SUBROUTINE tra_mfc
+
+   
+   SUBROUTINE diag_mfc( zdiagi, zdiagd, zdiags, p2dt, Kaa )
+
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::  zdiagi, zdiagd, zdiags  ! inout: tridaig. terms 
+      REAL(wp)                        , INTENT(in   ) ::   p2dt                   ! tracer time-step
+      INTEGER                         , INTENT(in   ) ::   Kaa                    ! ocean time level indices
+
+      INTEGER  ::   ji, jj, jk  ! dummy  loop arguments   
+
+         DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+            zdiagi(ji,jj,jk) = zdiagi(ji,jj,jk) + e3t(ji,jj,jk,Kaa) * p2dt *edmfa(ji,jj,jk)
+            zdiags(ji,jj,jk) = zdiags(ji,jj,jk) + e3t(ji,jj,jk,Kaa) * p2dt *edmfc(ji,jj,jk)
+            zdiagd(ji,jj,jk) = zdiagd(ji,jj,jk) + e3t(ji,jj,jk,Kaa) * p2dt *edmfb(ji,jj,jk)
+         END_3D
+
+   END SUBROUTINE diag_mfc
+
+   SUBROUTINE rhs_mfc( zrhs, jjn )
+
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   zrhs                   ! inout: rhs trend 
+      INTEGER                         , INTENT(in   ) ::   jjn                    ! tracer indices
+
+      INTEGER  ::   ji, jj, jk  ! dummy  loop arguments   
+
+      DO_3D( 0, 0, 0, 0, 1, jpkm1 )
+         zrhs(ji,jj,jk) = zrhs(ji,jj,jk) + edmftra(ji,jj,jk,jjn)
+      END_3D
+
+   END SUBROUTINE rhs_mfc
+
+
+
+   SUBROUTINE zdf_mfc_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_mfc_init  ***
+      !!                    
+      !! ** Purpose :   Initialization of the vertical eddy diffivity and
+      !!      mass flux
+      !!
+      !! ** Method  :   Read the namzdf_mfc namelist and check the parameters
+      !!      called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namlist namzdf_mfc
+      !!
+      !! ** Action  :   Increase by 1 the nstop flag is setting problem encounter
+      !!
+      !!----------------------------------------------------------------------
+      !
+      INTEGER ::   jk    ! dummy loop indices
+      INTEGER ::   ios   ! Local integer output status for namelist read
+      REAL(wp)::   zcr   ! local scalar
+      !!
+      NAMELIST/namzdf_mfc/ ln_edmfuv, rn_cemf, rn_cwmf, rn_cent, rn_cdet, rn_cap, App_max
+      !!----------------------------------------------------------
+      !
+      !
+!      REWIND( numnam_ref )              ! Namelist namzdf_mfc in reference namelist : Vertical eddy diffivity mass flux
+      READ  ( numnam_ref, namzdf_mfc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_edmf in reference namelist' )
+
+!      REWIND( numnam_cfg )              ! Namelist namzdf_mfc in configuration namelist : Vertical eddy diffivity mass flux
+      READ  ( numnam_cfg, namzdf_mfc, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_edmf in configuration namelist' )
+      IF(lwm) WRITE ( numond, namzdf_mfc )
+
+      IF(lwp) THEN                     !* Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_mfc_init'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_mfc : set eddy diffusivity Mass Flux Convection'
+         WRITE(numout,*) '   Apply mass flux on velocities (Not yet avail.)     ln_edmfuv = ', ln_edmfuv
+         WRITE(numout,*) '   Coeff for entrain/detrain T/S of plume (Neg => cte) rn_cemf  = ', rn_cemf
+         WRITE(numout,*) '   Coeff for entrain/detrain Wp of plume  (Neg => cte) rn_cwmf  = ', rn_cwmf
+         WRITE(numout,*) '   Coeff for entrain/detrain area of plume             rn_cap   = ', rn_cap
+         WRITE(numout,*) '   Coeff for entrain area of plume                     rn_cent  = ', rn_cent
+         WRITE(numout,*) '   Coeff for detrain area of plume                     rn_cdet  = ', rn_cdet
+         WRITE(numout,*) '   Max convective area                                 App_max  = ', App_max
+       ENDIF
+                                     !* allocate edmf arrays
+      IF( zdf_mfc_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_edmf_init : unable to allocate arrays' )
+      edmfa(:,:,:)     = 0._wp
+      edmfb(:,:,:)     = 0._wp
+      edmfc(:,:,:)     = 0._wp
+      edmftra(:,:,:,:) = 0._wp
+      !
+   END SUBROUTINE zdf_mfc_init
+
+   !!======================================================================
+ 
+   !!======================================================================
+END MODULE zdfmfc
+
+
+
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfosm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfosm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfosm.F90	(revision 14055)
@@ -25,8 +25,13 @@
    !!            (12) Replace zwstrl with zvstr in calculation of eddy viscosity.
    !! 27/09/2017 (13) Calculate Stokes drift and Stokes penetration depth from wave information
-   !!            (14) Bouyancy flux due to entrainment changed to include contribution from shear turbulence (for testing commented out).
+   !!            (14) Buoyancy flux due to entrainment changed to include contribution from shear turbulence.
    !! 28/09/2017 (15) Calculation of Stokes drift moved into separate do-loops to allow for different options for the determining the Stokes drift to be added.
    !!            (16) Calculation of Stokes drift from windspeed for PM spectrum (for testing, commented out)
    !!            (17) Modification to Langmuir velocity scale to include effects due to the Stokes penetration depth (for testing, commented out)
+   !! ??/??/2018 (18) Revision to code structure, selected using key_osmldpth1. Inline code moved into subroutines. Changes to physics made,
+   !!                  (a) Pycnocline temperature and salinity profies changed for unstable layers
+   !!                  (b) The stable OSBL depth parametrization changed.
+   !! 16/05/2019 (19) Fox-Kemper parametrization of restratification through mixed layer eddies added to revised code.
+   !! 23/05/19   (20) Old code where key_osmldpth1` is *not* set removed, together with the key key_osmldpth1
    !!----------------------------------------------------------------------
 
@@ -40,4 +45,6 @@
    !!   trc_osm       : compute and add to the passive tracer trend the non-local flux (TBD)
    !!   dyn_osm       : compute and add to u & v trensd the non-local flux
+   !!
+   !! Subroutines in revised code.
    !!----------------------------------------------------------------------
    USE oce            ! ocean dynamics and active tracers
@@ -69,5 +76,7 @@
    PUBLIC   tra_osm       ! routine called by step.F90
    PUBLIC   trc_osm       ! routine called by trcstp.F90
-   PUBLIC   dyn_osm       ! routine called by 'step.F90'
+   PUBLIC   dyn_osm       ! routine called by step.F90
+
+   PUBLIC   ln_osm_mle    ! logical needed by tra_mle_init in tramle.F90
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ghamu    !: non-local u-momentum flux
@@ -77,14 +86,28 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   etmean   !: averaging operator for avt
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hbl      !: boundary layer depth
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hbli     !: intial boundary layer depth for stable blayer
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dh       ! depth of pycnocline
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hml      ! ML depth
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dstokes  !: penetration depth of the Stokes drift.
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)           ::   r1_ft    ! inverse of the modified Coriolis parameter at t-pts
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hmle     ! Depth of layer affexted by mixed layer eddies in Fox-Kemper parametrization
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dbdx_mle ! zonal buoyancy gradient in ML
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dbdy_mle ! meridional buoyancy gradient in ML
+   INTEGER,  PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   mld_prof ! level of base of MLE layer.
 
    !                      !!** Namelist  namzdf_osm  **
    LOGICAL  ::   ln_use_osm_la      ! Use namelist  rn_osm_la
+
+   LOGICAL  ::   ln_osm_mle           !: flag to activate the Mixed Layer Eddy (MLE) parameterisation
+
    REAL(wp) ::   rn_osm_la          ! Turbulent Langmuir number
    REAL(wp) ::   rn_osm_dstokes     ! Depth scale of Stokes drift
+   REAL(wp) ::   rn_zdfosm_adjust_sd = 1.0 ! factor to reduce Stokes drift by
+   REAL(wp) ::   rn_osm_hblfrac = 0.1! for nn_osm_wave = 3/4 specify fraction in top of hbl
+   LOGICAL  ::   ln_zdfosm_ice_shelter      ! flag to activate ice sheltering
    REAL(wp) ::   rn_osm_hbl0 = 10._wp       ! Initial value of hbl for 1D runs
    INTEGER  ::   nn_ave             ! = 0/1 flag for horizontal average on avt
    INTEGER  ::   nn_osm_wave = 0    ! = 0/1/2 flag for getting stokes drift from La# / PM wind-waves/Inputs into sbcwave
+   INTEGER  ::   nn_osm_SD_reduce   ! = 0/1/2 flag for getting effective stokes drift from surface value
    LOGICAL  ::   ln_dia_osm         ! Use namelist  rn_osm_la
 
@@ -96,6 +119,26 @@
    REAL(wp) ::   rn_difconv = 1._wp     ! diffusivity when unstable below BL  (m2/s)
 
+! OSMOSIS mixed layer eddy parametrization constants
+   INTEGER  ::   nn_osm_mle             ! = 0/1 flag for horizontal average on avt
+   REAL(wp) ::   rn_osm_mle_ce           ! MLE coefficient
+   !                                        ! parameters used in nn_osm_mle = 0 case
+   REAL(wp) ::   rn_osm_mle_lf               ! typical scale of mixed layer front
+   REAL(wp) ::   rn_osm_mle_time             ! time scale for mixing momentum across the mixed layer
+   !                                        ! parameters used in nn_osm_mle = 1 case
+   REAL(wp) ::   rn_osm_mle_lat              ! reference latitude for a 5 km scale of ML front
+   LOGICAL  ::   ln_osm_hmle_limit           ! If true arbitrarily restrict hmle to rn_osm_hmle_limit*zmld
+   REAL(wp) ::   rn_osm_hmle_limit           ! If ln_osm_hmle_limit true arbitrarily restrict hmle to rn_osm_hmle_limit*zmld
+   REAL(wp) ::   rn_osm_mle_rho_c        ! Density criterion for definition of MLD used by FK
+   REAL(wp) ::   r5_21 = 5.e0 / 21.e0   ! factor used in mle streamfunction computation
+   REAL(wp) ::   rb_c                   ! ML buoyancy criteria = g rho_c /rho0 where rho_c is defined in zdfmld
+   REAL(wp) ::   rc_f                   ! MLE coefficient (= rn_ce / (5 km * fo) ) in nn_osm_mle=1 case
+   REAL(wp) ::   rn_osm_mle_thresh          ! Threshold buoyancy for deepening of MLE layer below OSBL base.
+   REAL(wp) ::   rn_osm_bl_thresh          ! Threshold buoyancy for deepening of OSBL base.
+   REAL(wp) ::   rn_osm_mle_tau             ! Adjustment timescale for MLE.
+
+
    !                                    !!! ** General constants  **
-   REAL(wp) ::   epsln   = 1.0e-20_wp   ! a small positive number
+   REAL(wp) ::   epsln   = 1.0e-20_wp   ! a small positive number to ensure no div by zero
+   REAL(wp) ::   depth_tol = 1.0e-6_wp  ! a small-ish positive number to give a hbl slightly shallower than gdepw
    REAL(wp) ::   pthird  = 1._wp/3._wp  ! 1/3
    REAL(wp) ::   p2third = 2._wp/3._wp  ! 2/3
@@ -118,9 +161,14 @@
       !!                 ***  FUNCTION zdf_osm_alloc  ***
       !!----------------------------------------------------------------------
-     ALLOCATE( ghamu(jpi,jpj,jpk), ghamv(jpi,jpj,jpk), ghamt(jpi,jpj,jpk), ghams(jpi,jpj,jpk), &
-          &      hbl(jpi,jpj)    ,  hbli(jpi,jpj)    , dstokes(jpi, jpj) ,                     &
-          &   etmean(jpi,jpj,jpk),  STAT= zdf_osm_alloc )
+     ALLOCATE( ghamu(jpi,jpj,jpk), ghamv(jpi,jpj,jpk), ghamt(jpi,jpj,jpk),ghams(jpi,jpj,jpk), &
+          &       hbl(jpi,jpj), dh(jpi,jpj), hml(jpi,jpj), dstokes(jpi, jpj), &
+          &       etmean(jpi,jpj,jpk), STAT= zdf_osm_alloc )
+
+     ALLOCATE(  hmle(jpi,jpj), r1_ft(jpi,jpj), dbdx_mle(jpi,jpj), dbdy_mle(jpi,jpj), &
+          &       mld_prof(jpi,jpj), STAT= zdf_osm_alloc )
+
+     CALL mpp_sum ( 'zdfosm', zdf_osm_alloc )
      IF( zdf_osm_alloc /= 0 )   CALL ctl_warn('zdf_osm_alloc: failed to allocate zdf_osm arrays')
-     CALL mpp_sum ( 'zdfosm', zdf_osm_alloc )
+
    END FUNCTION zdf_osm_alloc
 
@@ -166,4 +214,7 @@
       !!
       INTEGER ::   ji, jj, jk                   ! dummy loop indices
+
+      INTEGER ::   jl                   ! dummy loop indices
+
       INTEGER ::   ikbot, jkmax, jkm1, jkp2     !
 
@@ -196,4 +247,12 @@
       REAL(wp), DIMENSION(jpi,jpj) :: zwbav     ! Buoyancy flux - bl average
       REAL(wp), DIMENSION(jpi,jpj) :: zwb_ent   ! Buoyancy entrainment flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zwb_min
+
+
+      REAL(wp), DIMENSION(jpi,jpj) :: zwb_fk_b  ! MLE buoyancy flux averaged over OSBL
+      REAL(wp), DIMENSION(jpi,jpj) :: zwb_fk    ! max MLE buoyancy flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zdiff_mle ! extra MLE vertical diff
+      REAL(wp), DIMENSION(jpi,jpj) :: zvel_mle  ! velocity scale for dhdt with stable ML and FK
+
       REAL(wp), DIMENSION(jpi,jpj) :: zustke    ! Surface Stokes drift
       REAL(wp), DIMENSION(jpi,jpj) :: zla       ! Trubulent Langmuir number
@@ -201,5 +260,9 @@
       REAL(wp), DIMENSION(jpi,jpj) :: zsin_wind ! Sin angle of surface stress
       REAL(wp), DIMENSION(jpi,jpj) :: zhol      ! Stability parameter for boundary layer
-      LOGICAL, DIMENSION(:,:), ALLOCATABLE :: lconv ! unstable/stable bl
+      LOGICAL, DIMENSION(jpi,jpj)  :: lconv     ! unstable/stable bl
+      LOGICAL, DIMENSION(jpi,jpj)  :: lshear    ! Shear layers
+      LOGICAL, DIMENSION(jpi,jpj)  :: lpyc      ! OSBL pycnocline present
+      LOGICAL, DIMENSION(jpi,jpj)  :: lflux     ! surface flux extends below OSBL into MLE layer.
+      LOGICAL, DIMENSION(jpi,jpj)  :: lmle      ! MLE layer increases in hickness.
 
       ! mixed-layer variables
@@ -207,4 +270,6 @@
       INTEGER, DIMENSION(jpi,jpj) :: ibld ! level of boundary layer base
       INTEGER, DIMENSION(jpi,jpj) :: imld ! level of mixed-layer depth (pycnocline top)
+      INTEGER, DIMENSION(jpi,jpj) :: jp_ext, jp_ext_mle ! offset for external level
+      INTEGER, DIMENSION(jpi, jpj) :: j_ddh ! Type of shear layer
 
       REAL(wp) :: ztgrad,zsgrad,zbgrad ! Temporary variables used to calculate pycnocline gradients
@@ -213,12 +278,24 @@
       REAL(wp), DIMENSION(jpi,jpj) :: zhbl  ! bl depth - grid
       REAL(wp), DIMENSION(jpi,jpj) :: zhml  ! ml depth - grid
+
+      REAL(wp), DIMENSION(jpi,jpj) :: zhmle ! MLE depth - grid
+      REAL(wp), DIMENSION(jpi,jpj) :: zmld  ! ML depth on grid
+
       REAL(wp), DIMENSION(jpi,jpj) :: zdh   ! pycnocline depth - grid
       REAL(wp), DIMENSION(jpi,jpj) :: zdhdt ! BL depth tendency
-      REAL(wp), DIMENSION(jpi,jpj) :: zt_bl,zs_bl,zu_bl,zv_bl,zrh_bl  ! averages over the depth of the blayer
-      REAL(wp), DIMENSION(jpi,jpj) :: zt_ml,zs_ml,zu_ml,zv_ml,zrh_ml  ! averages over the depth of the mixed layer
-      REAL(wp), DIMENSION(jpi,jpj) :: zdt_bl,zds_bl,zdu_bl,zdv_bl,zdrh_bl,zdb_bl ! difference between blayer average and parameter at base of blayer
-      REAL(wp), DIMENSION(jpi,jpj) :: zdt_ml,zds_ml,zdu_ml,zdv_ml,zdrh_ml,zdb_ml ! difference between mixed layer average and parameter at base of blayer
-      REAL(wp), DIMENSION(jpi,jpj) :: zwth_ent,zws_ent ! heat and salinity fluxes at the top of the pycnocline
-      REAL(wp), DIMENSION(jpi,jpj) :: zuw_bse,zvw_bse  ! momentum fluxes at the top of the pycnocline
+      REAL(wp), DIMENSION(jpi,jpj) :: zddhdt                                    ! correction to dhdt due to internal structure.
+      REAL(wp), DIMENSION(jpi,jpj) :: zdtdz_bl_ext,zdsdz_bl_ext,zdbdz_bl_ext              ! external temperature/salinity and buoyancy gradients
+      REAL(wp), DIMENSION(jpi,jpj) :: zdtdz_mle_ext,zdsdz_mle_ext,zdbdz_mle_ext              ! external temperature/salinity and buoyancy gradients
+      REAL(wp), DIMENSION(jpi,jpj) :: zdtdx, zdtdy, zdsdx, zdsdy      ! horizontal gradients for Fox-Kemper parametrization.
+
+      REAL(wp), DIMENSION(jpi,jpj) :: zt_bl,zs_bl,zu_bl,zv_bl,zb_bl  ! averages over the depth of the blayer
+      REAL(wp), DIMENSION(jpi,jpj) :: zt_ml,zs_ml,zu_ml,zv_ml,zb_ml  ! averages over the depth of the mixed layer
+      REAL(wp), DIMENSION(jpi,jpj) :: zt_mle,zs_mle,zu_mle,zv_mle,zb_mle  ! averages over the depth of the MLE layer
+      REAL(wp), DIMENSION(jpi,jpj) :: zdt_bl,zds_bl,zdu_bl,zdv_bl,zdb_bl ! difference between blayer average and parameter at base of blayer
+      REAL(wp), DIMENSION(jpi,jpj) :: zdt_ml,zds_ml,zdu_ml,zdv_ml,zdb_ml ! difference between mixed layer average and parameter at base of blayer
+      REAL(wp), DIMENSION(jpi,jpj) :: zdt_mle,zds_mle,zdu_mle,zdv_mle,zdb_mle ! difference between MLE layer average and parameter at base of blayer
+!      REAL(wp), DIMENSION(jpi,jpj) :: zwth_ent,zws_ent ! heat and salinity fluxes at the top of the pycnocline
+      REAL(wp) :: zwth_ent,zws_ent ! heat and salinity fluxes at the top of the pycnocline
+      REAL(wp) :: zuw_bse,zvw_bse  ! momentum fluxes at the top of the pycnocline
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdtdz_pyc    ! parametrized gradient of temperature in pycnocline
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdsdz_pyc    ! parametrised gradient of salinity in pycnocline
@@ -226,11 +303,13 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdudz_pyc    ! u-shear across the pycnocline
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdvdz_pyc    ! v-shear across the pycnocline
-
+      REAL(wp), DIMENSION(jpi,jpj) :: zdbds_mle    ! Magnitude of horizontal buoyancy gradient.
       ! Flux-gradient relationship variables
+      REAL(wp), DIMENSION(jpi, jpj) :: zshear, zri_i ! Shear production and interfacial richardon number.
 
       REAL(wp) :: zl_c,zl_l,zl_eps  ! Used to calculate turbulence length scale.
 
-      REAL(wp), DIMENSION(jpi,jpj) :: zdifml_sc,zvisml_sc,zdifpyc_sc,zvispyc_sc,zbeta_d_sc,zbeta_v_sc ! Scales for eddy diffusivity/viscosity
+      REAL(wp) :: za_cubic, zb_cubic, zc_cubic, zd_cubic ! coefficients in cubic polynomial specifying diffusivity in pycnocline.  
       REAL(wp), DIMENSION(jpi,jpj) :: zsc_wth_1,zsc_ws_1 ! Temporary scales used to calculate scalar non-gradient terms.
+      REAL(wp), DIMENSION(jpi,jpj) :: zsc_wth_pyc, zsc_ws_pyc ! Scales for pycnocline transport term/
       REAL(wp), DIMENSION(jpi,jpj) :: zsc_uw_1,zsc_uw_2,zsc_vw_1,zsc_vw_2 ! Temporary scales for non-gradient momentum flux terms.
       REAL(wp), DIMENSION(jpi,jpj) :: zhbl_t ! holds boundary layer depth updated by full timestep
@@ -243,13 +322,23 @@
       ! Temporary variables
       INTEGER :: inhml
-      INTEGER :: i_lconv_alloc
       REAL(wp) :: znd,znd_d,zznd_ml,zznd_pyc,zznd_d ! temporary non-dimensional depths used in various routines
       REAL(wp) :: ztemp, zari, zpert, zzdhdt, zdb   ! temporary variables
       REAL(wp) :: zthick, zz0, zz1 ! temporary variables
       REAL(wp) :: zvel_max, zhbl_s ! temporary variables
-      REAL(wp) :: zfac             ! temporary variable
+      REAL(wp) :: zfac, ztmp       ! temporary variable
       REAL(wp) :: zus_x, zus_y     ! temporary Stokes drift
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zviscos ! viscosity
       REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdiffut ! t-diffusivity
+      REAL(wp), DIMENSION(jpi,jpj) :: zalpha_pyc
+      REAL(wp), DIMENSION(jpi,jpj) :: ztau_sc_u ! dissipation timescale at baes of WML.
+      REAL(wp) :: zdelta_pyc, zwt_pyc_sc_1, zws_pyc_sc_1, zzeta_pyc
+      REAL(wp) :: zbuoy_pyc_sc, zomega, zvw_max
+      INTEGER :: ibld_ext=0                          ! does not have to be zero for modified scheme
+      REAL(wp) :: zgamma_b_nd, zgamma_b, zdhoh, ztau
+      REAL(wp) :: zzeta_s = 0._wp
+      REAL(wp) :: zzeta_v = 0.46
+      REAL(wp) :: zabsstke
+      REAL(wp) :: zsqrtpi, z_two_thirds, zproportion, ztransp, zthickness
+      REAL(wp) :: z2k_times_thickness, zsqrt_depth, zexp_depth, zdstokes0, zf, zexperfc
 
       ! For debugging
@@ -257,7 +346,4 @@
       !!--------------------------------------------------------------------
       !
-      ALLOCATE( lconv(jpi,jpj),  STAT= i_lconv_alloc )
-      IF( i_lconv_alloc /= 0 )   CALL ctl_warn('zdf_osm: failed to allocate lconv')
-
       ibld(:,:)   = 0     ; imld(:,:)  = 0
       zrad0(:,:)  = 0._wp ; zradh(:,:) = 0._wp ; zradav(:,:)    = 0._wp ; zustar(:,:)    = 0._wp
@@ -267,22 +353,35 @@
       zustke(:,:) = 0._wp ; zla(:,:)   = 0._wp ; zcos_wind(:,:) = 0._wp ; zsin_wind(:,:) = 0._wp
       zhol(:,:)   = 0._wp
-      lconv(:,:)  = .FALSE.
+      lconv(:,:)  = .FALSE.; lpyc(:,:) = .FALSE. ; lflux(:,:) = .FALSE. ;  lmle(:,:) = .FALSE.
       ! mixed layer
       ! no initialization of zhbl or zhml (or zdh?)
       zhbl(:,:)    = 1._wp ; zhml(:,:)    = 1._wp ; zdh(:,:)      = 1._wp ; zdhdt(:,:)   = 0._wp
-      zt_bl(:,:)   = 0._wp ; zs_bl(:,:)   = 0._wp ; zu_bl(:,:)    = 0._wp ; zv_bl(:,:)   = 0._wp
-      zrh_bl(:,:)  = 0._wp ; zt_ml(:,:)   = 0._wp ; zs_ml(:,:)    = 0._wp ; zu_ml(:,:)   = 0._wp
-      zv_ml(:,:)   = 0._wp ; zrh_ml(:,:)  = 0._wp ; zdt_bl(:,:)   = 0._wp ; zds_bl(:,:)  = 0._wp
-      zdu_bl(:,:)  = 0._wp ; zdv_bl(:,:)  = 0._wp ; zdrh_bl(:,:)  = 0._wp ; zdb_bl(:,:)  = 0._wp
+      zt_bl(:,:)   = 0._wp ; zs_bl(:,:)   = 0._wp ; zu_bl(:,:)    = 0._wp
+      zv_bl(:,:)   = 0._wp ; zb_bl(:,:)  = 0._wp
+      zt_ml(:,:)   = 0._wp ; zs_ml(:,:)    = 0._wp ; zu_ml(:,:)   = 0._wp
+      zt_mle(:,:)   = 0._wp ; zs_mle(:,:)    = 0._wp ; zu_mle(:,:)   = 0._wp
+      zb_mle(:,:) = 0._wp
+      zv_ml(:,:)   = 0._wp ; zdt_bl(:,:)   = 0._wp ; zds_bl(:,:)  = 0._wp
+      zdu_bl(:,:)  = 0._wp ; zdv_bl(:,:)  = 0._wp ; zdb_bl(:,:)  = 0._wp
       zdt_ml(:,:)  = 0._wp ; zds_ml(:,:)  = 0._wp ; zdu_ml(:,:)   = 0._wp ; zdv_ml(:,:)  = 0._wp
-      zdrh_ml(:,:) = 0._wp ; zdb_ml(:,:)  = 0._wp ; zwth_ent(:,:) = 0._wp ; zws_ent(:,:) = 0._wp
-      zuw_bse(:,:) = 0._wp ; zvw_bse(:,:) = 0._wp
+      zdb_ml(:,:)  = 0._wp
+      zdt_mle(:,:)  = 0._wp ; zds_mle(:,:)  = 0._wp ; zdu_mle(:,:)   = 0._wp
+      zdv_mle(:,:)  = 0._wp ; zdb_mle(:,:)  = 0._wp
+      zwth_ent = 0._wp ; zws_ent = 0._wp
       !
       zdtdz_pyc(:,:,:) = 0._wp ; zdsdz_pyc(:,:,:) = 0._wp ; zdbdz_pyc(:,:,:) = 0._wp
       zdudz_pyc(:,:,:) = 0._wp ; zdvdz_pyc(:,:,:) = 0._wp
       !
+      zdtdz_bl_ext(:,:) = 0._wp ; zdsdz_bl_ext(:,:) = 0._wp ; zdbdz_bl_ext(:,:) = 0._wp
+
+      IF ( ln_osm_mle ) THEN  ! only initialise arrays if needed
+         zdtdx(:,:) = 0._wp ; zdtdy(:,:) = 0._wp ; zdsdx(:,:) = 0._wp
+         zdsdy(:,:) = 0._wp ; dbdx_mle(:,:) = 0._wp ; dbdy_mle(:,:) = 0._wp
+         zwb_fk(:,:) = 0._wp ; zvel_mle(:,:) = 0._wp; zdiff_mle(:,:) = 0._wp
+         zhmle(:,:) = 0._wp  ; zmld(:,:) = 0._wp
+      ENDIF
+      zwb_fk_b(:,:) = 0._wp   ! must be initialised even with ln_osm_mle=F as used in zdf_osm_calculate_dhdt
+
       ! Flux-Gradient arrays.
-      zdifml_sc(:,:)  = 0._wp ; zvisml_sc(:,:)  = 0._wp ; zdifpyc_sc(:,:) = 0._wp
-      zvispyc_sc(:,:) = 0._wp ; zbeta_d_sc(:,:) = 0._wp ; zbeta_v_sc(:,:) = 0._wp
       zsc_wth_1(:,:)  = 0._wp ; zsc_ws_1(:,:)   = 0._wp ; zsc_uw_1(:,:)   = 0._wp
       zsc_uw_2(:,:)   = 0._wp ; zsc_vw_1(:,:)   = 0._wp ; zsc_vw_2(:,:)   = 0._wp
@@ -292,4 +391,5 @@
       ghams(:,:,:)   = 0._wp ; ghamu(:,:,:)   = 0._wp ; ghamv(:,:,:) = 0._wp
 
+      zddhdt(:,:) = 0._wp
       ! hbl = MAX(hbl,epsln)
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -326,6 +426,6 @@
         zwbav(ji,jj) = grav  * zthermal * zwthav(ji,jj) - grav  * zbeta * zwsav(ji,jj)
         ! Surface upward velocity fluxes
-        zuw0(ji,jj) = -utau(ji,jj) * r1_rho0 * tmask(ji,jj,1)
-        zvw0(ji,jj) = -vtau(ji,jj) * r1_rho0 * tmask(ji,jj,1)
+        zuw0(ji,jj) = - 0.5 * (utau(ji-1,jj) + utau(ji,jj)) * r1_rho0 * tmask(ji,jj,1)
+        zvw0(ji,jj) = - 0.5 * (vtau(ji,jj-1) + vtau(ji,jj)) * r1_rho0 * tmask(ji,jj,1)
         ! Friction velocity (zustar), at T-point : LMD94 eq. 2
         zustar(ji,jj) = MAX( SQRT( SQRT( zuw0(ji,jj) * zuw0(ji,jj) + zvw0(ji,jj) * zvw0(ji,jj) ) ), 1.0e-8 )
@@ -340,6 +440,7 @@
            zus_x = zcos_wind(ji,jj) * zustar(ji,jj) / 0.3**2
            zus_y = zsin_wind(ji,jj) * zustar(ji,jj) / 0.3**2
+           ! Linearly
            zustke(ji,jj) = MAX ( SQRT( zus_x*zus_x + zus_y*zus_y), 1.0e-8 )
-           ! dstokes(ji,jj) set to constant value rn_osm_dstokes from namelist in zdf_osm_init
+           dstokes(ji,jj) = rn_osm_dstokes
         END_2D
      ! Assume Pierson-Moskovitz wind-wave spectrum
@@ -347,18 +448,81 @@
         DO_2D( 0, 0, 0, 0 )
            ! Use wind speed wndm included in sbc_oce module
-           zustke(ji,jj) = MAX ( 0.016 * wndm(ji,jj), 1.0e-8 )
-           dstokes(ji,jj) = 0.12 * wndm(ji,jj)**2 / grav
+           zustke(ji,jj) =  MAX ( 0.016 * wndm(ji,jj), 1.0e-8 )
+           dstokes(ji,jj) = MAX ( 0.12 * wndm(ji,jj)**2 / grav, 5.e-1)
         END_2D
      ! Use ECMWF wave fields as output from SBCWAVE
      CASE(2)
         zfac =  2.0_wp * rpi / 16.0_wp
+
         DO_2D( 0, 0, 0, 0 )
-           ! The Langmur number from the ECMWF model appears to give La<0.3 for wind-driven seas.
-           !    The coefficient 0.8 gives La=0.3  in this situation.
-           ! It could represent the effects of the spread of wave directions
-           ! around the mean wind. The effect of this adjustment needs to be tested.
-           zustke(ji,jj) = MAX ( 1.0 * ( zcos_wind(ji,jj) * ut0sd(ji,jj ) + zsin_wind(ji,jj)  * vt0sd(ji,jj) ), &
-                &                zustar(ji,jj) / ( 0.45 * 0.45 )                                                  )
-           dstokes(ji,jj) = MAX(zfac * hsw(ji,jj)*hsw(ji,jj) / ( MAX(zustke(ji,jj)*wmp(ji,jj), 1.0e-7 ) ), 5.0e-1) !rn_osm_dstokes !
+           IF (hsw(ji,jj) > 1.e-4) THEN
+              ! Use  wave fields
+              zabsstke = SQRT(ut0sd(ji,jj)**2 + vt0sd(ji,jj)**2)
+              zustke(ji,jj) = MAX ( ( zcos_wind(ji,jj) * ut0sd(ji,jj) + zsin_wind(ji,jj)  * vt0sd(ji,jj) ), 1.0e-8)
+              dstokes(ji,jj) = MAX (zfac * hsw(ji,jj)*hsw(ji,jj) / ( MAX(zabsstke * wmp(ji,jj), 1.0e-7 ) ), 5.0e-1)
+           ELSE
+              ! Assume masking issue (e.g. ice in ECMWF reanalysis but not in model run)
+              ! .. so default to Pierson-Moskowitz
+              zustke(ji,jj) = MAX ( 0.016 * wndm(ji,jj), 1.0e-8 )
+              dstokes(ji,jj) = MAX ( 0.12 * wndm(ji,jj)**2 / grav, 5.e-1)
+           END IF
+        END_2D
+     END SELECT
+
+     IF (ln_zdfosm_ice_shelter) THEN
+        ! Reduce both Stokes drift and its depth scale by ocean fraction to represent sheltering by ice
+        DO_2D( 0, 0, 0, 0 )
+           zustke(ji,jj) = zustke(ji,jj) * (1.0_wp - fr_i(ji,jj))
+           dstokes(ji,jj) = dstokes(ji,jj) * (1.0_wp - fr_i(ji,jj))
+        END_2D
+     END IF
+
+     SELECT CASE (nn_osm_SD_reduce)
+     ! Reduce surface Stokes drift by a constant factor or following Breivik (2016) + van  Roekel (2012) or Grant (2020).
+     CASE(0)
+        ! The Langmur number from the ECMWF model (or from PM)  appears to give La<0.3 for wind-driven seas.
+        !    The coefficient rn_zdfosm_adjust_sd = 0.8 gives La=0.3  in this situation.
+        ! It could represent the effects of the spread of wave directions
+        ! around the mean wind. The effect of this adjustment needs to be tested.
+        IF(nn_osm_wave > 0) THEN
+           zustke(2:jpim1,2:jpjm1) = rn_zdfosm_adjust_sd * zustke(2:jpim1,2:jpjm1)
+        END IF
+     CASE(1)
+        ! van  Roekel (2012): consider average SD over top 10% of boundary layer
+        ! assumes approximate depth profile of SD from Breivik (2016)
+        zsqrtpi = SQRT(rpi)
+        z_two_thirds = 2.0_wp / 3.0_wp
+
+        DO_2D( 0, 0, 0, 0 )
+           zthickness = rn_osm_hblfrac*hbl(ji,jj)
+           z2k_times_thickness =  zthickness * 2.0_wp / MAX( ABS( 5.97_wp * dstokes(ji,jj) ), 0.0000001_wp )
+           zsqrt_depth = SQRT(z2k_times_thickness)
+           zexp_depth  = EXP(-z2k_times_thickness)
+           zustke(ji,jj) = zustke(ji,jj) * (1.0_wp - zexp_depth  &
+                &              - z_two_thirds * ( zsqrtpi*zsqrt_depth*z2k_times_thickness * ERFC(zsqrt_depth) &
+                &              + 1.0_wp - (1.0_wp + z2k_times_thickness)*zexp_depth ) ) / z2k_times_thickness
+
+        END_2D
+     CASE(2)
+        ! Grant (2020): Match to exponential with same SD and d/dz(Sd) at depth 10% of boundary layer
+        ! assumes approximate depth profile of SD from Breivik (2016)
+        zsqrtpi = SQRT(rpi)
+
+        DO_2D( 0, 0, 0, 0 )
+           zthickness = rn_osm_hblfrac*hbl(ji,jj)
+           z2k_times_thickness =  zthickness * 2.0_wp / MAX( ABS( 5.97_wp * dstokes(ji,jj) ), 0.0000001_wp )
+
+           IF(z2k_times_thickness < 50._wp) THEN
+              zsqrt_depth = SQRT(z2k_times_thickness)
+              zexperfc = zsqrtpi * zsqrt_depth * ERFC(zsqrt_depth) * EXP(z2k_times_thickness)
+           ELSE
+              ! asymptotic expansion of sqrt(pi)*zsqrt_depth*EXP(z2k_times_thickness)*ERFC(zsqrt_depth) for large z2k_times_thickness
+              ! See Abramowitz and Stegun, Eq. 7.1.23
+              ! zexperfc = 1._wp - (1/2)/(z2k_times_thickness)  + (3/4)/(z2k_times_thickness**2) - (15/8)/(z2k_times_thickness**3)
+              zexperfc = ((- 1.875_wp/z2k_times_thickness + 0.75_wp)/z2k_times_thickness - 0.5_wp)/z2k_times_thickness + 1.0_wp
+           END IF
+           zf = z2k_times_thickness*(1.0_wp/zexperfc - 1.0_wp)
+           dstokes(ji,jj) = 5.97 * zf * dstokes(ji,jj)
+           zustke(ji,jj) = zustke(ji,jj) * EXP(z2k_times_thickness * ( 1.0_wp / (2. * zf) - 1.0_wp )) * ( 1.0_wp - zexperfc)
         END_2D
      END SELECT
@@ -369,12 +533,6 @@
         ! Langmuir velocity scale (zwstrl), at T-point
         zwstrl(ji,jj) = ( zustar(ji,jj) * zustar(ji,jj) * zustke(ji,jj) )**pthird
-        ! Modify zwstrl to allow for small and large values of dstokes/hbl.
-        ! Intended as a possible test. Doesn't affect LES results for entrainment,
-        !  but hasn't been shown to be correct as dstokes/h becomes large or small.
-        zwstrl(ji,jj) = zwstrl(ji,jj) *  &
-             & (1.12 * ( 1.0 - ( 1.0 - EXP( -hbl(ji,jj) / dstokes(ji,jj) ) ) * dstokes(ji,jj) / hbl(ji,jj) ))**pthird * &
-             & ( 1.0 - EXP( -15.0 * dstokes(ji,jj) / hbl(ji,jj) ))
-        ! define La this way so effects of Stokes penetration depth on velocity scale are included
-        zla(ji,jj) = SQRT ( zustar(ji,jj) / zwstrl(ji,jj) )**3
+        zla(ji,jj) = MAX(MIN(SQRT ( zustar(ji,jj) / ( zwstrl(ji,jj) + epsln ) )**3, 4.0), 0.2)
+        IF(zla(ji,jj) > 0.45) dstokes(ji,jj) = MIN(dstokes(ji,jj), 0.5_wp*hbl(ji,jj))
         ! Velocity scale that tends to zustar for large Langmuir numbers
         zvstr(ji,jj) = ( zwstrl(ji,jj)**3  + &
@@ -383,5 +541,4 @@
         ! limit maximum value of Langmuir number as approximate treatment for shear turbulence.
         ! Note zustke and zwstrl are not amended.
-        IF ( zla(ji,jj) >= 0.45 ) zla(ji,jj) = 0.45
         !
         ! get convective velocity (zwstrc), stabilty scale (zhol) and logical conection flag lconv
@@ -389,8 +546,6 @@
            zwstrc(ji,jj) = ( 2.0 * zwbav(ji,jj) * 0.9 * hbl(ji,jj) )**pthird
            zhol(ji,jj) = -0.9 * hbl(ji,jj) * 2.0 * zwbav(ji,jj) / (zvstr(ji,jj)**3 + epsln )
-           lconv(ji,jj) = .TRUE.
-        ELSE
+         ELSE
            zhol(ji,jj) = -hbl(ji,jj) *  2.0 * zwbav(ji,jj)/ (zvstr(ji,jj)**3  + epsln )
-           lconv(ji,jj) = .FALSE.
         ENDIF
      END_2D
@@ -399,86 +554,103 @@
      ! Mixed-layer model - calculate averages over the boundary layer, and the change in the boundary layer depth
      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-     ! BL must be always 2 levels deep.
-      hbl(:,:) = MAX(hbl(:,:), gdepw(:,:,3,Kmm) )
-      ibld(:,:) = 3
-      DO_3D( 0, 0, 0, 0, 4, jpkm1 )
+     ! BL must be always 4 levels deep.
+     ! For calculation of lateral buoyancy gradients for FK in
+     ! zdf_osm_zmld_horizontal_gradients need halo values for ibld, so must
+     ! previously exist for hbl also.
+
+     ! agn 23/6/20: not clear all this is needed, as hbl checked after it is re-calculated anyway
+     ! ##########################################################################
+      hbl(:,:) = MAX(hbl(:,:), gdepw(:,:,4,Kmm) )
+      ibld(:,:) = 4
+      DO_3D( 1, 1, 1, 1, 5, jpkm1 )
          IF ( hbl(ji,jj) >= gdepw(ji,jj,jk,Kmm) ) THEN
             ibld(ji,jj) = MIN(mbkt(ji,jj), jk)
          ENDIF
       END_3D
+     ! ##########################################################################
 
       DO_2D( 0, 0, 0, 0 )
-            zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
-            zbeta    = rab_n(ji,jj,1,jp_sal)
-            zt   = 0._wp
-            zs   = 0._wp
-            zu   = 0._wp
-            zv   = 0._wp
-            ! average over depth of boundary layer
-            zthick=0._wp
-            DO jm = 2, ibld(ji,jj)
-               zthick=zthick+e3t(ji,jj,jm,Kmm)
-               zt   = zt  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_tem,Kmm)
-               zs   = zs  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_sal,Kmm)
-               zu   = zu  + e3t(ji,jj,jm,Kmm) &
-                  &            * ( uu(ji,jj,jm,Kbb) + uu(ji - 1,jj,jm,Kbb) ) &
-                  &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
-               zv   = zv  + e3t(ji,jj,jm,Kmm) &
-                  &            * ( vv(ji,jj,jm,Kbb) + vv(ji,jj - 1,jm,Kbb) ) &
-                  &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
-            END DO
-            zt_bl(ji,jj) = zt / zthick
-            zs_bl(ji,jj) = zs / zthick
-            zu_bl(ji,jj) = zu / zthick
-            zv_bl(ji,jj) = zv / zthick
-            zdt_bl(ji,jj) = zt_bl(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_tem,Kmm)
-            zds_bl(ji,jj) = zs_bl(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_sal,Kmm)
-            zdu_bl(ji,jj) = zu_bl(ji,jj) - ( uu(ji,jj,ibld(ji,jj),Kbb) + uu(ji-1,jj,ibld(ji,jj) ,Kbb) ) &
-                  &    / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
-            zdv_bl(ji,jj) = zv_bl(ji,jj) - ( vv(ji,jj,ibld(ji,jj),Kbb) + vv(ji,jj-1,ibld(ji,jj) ,Kbb) ) &
-                  &   / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
-            zdb_bl(ji,jj) = grav * zthermal * zdt_bl(ji,jj) - grav * zbeta * zds_bl(ji,jj)
-            IF ( lconv(ji,jj) ) THEN    ! Convective
-                   zwb_ent(ji,jj) = -( 2.0 * 0.2 * zwbav(ji,jj) &
-                        &            + 0.135 * zla(ji,jj) * zwstrl(ji,jj)**3/hbl(ji,jj) )
-
-                   zvel_max =  - ( 1.0 + 1.0 * ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_Dt / hbl(ji,jj) ) &
-                        &   * zwb_ent(ji,jj) / ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
-! Entrainment including component due to shear turbulence. Modified Langmuir component, but gives same result for La=0.3 For testing uncomment.
-!                      zwb_ent(ji,jj) = -( 2.0 * 0.2 * zwbav(ji,jj) &
-!                           &            + ( 0.15 * ( 1.0 - EXP( -0.5 * zla(ji,jj) ) ) + 0.03 / zla(ji,jj)**2 ) * zustar(ji,jj)**3/hbl(ji,jj) )
-
-!                      zvel_max = - ( 1.0 + 1.0 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_Dt / zhbl(ji,jj) ) * zwb_ent(ji,jj) / &
-!                           &       ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
-                   zzdhdt = - zwb_ent(ji,jj) / ( zvel_max + MAX(zdb_bl(ji,jj),0.0) )
-            ELSE                        ! Stable
-                   zzdhdt = 0.32 * ( hbli(ji,jj) / hbl(ji,jj) -1.0 ) * zwstrl(ji,jj)**3 / hbli(ji,jj) &
-                        &   + ( ( 0.32 / 3.0 ) * exp ( -2.5 * ( hbli(ji,jj) / hbl(ji,jj) - 1.0 ) ) &
-                        & - ( 0.32 / 3.0 - 0.135 * zla(ji,jj) ) * exp ( -12.5 * ( hbli(ji,jj) / hbl(ji,jj) ) ) ) &
-                        &  * zwstrl(ji,jj)**3 / hbli(ji,jj)
-                   zzdhdt = zzdhdt + zwbav(ji,jj)
-                   IF ( zzdhdt < 0._wp ) THEN
-                   ! For long timsteps factor in brackets slows the rapid collapse of the OSBL
-                      zpert   = 2.0 * ( 1.0 + 2.0 * zwstrl(ji,jj) * rn_Dt / hbl(ji,jj) ) * zwstrl(ji,jj)**2 / hbl(ji,jj)
-                   ELSE
-                      zpert   = 2.0 * ( 1.0 + 2.0 * zwstrl(ji,jj) * rn_Dt / hbl(ji,jj) ) * zwstrl(ji,jj)**2 / hbl(ji,jj) &
-                           &  + MAX( zdb_bl(ji,jj), 0.0 )
-                   ENDIF
-                   zzdhdt = 2.0 * zzdhdt / zpert
-            ENDIF
-            zdhdt(ji,jj) = zzdhdt
+         zhbl(ji,jj) = gdepw(ji,jj,ibld(ji,jj),Kmm)
+         imld(ji,jj) = MAX(3,ibld(ji,jj) - MAX( INT( dh(ji,jj) / e3t(ji, jj, ibld(ji,jj), Kmm )) , 1 ))
+         zhml(ji,jj) = gdepw(ji,jj,imld(ji,jj),Kmm)
+         zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
       END_2D
-
-      ! Calculate averages over depth of boundary layer
-      imld = ibld           ! use imld to hold previous blayer index
-      ibld(:,:) = 3
-
-      zhbl_t(:,:) = hbl(:,:) + (zdhdt(:,:) - ww(ji,jj,ibld(ji,jj)))* rn_Dt ! certainly need wb here, so subtract it
-      zhbl_t(:,:) = MIN(zhbl_t(:,:), ht(:,:))
-      zdhdt(:,:) = MIN(zdhdt(:,:), (zhbl_t(:,:) - hbl(:,:))/rn_Dt + ww(ji,jj,ibld(ji,jj))) ! adjustment to represent limiting by ocean bottom
+      ! Averages over well-mixed and boundary layer
+      jp_ext(:,:) = 2
+      CALL zdf_osm_vertical_average(ibld, jp_ext, zt_bl, zs_bl, zb_bl, zu_bl, zv_bl, zdt_bl, zds_bl, zdb_bl, zdu_bl, zdv_bl)
+!      jp_ext(:,:) = ibld(:,:) - imld(:,:) + 1
+      CALL zdf_osm_vertical_average(ibld, ibld-imld+1, zt_ml, zs_ml, zb_ml, zu_ml, zv_ml, zdt_ml, zds_ml, zdb_ml, zdu_ml, zdv_ml)
+! Velocity components in frame aligned with surface stress.
+      CALL zdf_osm_velocity_rotation( zcos_wind, zsin_wind, zu_ml, zv_ml, zdu_ml, zdv_ml )
+      CALL zdf_osm_velocity_rotation( zcos_wind, zsin_wind, zu_bl, zv_bl, zdu_bl, zdv_bl )
+! Determine the state of the OSBL, stable/unstable, shear/no shear
+      CALL zdf_osm_osbl_state( lconv, lshear, j_ddh, zwb_ent, zwb_min, zshear, zri_i )
+
+      IF ( ln_osm_mle ) THEN
+! Fox-Kemper Scheme
+         mld_prof = 4
+         DO_3D( 0, 0, 0, 0, 5, jpkm1 )
+         IF ( hmle(ji,jj) >= gdepw(ji,jj,jk,Kmm) ) mld_prof(ji,jj) = MIN(mbkt(ji,jj), jk)
+         END_3D
+         jp_ext_mle(:,:) = 2
+        CALL zdf_osm_vertical_average(mld_prof, jp_ext_mle, zt_mle, zs_mle, zb_mle, zu_mle, zv_mle, zdt_mle, zds_mle, zdb_mle, zdu_mle, zdv_mle)
+
+         DO_2D( 0, 0, 0, 0 )
+           zhmle(ji,jj) = gdepw(ji,jj,mld_prof(ji,jj),Kmm)
+         END_2D
+
+!! External gradient
+         CALL zdf_osm_external_gradients( ibld+2, zdtdz_bl_ext, zdsdz_bl_ext, zdbdz_bl_ext )
+         CALL zdf_osm_zmld_horizontal_gradients( zmld, zdtdx, zdtdy, zdsdx, zdsdy, dbdx_mle, dbdy_mle, zdbds_mle )
+         CALL zdf_osm_external_gradients( mld_prof, zdtdz_mle_ext, zdsdz_mle_ext, zdbdz_mle_ext )
+         CALL zdf_osm_osbl_state_fk( lpyc, lflux, lmle, zwb_fk )
+         CALL zdf_osm_mle_parameters( mld_prof, hmle, zhmle, zvel_mle, zdiff_mle )
+      ELSE    ! ln_osm_mle
+! FK not selected, Boundary Layer only.
+         lpyc(:,:) = .TRUE.
+         lflux(:,:) = .FALSE.
+         lmle(:,:) = .FALSE.
+         DO_2D( 0, 0, 0, 0 )
+          IF ( lconv(ji,jj) .AND. zdb_bl(ji,jj) < rn_osm_bl_thresh ) lpyc(ji,jj) = .FALSE.
+         END_2D
+      ENDIF   ! ln_osm_mle
+
+! Test if pycnocline well resolved
+      DO_2D( 0, 0, 0, 0 )
+       IF (lconv(ji,jj) ) THEN
+          ztmp = 0.2 * zhbl(ji,jj) / e3w(ji,jj,ibld(ji,jj),Kmm)
+          IF ( ztmp > 6 ) THEN
+   ! pycnocline well resolved
+            jp_ext(ji,jj) = 1
+          ELSE
+   ! pycnocline poorly resolved
+            jp_ext(ji,jj) = 0
+          ENDIF
+       ELSE
+   ! Stable conditions
+         jp_ext(ji,jj) = 0
+       ENDIF
+      END_2D
+
+      CALL zdf_osm_vertical_average(ibld, jp_ext, zt_bl, zs_bl, zb_bl, zu_bl, zv_bl, zdt_bl, zds_bl, zdb_bl, zdu_bl, zdv_bl )
+!      jp_ext = ibld-imld+1
+      CALL zdf_osm_vertical_average(imld-1, ibld-imld+1, zt_ml, zs_ml, zb_ml, zu_ml, zv_ml, zdt_ml, zds_ml, zdb_ml, zdu_ml, zdv_ml)
+! Rate of change of hbl
+      CALL zdf_osm_calculate_dhdt( zdhdt, zddhdt )
+      DO_2D( 0, 0, 0, 0 )
+       zhbl_t(ji,jj) = hbl(ji,jj) + (zdhdt(ji,jj) - ww(ji,jj,ibld(ji,jj)))* rn_Dt ! certainly need ww here, so subtract it
+            ! adjustment to represent limiting by ocean bottom
+       IF ( zhbl_t(ji,jj) >= gdepw(ji, jj, mbkt(ji,jj) + 1, Kmm ) ) THEN
+          zhbl_t(ji,jj) = MIN(zhbl_t(ji,jj), gdepw(ji,jj, mbkt(ji,jj) + 1, Kmm) - depth_tol)! ht(:,:))
+          lpyc(ji,jj) = .FALSE.
+       ENDIF
+      END_2D
+
+      imld(:,:) = ibld(:,:)           ! use imld to hold previous blayer index
+      ibld(:,:) = 4
 
       DO_3D( 0, 0, 0, 0, 4, jpkm1 )
          IF ( zhbl_t(ji,jj) >= gdepw(ji,jj,jk,Kmm) ) THEN
-            ibld(ji,jj) =  MIN(mbkt(ji,jj), jk)
+            ibld(ji,jj) = jk
          ENDIF
       END_3D
@@ -487,397 +659,38 @@
 ! Step through model levels taking account of buoyancy change to determine the effect on dhdt
 !
+      CALL zdf_osm_timestep_hbl( zdhdt )
+! is external level in bounds?
+
+      CALL zdf_osm_vertical_average( ibld, jp_ext, zt_bl, zs_bl, zb_bl, zu_bl, zv_bl, zdt_bl, zds_bl, zdb_bl, zdu_bl, zdv_bl )
+!
+!
+! Check to see if lpyc needs to be changed 
+
+      CALL zdf_osm_pycnocline_thickness( dh, zdh )
+
       DO_2D( 0, 0, 0, 0 )
-         IF ( ibld(ji,jj) - imld(ji,jj) > 1 ) THEN
+       IF ( zdb_bl(ji,jj) < rn_osm_bl_thresh .or. ibld(ji,jj) + jp_ext(ji,jj) >= mbkt(ji,jj) .or. ibld(ji,jj)-imld(ji,jj) == 1 ) lpyc(ji,jj) = .FALSE. 
+      END_2D
+
+      dstokes(:,:) = MIN ( dstokes(:,:), hbl(:,:)/3. )  !  Limit delta for shallow boundary layers for calculating flux-gradient terms.
 !
-! If boundary layer changes by more than one level, need to check for stable layers between initial and final depths.
-!
-            zhbl_s = hbl(ji,jj)
-            jm = imld(ji,jj)
-            zthermal = rab_n(ji,jj,1,jp_tem)
-            zbeta = rab_n(ji,jj,1,jp_sal)
-            IF ( lconv(ji,jj) ) THEN
-!unstable
-               zvel_max =  - ( 1.0 + 1.0 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_Dt / hbl(ji,jj) ) &
-                    &   * zwb_ent(ji,jj) / ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
-
-               DO jk = imld(ji,jj), ibld(ji,jj)
-                  zdb = MAX( grav * ( zthermal * ( zt_bl(ji,jj) - ts(ji,jj,jm,jp_tem,Kmm) ) &
-                       & - zbeta * ( zs_bl(ji,jj) - ts(ji,jj,jm,jp_sal,Kmm) ) ), 0.0 ) + zvel_max
-
-                  zhbl_s = zhbl_s + MIN( - zwb_ent(ji,jj) / zdb * rn_Dt / FLOAT(ibld(ji,jj)-imld(ji,jj) ),   &
-                     &                     e3w(ji,jj,jk,Kmm) )
-                  zhbl_s = MIN(zhbl_s, ht(ji,jj))
-
-                  IF ( zhbl_s >= gdepw(ji,jj,jm+1,Kmm) ) jm = jm + 1
-               END DO
-               hbl(ji,jj) = zhbl_s
-               ibld(ji,jj) = jm
-               hbli(ji,jj) = hbl(ji,jj)
-            ELSE
-! stable
-               DO jk = imld(ji,jj), ibld(ji,jj)
-                  zdb = MAX( grav * ( zthermal * ( zt_bl(ji,jj) - ts(ji,jj,jm,jp_tem,Kmm) )          &
-                       &               - zbeta * ( zs_bl(ji,jj) - ts(ji,jj,jm,jp_sal,Kmm) ) ), 0.0 ) &
-                       & + 2.0 * zwstrl(ji,jj)**2 / zhbl_s
-
-                  zhbl_s = zhbl_s +  (                                                                                &
-                       &                     0.32         *                         ( hbli(ji,jj) / zhbl_s -1.0 )     &
-                       &               * zwstrl(ji,jj)**3 / hbli(ji,jj)                                               &
-                       &               + ( ( 0.32 / 3.0 )           * EXP( -  2.5 * ( hbli(ji,jj) / zhbl_s -1.0 ) )   &
-                       &               -   ( 0.32 / 3.0  - 0.0485 ) * EXP( - 12.5 * ( hbli(ji,jj) / zhbl_s      ) ) ) &
-                       &          * zwstrl(ji,jj)**3 / hbli(ji,jj) ) / zdb * e3w(ji,jj,jk,Kmm) / zdhdt(ji,jj)  ! ALMG to investigate whether need to include ww here
-
-                  zhbl_s = MIN(zhbl_s, ht(ji,jj))
-                  IF ( zhbl_s >= gdepw(ji,jj,jm,Kmm) ) jm = jm + 1
-               END DO
-               hbl(ji,jj) = MAX(zhbl_s, gdepw(ji,jj,3,Kmm) )
-               ibld(ji,jj) = MAX(jm, 3 )
-               IF ( hbl(ji,jj) > hbli(ji,jj) ) hbli(ji,jj) = hbl(ji,jj)
-            ENDIF   ! IF ( lconv )
-         ELSE
-! change zero or one model level.
-            hbl(ji,jj) = zhbl_t(ji,jj)
-            IF ( lconv(ji,jj) ) THEN
-               hbli(ji,jj) = hbl(ji,jj)
-            ELSE
-               hbl(ji,jj) = MAX(hbl(ji,jj), gdepw(ji,jj,3,Kmm) )
-               IF ( hbl(ji,jj) > hbli(ji,jj) ) hbli(ji,jj) = hbl(ji,jj)
-            ENDIF
-         ENDIF
-         zhbl(ji,jj) = gdepw(ji,jj,ibld(ji,jj),Kmm)
-      END_2D
-      dstokes(:,:) = MIN ( dstokes(:,:), hbl(:,:)/3. )  !  Limit delta for shallow boundary layers for calculating flux-gradient terms.
-
-! Recalculate averages over boundary layer after depth updated
-     ! Consider later  combining this into the loop above and looking for columns
-     ! where the index for base of the boundary layer have changed
-      DO_2D( 0, 0, 0, 0 )
-            zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
-            zbeta    = rab_n(ji,jj,1,jp_sal)
-            zt   = 0._wp
-            zs   = 0._wp
-            zu   = 0._wp
-            zv   = 0._wp
-            ! average over depth of boundary layer
-            zthick=0._wp
-            DO jm = 2, ibld(ji,jj)
-               zthick=zthick+e3t(ji,jj,jm,Kmm)
-               zt   = zt  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_tem,Kmm)
-               zs   = zs  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_sal,Kmm)
-               zu   = zu  + e3t(ji,jj,jm,Kmm) &
-                  &            * ( uu(ji,jj,jm,Kbb) + uu(ji - 1,jj,jm,Kbb) ) &
-                  &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
-               zv   = zv  + e3t(ji,jj,jm,Kmm) &
-                  &            * ( vv(ji,jj,jm,Kbb) + vv(ji,jj - 1,jm,Kbb) ) &
-                  &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
-            END DO
-            zt_bl(ji,jj) = zt / zthick
-            zs_bl(ji,jj) = zs / zthick
-            zu_bl(ji,jj) = zu / zthick
-            zv_bl(ji,jj) = zv / zthick
-            zdt_bl(ji,jj) = zt_bl(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_tem,Kmm)
-            zds_bl(ji,jj) = zs_bl(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_sal,Kmm)
-            zdu_bl(ji,jj) = zu_bl(ji,jj) - ( uu(ji,jj,ibld(ji,jj),Kbb) + uu(ji-1,jj,ibld(ji,jj) ,Kbb) ) &
-                   &   / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
-            zdv_bl(ji,jj) = zv_bl(ji,jj) - ( vv(ji,jj,ibld(ji,jj),Kbb) + vv(ji,jj-1,ibld(ji,jj) ,Kbb) ) &
-                   &  / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
-            zdb_bl(ji,jj) = grav * zthermal * zdt_bl(ji,jj) - grav * zbeta * zds_bl(ji,jj)
-            zhbl(ji,jj) = gdepw(ji,jj,ibld(ji,jj),Kmm)
-            IF ( lconv(ji,jj) ) THEN
-               IF ( zdb_bl(ji,jj) > 0._wp )THEN
-                  IF ( ( zwstrc(ji,jj) / zvstr(ji,jj) )**3 <= 0.5 ) THEN  ! near neutral stability
-                        zari = 4.5 * ( zvstr(ji,jj)**2 ) &
-                          & / ( zdb_bl(ji,jj) * zhbl(ji,jj) ) + 0.01
-                  ELSE                                                     ! unstable
-                        zari = 4.5 * ( zwstrc(ji,jj)**2 ) &
-                          & / ( zdb_bl(ji,jj) * zhbl(ji,jj) ) + 0.01
-                  ENDIF
-                  IF ( zari > 0.2 ) THEN                                                ! This test checks for weakly stratified pycnocline
-                     zari = 0.2
-                     zwb_ent(ji,jj) = 0._wp
-                  ENDIF
-                  inhml = MAX( INT( zari * zhbl(ji,jj)   &
-                     &              / e3t(ji,jj,ibld(ji,jj),Kmm) ), 1 )
-                  imld(ji,jj) = MAX( ibld(ji,jj) - inhml, 1)
-                  zhml(ji,jj) = gdepw(ji,jj,imld(ji,jj),Kmm)
-                  zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
-               ELSE  ! IF (zdb_bl)
-                  imld(ji,jj) = ibld(ji,jj) - 1
-                  zhml(ji,jj) = gdepw(ji,jj,imld(ji,jj),Kmm)
-                  zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
-               ENDIF
-            ELSE   ! IF (lconv)
-               IF ( zdhdt(ji,jj) >= 0.0 ) THEN    ! probably shouldn't include wm here
-               ! boundary layer deepening
-                  IF ( zdb_bl(ji,jj) > 0._wp ) THEN
-               ! pycnocline thickness set by stratification - use same relationship as for neutral conditions.
-                     zari = MIN( 4.5 * ( zvstr(ji,jj)**2 ) &
-                       & / ( zdb_bl(ji,jj) * zhbl(ji,jj) ) + 0.01  , 0.2 )
-                     inhml = MAX( INT( zari * zhbl(ji,jj)   &
-                        &             / e3t(ji,jj,ibld(ji,jj),Kmm) ), 1 )
-                     imld(ji,jj) = MAX( ibld(ji,jj) - inhml, 1)
-                     zhml(ji,jj) = gdepw(ji,jj,imld(ji,jj),Kmm)
-                     zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
-                  ELSE
-                     imld(ji,jj) = ibld(ji,jj) - 1
-                     zhml(ji,jj) = gdepw(ji,jj,imld(ji,jj),Kmm)
-                     zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
-                  ENDIF ! IF (zdb_bl > 0.0)
-               ELSE     ! IF(dhdt >= 0)
-               ! boundary layer collapsing.
-                  imld(ji,jj) = ibld(ji,jj)
-                  zhml(ji,jj) = zhbl(ji,jj)
-                  zdh(ji,jj) = 0._wp
-               ENDIF    ! IF (dhdt >= 0)
-            ENDIF       ! IF (lconv)
-      END_2D
-
-      ! Average over the depth of the mixed layer in the convective boundary layer
-      ! Also calculate entrainment fluxes for temperature and salinity
-      DO_2D( 0, 0, 0, 0 )
-         zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
-         zbeta    = rab_n(ji,jj,1,jp_sal)
-         IF ( lconv(ji,jj) ) THEN
-            zt   = 0._wp
-            zs   = 0._wp
-            zu   = 0._wp
-            zv   = 0._wp
-            ! average over depth of boundary layer
-            zthick=0._wp
-            DO jm = 2, imld(ji,jj)
-               zthick=zthick+e3t(ji,jj,jm,Kmm)
-               zt   = zt  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_tem,Kmm)
-               zs   = zs  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_sal,Kmm)
-               zu   = zu  + e3t(ji,jj,jm,Kmm) &
-                  &            * ( uu(ji,jj,jm,Kbb) + uu(ji - 1,jj,jm,Kbb) ) &
-                  &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
-               zv   = zv  + e3t(ji,jj,jm,Kmm) &
-                  &            * ( vv(ji,jj,jm,Kbb) + vv(ji,jj - 1,jm,Kbb) ) &
-                  &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
-            END DO
-            zt_ml(ji,jj) = zt / zthick
-            zs_ml(ji,jj) = zs / zthick
-            zu_ml(ji,jj) = zu / zthick
-            zv_ml(ji,jj) = zv / zthick
-            zdt_ml(ji,jj) = zt_ml(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_tem,Kmm)
-            zds_ml(ji,jj) = zs_ml(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_sal,Kmm)
-            zdu_ml(ji,jj) = zu_ml(ji,jj) - ( uu(ji,jj,ibld(ji,jj),Kbb) + uu(ji-1,jj,ibld(ji,jj) ,Kbb) ) &
-                  &    / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
-            zdv_ml(ji,jj) = zv_ml(ji,jj) - ( vv(ji,jj,ibld(ji,jj),Kbb) + vv(ji,jj-1,ibld(ji,jj) ,Kbb) ) &
-                  &    / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
-            zdb_ml(ji,jj) = grav * zthermal * zdt_ml(ji,jj) - grav * zbeta * zds_ml(ji,jj)
-         ELSE
-         ! stable, if entraining calulate average below interface layer.
-            IF ( zdhdt(ji,jj) >= 0._wp ) THEN
-               zt   = 0._wp
-               zs   = 0._wp
-               zu   = 0._wp
-               zv   = 0._wp
-               ! average over depth of boundary layer
-               zthick=0._wp
-               DO jm = 2, imld(ji,jj)
-                  zthick=zthick+e3t(ji,jj,jm,Kmm)
-                  zt   = zt  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_tem,Kmm)
-                  zs   = zs  + e3t(ji,jj,jm,Kmm) * ts(ji,jj,jm,jp_sal,Kmm)
-                  zu   = zu  + e3t(ji,jj,jm,Kmm) &
-                     &            * ( uu(ji,jj,jm,Kbb) + uu(ji - 1,jj,jm,Kbb) ) &
-                     &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
-                  zv   = zv  + e3t(ji,jj,jm,Kmm) &
-                     &            * ( vv(ji,jj,jm,Kbb) + vv(ji,jj - 1,jm,Kbb) ) &
-                     &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
-               END DO
-               zt_ml(ji,jj) = zt / zthick
-               zs_ml(ji,jj) = zs / zthick
-               zu_ml(ji,jj) = zu / zthick
-               zv_ml(ji,jj) = zv / zthick
-               zdt_ml(ji,jj) = zt_ml(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_tem,Kmm)
-               zds_ml(ji,jj) = zs_ml(ji,jj) - ts(ji,jj,ibld(ji,jj),jp_sal,Kmm)
-               zdu_ml(ji,jj) = zu_ml(ji,jj) - ( uu(ji,jj,ibld(ji,jj),Kbb) + uu(ji-1,jj,ibld(ji,jj) ,Kbb) ) &
-                     &    / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
-               zdv_ml(ji,jj) = zv_ml(ji,jj) - ( vv(ji,jj,ibld(ji,jj),Kbb) + vv(ji,jj-1,ibld(ji,jj) ,Kbb) ) &
-                     &    / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
-               zdb_ml(ji,jj) = grav * zthermal * zdt_ml(ji,jj) - grav * zbeta * zds_ml(ji,jj)
-            ENDIF
-         ENDIF
-      END_2D
-    !
+    ! Average over the depth of the mixed layer in the convective boundary layer
+!      jp_ext = ibld - imld +1
+      CALL zdf_osm_vertical_average( imld-1, ibld-imld+1, zt_ml, zs_ml, zb_ml, zu_ml, zv_ml, zdt_ml, zds_ml, zdb_ml, zdu_ml, zdv_ml )
     ! rotate mean currents and changes onto wind align co-ordinates
     !
-
-      DO_2D( 0, 0, 0, 0 )
-         ztemp = zu_ml(ji,jj)
-         zu_ml(ji,jj) = zu_ml(ji,jj) * zcos_wind(ji,jj) + zv_ml(ji,jj) * zsin_wind(ji,jj)
-         zv_ml(ji,jj) = zv_ml(ji,jj) * zcos_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
-         ztemp = zdu_ml(ji,jj)
-         zdu_ml(ji,jj) = zdu_ml(ji,jj) * zcos_wind(ji,jj) + zdv_ml(ji,jj) * zsin_wind(ji,jj)
-         zdv_ml(ji,jj) = zdv_ml(ji,jj) * zsin_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
- !
-         ztemp = zu_bl(ji,jj)
-         zu_bl = zu_bl(ji,jj) * zcos_wind(ji,jj) + zv_bl(ji,jj) * zsin_wind(ji,jj)
-         zv_bl(ji,jj) = zv_bl(ji,jj) * zcos_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
-         ztemp = zdu_bl(ji,jj)
-         zdu_bl(ji,jj) = zdu_bl(ji,jj) * zcos_wind(ji,jj) + zdv_bl(ji,jj) * zsin_wind(ji,jj)
-         zdv_bl(ji,jj) = zdv_bl(ji,jj) * zsin_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
-      END_2D
-
-     zuw_bse = 0._wp
-     zvw_bse = 0._wp
-     DO_2D( 0, 0, 0, 0 )
-
-        IF ( lconv(ji,jj) ) THEN
-           IF ( zdb_bl(ji,jj) > 0._wp ) THEN
-              zwth_ent(ji,jj) = zwb_ent(ji,jj) * zdt_ml(ji,jj) / (zdb_ml(ji,jj) + epsln)
-              zws_ent(ji,jj) = zwb_ent(ji,jj) * zds_ml(ji,jj) / (zdb_ml(ji,jj) + epsln)
-           ENDIF
-        ELSE
-           zwth_ent(ji,jj) = -2.0 * zwthav(ji,jj) * ( (1.0 - 0.8) - ( 1.0 - 0.8)**(3.0/2.0) )
-           zws_ent(ji,jj) = -2.0 * zwsav(ji,jj) * ( (1.0 - 0.8 ) - ( 1.0 - 0.8 )**(3.0/2.0) )
-        ENDIF
-     END_2D
-
+     CALL zdf_osm_velocity_rotation( zcos_wind, zsin_wind, zu_ml, zv_ml, zdu_ml, zdv_ml )
+     CALL zdf_osm_velocity_rotation( zcos_wind, zsin_wind, zu_bl, zv_bl, zdu_bl, zdv_bl )
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       !  Pycnocline gradients for scalars and velocity
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 
-       DO_2D( 0, 0, 0, 0 )
-       !
-          IF ( lconv (ji,jj) ) THEN
-          ! Unstable conditions
-             IF( zdb_bl(ji,jj) > 0._wp ) THEN
-             ! calculate pycnocline profiles, no need if zdb_bl <= 0. since profile is zero and arrays have been initialized to zero
-                ztgrad = ( zdt_ml(ji,jj) / zdh(ji,jj) )
-                zsgrad = ( zds_ml(ji,jj) / zdh(ji,jj) )
-                zbgrad = ( zdb_ml(ji,jj) / zdh(ji,jj) )
-                DO jk = 2 , ibld(ji,jj)
-                   znd = -( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zdh(ji,jj)
-                   zdtdz_pyc(ji,jj,jk) =  ztgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                   zdbdz_pyc(ji,jj,jk) =  zbgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                   zdsdz_pyc(ji,jj,jk) =  zsgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                END DO
-             ENDIF
-          ELSE
-          ! stable conditions
-          ! if pycnocline profile only defined when depth steady of increasing.
-             IF ( zdhdt(ji,jj) >= 0.0 ) THEN        ! Depth increasing, or steady.
-                IF ( zdb_bl(ji,jj) > 0._wp ) THEN
-                  IF ( zhol(ji,jj) >= 0.5 ) THEN      ! Very stable - 'thick' pycnocline
-                      ztgrad = zdt_bl(ji,jj) / zhbl(ji,jj)
-                      zsgrad = zds_bl(ji,jj) / zhbl(ji,jj)
-                      zbgrad = zdb_bl(ji,jj) / zhbl(ji,jj)
-                      DO jk = 2, ibld(ji,jj)
-                         znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
-                         zdtdz_pyc(ji,jj,jk) =  ztgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
-                         zdbdz_pyc(ji,jj,jk) =  zbgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
-                         zdsdz_pyc(ji,jj,jk) =  zsgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
-                      END DO
-                  ELSE                                   ! Slightly stable - 'thin' pycnoline - needed when stable layer begins to form.
-                      ztgrad = zdt_bl(ji,jj) / zdh(ji,jj)
-                      zsgrad = zds_bl(ji,jj) / zdh(ji,jj)
-                      zbgrad = zdb_bl(ji,jj) / zdh(ji,jj)
-                      DO jk = 2, ibld(ji,jj)
-                         znd = -( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zdh(ji,jj)
-                         zdtdz_pyc(ji,jj,jk) =  ztgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                         zdbdz_pyc(ji,jj,jk) =  zbgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                         zdsdz_pyc(ji,jj,jk) =  zsgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                      END DO
-                   ENDIF ! IF (zhol >=0.5)
-                ENDIF    ! IF (zdb_bl> 0.)
-             ENDIF       ! IF (zdhdt >= 0) zdhdt < 0 not considered since pycnocline profile is zero, profile arrays are intialized to zero
-          ENDIF          ! IF (lconv)
-         !
-       END_2D
-!
-       DO_2D( 0, 0, 0, 0 )
-       !
-          IF ( lconv (ji,jj) ) THEN
-          ! Unstable conditions
-              zugrad = ( zdu_ml(ji,jj) / zdh(ji,jj) ) + 0.275 * zustar(ji,jj)*zustar(ji,jj) / &
-            & (( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * zhml(ji,jj) ) / zla(ji,jj)**(8.0/3.0)
-             zvgrad = ( zdv_ml(ji,jj) / zdh(ji,jj) ) + 3.5 * ff_t(ji,jj) * zustke(ji,jj) / &
-           & ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
-             DO jk = 2 , ibld(ji,jj)-1
-                znd = -( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zdh(ji,jj)
-                zdudz_pyc(ji,jj,jk) =  zugrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-                zdvdz_pyc(ji,jj,jk) = zvgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
-             END DO
-          ELSE
-          ! stable conditions
-             zugrad = 3.25 * zdu_bl(ji,jj) / zhbl(ji,jj)
-             zvgrad = 2.75 * zdv_bl(ji,jj) / zhbl(ji,jj)
-             DO jk = 2, ibld(ji,jj)
-                znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
-                IF ( znd < 1.0 ) THEN
-                   zdudz_pyc(ji,jj,jk) = zugrad * EXP( -40.0 * ( znd - 1.0 )**2 )
-                ELSE
-                   zdudz_pyc(ji,jj,jk) = zugrad * EXP( -20.0 * ( znd - 1.0 )**2 )
-                ENDIF
-                zdvdz_pyc(ji,jj,jk) = zvgrad * EXP( -20.0 * ( znd - 0.85 )**2 )
-             END DO
-          ENDIF
-         !
-       END_2D
+      CALL zdf_osm_external_gradients( ibld+2, zdtdz_bl_ext, zdsdz_bl_ext, zdbdz_bl_ext )
+      CALL zdf_osm_pycnocline_scalar_profiles( zdtdz_pyc, zdsdz_pyc, zdbdz_pyc, zalpha_pyc )
+      CALL zdf_osm_pycnocline_shear_profiles( zdudz_pyc, zdvdz_pyc )
        !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        ! Eddy viscosity/diffusivity and non-gradient terms in the flux-gradient relationship
        !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-
-      ! WHERE ( lconv )
-      !     zdifml_sc = zhml * ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird
-      !     zvisml_sc = zdifml_sc
-      !     zdifpyc_sc = 0.165 * ( zwstrl**3 + zwstrc**3 )**pthird * ( zhbl - zhml )
-      !     zvispyc_sc = 0.142 * ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * ( zhbl - zhml )
-      !     zbeta_d_sc = 1.0 - (0.165 / 0.8 * ( zhbl - zhml ) / zhbl )**p2third
-      !     zbeta_v_sc = 1.0 -  2.0 * (0.142 /0.375) * (zhbl - zhml ) / zhml
-      !  ELSEWHERE
-      !     zdifml_sc = zwstrl * zhbl * EXP ( -( zhol / 0.183_wp )**2 )
-      !     zvisml_sc = zwstrl * zhbl * EXP ( -( zhol / 0.183_wp )**2 )
-      !  ENDWHERE
-       DO_2D( 0, 0, 0, 0 )
-          IF ( lconv(ji,jj) ) THEN
-            zdifml_sc(ji,jj) = zhml(ji,jj) * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
-            zvisml_sc(ji,jj) = zdifml_sc(ji,jj)
-            zdifpyc_sc(ji,jj) = 0.165 * ( zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3 )**pthird * zdh(ji,jj)
-            zvispyc_sc(ji,jj) = 0.142 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * zdh(ji,jj)
-            zbeta_d_sc(ji,jj) = 1.0 - (0.165 / 0.8 * zdh(ji,jj) / zhbl(ji,jj) )**p2third
-            zbeta_v_sc(ji,jj) = 1.0 -  2.0 * (0.142 /0.375) * zdh(ji,jj) / zhml(ji,jj)
-          ELSE
-            zdifml_sc(ji,jj) = zvstr(ji,jj) * zhbl(ji,jj) * EXP ( -( zhol(ji,jj) / 0.6_wp )**2 )
-            zvisml_sc(ji,jj) = zvstr(ji,jj) * zhbl(ji,jj) * EXP ( -( zhol(ji,jj) / 0.6_wp )**2 )
-         END IF
-       END_2D
-!
-       DO_2D( 0, 0, 0, 0 )
-          IF ( lconv(ji,jj) ) THEN
-             DO jk = 2, imld(ji,jj)   ! mixed layer diffusivity
-                 zznd_ml = gdepw(ji,jj,jk,Kmm) / zhml(ji,jj)
-                 !
-                 zdiffut(ji,jj,jk) = 0.8   * zdifml_sc(ji,jj) * zznd_ml * ( 1.0 - zbeta_d_sc(ji,jj) * zznd_ml    )**1.5
-                 !
-                 zviscos(ji,jj,jk) = 0.375 * zvisml_sc(ji,jj) * zznd_ml * ( 1.0 - zbeta_v_sc(ji,jj) * zznd_ml    ) &
-                      &            *                                      ( 1.0 -               0.5 * zznd_ml**2 )
-             END DO
-             ! pycnocline - if present linear profile
-             IF ( zdh(ji,jj) > 0._wp ) THEN
-                DO jk = imld(ji,jj)+1 , ibld(ji,jj)
-                    zznd_pyc = -( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zdh(ji,jj)
-                    !
-                    zdiffut(ji,jj,jk) = zdifpyc_sc(ji,jj) * ( 1.0 + zznd_pyc )
-                    !
-                    zviscos(ji,jj,jk) = zvispyc_sc(ji,jj) * ( 1.0 + zznd_pyc )
-                END DO
-             ENDIF
-             ! Temporay fix to ensure zdiffut is +ve; won't be necessary with ww taken out
-             zdiffut(ji,jj,ibld(ji,jj)) = zdhdt(ji,jj)* e3t(ji,jj,ibld(ji,jj),Kmm)
-             ! could be taken out, take account of entrainment represents as a diffusivity
-             ! should remove w from here, represents entrainment
-          ELSE
-          ! stable conditions
-             DO jk = 2, ibld(ji,jj)
-                zznd_ml = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
-                zdiffut(ji,jj,jk) = 0.75 * zdifml_sc(ji,jj) * zznd_ml * ( 1.0 - zznd_ml )**1.5
-                zviscos(ji,jj,jk) = 0.375 * zvisml_sc(ji,jj) * zznd_ml * (1.0 - zznd_ml) * ( 1.0 - zznd_ml**2 )
-             END DO
-          ENDIF   ! end if ( lconv )
-!
-       END_2D
+       CALL zdf_osm_diffusivity_viscosity( zdiffut, zviscos )
 
        !
@@ -918,15 +731,17 @@
        END_2D
 
-
 ! Stokes term in flux-gradient relationship (note in zsc_uw_n don't use zvstr since term needs to go to zero as zwstrl goes to zero)
        WHERE ( lconv )
-          zsc_uw_1 = ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * zustke /( 1.0 - 1.0 * 6.5 * zla**(8.0/3.0) )
-          zsc_uw_2 = ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * zustke / ( zla**(8.0/3.0) + epsln )
-          zsc_vw_1 = ff_t * zhml * zustke**3 * zla**(8.0/3.0) / ( ( zvstr**3 + 0.5 * zwstrc**3 )**(2.0/3.0) + epsln )
+          zsc_uw_1 = ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * zustke / MAX( ( 1.0 - 1.0 * 6.5 * zla**(8.0/3.0) ), 0.2 )
+          zsc_uw_2 = ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * zustke / MIN( zla**(8.0/3.0) + epsln, 0.12 )
+          zsc_vw_1 = ff_t * zhml * zustke**3 * MIN( zla**(8.0/3.0), 0.12 ) / ( ( zvstr**3 + 0.5 * zwstrc**3 )**(2.0/3.0) + epsln )
        ELSEWHERE
           zsc_uw_1 = zustar**2
-          zsc_vw_1 = ff_t * zhbl * zustke**3 * zla**(8.0/3.0) / (zvstr**2 + epsln)
+          zsc_vw_1 = ff_t * zhbl * zustke**3 * MIN( zla**(8.0/3.0), 0.12 ) / (zvstr**2 + epsln)
        ENDWHERE
-
+       IF(ln_dia_osm) THEN
+          IF ( iom_use("ghamu_00") ) CALL iom_put( "ghamu_00", wmask*ghamu )
+          IF ( iom_use("ghamv_00") ) CALL iom_put( "ghamv_00", wmask*ghamv )
+       END IF
        DO_2D( 0, 0, 0, 0 )
           IF ( lconv(ji,jj) ) THEN
@@ -970,10 +785,41 @@
                 zl_l = 2.0 * ( 1.0 - EXP ( - 2.0 * ( zznd_ml - zznd_ml**3 / 3.0 ) ) )                                           &
                      &     * ( 1.0 - EXP ( - 5.0 * (     1.0 - zznd_ml          ) ) ) * ( 1.0 + dstokes(ji,jj) / zhml (ji,jj) )
-                zl_eps = zl_l + ( zl_c - zl_l ) / ( 1.0 + EXP ( 3.0 * LOG10 ( - zhol(ji,jj) ) ) ) ** (3.0/2.0)
+                zl_eps = zl_l + ( zl_c - zl_l ) / ( 1.0 + EXP ( -3.0 * LOG10 ( - zhol(ji,jj) ) ) ) ** (3.0 / 2.0)
                 ! non-gradient buoyancy terms
                 ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.3 * 0.5 * zsc_wth_1(ji,jj) * zl_eps * zhml(ji,jj) / ( 0.15 + zznd_ml )
                 ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.3 * 0.5 *  zsc_ws_1(ji,jj) * zl_eps * zhml(ji,jj) / ( 0.15 + zznd_ml )
              END DO
-          ELSE
+             
+             IF ( lpyc(ji,jj) ) THEN
+               ztau_sc_u(ji,jj) = zhml(ji,jj) / ( zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**pthird
+               ztau_sc_u(ji,jj) = ztau_sc_u(ji,jj) * ( 1.4 -0.4 / ( 1.0 + EXP( -3.5 * LOG10( -zhol(ji,jj) ) ) )**1.5 )
+               zwth_ent =  -0.003 * ( 0.15 * zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**pthird * ( 1.0 - zdh(ji,jj) /zhbl(ji,jj) ) * zdt_ml(ji,jj)                  
+               zws_ent =  -0.003 * ( 0.15 * zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**pthird * ( 1.0 - zdh(ji,jj) /zhbl(ji,jj) ) * zds_ml(ji,jj)
+! Cubic profile used for buoyancy term
+               za_cubic = 0.755 * ztau_sc_u(ji,jj)
+               zb_cubic = 0.25 * ztau_sc_u(ji,jj)
+               DO jk = 2, ibld(ji,jj)
+                 zznd_pyc = -( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / zdh(ji,jj)
+                 ghamt(ji,jj,jk) = ghamt(ji,jj,jk) - 0.045 * ( ( zwth_ent * zdbdz_pyc(ji,jj,jk) ) * ztau_sc_u(ji,jj)**2 ) * MAX( ( 1.75 * zznd_pyc -0.15 * zznd_pyc**2 - 0.2 * zznd_pyc**3 ), 0.0 )
+
+                 ghams(ji,jj,jk) = ghams(ji,jj,jk) - 0.045 * ( ( zws_ent * zdbdz_pyc(ji,jj,jk) ) * ztau_sc_u(ji,jj)**2 ) * MAX( ( 1.75 * zznd_pyc -0.15 * zznd_pyc**2 - 0.2 * zznd_pyc**3 ), 0.0 )
+               END DO
+!
+               zbuoy_pyc_sc = zalpha_pyc(ji,jj) * zdb_ml(ji,jj) / zdh(ji,jj) + zdbdz_bl_ext(ji,jj)
+               zdelta_pyc = ( zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**pthird / SQRT( MAX( zbuoy_pyc_sc, ( zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**p2third / zdh(ji,jj)**2 ) )
+!
+               zwt_pyc_sc_1 = 0.325 * ( zalpha_pyc(ji,jj) * zdt_ml(ji,jj) / zdh(ji,jj) + zdtdz_bl_ext(ji,jj) ) * zdelta_pyc**2 / zdh(ji,jj)
+!
+               zws_pyc_sc_1 = 0.325 * ( zalpha_pyc(ji,jj) * zds_ml(ji,jj) / zdh(ji,jj) + zdsdz_bl_ext(ji,jj) ) * zdelta_pyc**2 / zdh(ji,jj)
+!
+               zzeta_pyc = 0.15 - 0.175 / ( 1.0 + EXP( -3.5 * LOG10( -zhol(ji,jj) ) ) ) 
+               DO jk = 2, ibld(ji,jj)
+                 zznd_pyc = -( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / zdh(ji,jj)
+                 ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.05 * zwt_pyc_sc_1 * EXP( -0.25 * ( zznd_pyc / zzeta_pyc )**2 ) * zdh(ji,jj) / ( zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**pthird
+!
+                 ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.05 * zws_pyc_sc_1 * EXP( -0.25 * ( zznd_pyc / zzeta_pyc )**2 ) * zdh(ji,jj) / ( zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 )**pthird
+               END DO
+            ENDIF ! End of pycnocline                  
+          ELSE ! lconv test - stable conditions
              DO jk = 2, ibld(ji,jj)
                 ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zsc_wth_1(ji,jj)
@@ -982,5 +828,4 @@
           ENDIF
        END_2D
-
 
        WHERE ( lconv )
@@ -1011,13 +856,54 @@
        END_2D
 
+       DO_2D( 0, 0, 0, 0 )
+        IF ( lpyc(ji,jj) ) THEN
+          IF ( j_ddh(ji,jj) == 0 ) THEN
+! Place holding code. Parametrization needs checking for these conditions.
+            zomega = ( 0.15 * zwstrl(ji,jj)**3 + zwstrc(ji,jj)**3 + 4.75 * ( zshear(ji,jj)* zhbl(ji,jj) )**pthird )**pthird
+            zuw_bse = -0.0035 * zomega * ( 1.0 - zdh(ji,jj) / zhbl(ji,jj) ) * zdu_ml(ji,jj)
+            zvw_bse = -0.0075 * zomega * ( 1.0 - zdh(ji,jj) / zhbl(ji,jj) ) * zdv_ml(ji,jj)
+          ELSE
+            zomega = ( 0.15 * zwstrl(ji,jj)**3 + zwstrc(ji,jj)**3 + 4.75 * ( zshear(ji,jj)* zhbl(ji,jj) )**pthird )**pthird
+            zuw_bse = -0.0035 * zomega * ( 1.0 - zdh(ji,jj) / zhbl(ji,jj) ) * zdu_ml(ji,jj)
+            zvw_bse = -0.0075 * zomega * ( 1.0 - zdh(ji,jj) / zhbl(ji,jj) ) * zdv_ml(ji,jj)
+          ENDIF
+          zd_cubic = zdh(ji,jj) / zhbl(ji,jj) * zuw0(ji,jj) - ( 2.0 + zdh(ji,jj) /zhml(ji,jj) ) * zuw_bse
+          zc_cubic = zuw_bse - zd_cubic
+! need ztau_sc_u to be available. Change to array. 
+          DO jk = imld(ji,jj), ibld(ji,jj)
+             zznd_pyc = - ( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / zdh(ji,jj)
+             ghamu(ji,jj,jk) = ghamu(ji,jj,jk) - 0.045 * ztau_sc_u(ji,jj)**2 * ( zc_cubic * zznd_pyc**2 + zd_cubic * zznd_pyc**3 ) * ( 0.75 + 0.25 * zznd_pyc )**2 * zdbdz_pyc(ji,jj,jk)
+          END DO
+          zvw_max = 0.7 * ff_t(ji,jj) * ( zustke(ji,jj) * dstokes(ji,jj) + 0.75 * zustar(ji,jj) * zhml(ji,jj) )
+          zd_cubic = zvw_max * zdh(ji,jj) / zhml(ji,jj) - ( 2.0 + zdh(ji,jj) /zhml(ji,jj) ) * zvw_bse
+          zc_cubic = zvw_bse - zd_cubic
+          DO jk = imld(ji,jj), ibld(ji,jj)
+            zznd_pyc = -( gdepw(ji,jj,jk,Kmm) -zhbl(ji,jj) ) / zdh(ji,jj)
+            ghamv(ji,jj,jk) = ghamv(ji,jj,jk) - 0.045 * ztau_sc_u(ji,jj)**2 * ( zc_cubic * zznd_pyc**2 + zd_cubic * zznd_pyc**3 ) * ( 0.75 + 0.25 * zznd_pyc )**2 * zdbdz_pyc(ji,jj,jk)
+          END DO
+        ENDIF  ! lpyc
+       END_2D
+
+       IF(ln_dia_osm) THEN
+          IF ( iom_use("ghamu_0") ) CALL iom_put( "ghamu_0", wmask*ghamu )
+          IF ( iom_use("zsc_uw_1_0") ) CALL iom_put( "zsc_uw_1_0", tmask(:,:,1)*zsc_uw_1 )
+       END IF
 ! Transport term in flux-gradient relationship [note : includes ROI ratio (X0.3) ]
 
-       WHERE ( lconv )
-          zsc_wth_1 = zwth0
-          zsc_ws_1 = zws0
-       ELSEWHERE
-          zsc_wth_1 = 2.0 * zwthav
-          zsc_ws_1 = zws0
-       ENDWHERE
+       DO_2D( 1, 0, 1, 0 )
+       
+         IF ( lconv(ji,jj) ) THEN
+           zsc_wth_1(ji,jj) = zwth0(ji,jj) / ( 1.0 - 0.56 * EXP( zhol(ji,jj) ) )
+           zsc_ws_1(ji,jj) = zws0(ji,jj) / (1.0 - 0.56 *EXP( zhol(ji,jj) ) )
+           IF ( lpyc(ji,jj) ) THEN
+! Pycnocline scales
+              zsc_wth_pyc(ji,jj) = -0.2 * zwb0(ji,jj) * zdt_bl(ji,jj) / zdb_bl(ji,jj)
+              zsc_ws_pyc(ji,jj) = -0.2 * zwb0(ji,jj) * zds_bl(ji,jj) / zdb_bl(ji,jj)
+            ENDIF
+         ELSE
+           zsc_wth_1(ji,jj) = 2.0 * zwthav(ji,jj)
+           zsc_ws_1(ji,jj) = zws0(ji,jj)
+         ENDIF
+       END_2D
 
        DO_2D( 0, 0, 0, 0 )
@@ -1035,16 +921,26 @@
                     &          * ( 1.0 - EXP ( -15.0 * (         1.0 - zznd_ml    ) ) )
             END DO
+!
+            IF ( lpyc(ji,jj) ) THEN
+! pycnocline
+              DO jk = imld(ji,jj), ibld(ji,jj)
+                zznd_pyc = - ( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / zdh(ji,jj)
+                ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 4.0 * zsc_wth_pyc(ji,jj) * ( 0.48 - EXP( -1.5 * ( zznd_pyc -0.3)**2 ) ) 
+                ghams(ji,jj,jk) = ghams(ji,jj,jk) + 4.0 * zsc_ws_pyc(ji,jj) * ( 0.48 - EXP( -1.5 * ( zznd_pyc -0.3)**2 ) ) 
+              END DO
+           ENDIF
          ELSE
-            DO jk = 2, ibld(ji,jj)
-               zznd_d = gdepw(ji,jj,jk,Kmm) / dstokes(ji,jj)
-               znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
-               ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.3 * ( -4.06 * EXP( -2.0 * zznd_d ) * (1.0 - EXP( -4.0 * zznd_d ) ) + &
-            &  7.5 * EXP ( -10.0 * ( 0.95 - znd )**2 ) * ( 1.0 - znd ) ) * zsc_wth_1(ji,jj)
-               ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.3 * ( -4.06 * EXP( -2.0 * zznd_d ) * (1.0 - EXP( -4.0 * zznd_d ) ) + &
-            &  7.5 * EXP ( -10.0 * ( 0.95 - znd )**2 ) * ( 1.0 - znd ) ) * zsc_ws_1(ji,jj)
-            END DO
+            IF( zdhdt(ji,jj) > 0. ) THEN
+              DO jk = 2, ibld(ji,jj)
+                 zznd_d = gdepw(ji,jj,jk,Kmm) / dstokes(ji,jj)
+                 znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
+                 ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.3 * ( -4.06 * EXP( -2.0 * zznd_d ) * (1.0 - EXP( -4.0 * zznd_d ) ) + &
+              &  7.5 * EXP ( -10.0 * ( 0.95 - znd )**2 ) * ( 1.0 - znd ) ) * zsc_wth_1(ji,jj)
+                 ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.3 * ( -4.06 * EXP( -2.0 * zznd_d ) * (1.0 - EXP( -4.0 * zznd_d ) ) + &
+               &  7.5 * EXP ( -10.0 * ( 0.95 - znd )**2 ) * ( 1.0 - znd ) ) * zsc_ws_1(ji,jj)
+              END DO
+            ENDIF
          ENDIF
        END_2D
-
 
        WHERE ( lconv )
@@ -1090,22 +986,23 @@
           ENDIF
        END_2D
+
+       IF(ln_dia_osm) THEN
+          IF ( iom_use("ghamu_f") ) CALL iom_put( "ghamu_f", wmask*ghamu )
+          IF ( iom_use("ghamv_f") ) CALL iom_put( "ghamv_f", wmask*ghamv )
+          IF ( iom_use("zsc_uw_1_f") ) CALL iom_put( "zsc_uw_1_f", tmask(:,:,1)*zsc_uw_1 )
+          IF ( iom_use("zsc_vw_1_f") ) CALL iom_put( "zsc_vw_1_f", tmask(:,:,1)*zsc_vw_1 )
+          IF ( iom_use("zsc_uw_2_f") ) CALL iom_put( "zsc_uw_2_f", tmask(:,:,1)*zsc_uw_2 )
+          IF ( iom_use("zsc_vw_2_f") ) CALL iom_put( "zsc_vw_2_f", tmask(:,:,1)*zsc_vw_2 )
+       END IF
 !
 ! Make surface forced velocity non-gradient terms go to zero at the base of the mixed layer.
 
+
+ ! Make surface forced velocity non-gradient terms go to zero at the base of the boundary layer.
+
       DO_2D( 0, 0, 0, 0 )
-         IF ( lconv(ji,jj) ) THEN
+         IF ( .not. lconv(ji,jj) ) THEN
             DO jk = 2, ibld(ji,jj)
-               znd = ( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zhml(ji,jj) !ALMG to think about
-               IF ( znd >= 0.0 ) THEN
-                  ghamu(ji,jj,jk) = ghamu(ji,jj,jk) * ( 1.0 - EXP( -30.0 * znd**2 ) )
-                  ghamv(ji,jj,jk) = ghamv(ji,jj,jk) * ( 1.0 - EXP( -30.0 * znd**2 ) )
-               ELSE
-                  ghamu(ji,jj,jk) = 0._wp
-                  ghamv(ji,jj,jk) = 0._wp
-               ENDIF
-            END DO
-         ELSE
-            DO jk = 2, ibld(ji,jj)
-               znd = ( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zhml(ji,jj) !ALMG to think about
+               znd = ( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / zhbl(ji,jj) !ALMG to think about
                IF ( znd >= 0.0 ) THEN
                   ghamu(ji,jj,jk) = ghamu(ji,jj,jk) * ( 1.0 - EXP( -10.0 * znd**2 ) )
@@ -1120,43 +1017,36 @@
 
       ! pynocline contributions
-       ! Temporary fix to avoid instabilities when zdb_bl becomes very very small
-       zsc_uw_1 = 0._wp ! 50.0 * zla**(8.0/3.0) * zustar**2 * zhbl / ( zdb_bl + epsln )
        DO_2D( 0, 0, 0, 0 )
-          DO jk= 2, ibld(ji,jj)
-             znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
-             ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zdiffut(ji,jj,jk) * zdtdz_pyc(ji,jj,jk)
-             ghams(ji,jj,jk) = ghams(ji,jj,jk) + zdiffut(ji,jj,jk) * zdsdz_pyc(ji,jj,jk)
-             ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zviscos(ji,jj,jk) * zdudz_pyc(ji,jj,jk)
-             ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zsc_uw_1(ji,jj) * ( 1.0 - znd )**(7.0/4.0) * zdbdz_pyc(ji,jj,jk)
-             ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zviscos(ji,jj,jk) * zdvdz_pyc(ji,jj,jk)
-          END DO
+         IF ( .not. lconv(ji,jj) ) THEN
+          IF ( ibld(ji,jj) + jp_ext(ji,jj) < mbkt(ji,jj) ) THEN
+             DO jk= 2, ibld(ji,jj)
+                znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
+                ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zdiffut(ji,jj,jk) * zdtdz_pyc(ji,jj,jk)
+                ghams(ji,jj,jk) = ghams(ji,jj,jk) + zdiffut(ji,jj,jk) * zdsdz_pyc(ji,jj,jk)
+                ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zviscos(ji,jj,jk) * zdudz_pyc(ji,jj,jk)
+                ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zviscos(ji,jj,jk) * zdvdz_pyc(ji,jj,jk)
+             END DO
+          END IF
+         END IF
        END_2D
-
-! Entrainment contribution.
+      IF(ln_dia_osm) THEN
+          IF ( iom_use("ghamu_b") ) CALL iom_put( "ghamu_b", wmask*ghamu )
+          IF ( iom_use("ghamv_b") ) CALL iom_put( "ghamv_b", wmask*ghamv )
+       END IF
 
        DO_2D( 0, 0, 0, 0 )
-          IF ( lconv(ji,jj) ) THEN
-            DO jk = 1, imld(ji,jj) - 1
-               znd=gdepw(ji,jj,jk,Kmm) / zhml(ji,jj)
-               ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zwth_ent(ji,jj) * znd
-               ghams(ji,jj,jk) = ghams(ji,jj,jk) + zws_ent(ji,jj) * znd
-               ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zuw_bse(ji,jj) * znd
-               ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zvw_bse(ji,jj) * znd
-            END DO
-            DO jk = imld(ji,jj), ibld(ji,jj)
-               znd = -( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) / zdh(ji,jj)
-               ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zwth_ent(ji,jj) * ( 1.0 + znd )
-               ghams(ji,jj,jk) = ghams(ji,jj,jk) + zws_ent(ji,jj) * ( 1.0 + znd )
-               ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zuw_bse(ji,jj) * ( 1.0 + znd )
-               ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zvw_bse(ji,jj) * ( 1.0 + znd )
-             END DO
-          ENDIF
-          ghamt(ji,jj,ibld(ji,jj)) = 0._wp
-          ghams(ji,jj,ibld(ji,jj)) = 0._wp
-          ghamu(ji,jj,ibld(ji,jj)) = 0._wp
-          ghamv(ji,jj,ibld(ji,jj)) = 0._wp
+          ghamt(ji,jj,ibld(ji,jj)+ibld_ext) = 0._wp
+          ghams(ji,jj,ibld(ji,jj)+ibld_ext) = 0._wp
+          ghamu(ji,jj,ibld(ji,jj)+ibld_ext) = 0._wp
+          ghamv(ji,jj,ibld(ji,jj)+ibld_ext) = 0._wp
        END_2D
 
-
+       IF(ln_dia_osm) THEN
+          IF ( iom_use("ghamu_1") ) CALL iom_put( "ghamu_1", wmask*ghamu )
+          IF ( iom_use("ghamv_1") ) CALL iom_put( "ghamv_1", wmask*ghamv )
+          IF ( iom_use("zdudz_pyc") ) CALL iom_put( "zdudz_pyc", wmask*zdudz_pyc )
+          IF ( iom_use("zdvdz_pyc") ) CALL iom_put( "zdvdz_pyc", wmask*zdvdz_pyc )
+          IF ( iom_use("zviscos") ) CALL iom_put( "zviscos", wmask*zviscos )
+       END IF
        !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        ! Need to put in code for contributions that are applied explicitly to
@@ -1180,4 +1070,6 @@
        IF(ln_dia_osm) THEN
           IF ( iom_use("zdtdz_pyc") ) CALL iom_put( "zdtdz_pyc", wmask*zdtdz_pyc )
+          IF ( iom_use("zdsdz_pyc") ) CALL iom_put( "zdsdz_pyc", wmask*zdsdz_pyc )
+          IF ( iom_use("zdbdz_pyc") ) CALL iom_put( "zdbdz_pyc", wmask*zdbdz_pyc )
        END IF
 
@@ -1222,6 +1114,45 @@
        END IF ! ln_convmix = .true.
 
+
+
+       IF ( ln_osm_mle ) THEN  ! set up diffusivity and non-gradient mixing
+          DO_2D( 0, 0, 0, 0 )
+              IF ( lflux(ji,jj) ) THEN ! MLE mixing extends below boundary layer
+             ! Calculate MLE flux contribution from surface fluxes
+                DO jk = 1, ibld(ji,jj)
+                  znd = gdepw(ji,jj,jk,Kmm) / MAX(zhbl(ji,jj),epsln)
+                  ghamt(ji,jj,jk) = ghamt(ji,jj,jk) - zwth0(ji,jj) * ( 1.0 - znd )
+                  ghams(ji,jj,jk) = ghams(ji,jj,jk) - zws0(ji,jj) * ( 1.0 - znd )
+                 END DO
+                 DO jk = 1, mld_prof(ji,jj)
+                   znd = gdepw(ji,jj,jk,Kmm) / MAX(zhmle(ji,jj),epsln)
+                   ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zwth0(ji,jj) * ( 1.0 - znd )
+                   ghams(ji,jj,jk) = ghams(ji,jj,jk) + zws0(ji,jj) * ( 1.0 -znd )
+                 END DO
+         ! Viscosity for MLEs
+                 DO jk = 1, mld_prof(ji,jj)
+                   znd = -gdepw(ji,jj,jk,Kmm) / MAX(zhmle(ji,jj),epsln)
+                   zdiffut(ji,jj,jk) = zdiffut(ji,jj,jk) + zdiff_mle(ji,jj) * ( 1.0 - ( 2.0 * znd + 1.0 )**2 ) * ( 1.0 + 5.0 / 21.0 * ( 2.0 * znd + 1.0 )** 2 )
+                 END DO
+              ELSE
+! Surface transports limited to OSBL.                 
+         ! Viscosity for MLEs
+                 DO jk = 1, mld_prof(ji,jj)
+                   znd = -gdepw(ji,jj,jk,Kmm) / MAX(zhmle(ji,jj),epsln)
+                   zdiffut(ji,jj,jk) = zdiffut(ji,jj,jk) + zdiff_mle(ji,jj) * ( 1.0 - ( 2.0 * znd + 1.0 )**2 ) * ( 1.0 + 5.0 / 21.0 * ( 2.0 * znd + 1.0 )** 2 )
+                 END DO
+              ENDIF
+          END_2D
+       ENDIF
+
+       IF(ln_dia_osm) THEN
+          IF ( iom_use("zdtdz_pyc") ) CALL iom_put( "zdtdz_pyc", wmask*zdtdz_pyc )
+          IF ( iom_use("zdsdz_pyc") ) CALL iom_put( "zdsdz_pyc", wmask*zdsdz_pyc )
+          IF ( iom_use("zdbdz_pyc") ) CALL iom_put( "zdbdz_pyc", wmask*zdbdz_pyc )
+       END IF
+
+
        ! Lateral boundary conditions on zvicos (sign unchanged), needed to caclulate viscosities on u and v grids
-       CALL lbc_lnk( 'zdfosm', zviscos(:,:,:), 'W', 1.0_wp )
+       !CALL lbc_lnk( 'zdfosm', zviscos(:,:,:), 'W', 1.0_wp )
 
        ! GN 25/8: need to change tmask --> wmask
@@ -1244,10 +1175,12 @@
             ghams(ji,jj,jk) =  ghams(ji,jj,jk) * tmask(ji,jj,jk)
        END_3D
+        ! Lateral boundary conditions on final outputs for hbl,  on T-grid (sign unchanged)
+        CALL lbc_lnk_multi( 'zdfosm', hbl, 'T', 1., dh, 'T', 1., hmle, 'T', 1. )
         ! Lateral boundary conditions on final outputs for gham[ts],  on W-grid  (sign unchanged)
-        ! Lateral boundary conditions on final outputs for gham[uv],  on [UV]-grid  (sign unchanged)
-        CALL lbc_lnk_multi( 'zdfosm', ghamt, 'W', 1.0_wp , ghams, 'W', 1.0_wp,   &
-         &                  ghamu, 'U', 1.0_wp , ghamv, 'V', 1.0_wp )
-
-       IF(ln_dia_osm) THEN
+        ! Lateral boundary conditions on final outputs for gham[uv],  on [UV]-grid  (sign changed)
+        CALL lbc_lnk_multi( 'zdfosm', ghamt, 'W',  1.0_wp , ghams, 'W',  1.0_wp,   &
+         &                            ghamu, 'U', -1.0_wp , ghamv, 'V', -1.0_wp )
+
+      IF(ln_dia_osm) THEN
          SELECT CASE (nn_osm_wave)
          ! Stokes drift set by assumimg onstant La#=0.3(=0)  or Pierson-Moskovitz spectrum (=1).
@@ -1257,7 +1190,12 @@
             IF ( iom_use("wind_wave_abs_power") ) CALL iom_put( "wind_wave_abs_power", 1000.*rho0*tmask(:,:,1)*zustar**2*zustke )
          ! Stokes drift read in from sbcwave  (=2).
-         CASE(2)
-            IF ( iom_use("us_x") ) CALL iom_put( "us_x", ut0sd )               ! x surface Stokes drift
-            IF ( iom_use("us_y") ) CALL iom_put( "us_y", vt0sd )               ! y surface Stokes drift
+         CASE(2:3)
+            IF ( iom_use("us_x") ) CALL iom_put( "us_x", ut0sd*umask(:,:,1) )               ! x surface Stokes drift
+            IF ( iom_use("us_y") ) CALL iom_put( "us_y", vt0sd*vmask(:,:,1) )               ! y surface Stokes drift
+            IF ( iom_use("wmp") ) CALL iom_put( "wmp", wmp*tmask(:,:,1) )                   ! wave mean period
+            IF ( iom_use("hsw") ) CALL iom_put( "hsw", hsw*tmask(:,:,1) )                   ! significant wave height
+            IF ( iom_use("wmp_NP") ) CALL iom_put( "wmp_NP", (2.*rpi*1.026/(0.877*grav) )*wndm*tmask(:,:,1) )                  ! wave mean period from NP spectrum
+            IF ( iom_use("hsw_NP") ) CALL iom_put( "hsw_NP", (0.22/grav)*wndm**2*tmask(:,:,1) )                   ! significant wave height from NP spectrum
+            IF ( iom_use("wndm") ) CALL iom_put( "wndm", wndm*tmask(:,:,1) )                   ! U_10
             IF ( iom_use("wind_wave_abs_power") ) CALL iom_put( "wind_wave_abs_power", 1000.*rho0*tmask(:,:,1)*zustar**2* &
                  & SQRT(ut0sd**2 + vt0sd**2 ) )
@@ -1270,5 +1208,12 @@
          IF ( iom_use("zws0") ) CALL iom_put( "zws0", tmask(:,:,1)*zws0 )                ! <Sw_0>
          IF ( iom_use("hbl") ) CALL iom_put( "hbl", tmask(:,:,1)*hbl )                  ! boundary-layer depth
-         IF ( iom_use("hbli") ) CALL iom_put( "hbli", tmask(:,:,1)*hbli )               ! Initial boundary-layer depth
+         IF ( iom_use("ibld") ) CALL iom_put( "ibld", tmask(:,:,1)*ibld )               ! boundary-layer max k
+         IF ( iom_use("zdt_bl") ) CALL iom_put( "zdt_bl", tmask(:,:,1)*zdt_bl )           ! dt at ml base
+         IF ( iom_use("zds_bl") ) CALL iom_put( "zds_bl", tmask(:,:,1)*zds_bl )           ! ds at ml base
+         IF ( iom_use("zdb_bl") ) CALL iom_put( "zdb_bl", tmask(:,:,1)*zdb_bl )           ! db at ml base
+         IF ( iom_use("zdu_bl") ) CALL iom_put( "zdu_bl", tmask(:,:,1)*zdu_bl )           ! du at ml base
+         IF ( iom_use("zdv_bl") ) CALL iom_put( "zdv_bl", tmask(:,:,1)*zdv_bl )           ! dv at ml base
+         IF ( iom_use("dh") ) CALL iom_put( "dh", tmask(:,:,1)*dh )               ! Initial boundary-layer depth
+         IF ( iom_use("hml") ) CALL iom_put( "hml", tmask(:,:,1)*hml )               ! Initial boundary-layer depth
          IF ( iom_use("dstokes") ) CALL iom_put( "dstokes", tmask(:,:,1)*dstokes )      ! Stokes drift penetration depth
          IF ( iom_use("zustke") ) CALL iom_put( "zustke", tmask(:,:,1)*zustke )            ! Stokes drift magnitude at T-points
@@ -1276,21 +1221,1228 @@
          IF ( iom_use("zwstrl") ) CALL iom_put( "zwstrl", tmask(:,:,1)*zwstrl )         ! Langmuir velocity scale
          IF ( iom_use("zustar") ) CALL iom_put( "zustar", tmask(:,:,1)*zustar )         ! friction velocity scale
+         IF ( iom_use("zvstr") ) CALL iom_put( "zvstr", tmask(:,:,1)*zvstr )         ! mixed velocity scale
+         IF ( iom_use("zla") ) CALL iom_put( "zla", tmask(:,:,1)*zla )         ! langmuir #
          IF ( iom_use("wind_power") ) CALL iom_put( "wind_power", 1000.*rho0*tmask(:,:,1)*zustar**3 ) ! BL depth internal to zdf_osm routine
          IF ( iom_use("wind_wave_power") ) CALL iom_put( "wind_wave_power", 1000.*rho0*tmask(:,:,1)*zustar**2*zustke )
          IF ( iom_use("zhbl") ) CALL iom_put( "zhbl", tmask(:,:,1)*zhbl )               ! BL depth internal to zdf_osm routine
          IF ( iom_use("zhml") ) CALL iom_put( "zhml", tmask(:,:,1)*zhml )               ! ML depth internal to zdf_osm routine
-         IF ( iom_use("zdh") ) CALL iom_put( "zdh", tmask(:,:,1)*zdh )               ! ML depth internal to zdf_osm routine
+         IF ( iom_use("imld") ) CALL iom_put( "imld", tmask(:,:,1)*imld )               ! index for ML depth internal to zdf_osm routine
+         IF ( iom_use("zdh") ) CALL iom_put( "zdh", tmask(:,:,1)*zdh )                  ! pyc thicknessh internal to zdf_osm routine
          IF ( iom_use("zhol") ) CALL iom_put( "zhol", tmask(:,:,1)*zhol )               ! ML depth internal to zdf_osm routine
-         IF ( iom_use("zwthav") ) CALL iom_put( "zwthav", tmask(:,:,1)*zwthav )               ! ML depth internal to zdf_osm routine
-         IF ( iom_use("zwth_ent") ) CALL iom_put( "zwth_ent", tmask(:,:,1)*zwth_ent )               ! ML depth internal to zdf_osm routine
-         IF ( iom_use("zt_ml") ) CALL iom_put( "zt_ml", tmask(:,:,1)*zt_ml )               ! average T in ML
+         IF ( iom_use("zwthav") ) CALL iom_put( "zwthav", tmask(:,:,1)*zwthav )         ! upward BL-avged turb temp flux
+         IF ( iom_use("zwth_ent") ) CALL iom_put( "zwth_ent", tmask(:,:,1)*zwth_ent )   ! upward turb temp entrainment flux
+         IF ( iom_use("zwb_ent") ) CALL iom_put( "zwb_ent", tmask(:,:,1)*zwb_ent )      ! upward turb buoyancy entrainment flux
+         IF ( iom_use("zws_ent") ) CALL iom_put( "zws_ent", tmask(:,:,1)*zws_ent )      ! upward turb salinity entrainment flux
+         IF ( iom_use("zt_ml") ) CALL iom_put( "zt_ml", tmask(:,:,1)*zt_ml )            ! average T in ML
+
+         IF ( iom_use("hmle") ) CALL iom_put( "hmle", tmask(:,:,1)*hmle )               ! FK layer depth
+         IF ( iom_use("zmld") ) CALL iom_put( "zmld", tmask(:,:,1)*zmld )               ! FK target layer depth
+         IF ( iom_use("zwb_fk") ) CALL iom_put( "zwb_fk", tmask(:,:,1)*zwb_fk )         ! FK b flux
+         IF ( iom_use("zwb_fk_b") ) CALL iom_put( "zwb_fk_b", tmask(:,:,1)*zwb_fk_b )   ! FK b flux averaged over ML
+         IF ( iom_use("mld_prof") ) CALL iom_put( "mld_prof", tmask(:,:,1)*mld_prof )! FK layer max k
+         IF ( iom_use("zdtdx") ) CALL iom_put( "zdtdx", umask(:,:,1)*zdtdx )            ! FK dtdx at u-pt
+         IF ( iom_use("zdtdy") ) CALL iom_put( "zdtdy", vmask(:,:,1)*zdtdy )            ! FK dtdy at v-pt
+         IF ( iom_use("zdsdx") ) CALL iom_put( "zdsdx", umask(:,:,1)*zdsdx )            ! FK dtdx at u-pt
+         IF ( iom_use("zdsdy") ) CALL iom_put( "zdsdy", vmask(:,:,1)*zdsdy )            ! FK dsdy at v-pt
+         IF ( iom_use("dbdx_mle") ) CALL iom_put( "dbdx_mle", umask(:,:,1)*dbdx_mle )            ! FK dbdx at u-pt
+         IF ( iom_use("dbdy_mle") ) CALL iom_put( "dbdy_mle", vmask(:,:,1)*dbdy_mle )            ! FK dbdy at v-pt
+         IF ( iom_use("zdiff_mle") ) CALL iom_put( "zdiff_mle", tmask(:,:,1)*zdiff_mle )! FK diff in MLE at t-pt
+         IF ( iom_use("zvel_mle") ) CALL iom_put( "zvel_mle", tmask(:,:,1)*zdiff_mle )! FK diff in MLE at t-pt
+
       END IF
-      ! Lateral boundary conditions on p_avt  (sign unchanged)
-      CALL lbc_lnk( 'zdfosm', p_avt(:,:,:), 'W', 1.0_wp )
+
+CONTAINS
+! subroutine code changed, needs syntax checking.
+  SUBROUTINE zdf_osm_diffusivity_viscosity( zdiffut, zviscos )
+
+!!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_osm_diffusivity_viscosity  ***
+     !!
+     !! ** Purpose : Determines the eddy diffusivity and eddy viscosity profiles in the mixed layer and the pycnocline.
+     !!
+     !! ** Method  : 
+     !!
+     !! !!----------------------------------------------------------------------
+     REAL(wp), DIMENSION(:,:,:) :: zdiffut
+     REAL(wp), DIMENSION(:,:,:) :: zviscos
+! local
+
+! Scales used to calculate eddy diffusivity and viscosity profiles
+      REAL(wp), DIMENSION(jpi,jpj) :: zdifml_sc, zvisml_sc
+      REAL(wp), DIMENSION(jpi,jpj) :: zdifpyc_n_sc, zdifpyc_s_sc, zdifpyc_shr
+      REAL(wp), DIMENSION(jpi,jpj) :: zvispyc_n_sc, zvispyc_s_sc,zvispyc_shr
+      REAL(wp), DIMENSION(jpi,jpj) :: zbeta_d_sc, zbeta_v_sc
+!
+      REAL(wp) :: zvel_sc_pyc, zvel_sc_ml, zstab_fac
+      
+      REAL(wp), PARAMETER :: rn_dif_ml = 0.8, rn_vis_ml = 0.375
+      REAL(wp), PARAMETER :: rn_dif_pyc = 0.15, rn_vis_pyc = 0.142
+      REAL(wp), PARAMETER :: rn_vispyc_shr = 0.15
+      
+      DO_2D( 0, 0, 0, 0 )
+          IF ( lconv(ji,jj) ) THEN
+          
+            zvel_sc_pyc = ( 0.15 * zvstr(ji,jj)**3 + zwstrc(ji,jj)**3 + 4.25 * zshear(ji,jj) * zhbl(ji,jj) )**pthird
+            zvel_sc_ml = ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+            zstab_fac = ( zhml(ji,jj) / zvel_sc_ml * ( 1.4 - 0.4 / ( 1.0 + EXP(-3.5 * LOG10(-zhol(ji,jj) ) ) )**1.25 ) )**2
+
+            zdifml_sc(ji,jj) = rn_dif_ml * zhml(ji,jj) * zvel_sc_ml
+            zvisml_sc(ji,jj) = rn_vis_ml * zdifml_sc(ji,jj)
+
+            IF ( lpyc(ji,jj) ) THEN
+              zdifpyc_n_sc(ji,jj) =  rn_dif_pyc * zvel_sc_ml * zdh(ji,jj)
+
+              IF ( lshear(ji,jj) .and. j_ddh(ji,jj) == 1 ) THEN
+                zdifpyc_n_sc(ji,jj) = zdifpyc_n_sc(ji,jj) + rn_vispyc_shr * ( zshear(ji,jj) * zhbl(ji,jj) )**pthird * zhbl(ji,jj)
+              ENDIF
+            
+              zdifpyc_s_sc(ji,jj) = zwb_ent(ji,jj) + 0.0025 * zvel_sc_pyc * ( zhbl(ji,jj) / zdh(ji,jj) - 1.0 ) * ( zb_ml(ji,jj) - zb_bl(ji,jj) )
+              zdifpyc_s_sc(ji,jj) = 0.09 * zdifpyc_s_sc(ji,jj) * zstab_fac
+              zdifpyc_s_sc(ji,jj) = MAX( zdifpyc_s_sc(ji,jj), -0.5 * zdifpyc_n_sc(ji,jj) )
+              
+              zvispyc_n_sc(ji,jj) = 0.09 * zvel_sc_pyc * ( 1.0 - zhbl(ji,jj) / zdh(ji,jj) )**2 * ( 0.005 * ( zu_ml(ji,jj)-zu_bl(ji,jj) )**2 + 0.0075 * ( zv_ml(ji,jj)-zv_bl(ji,jj) )**2 ) / zdh(ji,jj)
+              zvispyc_n_sc(ji,jj) = rn_vis_pyc * zvel_sc_ml * zdh(ji,jj) + zvispyc_n_sc(ji,jj) * zstab_fac
+              IF ( lshear(ji,jj) .and. j_ddh(ji,jj) == 1 ) THEN
+                zvispyc_n_sc(ji,jj) = zvispyc_n_sc(ji,jj) + rn_vispyc_shr * ( zshear(ji,jj) * zhbl(ji,jj ) )**pthird * zhbl(ji,jj)
+              ENDIF
+             
+              zvispyc_s_sc(ji,jj) = 0.09 * ( zwb_min(ji,jj) + 0.0025 * zvel_sc_pyc * ( zhbl(ji,jj) / zdh(ji,jj) - 1.0 ) * ( zb_ml(ji,jj) - zb_bl(ji,jj) ) )
+              zvispyc_s_sc(ji,jj) = zvispyc_s_sc(ji,jj) * zstab_fac
+              zvispyc_s_sc(ji,jj) = MAX( zvispyc_s_sc(ji,jj), -0.5 * zvispyc_s_sc(ji,jj) )
+
+              zbeta_d_sc(ji,jj) = 1.0 - ( ( zdifpyc_n_sc(ji,jj) + 1.4 * zdifpyc_s_sc(ji,jj) ) / ( zdifml_sc(ji,jj) + epsln ) )**p2third
+              zbeta_v_sc(ji,jj) = 1.0 -  2.0 * ( zvispyc_n_sc(ji,jj) + zvispyc_s_sc(ji,jj) ) / ( zvisml_sc(ji,jj) + epsln )
+            ELSE
+              zbeta_d_sc(ji,jj) = 1.0
+              zbeta_v_sc(ji,jj) = 1.0
+            ENDIF
+          ELSE
+            zdifml_sc(ji,jj) = zvstr(ji,jj) * zhbl(ji,jj) * MAX( EXP ( -( zhol(ji,jj) / 0.6_wp )**2 ), 0.2_wp)
+            zvisml_sc(ji,jj) = zvstr(ji,jj) * zhbl(ji,jj) * MAX( EXP ( -( zhol(ji,jj) / 0.6_wp )**2 ), 0.2_wp)
+          END IF
+      END_2D
+!
+       DO_2D( 0, 0, 0, 0 )
+          IF ( lconv(ji,jj) ) THEN
+             DO jk = 2, imld(ji,jj)   ! mixed layer diffusivity
+                 zznd_ml = gdepw(ji,jj,jk,Kmm) / zhml(ji,jj)
+                 !
+                 zdiffut(ji,jj,jk) = zdifml_sc(ji,jj) * zznd_ml * ( 1.0 - zbeta_d_sc(ji,jj) * zznd_ml )**1.5
+                 !
+                 zviscos(ji,jj,jk) = zvisml_sc(ji,jj) * zznd_ml * ( 1.0 - zbeta_v_sc(ji,jj) * zznd_ml ) &
+   &            *                                      ( 1.0 - 0.5 * zznd_ml**2 )
+             END DO
+! pycnocline
+             IF ( lpyc(ji,jj) ) THEN
+! Diffusivity profile in the pycnocline given by cubic polynomial.
+                za_cubic = 0.5
+                zb_cubic = -1.75 * zdifpyc_s_sc(ji,jj) / zdifpyc_n_sc(ji,jj)
+                zd_cubic = ( zdh(ji,jj) * zdifml_sc(ji,jj) / zhml(ji,jj) * SQRT( 1.0 - zbeta_d_sc(ji,jj) ) * ( 2.5 * zbeta_d_sc(ji,jj) - 1.0 ) &
+                     & - 0.85 * zdifpyc_s_sc(ji,jj) ) / MAX(zdifpyc_n_sc(ji,jj), 1.e-8)
+                zd_cubic = zd_cubic - zb_cubic - 2.0 * ( 1.0 - za_cubic  - zb_cubic )
+                zc_cubic = 1.0 - za_cubic - zb_cubic - zd_cubic
+                DO jk = imld(ji,jj) , ibld(ji,jj)
+                  zznd_pyc = -( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / MAX(zdh(ji,jj), 1.e-6)
+                      !
+                  zdiffut(ji,jj,jk) = zdifpyc_n_sc(ji,jj) * ( za_cubic + zb_cubic * zznd_pyc + zc_cubic * zznd_pyc**2 +   zd_cubic * zznd_pyc**3 )
+
+                  zdiffut(ji,jj,jk) = zdiffut(ji,jj,jk) + zdifpyc_s_sc(ji,jj) * ( 1.75 * zznd_pyc - 0.15 * zznd_pyc**2 - 0.2 * zznd_pyc**3 )
+                END DO
+ ! viscosity profiles.
+                za_cubic = 0.5
+                zb_cubic = -1.75 * zvispyc_s_sc(ji,jj) / zvispyc_n_sc(ji,jj)
+                zd_cubic = ( 0.5 * zvisml_sc(ji,jj) * zdh(ji,jj) / zhml(ji,jj) - 0.85 * zvispyc_s_sc(ji,jj)  )  / MAX(zvispyc_n_sc(ji,jj), 1.e-8)
+                zd_cubic = zd_cubic - zb_cubic - 2.0 * ( 1.0 - za_cubic - zd_cubic )
+                zc_cubic = 1.0 - za_cubic - zb_cubic - zd_cubic
+                DO jk = imld(ji,jj) , ibld(ji,jj)
+                   zznd_pyc = -( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / MAX(zdh(ji,jj), 1.e-6)
+                    zviscos(ji,jj,jk) = zvispyc_n_sc(ji,jj) * ( za_cubic + zb_cubic * zznd_pyc + zc_cubic * zznd_pyc**2 + zd_cubic * zznd_pyc**3 )
+                    zviscos(ji,jj,jk) = zviscos(ji,jj,jk) + zvispyc_s_sc(ji,jj) * ( 1.75 * zznd_pyc - 0.15 * zznd_pyc**2 -0.2 * zznd_pyc**3 )
+                END DO
+                IF ( zdhdt(ji,jj) > 0._wp ) THEN
+                 zdiffut(ji,jj,ibld(ji,jj)+1) = MAX( 0.5 * zdhdt(ji,jj) * e3w(ji,jj,ibld(ji,jj)+1,Kmm), 1.0e-6 )
+                 zviscos(ji,jj,ibld(ji,jj)+1) = MAX( 0.5 * zdhdt(ji,jj) * e3w(ji,jj,ibld(ji,jj)+1,Kmm), 1.0e-6 )
+                ELSE
+                  zdiffut(ji,jj,ibld(ji,jj)) = 0._wp
+                  zviscos(ji,jj,ibld(ji,jj)) = 0._wp
+                ENDIF
+             ENDIF
+          ELSE
+          ! stable conditions
+             DO jk = 2, ibld(ji,jj)
+                zznd_ml = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
+                zdiffut(ji,jj,jk) = 0.75 * zdifml_sc(ji,jj) * zznd_ml * ( 1.0 - zznd_ml )**1.5
+                zviscos(ji,jj,jk) = 0.375 * zvisml_sc(ji,jj) * zznd_ml * (1.0 - zznd_ml) * ( 1.0 - zznd_ml**2 )
+             END DO
+
+             IF ( zdhdt(ji,jj) > 0._wp ) THEN
+                zdiffut(ji,jj,ibld(ji,jj)) = MAX(zdhdt(ji,jj), 1.0e-6) * e3w(ji, jj, ibld(ji,jj), Kmm)
+                zviscos(ji,jj,ibld(ji,jj)) = MAX(zdhdt(ji,jj), 1.0e-6) * e3w(ji, jj, ibld(ji,jj), Kmm)
+             ENDIF
+          ENDIF   ! end if ( lconv )
+          !
+       END_2D
+       
+  END SUBROUTINE zdf_osm_diffusivity_viscosity
+  
+  SUBROUTINE zdf_osm_osbl_state( lconv, lshear, j_ddh, zwb_ent, zwb_min, zshear, zri_i )
+
+!!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_osm_osbl_state  ***
+     !!
+     !! ** Purpose : Determines the state of the OSBL, stable/unstable, shear/ noshear. Also determines shear production, entrainment buoyancy flux and interfacial Richardson number
+     !!
+     !! ** Method  : 
+     !!
+     !! !!----------------------------------------------------------------------
+
+     INTEGER, DIMENSION(jpi,jpj) :: j_ddh  ! j_ddh = 0, active shear layer; j_ddh=1, shear layer not active; j_ddh=2 shear production low.
+     
+     LOGICAL, DIMENSION(jpi,jpj) :: lconv, lshear
+
+     REAL(wp), DIMENSION(jpi,jpj) :: zwb_ent, zwb_min ! Buoyancy fluxes at base of well-mixed layer.
+     REAL(wp), DIMENSION(jpi,jpj) :: zshear  ! production of TKE due to shear across the pycnocline
+     REAL(wp), DIMENSION(jpi,jpj) :: zri_i  ! Interfacial Richardson Number
+
+! Local Variables
+
+     INTEGER :: jj, ji
+     
+     REAL(wp), DIMENSION(jpi,jpj) :: zekman
+     REAL(wp) :: zri_p, zri_b   ! Richardson numbers
+     REAL(wp) :: zshear_u, zshear_v, zwb_shr
+     REAL(wp) :: zwcor, zrf_conv, zrf_shear, zrf_langmuir, zr_stokes
+
+     REAL, PARAMETER :: za_shr = 0.4, zb_shr = 6.5, za_wb_s = 0.1
+     REAL, PARAMETER :: rn_ri_thres_a = 0.5, rn_ri_thresh_b = 0.59
+     REAL, PARAMETER :: zalpha_c = 0.2, zalpha_lc = 0.04     
+     REAL, PARAMETER :: zalpha_ls = 0.06, zalpha_s = 0.15
+     REAL, PARAMETER :: rn_ri_p_thresh = 27.0
+     REAL, PARAMETER :: zrot=0._wp  ! dummy rotation rate of surface stress.
+     
+! Determins stability and set flag lconv
+     DO_2D( 0, 0, 0, 0 )
+      IF ( zhol(ji,jj) < 0._wp ) THEN
+         lconv(ji,jj) = .TRUE.
+       ELSE
+          lconv(ji,jj) = .FALSE.
+       ENDIF
+     END_2D
+ 
+     zekman(:,:) = EXP( - 4.0 * ABS( ff_t(:,:) ) * zhbl(:,:) / MAX(zustar(:,:), 1.e-8 ) )
+     
+     WHERE ( lconv )
+       zri_i = zdb_ml * zhml**2 / MAX( ( zvstr**3 + 0.5 * zwstrc**3 )**p2third * zdh, 1.e-12 )
+     END WHERE
+
+     zshear(:,:) = 0._wp
+     j_ddh(:,:) = 1     
+ 
+     DO_2D( 0, 0, 0, 0 )
+      IF ( lconv(ji,jj) ) THEN
+         IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+           zri_p = MAX (  SQRT( zdb_bl(ji,jj) * zdh(ji,jj) / MAX( zdu_bl(ji,jj)**2 + zdv_bl(ji,jj)**2, 1.e-8) )  *  ( zhbl(ji,jj) / zdh(ji,jj) ) * ( zvstr(ji,jj) / MAX( zustar(ji,jj), 1.e-6 ) )**2 &
+                & / MAX( zekman(ji,jj), 1.e-6 )  , 5._wp )
+         
+           zri_b = zdb_ml(ji,jj) * zdh(ji,jj) / MAX( zdu_ml(ji,jj)**2 + zdv_ml(ji,jj)**2, 1.e-8 )
+                     
+           zshear(ji,jj) = za_shr * zekman(ji,jj) * ( MAX( zustar(ji,jj)**2 * zdu_ml(ji,jj) / zhbl(ji,jj), 0._wp ) + zb_shr * MAX( -ff_t(ji,jj) * zustke(ji,jj) * dstokes(ji,jj) * zdv_ml(ji,jj) / zhbl(ji,jj), 0._wp ) )
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Test ensures j_ddh=0 is not selected. Change to zri_p<27 when  !
+! full code available                                          !
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+           IF ( zri_p < -rn_ri_p_thresh .and. zshear(ji,jj) > 0._wp ) THEN
+! Growing shear layer
+             j_ddh(ji,jj) = 0
+             lshear(ji,jj) = .TRUE.
+           ELSE
+             j_ddh(ji,jj) = 1
+             IF ( zri_b <= 1.5 .and. zshear(ji,jj) > 0._wp ) THEN
+! shear production large enough to determine layer charcteristics, but can't maintain a shear layer.
+               lshear(ji,jj) = .TRUE.
+             ELSE
+! Shear production may not be zero, but is small and doesn't determine characteristics of pycnocline.
+               zshear(ji,jj) = 0.5 * zshear(ji,jj)
+               lshear(ji,jj) = .FALSE.
+             ENDIF 
+           ENDIF                
+         ELSE                ! zdb_bl test, note zshear set to zero
+           j_ddh(ji,jj) = 2
+           lshear(ji,jj) = .FALSE.
+         ENDIF
+       ENDIF
+     END_2D
+ 
+! Calculate entrainment buoyancy flux due to surface fluxes.
+
+     DO_2D( 0, 0, 0, 0 )
+      IF ( lconv(ji,jj) ) THEN
+        zwcor = ABS(ff_t(ji,jj)) * zhbl(ji,jj) + epsln
+        zrf_conv = TANH( ( zwstrc(ji,jj) / zwcor )**0.69 )
+        zrf_shear = TANH( ( zustar(ji,jj) / zwcor )**0.69 )
+        zrf_langmuir = TANH( ( zwstrl(ji,jj) / zwcor )**0.69 )
+        IF (nn_osm_SD_reduce > 0 ) THEN
+        ! Effective Stokes drift already reduced from surface value
+           zr_stokes = 1.0_wp
+        ELSE
+         ! Effective Stokes drift only reduced by factor rn_zdfodm_adjust_sd,
+          ! requires further reduction where BL is deep
+           zr_stokes = 1.0 - EXP( -25.0 * dstokes(ji,jj) / hbl(ji,jj) &
+         &                  * ( 1.0 + 4.0 * dstokes(ji,jj) / hbl(ji,jj) ) )
+        END IF
+        zwb_ent(ji,jj) = - 2.0 * 0.2 * zrf_conv * zwbav(ji,jj) &
+               &                  - 0.15 * zrf_shear * zustar(ji,jj)**3 /zhml(ji,jj) &
+               &         + zr_stokes * ( 0.15 * EXP( -1.5 * zla(ji,jj) ) * zrf_shear * zustar(ji,jj)**3 &
+               &                                         - zrf_langmuir * 0.03 * zwstrl(ji,jj)**3 ) / zhml(ji,jj)
+          !
+      ENDIF
+     END_2D
+
+     zwb_min(:,:) = 0._wp
+
+     DO_2D( 0, 0, 0, 0 )
+      IF ( lshear(ji,jj) ) THEN
+        IF ( lconv(ji,jj) ) THEN
+! Unstable OSBL
+           zwb_shr = -za_wb_s * zshear(ji,jj)
+           IF ( j_ddh(ji,jj) == 0 ) THEN
+
+! Developing shear layer, additional shear production possible.
+
+             zshear_u = MAX( zustar(ji,jj)**2 * zdu_ml(ji,jj) /  zhbl(ji,jj), 0._wp )
+             zshear(ji,jj) = zshear(ji,jj) + zshear_u * ( 1.0 - MIN( zri_p / rn_ri_p_thresh, 1.d0 ) )
+             zshear(ji,jj) = MIN( zshear(ji,jj), zshear_u )
+             
+             zwb_shr = -za_wb_s * zshear(ji,jj)
+             
+           ENDIF                
+           zwb_ent(ji,jj) = zwb_ent(ji,jj) + zwb_shr
+           zwb_min(ji,jj) = zwb_ent(ji,jj) + zdh(ji,jj) / zhbl(ji,jj) * zwb0(ji,jj)
+        ELSE    ! IF ( lconv ) THEN - ENDIF
+! Stable OSBL  - shear production not coded for first attempt.           
+        ENDIF  ! lconv
+      ELSE  ! lshear
+        IF ( lconv(ji,jj) ) THEN
+! Unstable OSBL
+           zwb_shr = -za_wb_s * zshear(ji,jj)
+           zwb_ent(ji,jj) = zwb_ent(ji,jj) + zwb_shr
+           zwb_min(ji,jj) = zwb_ent(ji,jj) + zdh(ji,jj) / zhbl(ji,jj) * zwb0(ji,jj)
+        ENDIF  ! lconv
+      ENDIF    ! lshear
+     END_2D
+   END SUBROUTINE zdf_osm_osbl_state
+     
+     
+   SUBROUTINE zdf_osm_vertical_average( jnlev_av, jp_ext, zt, zs, zb, zu, zv, zdt, zds, zdb, zdu, zdv )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_vertical_average  ***
+     !!
+     !! ** Purpose : Determines vertical averages from surface to jnlev.
+     !!
+     !! ** Method  : Averages are calculated from the surface to jnlev.
+     !!              The external level used to calculate differences is ibld+ibld_ext
+     !!
+     !!----------------------------------------------------------------------
+
+        INTEGER, DIMENSION(jpi,jpj) :: jnlev_av  ! Number of levels to average over.
+        INTEGER, DIMENSION(jpi,jpj) :: jp_ext
+
+        ! Alan: do we need zb?
+        REAL(wp), DIMENSION(jpi,jpj) :: zt, zs, zb        ! Average temperature and salinity
+        REAL(wp), DIMENSION(jpi,jpj) :: zu,zv         ! Average current components
+        REAL(wp), DIMENSION(jpi,jpj) :: zdt, zds, zdb ! Difference between average and value at base of OSBL
+        REAL(wp), DIMENSION(jpi,jpj) :: zdu, zdv      ! Difference for velocity components.
+
+        INTEGER :: jk, ji, jj, ibld_ext
+        REAL(wp) :: zthick, zthermal, zbeta
+
+
+        zt   = 0._wp
+        zs   = 0._wp
+        zu   = 0._wp
+        zv   = 0._wp
+        DO_2D( 0, 0, 0, 0 )
+         zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
+         zbeta    = rab_n(ji,jj,1,jp_sal)
+            ! average over depth of boundary layer
+         zthick = epsln
+         DO jk = 2, jnlev_av(ji,jj)
+            zthick = zthick + e3t(ji,jj,jk,Kmm)
+            zt(ji,jj)   = zt(ji,jj)  + e3t(ji,jj,jk,Kmm) * ts(ji,jj,jk,jp_tem,Kmm)
+            zs(ji,jj)   = zs(ji,jj)  + e3t(ji,jj,jk,Kmm) * ts(ji,jj,jk,jp_sal,Kmm)
+            zu(ji,jj)   = zu(ji,jj)  + e3t(ji,jj,jk,Kmm) &
+                  &            * ( uu(ji,jj,jk,Kbb) + uu(ji - 1,jj,jk,Kbb) ) &
+                  &            / MAX( 1. , umask(ji,jj,jk) + umask(ji - 1,jj,jk) )
+            zv(ji,jj)   = zv(ji,jj)  + e3t(ji,jj,jk,Kmm) &
+                  &            * ( vv(ji,jj,jk,Kbb) + vv(ji,jj - 1,jk,Kbb) ) &
+                  &            / MAX( 1. , vmask(ji,jj,jk) + vmask(ji,jj - 1,jk) )
+         END DO
+         zt(ji,jj) = zt(ji,jj) / zthick
+         zs(ji,jj) = zs(ji,jj) / zthick
+         zu(ji,jj) = zu(ji,jj) / zthick
+         zv(ji,jj) = zv(ji,jj) / zthick
+         zb(ji,jj) = grav * zthermal * zt(ji,jj) - grav * zbeta * zs(ji,jj)
+         ibld_ext = jnlev_av(ji,jj) + jp_ext(ji,jj)
+         IF ( ibld_ext < mbkt(ji,jj) ) THEN
+           zdt(ji,jj) = zt(ji,jj) - ts(ji,jj,ibld_ext,jp_tem,Kmm)
+           zds(ji,jj) = zs(ji,jj) - ts(ji,jj,ibld_ext,jp_sal,Kmm)
+           zdu(ji,jj) = zu(ji,jj) - ( uu(ji,jj,ibld_ext,Kbb) + uu(ji-1,jj,ibld_ext,Kbb ) ) &
+                  &    / MAX(1. , umask(ji,jj,ibld_ext ) + umask(ji-1,jj,ibld_ext ) )
+           zdv(ji,jj) = zv(ji,jj) - ( vv(ji,jj,ibld_ext,Kbb) + vv(ji,jj-1,ibld_ext,Kbb ) ) &
+                  &   / MAX(1. , vmask(ji,jj,ibld_ext ) + vmask(ji,jj-1,ibld_ext ) )
+           zdb(ji,jj) = grav * zthermal * zdt(ji,jj) - grav * zbeta * zds(ji,jj)
+         ELSE
+           zdt(ji,jj) = 0._wp
+           zds(ji,jj) = 0._wp
+           zdu(ji,jj) = 0._wp
+           zdv(ji,jj) = 0._wp
+           zdb(ji,jj) = 0._wp
+         ENDIF
+        END_2D
+   END SUBROUTINE zdf_osm_vertical_average
+
+   SUBROUTINE zdf_osm_velocity_rotation( zcos_w, zsin_w, zu, zv, zdu, zdv )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_velocity_rotation  ***
+     !!
+     !! ** Purpose : Rotates frame of reference of averaged velocity components.
+     !!
+     !! ** Method  : The velocity components are rotated into frame specified by zcos_w and zsin_w
+     !!
+     !!----------------------------------------------------------------------
+
+        REAL(wp), DIMENSION(jpi,jpj) :: zcos_w, zsin_w       ! Cos and Sin of rotation angle
+        REAL(wp), DIMENSION(jpi,jpj) :: zu, zv               ! Components of current
+        REAL(wp), DIMENSION(jpi,jpj) :: zdu, zdv             ! Change in velocity components across pycnocline
+
+        INTEGER :: ji, jj
+        REAL(wp) :: ztemp
+
+        DO_2D( 0, 0, 0, 0 )
+           ztemp = zu(ji,jj)
+           zu(ji,jj) = zu(ji,jj) * zcos_w(ji,jj) + zv(ji,jj) * zsin_w(ji,jj)
+           zv(ji,jj) = zv(ji,jj) * zcos_w(ji,jj) - ztemp * zsin_w(ji,jj)
+           ztemp = zdu(ji,jj)
+           zdu(ji,jj) = zdu(ji,jj) * zcos_w(ji,jj) + zdv(ji,jj) * zsin_w(ji,jj)
+           zdv(ji,jj) = zdv(ji,jj) * zsin_w(ji,jj) - ztemp * zsin_w(ji,jj)
+        END_2D
+    END SUBROUTINE zdf_osm_velocity_rotation
+
+    SUBROUTINE zdf_osm_osbl_state_fk( lpyc, lflux, lmle, zwb_fk )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_osm_osbl_state_fk  ***
+     !!
+     !! ** Purpose : Determines the state of the OSBL and MLE layer. Info is returned in the logicals lpyc,lflux and lmle. Used with Fox-Kemper scheme.
+     !!  lpyc :: determines whether pycnocline flux-grad relationship needs to be determined
+     !!  lflux :: determines whether effects of surface flux extend below the base of the OSBL
+     !!  lmle  :: determines whether the layer with MLE is increasing with time or if base is relaxing towards hbl. 
+     !!
+     !! ** Method  : 
+     !!
+     !! 
+     !!----------------------------------------------------------------------
+      
+! Outputs
+      LOGICAL,  DIMENSION(jpi,jpj)  :: lpyc, lflux, lmle
+      REAL(wp), DIMENSION(jpi,jpj)  :: zwb_fk
+!
+      REAL(wp), DIMENSION(jpi,jpj)  :: znd_param
+      REAL(wp)                      :: zbuoy, ztmp, zpe_mle_layer
+      REAL(wp)                      :: zpe_mle_ref, zwb_ent, zdbdz_mle_int
+      
+      znd_param(:,:) = 0._wp
+
+        DO_2D( 0, 0, 0, 0 )
+          ztmp =  r1_ft(ji,jj) *  MIN( 111.e3_wp , e1u(ji,jj) ) / rn_osm_mle_lf
+          zwb_fk(ji,jj) = rn_osm_mle_ce * hmle(ji,jj) * hmle(ji,jj) * ztmp * zdbds_mle(ji,jj) * zdbds_mle(ji,jj)
+        END_2D
+        DO_2D( 0, 0, 0, 0 )
+                 !
+         IF ( lconv(ji,jj) ) THEN
+           IF ( zhmle(ji,jj) > 1.2 * zhbl(ji,jj) ) THEN
+             zt_mle(ji,jj) = ( zt_mle(ji,jj) * zhmle(ji,jj) - zt_bl(ji,jj) * zhbl(ji,jj) ) / ( zhmle(ji,jj) - zhbl(ji,jj) )
+             zs_mle(ji,jj) = ( zs_mle(ji,jj) * zhmle(ji,jj) - zs_bl(ji,jj) * zhbl(ji,jj) ) / ( zhmle(ji,jj) - zhbl(ji,jj) )
+             zb_mle(ji,jj) = ( zb_mle(ji,jj) * zhmle(ji,jj) - zb_bl(ji,jj) * zhbl(ji,jj) ) / ( zhmle(ji,jj) - zhbl(ji,jj) )
+             zdbdz_mle_int = ( zb_bl(ji,jj) - ( 2.0 * zb_mle(ji,jj) -zb_bl(ji,jj) ) ) / ( zhmle(ji,jj) - zhbl(ji,jj) )
+! Calculate potential energies of actual profile and reference profile.
+             zpe_mle_layer = 0._wp
+             zpe_mle_ref = 0._wp
+             DO jk = ibld(ji,jj), mld_prof(ji,jj)
+               zbuoy = grav * ( zthermal * ts(ji,jj,jk,jp_tem,Kmm) - zbeta * ts(ji,jj,jk,jp_sal,Kmm) )
+               zpe_mle_layer = zpe_mle_layer + zbuoy * gdepw(ji,jj,jk,Kmm) * e3w(ji,jj,jk,Kmm)
+               zpe_mle_ref = zpe_mle_ref + ( zb_bl(ji,jj) - zdbdz_mle_int * ( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) ) * gdepw(ji,jj,jk,Kmm) * e3w(ji,jj,jk,Kmm)
+             END DO
+! Non-dimensional parameter to diagnose the presence of thermocline
+                
+             znd_param(ji,jj) = ( zpe_mle_layer - zpe_mle_ref ) * ABS( ff_t(ji,jj) ) / ( MAX( zwb_fk(ji,jj), 1.0e-10 ) * zhmle(ji,jj) )
+           ENDIF
+         ENDIF
+        END_2D
+
+! Diagnosis
+        DO_2D( 0, 0, 0, 0 )
+          IF ( lconv(ji,jj) ) THEN
+            zwb_ent = - 2.0 * 0.2 * zwbav(ji,jj) &
+               &                  - 0.15 * zustar(ji,jj)**3 /zhml(ji,jj) &
+               &         + ( 0.15 * EXP( -1.5 * zla(ji,jj) ) * zustar(ji,jj)**3 &
+               &         - 0.03 * zwstrl(ji,jj)**3 ) / zhml(ji,jj)
+            IF ( -2.0 * zwb_fk(ji,jj) / zwb_ent > 0.5 ) THEN
+              IF ( zhmle(ji,jj) > 1.2 * zhbl(ji,jj) ) THEN
+! MLE layer growing
+                IF ( znd_param (ji,jj) > 100. ) THEN
+! Thermocline present
+                  lflux(ji,jj) = .FALSE.
+                  lmle(ji,jj) =.FALSE.
+                ELSE
+! Thermocline not present
+                  lflux(ji,jj) = .TRUE.
+                  lmle(ji,jj) = .TRUE.
+                ENDIF  ! znd_param > 100
+!
+                IF ( zdb_bl(ji,jj) < rn_osm_bl_thresh ) THEN
+                  lpyc(ji,jj) = .FALSE.
+                ELSE
+                   lpyc = .TRUE.
+                ENDIF
+              ELSE
+! MLE layer restricted to OSBL or just below.
+                IF ( zdb_bl(ji,jj) < rn_osm_bl_thresh ) THEN
+! Weak stratification MLE layer can grow.
+                  lpyc(ji,jj) = .FALSE.
+                  lflux(ji,jj) = .TRUE.
+                  lmle(ji,jj) = .TRUE.
+                ELSE
+! Strong stratification
+                  lpyc(ji,jj) = .TRUE.
+                  lflux(ji,jj) = .FALSE.
+                  lmle(ji,jj) = .FALSE.
+                ENDIF ! zdb_bl < rn_mle_thresh_bl and 
+              ENDIF  ! zhmle > 1.2 zhbl
+            ELSE
+              lpyc(ji,jj) = .TRUE.
+              lflux(ji,jj) = .FALSE.
+              lmle(ji,jj) = .FALSE.
+              IF ( zdb_bl(ji,jj) < rn_osm_bl_thresh ) lpyc(ji,jj) = .FALSE.
+            ENDIF !  -2.0 * zwb_fk(ji,jj) / zwb_ent > 0.5 
+          ELSE
+! Stable Boundary Layer
+            lpyc(ji,jj) = .FALSE.
+            lflux(ji,jj) = .FALSE.
+            lmle(ji,jj) = .FALSE.
+          ENDIF  ! lconv
+        END_2D
+    END SUBROUTINE zdf_osm_osbl_state_fk
+
+    SUBROUTINE zdf_osm_external_gradients(jbase, zdtdz, zdsdz, zdbdz )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_osm_external_gradients  ***
+     !!
+     !! ** Purpose : Calculates the gradients below the OSBL
+     !!
+     !! ** Method  : Uses ibld and ibld_ext to determine levels to calculate the gradient.
+     !!
+     !!----------------------------------------------------------------------
+
+     INTEGER, DIMENSION(jpi,jpj)  :: jbase
+     REAL(wp), DIMENSION(jpi,jpj) :: zdtdz, zdsdz, zdbdz   ! External gradients of temperature, salinity and buoyancy.
+
+     INTEGER :: jj, ji, jkb, jkb1
+     REAL(wp) :: zthermal, zbeta
+
+
+     DO_2D( 0, 0, 0, 0 )
+        IF ( jbase(ji,jj)+1 < mbkt(ji,jj) ) THEN
+           zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
+           zbeta    = rab_n(ji,jj,1,jp_sal)
+           jkb = jbase(ji,jj)
+           jkb1 = MIN(jkb + 1, mbkt(ji,jj))
+           zdtdz(ji,jj) = - ( ts(ji,jj,jkb1,jp_tem,Kmm) - ts(ji,jj,jkb,jp_tem,Kmm ) ) &
+                &   / e3t(ji,jj,ibld(ji,jj),Kmm)
+           zdsdz(ji,jj) = - ( ts(ji,jj,jkb1,jp_sal,Kmm) - ts(ji,jj,jkb,jp_sal,Kmm ) ) &
+                &   / e3t(ji,jj,ibld(ji,jj),Kmm)
+           zdbdz(ji,jj) = grav * zthermal * zdtdz(ji,jj) - grav * zbeta * zdsdz(ji,jj)
+        ELSE
+           zdtdz(ji,jj) = 0._wp
+           zdsdz(ji,jj) = 0._wp
+           zdbdz(ji,jj) = 0._wp
+        END IF
+     END_2D
+    END SUBROUTINE zdf_osm_external_gradients
+
+    SUBROUTINE zdf_osm_pycnocline_scalar_profiles( zdtdz, zdsdz, zdbdz, zalpha )
+
+     REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdtdz, zdsdz, zdbdz      ! gradients in the pycnocline
+     REAL(wp), DIMENSION(jpi,jpj) :: zalpha
+
+     INTEGER :: jk, jj, ji
+     REAL(wp) :: ztgrad, zsgrad, zbgrad
+     REAL(wp) :: zgamma_b_nd, znd
+     REAL(wp) :: zzeta_m, zzeta_en, zbuoy_pyc_sc
+     REAL(wp), PARAMETER :: zgamma_b = 2.25, zzeta_sh = 0.15
+
+     DO_2D( 0, 0, 0, 0 )
+        IF ( ibld(ji,jj) + jp_ext(ji,jj) < mbkt(ji,jj) ) THEN
+           IF ( lconv(ji,jj) ) THEN  ! convective conditions
+             IF ( lpyc(ji,jj) ) THEN
+                zzeta_m = 0.1 + 0.3 / ( 1.0 + EXP( -3.5 * LOG10( -zhol(ji,jj) ) ) )
+                zalpha(ji,jj) = 2.0 * ( 1.0 - ( 0.80 * zzeta_m + 0.5 * SQRT( 3.14159 / zgamma_b ) ) * zdbdz_bl_ext(ji,jj) * zdh(ji,jj) / zdb_ml(ji,jj) ) / ( 0.723 + SQRT( 3.14159 / zgamma_b ) )
+                zalpha(ji,jj) = MAX( zalpha(ji,jj), 0._wp )
+
+                ztmp = 1._wp/MAX(zdh(ji,jj), epsln)
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+! Commented lines in this section are not needed in new code, once tested !
+! can be removed                                                          !
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!                   ztgrad = zalpha * zdt_ml(ji,jj) * ztmp + zdtdz_bl_ext(ji,jj)
+!                   zsgrad = zalpha * zds_ml(ji,jj) * ztmp + zdsdz_bl_ext(ji,jj)
+                zbgrad = zalpha(ji,jj) * zdb_ml(ji,jj) * ztmp + zdbdz_bl_ext(ji,jj)
+                zgamma_b_nd = zdbdz_bl_ext(ji,jj) * zdh(ji,jj) / MAX(zdb_ml(ji,jj), epsln)
+                DO jk = 2, ibld(ji,jj)+ibld_ext
+                  znd = -( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) * ztmp
+                  IF ( znd <= zzeta_m ) THEN
+!                        zdtdz(ji,jj,jk) = zdtdz_bl_ext(ji,jj) + zalpha * zdt_ml(ji,jj) * ztmp * &
+!                &        EXP( -6.0 * ( znd -zzeta_m )**2 )
+!                        zdsdz(ji,jj,jk) = zdsdz_bl_ext(ji,jj) + zalpha * zds_ml(ji,jj) * ztmp * &
+!                                  & EXP( -6.0 * ( znd -zzeta_m )**2 )
+                     zdbdz(ji,jj,jk) = zdbdz_bl_ext(ji,jj) + zalpha(ji,jj) * zdb_ml(ji,jj) * ztmp * &
+                               & EXP( -6.0 * ( znd -zzeta_m )**2 )
+                  ELSE
+!                         zdtdz(ji,jj,jk) =  ztgrad * EXP( -zgamma_b * ( znd - zzeta_m )**2 )
+!                         zdsdz(ji,jj,jk) =  zsgrad * EXP( -zgamma_b * ( znd - zzeta_m )**2 )
+                      zdbdz(ji,jj,jk) =  zbgrad * EXP( -zgamma_b * ( znd - zzeta_m )**2 )
+                  ENDIF
+               END DO
+            ENDIF ! if no pycnocline pycnocline gradients set to zero
+           ELSE
+              ! stable conditions
+              ! if pycnocline profile only defined when depth steady of increasing.
+              IF ( zdhdt(ji,jj) > 0.0 ) THEN        ! Depth increasing, or steady.
+                 IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+                    IF ( zhol(ji,jj) >= 0.5 ) THEN      ! Very stable - 'thick' pycnocline
+                       ztmp = 1._wp/MAX(zhbl(ji,jj), epsln)
+                       ztgrad = zdt_bl(ji,jj) * ztmp
+                       zsgrad = zds_bl(ji,jj) * ztmp
+                       zbgrad = zdb_bl(ji,jj) * ztmp
+                       DO jk = 2, ibld(ji,jj)
+                          znd = gdepw(ji,jj,jk,Kmm) * ztmp
+                          zdtdz(ji,jj,jk) =  ztgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
+                          zdbdz(ji,jj,jk) =  zbgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
+                          zdsdz(ji,jj,jk) =  zsgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
+                       END DO
+                    ELSE                                   ! Slightly stable - 'thin' pycnoline - needed when stable layer begins to form.
+                       ztmp = 1._wp/MAX(zdh(ji,jj), epsln)
+                       ztgrad = zdt_bl(ji,jj) * ztmp
+                       zsgrad = zds_bl(ji,jj) * ztmp
+                       zbgrad = zdb_bl(ji,jj) * ztmp
+                       DO jk = 2, ibld(ji,jj)
+                          znd = -( gdepw(ji,jj,jk,Kmm) - zhml(ji,jj) ) * ztmp
+                          zdtdz(ji,jj,jk) =  ztgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                          zdbdz(ji,jj,jk) =  zbgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                          zdsdz(ji,jj,jk) =  zsgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                       END DO
+                    ENDIF ! IF (zhol >=0.5)
+                 ENDIF    ! IF (zdb_bl> 0.)
+              ENDIF       ! IF (zdhdt >= 0) zdhdt < 0 not considered since pycnocline profile is zero and profile arrays are intialized to zero
+           ENDIF          ! IF (lconv)
+        ENDIF      ! IF ( ibld(ji,jj) < mbkt(ji,jj) )
+     END_2D
+
+    END SUBROUTINE zdf_osm_pycnocline_scalar_profiles
+
+    SUBROUTINE zdf_osm_pycnocline_shear_profiles( zdudz, zdvdz )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_osm_pycnocline_shear_profiles  ***
+      !!
+      !! ** Purpose : Calculates velocity shear in the pycnocline
+      !!
+      !! ** Method  :
+      !!
+      !!----------------------------------------------------------------------
+
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdudz, zdvdz
+
+      INTEGER :: jk, jj, ji
+      REAL(wp) :: zugrad, zvgrad, znd
+      REAL(wp) :: zzeta_v = 0.45
       !
-   END SUBROUTINE zdf_osm
-
-
-   SUBROUTINE zdf_osm_init( Kmm ) 
+      DO_2D( 0, 0, 0, 0 )
+         !
+         IF ( ibld(ji,jj) + jp_ext(ji,jj) < mbkt(ji,jj) ) THEN
+            IF ( lconv (ji,jj) ) THEN
+               ! Unstable conditions. Shouldn;t be needed with no pycnocline code.
+!                  zugrad = 0.7 * zdu_ml(ji,jj) / zdh(ji,jj) + 0.3 * zustar(ji,jj)*zustar(ji,jj) / &
+!                       &      ( ( ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * zhml(ji,jj) ) * &
+!                      &      MIN(zla(ji,jj)**(8.0/3.0) + epsln, 0.12 ))
+               !Alan is this right?
+!                  zvgrad = ( 0.7 * zdv_ml(ji,jj) + &
+!                       &    2.0 * ff_t(ji,jj) * zustke(ji,jj) * dstokes(ji,jj) / &
+!                       &          ( ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird  + epsln ) &
+!                       &      )/ (zdh(ji,jj)  + epsln )
+!                  DO jk = 2, ibld(ji,jj) - 1 + ibld_ext
+!                     znd = -( gdepw(ji,jj,jk,Kmm) - zhbl(ji,jj) ) / (zdh(ji,jj) + epsln ) - zzeta_v
+!                     IF ( znd <= 0.0 ) THEN
+!                        zdudz(ji,jj,jk) = 1.25 * zugrad * EXP( 3.0 * znd )
+!                        zdvdz(ji,jj,jk) = 1.25 * zvgrad * EXP( 3.0 * znd )
+!                     ELSE
+!                        zdudz(ji,jj,jk) = 1.25 * zugrad * EXP( -2.0 * znd )
+!                        zdvdz(ji,jj,jk) = 1.25 * zvgrad * EXP( -2.0 * znd )
+!                     ENDIF
+!                  END DO
+            ELSE
+               ! stable conditions
+               zugrad = 3.25 * zdu_bl(ji,jj) / zhbl(ji,jj)
+               zvgrad = 2.75 * zdv_bl(ji,jj) / zhbl(ji,jj)
+               DO jk = 2, ibld(ji,jj)
+                  znd = gdepw(ji,jj,jk,Kmm) / zhbl(ji,jj)
+                  IF ( znd < 1.0 ) THEN
+                     zdudz(ji,jj,jk) = zugrad * EXP( -40.0 * ( znd - 1.0 )**2 )
+                  ELSE
+                     zdudz(ji,jj,jk) = zugrad * EXP( -20.0 * ( znd - 1.0 )**2 )
+                  ENDIF
+                  zdvdz(ji,jj,jk) = zvgrad * EXP( -20.0 * ( znd - 0.85 )**2 )
+               END DO
+            ENDIF
+            !
+         END IF      ! IF ( ibld(ji,jj) + ibld_ext < mbkt(ji,jj) )
+      END_2D
+    END SUBROUTINE zdf_osm_pycnocline_shear_profiles
+
+   SUBROUTINE zdf_osm_calculate_dhdt( zdhdt, zddhdt )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_osm_calculate_dhdt  ***
+     !!
+     !! ** Purpose : Calculates the rate at which hbl changes.
+     !!
+     !! ** Method  :
+     !!
+     !!----------------------------------------------------------------------
+
+    REAL(wp), DIMENSION(jpi,jpj) :: zdhdt, zddhdt        ! Rate of change of hbl
+
+    INTEGER :: jj, ji
+    REAL(wp) :: zgamma_b_nd, zgamma_dh_nd, zpert, zpsi
+    REAL(wp) :: zvel_max!, zwb_min
+    REAL(wp) :: zzeta_m = 0.3
+    REAL(wp) :: zgamma_c = 2.0
+    REAL(wp) :: zdhoh = 0.1
+    REAL(wp) :: alpha_bc = 0.5
+    REAL, PARAMETER :: a_ddh = 2.5, a_ddh_2 = 3.5 ! also in pycnocline_depth
+ 
+  DO_2D( 0, 0, 0, 0 )
+    
+    IF ( lshear(ji,jj) ) THEN
+       IF ( lconv(ji,jj) ) THEN    ! Convective
+
+          IF ( ln_osm_mle ) THEN
+
+             IF ( hmle(ji,jj) > hbl(ji,jj) ) THEN
+       ! Fox-Kemper buoyancy flux average over OSBL
+                zwb_fk_b(ji,jj) = zwb_fk(ji,jj) *  &
+                     (1.0 + hmle(ji,jj) / ( 6.0 * hbl(ji,jj) ) * (-1.0 + ( 1.0 - 2.0 * hbl(ji,jj) / hmle(ji,jj))**3) )
+             ELSE
+                zwb_fk_b(ji,jj) = 0.5 * zwb_fk(ji,jj) * hmle(ji,jj) / hbl(ji,jj)
+             ENDIF
+             zvel_max = ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**p2third / hbl(ji,jj)
+             IF ( ( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) < 0.0 ) THEN
+                ! OSBL is deepening, entrainment > restratification
+                IF ( zdb_bl(ji,jj) > 0.0 .and. zdbdz_bl_ext(ji,jj) > 0.0 ) THEN
+! *** Used for shear Needs to be changed to work stabily
+!                zgamma_b_nd = zdbdz_bl_ext * dh / zdb_ml
+!                zalpha_b = 6.7 * zgamma_b_nd / ( 1.0 + zgamma_b_nd )
+!                zgamma_b = zgamma_b_nd / ( 0.12 * ( 1.25 + zgamma_b_nd ) )
+!                za_1 = 1.0 / zgamma_b**2 - 0.017
+!                za_2 = 1.0 / zgamma_b**3 - 0.0025
+!                zpsi = zalpha_b * ( 1.0 + zgamma_b_nd ) * ( za_1 - 2.0 * za_2 * dh / hbl )
+                   zpsi = 0._wp
+                   zdhdt(ji,jj) = -( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) / ( zvel_max + MAX(zdb_bl(ji,jj), 1.0e-15) )
+                   zdhdt(ji,jj) = zdhdt(ji,jj)! - zpsi * ( -1.0 / zhml(ji,jj) + 2.4 * zdbdz_bl_ext(ji,jj) / zdb_ml(ji,jj) ) * zwb_min(ji,jj) * zdh(ji,jj) / zdb_bl(ji,jj)
+                   IF ( j_ddh(ji,jj) == 1 ) THEN
+                     IF ( ( zwstrc(ji,jj) / zvstr(ji,jj) )**3 <= 0.5 ) THEN
+                        zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zvstr(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+                     ELSE
+                        zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zwstrc(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+                     ENDIF
+! Relaxation to dh_ref = zari * hbl
+                     zddhdt(ji,jj) = -a_ddh_2 * ( 1.0 - zdh(ji,jj) / ( zari * zhbl(ji,jj) ) ) * zwb_ent(ji,jj) / zdb_bl(ji,jj)
+                     
+                   ELSE  ! j_ddh == 0
+! Growing shear layer
+                     zddhdt(ji,jj) = -a_ddh * ( 1.0 - zdh(ji,jj) / zhbl(ji,jj) ) * zwb_ent(ji,jj) / zdb_bl(ji,jj)
+                   ENDIF ! j_ddh
+                     zdhdt(ji,jj) = zdhdt(ji,jj) ! + zpsi * zddhdt(ji,jj)
+                ELSE    ! zdb_bl >0
+                   zdhdt(ji,jj) = -( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) /  MAX( zvel_max, 1.0e-15)
+                ENDIF
+             ELSE   ! zwb_min + 2*zwb_fk_b < 0
+                ! OSBL shoaling due to restratification flux. This is the velocity defined in Fox-Kemper et al (2008)
+                zdhdt(ji,jj) = - zvel_mle(ji,jj)
+
+
+             ENDIF
+
+          ELSE
+             ! Fox-Kemper not used.
+
+               zvel_max = - ( 1.0 + 1.0 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_Dt / hbl(ji,jj) ) * zwb_ent(ji,jj) / &
+               &        MAX((zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird, epsln)
+               zdhdt(ji,jj) = -zwb_ent(ji,jj) / ( zvel_max + MAX(zdb_bl(ji,jj), 1.0e-15) )
+             ! added ajgn 23 July as temporay fix
+
+          ENDIF  ! ln_osm_mle
+
+         ELSE    ! lconv - Stable
+             zdhdt(ji,jj) = ( 0.06 + 0.52 * zhol(ji,jj) / 2.0 ) * zvstr(ji,jj)**3 / hbl(ji,jj) + zwbav(ji,jj)
+             IF ( zdhdt(ji,jj) < 0._wp ) THEN
+                ! For long timsteps factor in brackets slows the rapid collapse of the OSBL
+                 zpert = 2.0 * ( 1.0 + 0.0 * 2.0 * zvstr(ji,jj) * rn_Dt / hbl(ji,jj) ) * zvstr(ji,jj)**2 / hbl(ji,jj)
+             ELSE
+                 zpert = MAX( 2.0 * zvstr(ji,jj)**2 / hbl(ji,jj), zdb_bl(ji,jj) )
+             ENDIF
+             zdhdt(ji,jj) = 2.0 * zdhdt(ji,jj) / MAX(zpert, epsln)
+         ENDIF  ! lconv
+    ELSE ! lshear
+      IF ( lconv(ji,jj) ) THEN    ! Convective
+
+          IF ( ln_osm_mle ) THEN
+
+             IF ( hmle(ji,jj) > hbl(ji,jj) ) THEN
+       ! Fox-Kemper buoyancy flux average over OSBL
+                zwb_fk_b(ji,jj) = zwb_fk(ji,jj) *  &
+                     (1.0 + hmle(ji,jj) / ( 6.0 * hbl(ji,jj) ) * (-1.0 + ( 1.0 - 2.0 * hbl(ji,jj) / hmle(ji,jj))**3) )
+             ELSE
+                zwb_fk_b(ji,jj) = 0.5 * zwb_fk(ji,jj) * hmle(ji,jj) / hbl(ji,jj)
+             ENDIF
+             zvel_max = ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**p2third / hbl(ji,jj)
+             IF ( ( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) < 0.0 ) THEN
+                ! OSBL is deepening, entrainment > restratification
+                IF ( zdb_bl(ji,jj) > 0.0 .and. zdbdz_bl_ext(ji,jj) > 0.0 ) THEN
+                   zdhdt(ji,jj) = -( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) / ( zvel_max + MAX(zdb_bl(ji,jj), 1.0e-15) )
+                ELSE
+                   zdhdt(ji,jj) = -( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) /  MAX( zvel_max, 1.0e-15)
+                ENDIF
+             ELSE
+                ! OSBL shoaling due to restratification flux. This is the velocity defined in Fox-Kemper et al (2008)
+                zdhdt(ji,jj) = - zvel_mle(ji,jj)
+
+
+             ENDIF
+
+          ELSE
+             ! Fox-Kemper not used.
+
+               zvel_max = -zwb_ent(ji,jj) / &
+               &        MAX((zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird, epsln)
+               zdhdt(ji,jj) = -zwb_ent(ji,jj) / ( zvel_max + MAX(zdb_bl(ji,jj), 1.0e-15) )
+             ! added ajgn 23 July as temporay fix
+
+          ENDIF  ! ln_osm_mle
+
+         ELSE                        ! Stable
+             zdhdt(ji,jj) = ( 0.06 + 0.52 * zhol(ji,jj) / 2.0 ) * zvstr(ji,jj)**3 / hbl(ji,jj) + zwbav(ji,jj)
+             IF ( zdhdt(ji,jj) < 0._wp ) THEN
+                ! For long timsteps factor in brackets slows the rapid collapse of the OSBL
+                 zpert = 2.0 * zvstr(ji,jj)**2 / hbl(ji,jj)
+             ELSE
+                 zpert = MAX( 2.0 * zvstr(ji,jj)**2 / hbl(ji,jj), zdb_bl(ji,jj) )
+             ENDIF
+             zdhdt(ji,jj) = 2.0 * zdhdt(ji,jj) / MAX(zpert, epsln)
+         ENDIF  ! lconv
+      ENDIF ! lshear
+  END_2D
+    END SUBROUTINE zdf_osm_calculate_dhdt
+
+    SUBROUTINE zdf_osm_timestep_hbl( zdhdt )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE zdf_osm_timestep_hbl  ***
+     !!
+     !! ** Purpose : Increments hbl.
+     !!
+     !! ** Method  : If thechange in hbl exceeds one model level the change is
+     !!              is calculated by moving down the grid, changing the buoyancy
+     !!              jump. This is to ensure that the change in hbl does not
+     !!              overshoot a stable layer.
+     !!
+     !!----------------------------------------------------------------------
+
+
+    REAL(wp), DIMENSION(jpi,jpj) :: zdhdt   ! rates of change of hbl.
+
+    INTEGER :: jk, jj, ji, jm
+    REAL(wp) :: zhbl_s, zvel_max, zdb
+    REAL(wp) :: zthermal, zbeta
+
+     DO_2D( 0, 0, 0, 0 )
+        IF ( ibld(ji,jj) - imld(ji,jj) > 1 ) THEN
+!
+! If boundary layer changes by more than one level, need to check for stable layers between initial and final depths.
+!
+           zhbl_s = hbl(ji,jj)
+           jm = imld(ji,jj)
+           zthermal = rab_n(ji,jj,1,jp_tem)
+           zbeta = rab_n(ji,jj,1,jp_sal)
+
+
+           IF ( lconv(ji,jj) ) THEN
+!unstable
+
+              IF( ln_osm_mle ) THEN
+                 zvel_max = ( zwstrl(ji,jj)**3 + zwstrc(ji,jj)**3 )**p2third / hbl(ji,jj)
+              ELSE
+
+                 zvel_max = -( 1.0 + 1.0 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_Dt / hbl(ji,jj) ) * zwb_ent(ji,jj) / &
+                   &      ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+
+              ENDIF
+
+              DO jk = imld(ji,jj), ibld(ji,jj)
+                 zdb = MAX( grav * ( zthermal * ( zt_bl(ji,jj) - ts(ji,jj,jm,jp_tem,Kmm) ) &
+                      & - zbeta * ( zs_bl(ji,jj) - ts(ji,jj,jm,jp_sal,Kmm) ) ), &
+                      &  0.0 ) + zvel_max
+
+
+                 IF ( ln_osm_mle ) THEN
+                    zhbl_s = zhbl_s + MIN( &
+                     & rn_Dt * ( ( -zwb_ent(ji,jj) - 2.0 * zwb_fk_b(ji,jj) )/ zdb ) / FLOAT(ibld(ji,jj) - imld(ji,jj) ), &
+                     & e3w(ji,jj,jm,Kmm) )
+                 ELSE
+                   zhbl_s = zhbl_s + MIN( &
+                     & rn_Dt * (  -zwb_ent(ji,jj) / zdb ) / FLOAT(ibld(ji,jj) - imld(ji,jj) ), &
+                     & e3w(ji,jj,jm,Kmm) )
+                 ENDIF
+
+!                    zhbl_s = MIN(zhbl_s,  gdepw(ji,jj, mbkt(ji,jj) + 1,Kmm) - depth_tol)
+                 IF ( zhbl_s >= gdepw(ji,jj,mbkt(ji,jj) + 1,Kmm) ) THEN
+                   zhbl_s = MIN(zhbl_s,  gdepw(ji,jj, mbkt(ji,jj) + 1,Kmm) - depth_tol)
+                   lpyc(ji,jj) = .FALSE.
+                 ENDIF
+                 IF ( zhbl_s >= gdepw(ji,jj,jm+1,Kmm) ) jm = jm + 1
+              END DO
+              hbl(ji,jj) = zhbl_s
+              ibld(ji,jj) = jm
+          ELSE
+! stable
+              DO jk = imld(ji,jj), ibld(ji,jj)
+                 zdb = MAX( &
+                      & grav * ( zthermal * ( zt_bl(ji,jj) - ts(ji,jj,jm,jp_tem,Kmm) )&
+                      &           - zbeta * ( zs_bl(ji,jj) - ts(ji,jj,jm,jp_sal,Kmm) ) ),&
+                      & 0.0 ) + &
+          &       2.0 * zvstr(ji,jj)**2 / zhbl_s
+
+                 ! Alan is thuis right? I have simply changed hbli to hbl
+                 zhol(ji,jj) = -zhbl_s / ( ( zvstr(ji,jj)**3 + epsln )/ zwbav(ji,jj) )
+                 zdhdt(ji,jj) = -( zwbav(ji,jj) - 0.04 / 2.0 * zwstrl(ji,jj)**3 / zhbl_s - 0.15 / 2.0 * ( 1.0 - EXP( -1.5 * zla(ji,jj) ) ) * &
+            &                  zustar(ji,jj)**3 / zhbl_s ) * ( 0.725 + 0.225 * EXP( -7.5 * zhol(ji,jj) ) )
+                 zdhdt(ji,jj) = zdhdt(ji,jj) + zwbav(ji,jj)
+                 zhbl_s = zhbl_s + MIN( zdhdt(ji,jj) / zdb * rn_Dt / FLOAT( ibld(ji,jj) - imld(ji,jj) ), e3w(ji,jj,jm,Kmm) )
+
+!                    zhbl_s = MIN(zhbl_s, gdepw(ji,jj, mbkt(ji,jj) + 1,Kmm) - depth_tol)
+                 IF ( zhbl_s >= mbkt(ji,jj) + 1 ) THEN
+                   zhbl_s = MIN(zhbl_s,  gdepw(ji,jj, mbkt(ji,jj) + 1,Kmm) - depth_tol)
+                   lpyc(ji,jj) = .FALSE.
+                 ENDIF
+                 IF ( zhbl_s >= gdepw(ji,jj,jm,Kmm) ) jm = jm + 1
+              END DO
+          ENDIF   ! IF ( lconv )
+          hbl(ji,jj) = MAX(zhbl_s, gdepw(ji,jj,4,Kmm) )
+          ibld(ji,jj) = MAX(jm, 4 )
+        ELSE
+! change zero or one model level.
+          hbl(ji,jj) = MAX(zhbl_t(ji,jj), gdepw(ji,jj,4,Kmm) )
+        ENDIF
+        zhbl(ji,jj) = gdepw(ji,jj,ibld(ji,jj),Kmm)
+     END_2D
+
+    END SUBROUTINE zdf_osm_timestep_hbl
+
+    SUBROUTINE zdf_osm_pycnocline_thickness( dh, zdh )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_osm_pycnocline_thickness  ***
+      !!
+      !! ** Purpose : Calculates thickness of the pycnocline
+      !!
+      !! ** Method  : The thickness is calculated from a prognostic equation
+      !!              that relaxes the pycnocine thickness to a diagnostic
+      !!              value. The time change is calculated assuming the
+      !!              thickness relaxes exponentially. This is done to deal
+      !!              with large timesteps.
+      !!
+      !!----------------------------------------------------------------------
+
+      REAL(wp), DIMENSION(jpi,jpj) :: dh, zdh     ! pycnocline thickness.
+       !
+      INTEGER :: jj, ji
+      INTEGER :: inhml
+      REAL(wp) :: zari, ztau, zdh_ref
+      REAL, PARAMETER :: a_ddh_2 = 3.5 ! also in pycnocline_depth
+
+    DO_2D( 0, 0, 0, 0 )
+
+      IF ( lshear(ji,jj) ) THEN
+         IF ( lconv(ji,jj) ) THEN
+           IF ( j_ddh(ji,jj) == 0 ) THEN
+! ddhdt for pycnocline determined in osm_calculate_dhdt
+             dh(ji,jj) = dh(ji,jj) + zddhdt(ji,jj) * rn_Dt
+           ELSE
+! Temporary (probably) Recalculate dh_ref to ensure dh doesn't go negative. Can't do this using zddhdt from calculate_dhdt 
+             IF ( ( zwstrc(ji,jj) / zvstr(ji,jj) )**3 <= 0.5 ) THEN
+               zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zvstr(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+             ELSE
+               zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zwstrc(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+             ENDIF
+             ztau = MAX( zdb_bl(ji,jj) * ( zari * hbl(ji,jj) ) / ( a_ddh_2 * MAX(-zwb_ent(ji,jj), 1.e-12) ), 2.0 * rn_Dt )
+             dh(ji,jj) = dh(ji,jj) * EXP( -rn_Dt / ztau ) + zari * zhbl(ji,jj) * ( 1.0 - EXP( -rn_Dt / ztau ) )
+             IF ( dh(ji,jj) >= hbl(ji,jj) ) dh(ji,jj) = zari * zhbl(ji,jj)
+           ENDIF
+            
+         ELSE ! lconv
+! Initially shear only for entraining OSBL. Stable code will be needed if extended to stable OSBL 
+
+            ztau = hbl(ji,jj) / MAX(zvstr(ji,jj), epsln)
+            IF ( zdhdt(ji,jj) >= 0.0 ) THEN    ! probably shouldn't include wm here
+               ! boundary layer deepening
+               IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+                  ! pycnocline thickness set by stratification - use same relationship as for neutral conditions.
+                  zari = MIN( 4.5 * ( zvstr(ji,jj)**2 ) &
+                       & /  MAX(zdb_bl(ji,jj) * zhbl(ji,jj), epsln ) + 0.01  , 0.2 )
+                  zdh_ref = MIN( zari, 0.2 ) * hbl(ji,jj)
+               ELSE
+                  zdh_ref = 0.2 * hbl(ji,jj)
+               ENDIF
+            ELSE     ! IF(dhdt < 0)
+               zdh_ref = 0.2 * hbl(ji,jj)
+            ENDIF    ! IF (dhdt >= 0)
+            dh(ji,jj) = dh(ji,jj) * EXP( -rn_Dt / ztau )+ zdh_ref * ( 1.0 - EXP( -rn_Dt / ztau ) )
+            IF ( zdhdt(ji,jj) < 0._wp .and. dh(ji,jj) >= hbl(ji,jj) ) dh(ji,jj) = zdh_ref       ! can be a problem with dh>hbl for rapid collapse
+            ! Alan: this hml is never defined or used -- do we need it?
+         ENDIF
+          
+      ELSE   ! lshear  
+! for lshear = .FALSE. calculate ddhdt here
+
+          IF ( lconv(ji,jj) ) THEN
+
+            IF( ln_osm_mle ) THEN
+               IF ( ( zwb_ent(ji,jj) + 2.0 * zwb_fk_b(ji,jj) ) < 0._wp ) THEN
+                  ! OSBL is deepening. Note wb_fk_b is zero if ln_osm_mle=F
+                  IF ( zdb_bl(ji,jj) > 0._wp .and. zdbdz_bl_ext(ji,jj) > 0._wp)THEN
+                     IF ( ( zwstrc(ji,jj) / MAX(zvstr(ji,jj), epsln) )**3 <= 0.5 ) THEN  ! near neutral stability
+                        zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zvstr(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+                     ELSE                                                     ! unstable
+                        zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zwstrc(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+                     ENDIF
+                     ztau = 0.2 * hbl(ji,jj) / MAX(epsln, (zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3)**pthird)
+                     zdh_ref = zari * hbl(ji,jj)
+                  ELSE
+                     ztau = 0.2 * hbl(ji,jj) / MAX(epsln, (zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3)**pthird)
+                     zdh_ref = 0.2 * hbl(ji,jj)
+                  ENDIF
+               ELSE
+                  ztau = 0.2 * hbl(ji,jj) /  MAX(epsln, (zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3)**pthird)
+                  zdh_ref = 0.2 * hbl(ji,jj)
+               ENDIF
+            ELSE ! ln_osm_mle
+               IF ( zdb_bl(ji,jj) > 0._wp .and. zdbdz_bl_ext(ji,jj) > 0._wp)THEN
+                  IF ( ( zwstrc(ji,jj) / MAX(zvstr(ji,jj), epsln) )**3 <= 0.5 ) THEN  ! near neutral stability
+                     zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zvstr(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+                  ELSE                                                     ! unstable
+                     zari = MIN( 1.5 * zdb_bl(ji,jj) / ( zhbl(ji,jj) * ( MAX(zdbdz_bl_ext(ji,jj),0._wp) + zdb_bl(ji,jj)**2 / MAX(4.5 * zwstrc(ji,jj)**2 , 1.e-12 )) ), 0.2d0 )
+                  ENDIF
+                  ztau = hbl(ji,jj) / MAX(epsln, (zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3)**pthird)
+                  zdh_ref = zari * hbl(ji,jj)
+               ELSE
+                  ztau = hbl(ji,jj) / MAX(epsln, (zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3)**pthird)
+                  zdh_ref = 0.2 * hbl(ji,jj)
+               ENDIF
+
+            END IF  ! ln_osm_mle
+
+            dh(ji,jj) = dh(ji,jj) * EXP( -rn_Dt / ztau ) + zdh_ref * ( 1.0 - EXP( -rn_Dt / ztau ) )
+!               IF ( zdhdt(ji,jj) < 0._wp .and. dh(ji,jj) >= hbl(ji,jj) ) dh(ji,jj) = zdh_ref
+            IF ( dh(ji,jj) >= hbl(ji,jj) ) dh(ji,jj) = zdh_ref
+            ! Alan: this hml is never defined or used
+         ELSE   ! IF (lconv)
+            ztau = hbl(ji,jj) / MAX(zvstr(ji,jj), epsln)
+            IF ( zdhdt(ji,jj) >= 0.0 ) THEN    ! probably shouldn't include wm here
+               ! boundary layer deepening
+               IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+                  ! pycnocline thickness set by stratification - use same relationship as for neutral conditions.
+                  zari = MIN( 4.5 * ( zvstr(ji,jj)**2 ) &
+                       & /  MAX(zdb_bl(ji,jj) * zhbl(ji,jj), epsln ) + 0.01  , 0.2 )
+                  zdh_ref = MIN( zari, 0.2 ) * hbl(ji,jj)
+               ELSE
+                  zdh_ref = 0.2 * hbl(ji,jj)
+               ENDIF
+            ELSE     ! IF(dhdt < 0)
+               zdh_ref = 0.2 * hbl(ji,jj)
+            ENDIF    ! IF (dhdt >= 0)
+            dh(ji,jj) = dh(ji,jj) * EXP( -rn_Dt / ztau )+ zdh_ref * ( 1.0 - EXP( -rn_Dt / ztau ) )
+            IF ( zdhdt(ji,jj) < 0._wp .and. dh(ji,jj) >= hbl(ji,jj) ) dh(ji,jj) = zdh_ref       ! can be a problem with dh>hbl for rapid collapse
+         ENDIF       ! IF (lconv)
+      ENDIF  ! lshear
+ 
+      hml(ji,jj) = hbl(ji,jj) - dh(ji,jj)
+      inhml = MAX( INT( dh(ji,jj) / MAX(e3t(ji,jj,ibld(ji,jj),Kmm), 1.e-3) ) , 1 )
+      imld(ji,jj) = MAX( ibld(ji,jj) - inhml, 3)
+      zhml(ji,jj) = gdepw(ji,jj,imld(ji,jj),Kmm)
+      zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
+    END_2D
+
+    END SUBROUTINE zdf_osm_pycnocline_thickness
+
+
+   SUBROUTINE zdf_osm_zmld_horizontal_gradients( zmld, zdtdx, zdtdy, zdsdx, zdsdy, dbdx_mle, dbdy_mle, zdbds_mle )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_osm_horizontal_gradients  ***
+      !!
+      !! ** Purpose :   Calculates horizontal gradients of buoyancy for use with Fox-Kemper parametrization.
+      !!
+      !! ** Method  :
+      !!
+      !! References: Fox-Kemper et al., JPO, 38, 1145-1165, 2008
+      !!             Fox-Kemper and Ferrari, JPO, 38, 1166-1179, 2008
+
+
+      REAL(wp), DIMENSION(jpi,jpj)     :: dbdx_mle, dbdy_mle ! MLE horiz gradients at u & v points
+      REAL(wp), DIMENSION(jpi,jpj)     :: zdbds_mle ! Magnitude of horizontal buoyancy gradient.
+      REAL(wp), DIMENSION(jpi,jpj)     :: zmld ! ==  estimated FK BLD used for MLE horiz gradients  == !
+      REAL(wp), DIMENSION(jpi,jpj)     :: zdtdx, zdtdy, zdsdx, zdsdy
+
+      INTEGER  ::   ji, jj, jk          ! dummy loop indices
+      INTEGER  ::   ii, ij, ik, ikmax   ! local integers
+      REAL(wp)                         :: zc
+      REAL(wp)                         :: zN2_c           ! local buoyancy difference from 10m value
+      REAL(wp), DIMENSION(jpi,jpj)     :: ztm, zsm, zLf_NH, zLf_MH
+      REAL(wp), DIMENSION(jpi,jpj,jpts):: ztsm_midu, ztsm_midv, zabu, zabv
+      REAL(wp), DIMENSION(jpi,jpj)     :: zmld_midu, zmld_midv
+!!----------------------------------------------------------------------
+      !
+      !                                      !==  MLD used for MLE  ==!
+
+      mld_prof(:,:)  = nlb10               ! Initialization to the number of w ocean point
+      zmld(:,:)  = 0._wp               ! here hmlp used as a dummy variable, integrating vertically N^2
+      zN2_c = grav * rn_osm_mle_rho_c * r1_rho0   ! convert density criteria into N^2 criteria
+      DO_3D( 1, 1, 1, 1, nlb10, jpkm1 )
+         ikt = mbkt(ji,jj)
+         zmld(ji,jj) = zmld(ji,jj) + MAX( rn2b(ji,jj,jk) , 0._wp ) * e3w(ji,jj,jk,Kmm)
+         IF( zmld(ji,jj) < zN2_c )   mld_prof(ji,jj) = MIN( jk , ikt ) + 1   ! Mixed layer level
+      END_3D
+      DO_2D( 1, 1, 1, 1 )
+         mld_prof(ji,jj) = MAX(mld_prof(ji,jj),ibld(ji,jj))
+         zmld(ji,jj) = gdepw(ji,jj,mld_prof(ji,jj),Kmm)
+      END_2D
+      ! ensure mld_prof .ge. ibld
+      !
+      ikmax = MIN( MAXVAL( mld_prof(:,:) ), jpkm1 )                  ! max level of the computation
+      !
+      ztm(:,:) = 0._wp
+      zsm(:,:) = 0._wp
+      DO_3D( 1, 1, 1, 1, 1, ikmax )
+         zc = e3t(ji,jj,jk,Kmm) * REAL( MIN( MAX( 0, mld_prof(ji,jj)-jk ) , 1  )  )    ! zc being 0 outside the ML t-points
+         ztm(ji,jj) = ztm(ji,jj) + zc * ts(ji,jj,jk,jp_tem,Kmm)
+         zsm(ji,jj) = zsm(ji,jj) + zc * ts(ji,jj,jk,jp_sal,Kmm)
+      END_3D
+      ! average temperature and salinity.
+      ztm(:,:) = ztm(:,:) / MAX( e3t(:,:,1,Kmm), zmld(:,:) )
+      zsm(:,:) = zsm(:,:) / MAX( e3t(:,:,1,Kmm), zmld(:,:) )
+      ! calculate horizontal gradients at u & v points
+
+      DO_2D( 0, 0, 1, 0 )
+         zdtdx(ji,jj) = ( ztm(ji+1,jj) - ztm( ji,jj) )  * umask(ji,jj,1) / e1u(ji,jj)
+         zdsdx(ji,jj) = ( zsm(ji+1,jj) - zsm( ji,jj) )  * umask(ji,jj,1) / e1u(ji,jj)
+         zmld_midu(ji,jj) = 0.25_wp * (zmld(ji+1,jj) + zmld( ji,jj))
+         ztsm_midu(ji,jj,jp_tem) = 0.5_wp * ( ztm(ji+1,jj) + ztm( ji,jj) )
+         ztsm_midu(ji,jj,jp_sal) = 0.5_wp * ( zsm(ji+1,jj) + zsm( ji,jj) )
+      END_2D
+
+      DO_2D( 1, 0, 0, 0 )
+         zdtdy(ji,jj) = ( ztm(ji,jj+1) - ztm( ji,jj) ) * vmask(ji,jj,1) / e1v(ji,jj)
+         zdsdy(ji,jj) = ( zsm(ji,jj+1) - zsm( ji,jj) ) * vmask(ji,jj,1) / e1v(ji,jj)
+         zmld_midv(ji,jj) = 0.25_wp * (zmld(ji,jj+1) + zmld( ji,jj))
+         ztsm_midv(ji,jj,jp_tem) = 0.5_wp * ( ztm(ji,jj+1) + ztm( ji,jj) )
+         ztsm_midv(ji,jj,jp_sal) = 0.5_wp * ( zsm(ji,jj+1) + zsm( ji,jj) )
+      END_2D
+
+      CALL eos_rab(ztsm_midu, zmld_midu, zabu, Kmm)
+      CALL eos_rab(ztsm_midv, zmld_midv, zabv, Kmm)
+
+      DO_2D( 0, 0, 1, 0 )
+         dbdx_mle(ji,jj) = grav*(zdtdx(ji,jj)*zabu(ji,jj,jp_tem) - zdsdx(ji,jj)*zabu(ji,jj,jp_sal))
+      END_2D
+      DO_2D( 1, 0, 0, 0 )
+         dbdy_mle(ji,jj) = grav*(zdtdy(ji,jj)*zabv(ji,jj,jp_tem) - zdsdy(ji,jj)*zabv(ji,jj,jp_sal))
+      END_2D
+
+      DO_2D( 0, 0, 0, 0 )
+        ztmp =  r1_ft(ji,jj) *  MIN( 111.e3_wp , e1u(ji,jj) ) / rn_osm_mle_lf
+        zdbds_mle(ji,jj) = SQRT( 0.5_wp * ( dbdx_mle(ji,jj) * dbdx_mle(ji,jj) + dbdy_mle(ji,jj) * dbdy_mle(ji,jj) &
+             & + dbdx_mle(ji-1,jj) * dbdx_mle(ji-1,jj) + dbdy_mle(ji,jj-1) * dbdy_mle(ji,jj-1) ) )
+      END_2D
+      
+ END SUBROUTINE zdf_osm_zmld_horizontal_gradients
+  SUBROUTINE zdf_osm_mle_parameters( mld_prof, hmle, zhmle, zvel_mle, zdiff_mle )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_osm_mle_parameters  ***
+      !!
+      !! ** Purpose :   Timesteps the mixed layer eddy depth, hmle and calculates the mixed layer eddy fluxes for buoyancy, heat and salinity.
+      !!
+      !! ** Method  :
+      !!
+      !! References: Fox-Kemper et al., JPO, 38, 1145-1165, 2008
+      !!             Fox-Kemper and Ferrari, JPO, 38, 1166-1179, 2008
+
+      INTEGER, DIMENSION(jpi,jpj)      :: mld_prof
+      REAL(wp), DIMENSION(jpi,jpj)     :: hmle, zhmle, zwb_fk, zvel_mle, zdiff_mle
+      INTEGER  ::   ji, jj, jk          ! dummy loop indices
+      INTEGER  ::   ii, ij, ik, jkb, jkb1  ! local integers
+      INTEGER , DIMENSION(jpi,jpj)     :: inml_mle
+      REAL(wp) ::  ztmp, zdbdz, zdtdz, zdsdz, zthermal,zbeta, zbuoy, zdb_mle
+
+   ! Calculate vertical buoyancy, heat and salinity fluxes due to MLE.
+
+      DO_2D( 0, 0, 0, 0 )
+       IF ( lconv(ji,jj) ) THEN
+          ztmp =  r1_ft(ji,jj) *  MIN( 111.e3_wp , e1u(ji,jj) ) / rn_osm_mle_lf
+   ! This velocity scale, defined in Fox-Kemper et al (2008), is needed for calculating dhdt.
+          zvel_mle(ji,jj) = zdbds_mle(ji,jj) * ztmp * hmle(ji,jj) * tmask(ji,jj,1)
+          zdiff_mle(ji,jj) = 5.e-4_wp * rn_osm_mle_ce * ztmp * zdbds_mle(ji,jj) * zhmle(ji,jj)**2
+       ENDIF
+      END_2D
+   ! Timestep mixed layer eddy depth.
+      DO_2D( 0, 0, 0, 0 )
+        IF ( lmle(ji,jj) ) THEN  ! MLE layer growing.
+! Buoyancy gradient at base of MLE layer.
+           zthermal = rab_n(ji,jj,1,jp_tem)
+           zbeta    = rab_n(ji,jj,1,jp_sal)
+           jkb = mld_prof(ji,jj)
+           jkb1 = MIN(jkb + 1, mbkt(ji,jj))
+!              
+           zbuoy = grav * ( zthermal * ts(ji,jj,mld_prof(ji,jj)+2,jp_tem,Kmm) - zbeta * ts(ji,jj,mld_prof(ji,jj)+2,jp_sal,Kmm) )
+           zdb_mle = zb_bl(ji,jj) - zbuoy 
+! Timestep hmle. 
+           hmle(ji,jj) = hmle(ji,jj) + zwb0(ji,jj) * rn_Dt / zdb_mle
+        ELSE
+           IF ( zhmle(ji,jj) > zhbl(ji,jj) ) THEN
+              hmle(ji,jj) = hmle(ji,jj) - ( hmle(ji,jj) - hbl(ji,jj) ) * rn_Dt / rn_osm_mle_tau
+           ELSE
+              hmle(ji,jj) = hmle(ji,jj) - 10.0 * ( hmle(ji,jj) - hbl(ji,jj) ) * rn_Dt /rn_osm_mle_tau
+           ENDIF
+        ENDIF
+        hmle(ji,jj) = MIN(hmle(ji,jj), ht(ji,jj))
+       IF(ln_osm_hmle_limit) hmle(ji,jj) = MIN(hmle(ji,jj), MAX(rn_osm_hmle_limit,1.2*hbl(ji,jj)) )
+      END_2D
+
+      mld_prof = 4
+      DO_3D( 0, 0, 0, 0, 5, jpkm1 )
+      IF ( hmle(ji,jj) >= gdepw(ji,jj,jk,Kmm) ) mld_prof(ji,jj) = MIN(mbkt(ji,jj), jk)
+      END_3D
+      DO_2D( 0, 0, 0, 0 )
+         zhmle(ji,jj) = gdepw(ji,jj, mld_prof(ji,jj),Kmm)
+      END_2D
+END SUBROUTINE zdf_osm_mle_parameters
+
+END SUBROUTINE zdf_osm
+
+
+   SUBROUTINE zdf_osm_init( Kmm )
      !!----------------------------------------------------------------------
      !!                  ***  ROUTINE zdf_osm_init  ***
@@ -1304,12 +2456,17 @@
      !! ** input   :   Namlist namosm
      !!----------------------------------------------------------------------
-     INTEGER, INTENT(in)    :: Kmm ! time level index (middle)
-     !
+     INTEGER, INTENT(in)   ::   Kmm       ! time level
      INTEGER  ::   ios            ! local integer
      INTEGER  ::   ji, jj, jk     ! dummy loop indices
+     REAL z1_t2
      !!
      NAMELIST/namzdf_osm/ ln_use_osm_la, rn_osm_la, rn_osm_dstokes, nn_ave &
-          & ,nn_osm_wave, ln_dia_osm, rn_osm_hbl0 &
-          & ,ln_kpprimix, rn_riinfty, rn_difri, ln_convmix, rn_difconv
+          & ,nn_osm_wave, ln_dia_osm, rn_osm_hbl0, rn_zdfosm_adjust_sd &
+          & ,ln_kpprimix, rn_riinfty, rn_difri, ln_convmix, rn_difconv, nn_osm_wave &
+          & ,nn_osm_SD_reduce, ln_osm_mle, rn_osm_hblfrac, rn_osm_bl_thresh, ln_zdfosm_ice_shelter
+! Namelist for Fox-Kemper parametrization.
+      NAMELIST/namosm_mle/ nn_osm_mle, rn_osm_mle_ce, rn_osm_mle_lf, rn_osm_mle_time, rn_osm_mle_lat,&
+           & rn_osm_mle_rho_c, rn_osm_mle_thresh, rn_osm_mle_tau, ln_osm_hmle_limit, rn_osm_hmle_limit
+
      !!----------------------------------------------------------------------
      !
@@ -1325,9 +2482,11 @@
         WRITE(numout,*) 'zdf_osm_init : OSMOSIS Parameterisation'
         WRITE(numout,*) '~~~~~~~~~~~~'
-        WRITE(numout,*) '   Namelist namzdf_osm : set tke mixing parameters'
-        WRITE(numout,*) '     Use namelist  rn_osm_la                     ln_use_osm_la = ', ln_use_osm_la
+        WRITE(numout,*) '   Namelist namzdf_osm : set osm mixing parameters'
+        WRITE(numout,*) '     Use  rn_osm_la                                ln_use_osm_la = ', ln_use_osm_la
+        WRITE(numout,*) '     Use  MLE in OBL, i.e. Fox-Kemper param        ln_osm_mle = ', ln_osm_mle
         WRITE(numout,*) '     Turbulent Langmuir number                     rn_osm_la   = ', rn_osm_la
+        WRITE(numout,*) '     Stokes drift reduction factor                 rn_zdfosm_adjust_sd   = ', rn_zdfosm_adjust_sd
         WRITE(numout,*) '     Initial hbl for 1D runs                       rn_osm_hbl0   = ', rn_osm_hbl0
-        WRITE(numout,*) '     Depth scale of Stokes drift                rn_osm_dstokes = ', rn_osm_dstokes
+        WRITE(numout,*) '     Depth scale of Stokes drift                   rn_osm_dstokes = ', rn_osm_dstokes
         WRITE(numout,*) '     horizontal average flag                       nn_ave      = ', nn_ave
         WRITE(numout,*) '     Stokes drift                                  nn_osm_wave = ', nn_osm_wave
@@ -1339,6 +2498,19 @@
         CASE(2)
            WRITE(numout,*) '     calculated from ECMWF wave fields'
+         END SELECT
+        WRITE(numout,*) '     Stokes drift reduction                        nn_osm_SD_reduce', nn_osm_SD_reduce
+        WRITE(numout,*) '     fraction of hbl to average SD over/fit'
+        WRITE(numout,*) '     exponential with nn_osm_SD_reduce = 1 or 2    rn_osm_hblfrac =  ', rn_osm_hblfrac
+        SELECT CASE (nn_osm_SD_reduce)
+        CASE(0)
+           WRITE(numout,*) '     No reduction'
+        CASE(1)
+           WRITE(numout,*) '     Average SD over upper rn_osm_hblfrac of BL'
+        CASE(2)
+           WRITE(numout,*) '     Fit exponential to slope rn_osm_hblfrac of BL'
         END SELECT
+        WRITE(numout,*) '     reduce surface SD and depth scale under ice   ln_zdfosm_ice_shelter=', ln_zdfosm_ice_shelter
         WRITE(numout,*) '     Output osm diagnostics                       ln_dia_osm  = ',  ln_dia_osm
+        WRITE(numout,*) '         Threshold used to define BL              rn_osm_bl_thresh  = ', rn_osm_bl_thresh, 'm^2/s'
         WRITE(numout,*) '     Use KPP-style shear instability mixing       ln_kpprimix = ', ln_kpprimix
         WRITE(numout,*) '     local Richardson Number limit for shear instability rn_riinfty = ', rn_riinfty
@@ -1359,5 +2531,68 @@
      IF( zdf_osm_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_osm_init : unable to allocate arrays' )
 
-     call osm_rst( nit000, Kmm, 'READ' ) !* read or initialize hbl
+
+     IF( ln_osm_mle ) THEN
+! Initialise Fox-Kemper parametrization
+         READ  ( numnam_ref, namosm_mle, IOSTAT = ios, ERR = 903)
+903      IF( ios /= 0 )   CALL ctl_nam ( ios , 'namosm_mle in reference namelist')
+
+         READ  ( numnam_cfg, namosm_mle, IOSTAT = ios, ERR = 904 )
+904      IF( ios >  0 )   CALL ctl_nam ( ios , 'namosm_mle in configuration namelist')
+         IF(lwm) WRITE ( numond, namosm_mle )
+
+         IF(lwp) THEN                     ! Namelist print
+            WRITE(numout,*)
+            WRITE(numout,*) 'zdf_osm_init : initialise mixed layer eddy (MLE)'
+            WRITE(numout,*) '~~~~~~~~~~~~~'
+            WRITE(numout,*) '   Namelist namosm_mle : '
+            WRITE(numout,*) '         MLE type: =0 standard Fox-Kemper ; =1 new formulation        nn_osm_mle    = ', nn_osm_mle
+            WRITE(numout,*) '         magnitude of the MLE (typical value: 0.06 to 0.08)           rn_osm_mle_ce    = ', rn_osm_mle_ce
+            WRITE(numout,*) '         scale of ML front (ML radius of deformation) (nn_osm_mle=0)      rn_osm_mle_lf     = ', rn_osm_mle_lf, 'm'
+            WRITE(numout,*) '         maximum time scale of MLE                    (nn_osm_mle=0)      rn_osm_mle_time   = ', rn_osm_mle_time, 's'
+            WRITE(numout,*) '         reference latitude (degrees) of MLE coef.    (nn_osm_mle=1)      rn_osm_mle_lat    = ', rn_osm_mle_lat, 'deg'
+            WRITE(numout,*) '         Density difference used to define ML for FK              rn_osm_mle_rho_c  = ', rn_osm_mle_rho_c
+            WRITE(numout,*) '         Threshold used to define MLE for FK                      rn_osm_mle_thresh  = ', rn_osm_mle_thresh, 'm^2/s'
+            WRITE(numout,*) '         Timescale for OSM-FK                                         rn_osm_mle_tau  = ', rn_osm_mle_tau, 's'
+            WRITE(numout,*) '         switch to limit hmle                                      ln_osm_hmle_limit  = ', ln_osm_hmle_limit
+            WRITE(numout,*) '         fraction of zmld to limit hmle to if ln_osm_hmle_limit =.T.  rn_osm_hmle_limit = ', rn_osm_hmle_limit
+         ENDIF         !
+     ENDIF
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         IF( ln_osm_mle ) THEN
+            WRITE(numout,*) '   ==>>>   Mixed Layer Eddy induced transport added to OSMOSIS BL calculation'
+            IF( nn_osm_mle == 0 )   WRITE(numout,*) '              Fox-Kemper et al 2010 formulation'
+            IF( nn_osm_mle == 1 )   WRITE(numout,*) '              New formulation'
+         ELSE
+            WRITE(numout,*) '   ==>>>   Mixed Layer induced transport NOT added to OSMOSIS BL calculation'
+         ENDIF
+      ENDIF
+      !
+      IF( ln_osm_mle ) THEN                ! MLE initialisation
+         !
+         rb_c = grav * rn_osm_mle_rho_c /rho0        ! Mixed Layer buoyancy criteria
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '      ML buoyancy criteria = ', rb_c, ' m/s2 '
+         IF(lwp) WRITE(numout,*) '      associated ML density criteria defined in zdfmxl = ', rn_osm_mle_rho_c, 'kg/m3'
+         !
+         IF( nn_osm_mle == 0 ) THEN           ! MLE array allocation & initialisation            !
+!
+         ELSEIF( nn_osm_mle == 1 ) THEN           ! MLE array allocation & initialisation
+            rc_f = rn_osm_mle_ce/ (  5.e3_wp * 2._wp * omega * SIN( rad * rn_osm_mle_lat )  )
+            !
+         ENDIF
+         !                                ! 1/(f^2+tau^2)^1/2 at t-point (needed in both nn_osm_mle case)
+         z1_t2 = 2.e-5
+         DO_2D( 1, 1, 1, 1 )
+            r1_ft(ji,jj) = MIN(1./( ABS(ff_t(ji,jj)) + epsln ), ABS(ff_t(ji,jj))/z1_t2**2)
+         END_2D
+         ! z1_t2 = 1._wp / ( rn_osm_mle_time * rn_osm_mle_timeji,jj )
+         ! r1_ft(:,:) = 1._wp / SQRT(  ff_t(:,:) * ff_t(:,:) + z1_t2  )
+         !
+      ENDIF
+
+     call osm_rst( nit000, Kmm,  'READ' ) !* read or initialize hbl, dh, hmle
+
 
      IF( ln_zdfddm) THEN
@@ -1437,9 +2672,4 @@
      ghamv(:,:,:) = 0.
      !
-     IF( lwxios ) THEN
-        CALL iom_set_rstw_var_active('wn')
-        CALL iom_set_rstw_var_active('hbl')
-        CALL iom_set_rstw_var_active('hbli')
-     ENDIF
    END SUBROUTINE zdf_osm_init
 
@@ -1459,5 +2689,5 @@
      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
 
-     INTEGER ::   id1, id2   ! iom enquiry index
+     INTEGER ::   id1, id2, id3   ! iom enquiry index
      INTEGER  ::   ji, jj, jk     ! dummy loop indices
      INTEGER  ::   iiki, ikt ! local integer
@@ -1465,5 +2695,5 @@
      REAL(wp) ::   zN2_c           ! local scalar
      REAL(wp) ::   rho_c = 0.01_wp    !: density criterion for mixed layer depth
-     INTEGER, DIMENSION(:,:), ALLOCATABLE :: imld_rst ! level of mixed-layer depth (pycnocline top)
+     INTEGER, DIMENSION(jpi,jpj) :: imld_rst ! level of mixed-layer depth (pycnocline top)
      !!----------------------------------------------------------------------
      !
@@ -1474,18 +2704,29 @@
         id1 = iom_varid( numror, 'wn'   , ldstop = .FALSE. )
         IF( id1 > 0 ) THEN                       ! 'wn' exists; read
-           CALL iom_get( numror, jpdom_auto, 'wn', ww, ldxios = lrxios )
-           WRITE(numout,*) ' ===>>>> :  ww read from restart file'
+           CALL iom_get( numror, jpdom_auto, 'wn', ww )
+           WRITE(numout,*) ' ===>>>> :  wn read from restart file'
         ELSE
            ww(:,:,:) = 0._wp
-           WRITE(numout,*) ' ===>>>> :  ww not in restart file, set to zero initially'
+           WRITE(numout,*) ' ===>>>> :  wn not in restart file, set to zero initially'
         END IF
+
         id1 = iom_varid( numror, 'hbl'   , ldstop = .FALSE. )
-        id2 = iom_varid( numror, 'hbli'   , ldstop = .FALSE. )
+        id2 = iom_varid( numror, 'dh'   , ldstop = .FALSE. )
         IF( id1 > 0 .AND. id2 > 0) THEN                       ! 'hbl' exists; read and return
-           CALL iom_get( numror, jpdom_auto, 'hbl' , hbl , ldxios = lrxios )
-           CALL iom_get( numror, jpdom_auto, 'hbli', hbli, ldxios = lrxios  )
-           WRITE(numout,*) ' ===>>>> :  hbl & hbli read from restart file'
+           CALL iom_get( numror, jpdom_auto, 'hbl' , hbl  )
+           CALL iom_get( numror, jpdom_auto, 'dh', dh )
+           WRITE(numout,*) ' ===>>>> :  hbl & dh read from restart file'
+           IF( ln_osm_mle ) THEN
+              id3 = iom_varid( numror, 'hmle'   , ldstop = .FALSE. )
+              IF( id3 > 0) THEN
+                 CALL iom_get( numror, jpdom_auto, 'hmle' , hmle )
+                 WRITE(numout,*) ' ===>>>> :  hmle read from restart file'
+              ELSE
+                 WRITE(numout,*) ' ===>>>> :  hmle not found, set to hbl'
+                 hmle(:,:) = hbl(:,:)            ! Initialise MLE depth.
+              END IF
+           END IF
            RETURN
-        ELSE                      ! 'hbl' & 'hbli' not in restart file, recalculate
+        ELSE                      ! 'hbl' & 'dh' not in restart file, recalculate
            WRITE(numout,*) ' ===>>>> : previous run without osmosis scheme, hbl computed from stratification'
         END IF
@@ -1495,9 +2736,12 @@
      ! If READ/WRITE Flag is 'WRITE', write hbl into the restart file, then return
      !!-----------------------------------------------------------------------------
-     IF( TRIM(cdrw) == 'WRITE') THEN     !* Write hbli into the restart file, then return
+     IF( TRIM(cdrw) == 'WRITE') THEN     !* Write hbl into the restart file, then return
         IF(lwp) WRITE(numout,*) '---- osm-rst ----'
-         CALL iom_rstput( kt, nitrst, numrow, 'wn'     , ww  , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'hbl'    , hbl , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'hbli'   , hbli, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'wn'     , ww  )
+         CALL iom_rstput( kt, nitrst, numrow, 'hbl'    , hbl )
+         CALL iom_rstput( kt, nitrst, numrow, 'dh'     , dh  )
+         IF( ln_osm_mle ) THEN
+            CALL iom_rstput( kt, nitrst, numrow, 'hmle', hmle )
+         END IF
         RETURN
      END IF
@@ -1507,5 +2751,4 @@
      !!-----------------------------------------------------------------------------
      IF( lwp ) WRITE(numout,*) ' ===>>>> : calculating hbl computed from stratification'
-     ALLOCATE( imld_rst(jpi,jpj) )
      ! w-level of the mixing and mixed layers
      CALL eos_rab( ts(:,:,:,:,Kmm), rab_n, Kmm )
@@ -1516,5 +2759,5 @@
      !
      hbl(:,:)  = 0._wp              ! here hbl used as a dummy variable, integrating vertically N^2
-     DO_3D( 1, 1, 1, 1, 1, jpkm1 )  ! Mixed layer level: w-level
+     DO_3D( 1, 1, 1, 1, 1, jpkm1 )
         ikt = mbkt(ji,jj)
         hbl(ji,jj) = hbl(ji,jj) + MAX( rn2(ji,jj,jk) , 0._wp ) * e3w(ji,jj,jk,Kmm)
@@ -1523,11 +2766,18 @@
      !
      DO_2D( 1, 1, 1, 1 )
-        iiki = imld_rst(ji,jj)
-        hbl (ji,jj) = gdepw(ji,jj,iiki  ,Kmm) * ssmask(ji,jj)    ! Turbocline depth
+        iiki = MAX(4,imld_rst(ji,jj))
+        hbl (ji,jj) = gdepw(ji,jj,iiki,Kmm  )    ! Turbocline depth
+        dh (ji,jj) = e3t(ji,jj,iiki-1,Kmm  )     ! Turbocline depth
      END_2D
-     hbl = MAX(hbl,epsln)
-     hbli(:,:) = hbl(:,:)
-     DEALLOCATE( imld_rst )
+
      WRITE(numout,*) ' ===>>>> : hbl computed from stratification'
+
+     IF( ln_osm_mle ) THEN
+        hmle(:,:) = hbl(:,:)            ! Initialise MLE depth.
+        WRITE(numout,*) ' ===>>>> : hmle set = to hbl'
+     END IF
+
+     ww(:,:,:) = 0._wp
+     WRITE(numout,*) ' ===>>>> :  wn not in restart file, set to zero initially'
    END SUBROUTINE osm_rst
 
@@ -1550,7 +2800,9 @@
       !
       IF( kt == nit000 ) THEN
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) 'tra_osm : OSM non-local tracer fluxes'
-         IF(lwp) WRITE(numout,*) '~~~~~~~   '
+         IF( ntile == 0 .OR. ntile == 1 ) THEN                    ! Do only on the first tile
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'tra_osm : OSM non-local tracer fluxes'
+            IF(lwp) WRITE(numout,*) '~~~~~~~   '
+         ENDIF
       ENDIF
 
@@ -1560,5 +2812,4 @@
       ENDIF
 
-      ! add non-local temperature and salinity flux
       DO_3D( 0, 0, 0, 0, 1, jpkm1 )
          pts(ji,jj,jk,jp_tem,Krhs) =  pts(ji,jj,jk,jp_tem,Krhs)                      &
@@ -1570,12 +2821,11 @@
       END_3D
 
-
-      ! save the non-local tracer flux trends for diagnostic
+      ! save the non-local tracer flux trends for diagnostics
       IF( l_trdtra )   THEN
          ztrdt(:,:,:) = pts(:,:,:,jp_tem,Krhs) - ztrdt(:,:,:)
          ztrds(:,:,:) = pts(:,:,:,jp_sal,Krhs) - ztrds(:,:,:)
-!!bug gm jpttdzdf ==> jpttosm
-         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_zdf, ztrdt )
-         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_zdf, ztrds )
+
+         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_tem, jptra_osm, ztrdt )
+         CALL trd_tra( kt, Kmm, Krhs, 'TRA', jp_sal, jptra_osm, ztrds )
          DEALLOCATE( ztrdt )      ;     DEALLOCATE( ztrds )
       ENDIF
@@ -1643,3 +2893,4 @@
 
    !!======================================================================
+
 END MODULE zdfosm
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfphy.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfphy.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfphy.F90	(revision 14055)
@@ -21,4 +21,5 @@
    USE zdfddm         ! vertical physics: double diffusion mixing      
    USE zdfevd         ! vertical physics: convection via enhanced vertical diffusion  
+   USE zdfmfc         ! vertical physics: Mass Flux Convection 
    USE zdfiwm         ! vertical physics: internal wave-induced mixing  
    USE zdfswm         ! vertical physics: surface  wave-induced mixing
@@ -78,4 +79,5 @@
       NAMELIST/namzdf/ ln_zdfcst, ln_zdfric, ln_zdftke, ln_zdfgls,   &     ! type of closure scheme
          &             ln_zdfosm,                                    &     ! type of closure scheme
+         &             ln_zdfmfc,                                    &     ! convection : mass flux
          &             ln_zdfevd, nn_evdm, rn_evd ,                  &     ! convection : evd
          &             ln_zdfnpc, nn_npc , nn_npcp,                  &     ! convection : npc
@@ -112,4 +114,5 @@
          WRITE(numout,*) '         OSMOSIS-OBL closure (OSM)               ln_zdfosm = ', ln_zdfosm
          WRITE(numout,*) '      convection: '
+         WRITE(numout,*) '         convection mass flux (mfc)              ln_zdfmfc = ', ln_zdfmfc
          WRITE(numout,*) '         enhanced vertical diffusion             ln_zdfevd = ', ln_zdfevd
          WRITE(numout,*) '            applied on momentum (=1/0)             nn_evdm = ', nn_evdm
@@ -172,10 +175,15 @@
       IF( ln_zdfnpc .AND. ln_zdfevd )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfnpc and ln_zdfevd' )
       IF( ln_zdfosm .AND. ln_zdfevd )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfosm and ln_zdfevd' )
+      IF( ln_zdfmfc .AND. ln_zdfevd )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfmfc and ln_zdfevd' )
+      IF( ln_zdfmfc .AND. ln_zdfnpc )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfmfc and ln_zdfnpc' )
+      IF( ln_zdfmfc .AND. ln_zdfosm )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfmfc and ln_zdfosm' )
       IF( lk_top    .AND. ln_zdfnpc )   CALL ctl_stop( 'zdf_phy_init: npc scheme is not working with key_top' )
-      IF( lk_top    .AND. ln_zdfosm )   CALL ctl_stop( 'zdf_phy_init: osmosis scheme is not working with key_top' )
+      IF( lk_top    .AND. ln_zdfosm )   CALL ctl_warn( 'zdf_phy_init: osmosis gives no non-local fluxes for TOP tracers yet' )
+      IF( lk_top    .AND. ln_zdfmfc )   CALL ctl_stop( 'zdf_phy_init: Mass Flux scheme is not working with key_top' )
       IF(lwp) THEN
          WRITE(numout,*)
          IF    ( ln_zdfnpc ) THEN  ;   WRITE(numout,*) '   ==>>>   convection: use non penetrative convective scheme'
          ELSEIF( ln_zdfevd ) THEN  ;   WRITE(numout,*) '   ==>>>   convection: use enhanced vertical diffusion scheme'
+         ELSEIF( ln_zdfmfc ) THEN  ;   WRITE(numout,*) '   ==>>>   convection: use Mass Flux scheme'
          ELSE                      ;   WRITE(numout,*) '   ==>>>   convection: no specific scheme used'
          ENDIF
@@ -205,5 +213,7 @@
       ELSE                   ;   l_zdfsh2 = .TRUE.
       ENDIF
-
+      !                          !== Mass Flux Convectiive algorithm  ==!
+      IF( ln_zdfmfc )   CALL zdf_mfc_init       ! Convection computed with eddy diffusivity mass flux
+      !
       !                          !== gravity wave-driven mixing  ==!
       IF( ln_zdfiwm )   CALL zdf_iwm_init       ! internal wave-driven mixing
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfric.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfric.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfric.F90	(revision 14055)
@@ -103,8 +103,4 @@
       CALL ric_rst( nit000, 'READ' )  !* read or initialize all required files
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('avt_k')
-         CALL iom_set_rstw_var_active('avm_k')
-      ENDIF
    END SUBROUTINE zdf_ric_init
 
@@ -214,6 +210,6 @@
             !
             IF( MIN( id1, id2 ) > 0 ) THEN         ! restart exists => read it
-               CALL iom_get( numror, jpdom_auto, 'avt_k', avt_k, ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'avm_k', avm_k, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'avt_k', avt_k )
+               CALL iom_get( numror, jpdom_auto, 'avm_k', avm_k )
             ENDIF
          ENDIF
@@ -223,8 +219,6 @@
          !                                   ! -------------------
          IF(lwp) WRITE(numout,*) '---- ric-rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
-         CALL iom_rstput( kt, nitrst, numrow, 'avt_k', avt_k, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'avm_k', avm_k, ldxios = lwxios)
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'avt_k', avt_k )
+         CALL iom_rstput( kt, nitrst, numrow, 'avm_k', avm_k)
          !
       ENDIF
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfsh2.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfsh2.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdfsh2.F90	(revision 14055)
@@ -6,4 +6,6 @@
    !! History :   -   !  2014-10  (A. Barthelemy, G. Madec)  original code
    !!   NEMO     4.0  !  2017-04  (G. Madec)  remove u-,v-pts avm
+   !!   NEMO     4.2  !  2020-12  (G. Madec, E. Clementi) add Stokes Drift Shear
+   !                  !           for wave coupling
    !!----------------------------------------------------------------------
 
@@ -13,4 +15,6 @@
    USE oce
    USE dom_oce        ! domain: ocean
+   USE sbcwave        ! Surface Waves (add Stokes shear)
+   USE sbc_oce , ONLY: ln_stshear  !Stoked Drift shear contribution
    !
    USE in_out_manager ! I/O manager
@@ -21,5 +25,5 @@
 
    PUBLIC   zdf_sh2        ! called by zdftke, zdfglf, and zdfric
-   
+
    !! * Substitutions
 #  include "do_loop_substitute.h90"
@@ -59,22 +63,37 @@
       !!--------------------------------------------------------------------
       !
-      DO jk = 2, jpkm1
-         DO_2D( 1, 0, 1, 0 )     !* 2 x shear production at uw- and vw-points (energy conserving form)
-            zsh2u(ji,jj) = ( p_avm(ji+1,jj,jk) + p_avm(ji,jj,jk) ) &
-               &         * (   uu(ji,jj,jk-1,Kmm) -   uu(ji,jj,jk,Kmm) ) &
-               &         * (   uu(ji,jj,jk-1,Kbb) -   uu(ji,jj,jk,Kbb) ) & 
-               &         / ( e3uw(ji,jj,jk  ,Kmm) * e3uw(ji,jj,jk,Kbb) ) &
-               &         * wumask(ji,jj,jk)
-            zsh2v(ji,jj) = ( p_avm(ji,jj+1,jk) + p_avm(ji,jj,jk) ) &
-               &         * (   vv(ji,jj,jk-1,Kmm) -   vv(ji,jj,jk,Kmm) ) &
-               &         * (   vv(ji,jj,jk-1,Kbb) -   vv(ji,jj,jk,Kbb) ) &
-               &         / ( e3vw(ji,jj,jk  ,Kmm) * e3vw(ji,jj,jk,Kbb) ) &
-               &         * wvmask(ji,jj,jk)
-         END_2D
+      DO jk = 2, jpkm1                 !* Shear production at uw- and vw-points (energy conserving form)
+         IF ( cpl_sdrftx .AND. ln_stshear )  THEN       ! Surface Stokes Drift available  ===>>>  shear + stokes drift contibution
+            DO_2D( 1, 0, 1, 0 )
+               zsh2u(ji,jj) = ( p_avm(ji+1,jj,jk) + p_avm(ji,jj,jk) )        &
+                  &         * ( uu (ji,jj,jk-1,Kmm) -   uu (ji,jj,jk,Kmm)    &
+                  &           + usd(ji,jj,jk-1) -   usd(ji,jj,jk) )  &
+                  &         * ( uu (ji,jj,jk-1,Kbb) -   uu (ji,jj,jk,Kbb) )  &
+                  &         / ( e3uw(ji,jj,jk,Kmm) * e3uw(ji,jj,jk,Kbb) ) * wumask(ji,jj,jk)
+               zsh2v(ji,jj) = ( p_avm(ji,jj+1,jk) + p_avm(ji,jj,jk) )         &
+                  &         * ( vv (ji,jj,jk-1,Kmm) -   vv (ji,jj,jk,Kmm)     &
+                  &           + vsd(ji,jj,jk-1) -   vsd(ji,jj,jk) )   &
+                  &         * ( vv (ji,jj,jk-1,Kbb) -   vv (ji,jj,jk,Kbb) )   &
+                  &/ ( e3vw(ji,jj,jk,Kmm) * e3vw(ji,jj,jk,Kbb) ) * wvmask(ji,jj,jk)
+            END_2D
+         ELSE
+            DO_2D( 1, 0, 1, 0 )     !* 2 x shear production at uw- and vw-points (energy conserving form)
+               zsh2u(ji,jj) = ( p_avm(ji+1,jj,jk) + p_avm(ji,jj,jk) ) &
+                  &         * (   uu(ji,jj,jk-1,Kmm) -   uu(ji,jj,jk,Kmm) ) &
+                  &         * (   uu(ji,jj,jk-1,Kbb) -   uu(ji,jj,jk,Kbb) ) & 
+                  &         / ( e3uw(ji,jj,jk  ,Kmm) * e3uw(ji,jj,jk,Kbb) ) &
+                  &         * wumask(ji,jj,jk)
+               zsh2v(ji,jj) = ( p_avm(ji,jj+1,jk) + p_avm(ji,jj,jk) ) &
+                  &         * (   vv(ji,jj,jk-1,Kmm) -   vv(ji,jj,jk,Kmm) ) &
+                  &         * (   vv(ji,jj,jk-1,Kbb) -   vv(ji,jj,jk,Kbb) ) &
+                  &         / ( e3vw(ji,jj,jk  ,Kmm) * e3vw(ji,jj,jk,Kbb) ) &
+                  &         * wvmask(ji,jj,jk)
+            END_2D
+         ENDIF
          DO_2D( 0, 0, 0, 0 )     !* shear production at w-point ! coast mask: =2 at the coast ; =1 otherwise (NB: wmask useless as zsh2 are masked)
             p_sh2(ji,jj,jk) = 0.25 * (   ( zsh2u(ji-1,jj) + zsh2u(ji,jj) ) * ( 2. - umask(ji-1,jj,jk) * umask(ji,jj,jk) )   &
                &                       + ( zsh2v(ji,jj-1) + zsh2v(ji,jj) ) * ( 2. - vmask(ji,jj-1,jk) * vmask(ji,jj,jk) )   )
          END_2D
-      END DO 
+      END DO
       !
    END SUBROUTINE zdf_sh2
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdftke.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdftke.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/ZDF/zdftke.F90	(revision 14055)
@@ -29,4 +29,6 @@
    !!            4.0  !  2017-04  (G. Madec)  remove CPP ddm key & avm at t-point only 
    !!             -   !  2017-05  (G. Madec)  add top/bottom friction as boundary condition
+   !!            4.2  !  2020-12  (G. Madec, E. Clementi) add wave coupling
+   !                  !           following Couvelard et al., 2019
    !!----------------------------------------------------------------------
 
@@ -58,4 +60,5 @@
    USE prtctl         ! Print control
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+   USE sbcwave        ! Surface boundary waves
 
    IMPLICIT NONE
@@ -68,4 +71,5 @@
    !                      !!** Namelist  namzdf_tke  **
    LOGICAL  ::   ln_mxl0   ! mixing length scale surface value as function of wind stress or not
+   LOGICAL  ::   ln_mxhsw  ! mixing length scale surface value as a fonction of wave height
    INTEGER  ::   nn_mxlice ! type of scaling under sea-ice (=0/1/2/3)
    REAL(wp) ::   rn_mxlice ! ice thickness value when scaling under sea-ice
@@ -81,4 +85,6 @@
    INTEGER  ::   nn_etau   ! type of depth penetration of surface tke (=0/1/2/3)
    INTEGER  ::      nn_htau   ! type of tke profile of penetration (=0/1)
+   INTEGER  ::   nn_bc_surf! surface condition (0/1=Dir/Neum) ! Only applicable for wave coupling
+   INTEGER  ::   nn_bc_bot ! surface condition (0/1=Dir/Neum) ! Only applicable for wave coupling
    REAL(wp) ::      rn_efr    ! fraction of TKE surface value which penetrates in the ocean
    LOGICAL  ::   ln_lc     ! Langmuir cells (LC) as a source term of TKE or not
@@ -209,6 +215,7 @@
       REAL(wp) ::   zus   , zwlc  , zind       !   -      -
       REAL(wp) ::   zzd_up, zzd_lw             !   -      -
+      REAL(wp) ::   ztaui, ztauj, z1_norm
       INTEGER , DIMENSION(jpi,jpj)     ::   imlc
-      REAL(wp), DIMENSION(jpi,jpj)     ::   zice_fra, zhlc, zus3
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zice_fra, zhlc, zus3, zWlc2
       REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zpelc, zdiag, zd_up, zd_lw
       !!--------------------------------------------------------------------
@@ -219,4 +226,6 @@
       zfact2  = 1.5_wp * rn_Dt * rn_ediss
       zfact3  = 0.5_wp         * rn_ediss
+      !
+      zpelc(:,:,:) = 0._wp ! need to be initialised in case ln_lc is not used
       !
       ! ice fraction considered for attenuation of langmuir & wave breaking
@@ -232,10 +241,9 @@
       !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
       !
-      DO_2D( 0, 0, 0, 0 )         ! en(1)   = rn_ebb taum / rau0  (min value rn_emin0)
-!! clem: this should be the right formulation but it makes the model unstable unless drags are calculated implicitly
-!!       one way around would be to increase zbbirau 
-!!          en(ji,jj,1) = MAX( rn_emin0, ( ( 1._wp - fr_i(ji,jj) ) * zbbrau + &
-!!             &                                     fr_i(ji,jj)   * zbbirau ) * taum(ji,jj) ) * tmask(ji,jj,1)
+      DO_2D( 0, 0, 0, 0 )
          en(ji,jj,1) = MAX( rn_emin0, zbbrau * taum(ji,jj) ) * tmask(ji,jj,1)
+         zdiag(ji,jj,1) = 1._wp/en(ji,jj,1)
+         zd_lw(ji,jj,1) = 1._wp  
+         zd_up(ji,jj,1) = 0._wp
       END_2D
       !
@@ -274,8 +282,45 @@
       !
       !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-      IF( ln_lc ) THEN      !  Langmuir circulation source term added to tke   !   (Axell JGR 2002)
+      IF( ln_lc ) THEN      !  Langmuir circulation source term added to tke (Axell JGR 2002)
          !                  !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
          !
-         !                        !* total energy produce by LC : cumulative sum over jk
+         !                       !* Langmuir velocity scale
+         !
+         IF ( cpl_sdrftx )  THEN       ! Surface Stokes Drift available
+            !                                ! Craik-Leibovich velocity scale Wlc = ( u* u_s )^1/2    with u* = (taum/rho0)^1/2
+            !                                ! associated kinetic energy : 1/2 (Wlc)^2 = u* u_s
+            !                                ! more precisely, it is the dot product that must be used :
+            !                                !     1/2  (W_lc)^2 = MAX( u* u_s + v* v_s , 0 )   only the positive part
+!!gm  ! PS: currently we don't have neither the 2 stress components at t-point !nor the angle between u* and u_s
+!!gm  ! so we will overestimate the LC velocity....   !!gm I will do the work if !LC have an effect !
+            DO_2D( 0, 0, 0, 0 )
+!!XC                  zWlc2(ji,jj) = 0.5_wp * SQRT( taum(ji,jj) * r1_rho0 * ( ut0sd(ji,jj)**2 +vt0sd(ji,jj)**2 )  )
+                  zWlc2(ji,jj) = 0.5_wp *  ( ut0sd(ji,jj)**2 +vt0sd(ji,jj)**2 )
+            END_2D
+!
+!  Projection of Stokes drift in the wind stress direction
+!
+            DO_2D( 0, 0, 0, 0 )
+                  ztaui   = 0.5_wp * ( utau(ji,jj) + utau(ji-1,jj) )
+                  ztauj   = 0.5_wp * ( vtau(ji,jj) + vtau(ji,jj-1) )
+                  z1_norm = 1._wp / MAX( SQRT(ztaui*ztaui+ztauj*ztauj), 1.e-12 ) * tmask(ji,jj,1)
+                  zWlc2(ji,jj) = 0.5_wp * z1_norm * ( MAX( ut0sd(ji,jj)*ztaui + vt0sd(ji,jj)*ztauj, 0._wp ) )**2
+            END_2D
+         CALL lbc_lnk      ( 'zdftke', zWlc2, 'T', 1. )
+!
+         ELSE                          ! Surface Stokes drift deduced from surface stress
+            !                                ! Wlc = u_s   with u_s = 0.016*U_10m, the surface stokes drift  (Axell 2002, Eq.44)
+            !                                ! using |tau| = rho_air Cd |U_10m|^2 , it comes:
+            !                                ! Wlc = 0.016 * [|tau|/(rho_air Cdrag) ]^1/2   and thus:
+            !                                ! 1/2 Wlc^2 = 0.5 * 0.016 * 0.016 |tau| /( rho_air Cdrag )
+            zcof = 0.5 * 0.016 * 0.016 / ( zrhoa * zcdrag )      ! to convert stress in 10m wind using a constant drag
+            DO_2D( 1, 1, 1, 1 )
+               zWlc2(ji,jj) = zcof * taum(ji,jj)
+            END_2D
+            !
+         ENDIF
+         !
+         !                       !* Depth of the LC circulation  (Axell 2002, Eq.47)
+         !                             !- LHS of Eq.47
          zpelc(:,:,1) =  MAX( rn2b(:,:,1), 0._wp ) * gdepw(:,:,1,Kmm) * e3w(:,:,1,Kmm)
          DO jk = 2, jpk
@@ -283,10 +328,9 @@
                &        MAX( rn2b(:,:,jk), 0._wp ) * gdepw(:,:,jk,Kmm) * e3w(:,:,jk,Kmm)
          END DO
-         !                        !* finite Langmuir Circulation depth
-         zcof = 0.5 * 0.016 * 0.016 / ( zrhoa * zcdrag )
+         !
+         !                             !- compare LHS to RHS of Eq.47
          imlc(:,:) = mbkt(:,:) + 1       ! Initialization to the number of w ocean point (=2 over land)
-         DO_3DS( 1, 1, 1, 1, jpkm1, 2, -1 )   ! Last w-level at which zpelc>=0.5*us*us 
-            zus = zcof * taum(ji,jj)          !      with us=0.016*wind(starting from jpk-1)
-            IF( zpelc(ji,jj,jk) > zus )   imlc(ji,jj) = jk
+         DO_3DS( 1, 1, 1, 1, jpkm1, 2, -1 )
+            IF( zpelc(ji,jj,jk) > zWlc2(ji,jj) )   imlc(ji,jj) = jk
          END_3D
          !                               ! finite LC depth
@@ -294,7 +338,8 @@
             zhlc(ji,jj) = gdepw(ji,jj,imlc(ji,jj),Kmm)
          END_2D
+         !
          zcof = 0.016 / SQRT( zrhoa * zcdrag )
          DO_2D( 0, 0, 0, 0 )
-            zus  = zcof * SQRT( taum(ji,jj) )           ! Stokes drift
+            zus = SQRT( 2. * zWlc2(ji,jj) )             ! Stokes drift
             zus3(ji,jj) = MAX( 0._wp, 1._wp - zice_fra(ji,jj) ) * zus * zus * zus * tmask(ji,jj,1) ! zus > 0. ok
          END_2D
@@ -351,12 +396,43 @@
             &                                ) * wmask(ji,jj,jk)
       END_3D
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     !  Surface boundary condition on tke if
+      !                     !  coupling with waves
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !
+      IF ( cpl_phioc .and. ln_phioc )  THEN
+         SELECT CASE (nn_bc_surf) ! Boundary Condition using surface TKE flux from waves 
+
+         CASE ( 0 ) ! Dirichlet BC
+            DO_2D( 0, 0, 0, 0 )    ! en(1)   = rn_ebb taum / rho0  (min value rn_emin0)
+               IF ( phioc(ji,jj) < 0 )  phioc(ji,jj) = 0._wp
+               en(ji,jj,1) = MAX( rn_emin0, .5 * ( 15.8 * phioc(ji,jj) / rho0 )**(2./3.) )  * tmask(ji,jj,1)
+               zdiag(ji,jj,1) = 1._wp/en(ji,jj,1)  ! choose to keep coherence with former estimation of
+            END_2D
+
+         CASE ( 1 ) ! Neumann BC
+            DO_2D( 0, 0, 0, 0 )
+               IF ( phioc(ji,jj) < 0 )  phioc(ji,jj) = 0._wp
+               en(ji,jj,2)    = en(ji,jj,2) + ( rn_Dt * phioc(ji,jj) / rho0 ) /e3w(ji,jj,2,Kmm)
+               en(ji,jj,1)    = en(ji,jj,2) + (2 * e3t(ji,jj,1,Kmm) * phioc(ji,jj)/rho0) / ( p_avm(ji,jj,1) + p_avm(ji,jj,2) )
+               zdiag(ji,jj,2) = zdiag(ji,jj,2) + zd_lw(ji,jj,2)
+               zdiag(ji,jj,1) = 1._wp
+               zd_lw(ji,jj,2) = 0._wp
+            END_2D
+
+         END SELECT
+
+      ENDIF
+      !
       !                          !* Matrix inversion from level 2 (tke prescribed at level 1)
-      DO_3D( 0, 0, 0, 0, 3, jpkm1 )                ! First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1
+      DO_3D( 0, 0, 0, 0, 2, jpkm1 )                ! First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1
          zdiag(ji,jj,jk) = zdiag(ji,jj,jk) - zd_lw(ji,jj,jk) * zd_up(ji,jj,jk-1) / zdiag(ji,jj,jk-1)
       END_3D
-      DO_2D( 0, 0, 0, 0 )                          ! Second recurrence : Lk = RHSk - Lk / Dk-1 * Lk-1
-         zd_lw(ji,jj,2) = en(ji,jj,2) - zd_lw(ji,jj,2) * en(ji,jj,1)    ! Surface boudary conditions on tke
-      END_2D
-      DO_3D( 0, 0, 0, 0, 3, jpkm1 )
+!XC : commented to allow for neumann boundary condition
+!      DO_2D( 0, 0, 0, 0 )
+!         zd_lw(ji,jj,2) = en(ji,jj,2) - zd_lw(ji,jj,2) * en(ji,jj,1)    ! Surface boudary conditions on tke
+!      END_2D
+      DO_3D( 0, 0, 0, 0, 2, jpkm1 )
          zd_lw(ji,jj,jk) = en(ji,jj,jk) - zd_lw(ji,jj,jk) / zdiag(ji,jj,jk-1) *zd_lw(ji,jj,jk-1)
       END_3D
@@ -460,56 +536,63 @@
       zmxlm(:,:,:)  = rmxl_min    
       zmxld(:,:,:)  = rmxl_min
+      !
+      IF(ln_sdw .AND. ln_mxhsw) THEN
+         zmxlm(:,:,1)= vkarmn * MAX ( 1.6 * hsw(:,:) , 0.02 )        ! surface mixing length = F(wave height)
+         ! from terray et al 1999 and mellor and blumberg 2004 it should be 0.85 and not 1.6
+         zcoef       = vkarmn * ( (rn_ediff*rn_ediss)**0.25 ) / rn_ediff
+         zmxlm(:,:,1)= zcoef * MAX ( 1.6 * hsw(:,:) , 0.02 )        ! surface mixing length = F(wave height)
+      ELSE
       ! 
-     IF( ln_mxl0 ) THEN            ! surface mixing length = F(stress) : l=vkarmn*2.e5*taum/(rho0*g)
-         !
-         zraug = vkarmn * 2.e5_wp / ( rho0 * grav )
+         IF( ln_mxl0 ) THEN            ! surface mixing length = F(stress) : l=vkarmn*2.e5*taum/(rho0*g)
+         !
+            zraug = vkarmn * 2.e5_wp / ( rho0 * grav )
 #if ! defined key_si3 && ! defined key_cice
-         DO_2D( 0, 0, 0, 0 )                  ! No sea-ice
-            zmxlm(ji,jj,1) =  zraug * taum(ji,jj) * tmask(ji,jj,1)
-         END_2D
+            DO_2D( 0, 0, 0, 0 )                  ! No sea-ice
+               zmxlm(ji,jj,1) =  zraug * taum(ji,jj) * tmask(ji,jj,1)
+            END_2D
 #else
-         SELECT CASE( nn_mxlice )             ! Type of scaling under sea-ice
-         !
-         CASE( 0 )                      ! No scaling under sea-ice
+            SELECT CASE( nn_mxlice )             ! Type of scaling under sea-ice
+            !
+            CASE( 0 )                      ! No scaling under sea-ice
+               DO_2D( 0, 0, 0, 0 )
+                  zmxlm(ji,jj,1) = zraug * taum(ji,jj) * tmask(ji,jj,1)
+               END_2D
+               !
+            CASE( 1 )                      ! scaling with constant sea-ice thickness
+               DO_2D( 0, 0, 0, 0 )
+                  zmxlm(ji,jj,1) =  ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                          fr_i(ji,jj)   * rn_mxlice           ) * tmask(ji,jj,1)
+               END_2D
+               !
+            CASE( 2 )                      ! scaling with mean sea-ice thickness
+               DO_2D( 0, 0, 0, 0 )
+#if defined key_si3
+                  zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                         fr_i(ji,jj)   * hm_i(ji,jj) * 2._wp ) * tmask(ji,jj,1)
+#elif defined key_cice
+                  zmaxice = MAXVAL( h_i(ji,jj,:) )
+                  zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                         fr_i(ji,jj)   * zmaxice             ) * tmask(ji,jj,1)
+#endif
+               END_2D
+               !
+            CASE( 3 )                      ! scaling with max sea-ice thickness
+               DO_2D( 0, 0, 0, 0 )
+                  zmaxice = MAXVAL( h_i(ji,jj,:) )
+                  zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                         fr_i(ji,jj)   * zmaxice             ) * tmask(ji,jj,1)
+               END_2D
+               !
+            END SELECT
+#endif
+            !
             DO_2D( 0, 0, 0, 0 )
-               zmxlm(ji,jj,1) = zraug * taum(ji,jj) * tmask(ji,jj,1)
+               zmxlm(ji,jj,1) = MAX( rn_mxl0, zmxlm(ji,jj,1) )
             END_2D
             !
-         CASE( 1 )                      ! scaling with constant sea-ice thickness
-            DO_2D( 0, 0, 0, 0 )
-               zmxlm(ji,jj,1) =  ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
-                  &                          fr_i(ji,jj)   * rn_mxlice           ) * tmask(ji,jj,1)
-            END_2D
-            !
-         CASE( 2 )                      ! scaling with mean sea-ice thickness
-            DO_2D( 0, 0, 0, 0 )
-#if defined key_si3
-               zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
-                  &                         fr_i(ji,jj)   * hm_i(ji,jj) * 2._wp ) * tmask(ji,jj,1)
-#elif defined key_cice
-               zmaxice = MAXVAL( h_i(ji,jj,:) )
-               zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
-                  &                         fr_i(ji,jj)   * zmaxice             ) * tmask(ji,jj,1)
-#endif
-            END_2D
-            !
-         CASE( 3 )                      ! scaling with max sea-ice thickness
-            DO_2D( 0, 0, 0, 0 )
-               zmaxice = MAXVAL( h_i(ji,jj,:) )
-               zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
-                  &                         fr_i(ji,jj)   * zmaxice             ) * tmask(ji,jj,1)
-            END_2D
-            !
-         END SELECT
-#endif
-         !
-         DO_2D( 0, 0, 0, 0 )
-            zmxlm(ji,jj,1) = MAX( rn_mxl0, zmxlm(ji,jj,1) )
-         END_2D
-         !
-      ELSE
-         zmxlm(:,:,1) = rn_mxl0
-      ENDIF
-
+         ELSE
+            zmxlm(:,:,1) = rn_mxl0
+         ENDIF
+      ENDIF
       !
       DO_3D( 0, 0, 0, 0, 2, jpkm1 )
@@ -624,5 +707,6 @@
          &                 rn_mxl0 , nn_mxlice, rn_mxlice,             &
          &                 nn_pdl  , ln_lc    , rn_lc    ,             &
-         &                 nn_etau , nn_htau  , rn_efr   , nn_eice  
+         &                 nn_etau , nn_htau  , rn_efr   , nn_eice  ,  &   
+         &                 nn_bc_surf, nn_bc_bot, ln_mxhsw
       !!----------------------------------------------------------------------
       !
@@ -666,4 +750,10 @@
          WRITE(numout,*) '      Langmuir cells parametrization              ln_lc     = ', ln_lc
          WRITE(numout,*) '         coef to compute vertical velocity of LC     rn_lc  = ', rn_lc
+         IF ( cpl_phioc .and. ln_phioc )  THEN
+            SELECT CASE( nn_bc_surf)             ! Type of scaling under sea-ice
+            CASE( 0 )   ;   WRITE(numout,*) '  nn_bc_surf=0 ==>>> DIRICHLET SBC using surface TKE flux from waves'
+            CASE( 1 )   ;   WRITE(numout,*) '  nn_bc_surf=1 ==>>> NEUMANN SBC using surface TKE flux from waves'
+            END SELECT
+         ENDIF
          WRITE(numout,*) '      test param. to add tke induced by wind      nn_etau   = ', nn_etau
          WRITE(numout,*) '          type of tke penetration profile            nn_htau   = ', nn_htau
@@ -721,10 +811,4 @@
       CALL tke_rst( nit000, 'READ' )      ! (en, avt_k, avm_k, dissl) 
       !
-      IF( lwxios ) THEN
-         CALL iom_set_rstw_var_active('en')
-         CALL iom_set_rstw_var_active('avt_k')
-         CALL iom_set_rstw_var_active('avm_k')
-         CALL iom_set_rstw_var_active('dissl')
-      ENDIF
    END SUBROUTINE zdf_tke_init
 
@@ -758,8 +842,8 @@
             !
             IF( MIN( id1, id2, id3, id4 ) > 0 ) THEN      ! fields exist
-               CALL iom_get( numror, jpdom_auto, 'en'   , en   , ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'avt_k', avt_k, ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'avm_k', avm_k, ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'dissl', dissl, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'en'   , en    )
+               CALL iom_get( numror, jpdom_auto, 'avt_k', avt_k )
+               CALL iom_get( numror, jpdom_auto, 'avm_k', avm_k )
+               CALL iom_get( numror, jpdom_auto, 'dissl', dissl )
             ELSE                                          ! start TKE from rest
                IF(lwp) WRITE(numout,*)
@@ -780,10 +864,8 @@
          !                                   ! -------------------
          IF(lwp) WRITE(numout,*) '---- tke_rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          ) 
-         CALL iom_rstput( kt, nitrst, numrow, 'en'   , en   , ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'avt_k', avt_k, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'avm_k', avm_k, ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'dissl', dissl, ldxios = lwxios )
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'en'   , en    )
+         CALL iom_rstput( kt, nitrst, numrow, 'avt_k', avt_k )
+         CALL iom_rstput( kt, nitrst, numrow, 'avm_k', avm_k )
+         CALL iom_rstput( kt, nitrst, numrow, 'dissl', dissl )
          !
       ENDIF
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/do_loop_substitute.h90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/do_loop_substitute.h90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/do_loop_substitute.h90	(revision 14055)
@@ -59,5 +59,14 @@
 #endif
 
-#define DO_2D(B, T, L, R) DO jj = Njs0-(B), Nje0+(T)   ;   DO ji = Nis0-(L), Nie0+(R)
+#define DO_2D(B, T, L, R) DO jj = ntsj-(B), ntej+(T)   ;   DO ji = ntsi-(L), ntei+(R)
+#define A1Di(H) ntsi-H:ntei+H
+#define A1Dj(H) ntsj-H:ntej+H
+#define A2D(H) A1Di(H),A1Dj(H)
+#define A1Di_T(T) (ntsi-nn_hls-1)*T+1:
+#define A1Dj_T(T) (ntsj-nn_hls-1)*T+1:
+#define A2D_T(T) A1Di_T(T),A1Dj_T(T)
+#define JPK  :
+#define JPTS  :
+#define KJPT  :
 
 #define DO_3D(B, T, L, R, ks, ke) DO jk = ks, ke   ;   DO_2D(B, T, L, R)
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/module_example
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/module_example	(revision 14048)
+++ 	(revision )
@@ -1,194 +1,0 @@
-MODULE exampl
-   !!======================================================================
-   !!                       ***  MODULE  exampl  ***
-   !! Ocean physics:  brief description of the purpose of the module
-   !!                 (please no more than 2 lines)
-   !!======================================================================
-   !! History : 3.0  !  2008-06  (Author Names)  Original code
-   !!            -   !  2008-08  (Author names)  brief description of modifications
-   !!           3.3  !  2010-11  (Author names)        -              -
-   !!----------------------------------------------------------------------
-#if defined key_example
-   !!----------------------------------------------------------------------
-   !!   'key_example'  :                brief description of the key option
-   !!----------------------------------------------------------------------
-   !!   exa_mpl       : list of module subroutine (caution, never use the
-   !!   exa_mpl_init  : name of the module for a routine)
-   !!   exa_mpl_stp   : Please try to use 3 letter block for routine names
-   !!----------------------------------------------------------------------
-   USE module_name1   ! brief description of the used module
-   USE module_name2   ! ....
-
-   IMPLICIT NONE
-   PRIVATE
-
-   PUBLIC   exa_mpl        ! routine called in xxx.F90 module
-   PUBLIC   exa_mpl_init   ! routine called in nemogcm.F90 module
-
-   TYPE ::   FLD_E                !: Structure type definition
-      CHARACTER(lc) ::   clname      ! clname description (default length, lc, is 256, see par_kind.F90)
-      INTEGER       ::   nfreqh      ! nfreqh description 
-   END TYPE FLD_E 
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   var1         !: var1 description. CAUTION always use !: to describe
-   !                                                          !  a PUBLIC variable: simplify its search : 
-   !                                                          !  grep var1 *90 | grep '!:'
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   var2, var2   !: several variable on a same line OK, but 
-   !                                                          !  DO NOT use continuation lines in declaration
-
-   !                               !!* namelist nam_xxx *
-   LOGICAL   ::   ln_opt = .TRUE.   ! give the default value of each namelist parameter
-   CHARACTER ::   cn_tex = 'T'      ! short description  of the variable
-   INTEGER   ::   nn_opt = 1        ! please respect the DOCTOR norm for namelist variable
-   REAL(wp)  ::   rn_var = 2._wp    ! (it becomes easy to identify them in the code)
-   TYPE(FLD) ::   sn_ex             ! structure
-
-   INTEGER                          ::   nint    ! nint  description (local permanent variable)
-   REAL(wp)                         ::   var     ! var         -                -
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   array   ! array       -                -
-
-   !! * Substitutions
-#  include "exampl_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
-   !! $Id$ 
-   !! Software governed by the CeCILL license (see ./LICENSE)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   INTEGER FUNCTION exa_mpl_alloc()
-      !!----------------------------------------------------------------------
-      !!                ***  FUNCTION exa_mpl_alloc  ***
-      !!----------------------------------------------------------------------
-      ALLOCATE( array(jpi,jpj,jpk) , STAT= exa_mpl_alloc )   ! Module array                                                                
-      !
-      CALL mpp_sum ( 'module_example', exa_mpl_alloc )
-      IF( exa_mpl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'exa_mpl_alloc: failed to allocate arrays' )
-      !
-   END FUNCTION exa_mpl_alloc
-   
-
-   SUBROUTINE exa_mpl( kt, pvar1, pvar2, ptab )
-      !!----------------------------------------------------------------------
-      !!                    ***  ROUTINE exa_mpl  ***
-      !!
-      !! ** Purpose :   Brief description of the routine
-      !!
-      !! ** Method  :   description of the methodoloy used to achieve the
-      !!                objectives of the routine. Be as clear as possible!
-      !!
-      !! ** Action  : - first action (share memory array/varible modified
-      !!                in this routine
-      !!              - second action .....
-      !!              - .....
-      !!
-      !! References :   Author et al., Short_name_review, Year
-      !!                Give references if exist otherwise suppress these lines
-      !!----------------------------------------------------------------------
-      INTEGER , INTENT(in   )                     ::   kt      ! short description 
-      INTEGER , INTENT(inout)                     ::   pvar1   !   -         -
-      REAL(wp), INTENT(  out)                     ::   pvar2   !   -         -
-      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   pvar2   !   -         -
-      !!
-      INTEGER  ::   ji, jj, jk       ! dummy loop arguments  (DOCTOR : start with j, but not jp)
-      INTEGER  ::   itoto, itata     ! temporary integers    (DOCTOR : start with i
-      REAL(wp) ::   zmlmin, zbbrho   ! temporary scalars     (DOCTOR : start with z)
-      REAL(wp) ::   zfact1, zfact2   ! do not use continuation lines in declaration
-      REAL(wp), DIMENSION(jpi,jpj) ::   zwrk_2d   ! 2D workspace
-      !!--------------------------------------------------------------------
-      !
-      IF( kt == nit000  )   CALL exa_mpl_init    ! Initialization (first time-step only)
-
-      zmlmin = 1.e-8                             ! Local constant initialization
-      zbbrho =  .5 * ebb / rho0
-      zfact1 = -.5 * rdt * efave
-      zfact2 = 1.5 * rdt * ediss
-
-      SELECT CASE ( npdl )                       ! short description of the action
-      !
-      CASE ( 0 )                                      ! describe case 1
-         DO jk = 2, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
-                  avm(ji,jj,jk) = ....
-               END DO
-            END DO
-         END DO
-         !
-      CASE ( 1 )                                      ! describe case 2
-         DO jk = 2, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
-                  avm(ji,jj,jk) = ...
-               END DO
-            END DO
-         END DO
-         !
-      END SELECT
-      !
-      CALL lbc_lnk( 'module_example', avm, 'T', 1. )              ! Lateral boundary conditions (unchanged sign)
-      !
-   END SUBROUTINE exa_mpl
-
-
-   SUBROUTINE exa_mpl_init
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE exa_mpl_init  ***
-      !!                   
-      !! ** Purpose :   initialization of ....
-      !!
-      !! ** Method  :   blah blah blah ...
-      !!
-      !! ** input   :   Namlist namexa
-      !!
-      !! ** Action  :   ...  
-      !!----------------------------------------------------------------------
-      INTEGER ::   ji, jj, jk, jit   ! dummy loop indices
-      INTEGER  ::   ios              ! Local integer output status for namelist read
-      !!
-      NAMELIST/namexa/ exa_v1, exa_v2, nexa_0, sn_ex     
-      !!----------------------------------------------------------------------
-      !
-      REWIND( numnam_ref )              ! Namelist namexa in reference namelist : Example
-      READ  ( numnam_ref, namexa, IOSTAT = ios, ERR = 901)
-901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namexa in reference namelist' )
-      !
-      REWIND( numnam_cfg )              ! Namelist namexa in configuration namelist : Example
-      READ  ( numnam_cfg, namexa, IOSTAT = ios, ERR = 902 )
-902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namexa in configuration namelist' )
-   ! Output namelist for control
-      WRITE ( numond, namexa )
-      !
-      IF(lwp) THEN                              ! Control print
-         WRITE(numout,*)
-         WRITE(numout,*) 'exa_mpl_init : example '
-         WRITE(numout,*) '~~~~~~~~~~~~'
-         WRITE(numout,*) '   Namelist namexa : set example parameters'
-         WRITE(numout,*) '      brief desciption               exa_v1  = ', exa_v1
-         WRITE(numout,*) '      brief desciption               exa_v2  = ', exa_v2
-         WRITE(numout,*) '      brief desciption               nexa_0  = ', nexa_0
-         WRITE(numout,*) '      brief desciption          sn_ex%clname = ', sn_ex%clname
-         WRITE(numout,*) '      brief desciption          sn_ex%nfreqh = ', sn_ex%nfreqh
-      ENDIF
-      !
-      !                              ! allocate exa_mpl arrays      
-      IF( exa_mpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'exa_mpl_init : unable to allocate arrays' )
-      !                              ! Parameter control
-      IF( ln_opt      )   CALL ctl_stop( 'exa_mpl_init: this work and option xxx are incompatible'   )
-      IF( nn_opt == 2 )   CALL ctl_stop( 'STOP',  'exa_mpl_init: this work and option yyy may cause problems'  )
-      !
-   END SUBROUTINE exa_mpl_init
-
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option :                                         NO example
-   !!----------------------------------------------------------------------
-CONTAINS
-   SUBROUTINE exa_mpl( kt, pvar1, pvar2, ptab )              ! Empty routine
-      REAL::   ptab(:,:)
-      WRITE(*,*) 'exa_mpl: You should not have seen this print! error?', kt, pvar1, pvar2, ptab(1,1)
-   END SUBROUTINE exa_mpl
-#endif
-
-   !!======================================================================
-END MODULE exampl
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/module_example.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/module_example.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/module_example.F90	(revision 14055)
@@ -0,0 +1,197 @@
+MODULE exampl
+   !!======================================================================
+   !!                       ***  MODULE  exampl  ***
+   !! Ocean physics:  brief description of the purpose of the module
+   !!                 (please no more than 2 lines)
+   !!======================================================================
+   !! History : 3.0  !  2008-06  (Author Names)  Original code
+   !!            -   !  2008-08  (Author names)  brief description of modifications
+   !!           3.3  !  2010-11  (Author names)        -              -
+   !!----------------------------------------------------------------------
+#if defined key_example
+   !!----------------------------------------------------------------------
+   !!   'key_example'  :                brief description of the key option
+   !!----------------------------------------------------------------------
+   !!   exa_mpl       : list of module subroutine (caution, never use the
+   !!   exa_mpl_init  : name of the module for a routine)
+   !!   exa_mpl_stp   : Please try to use 3 letter block for routine names
+   !!----------------------------------------------------------------------
+   USE module_name1   ! brief description of the used module
+   USE module_name2   ! ....
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   exa_mpl        ! routine called in xxx.F90 module
+   PUBLIC   exa_mpl_init   ! routine called in nemogcm.F90 module
+
+   TYPE ::   FLD_E                !: Structure type definition
+      CHARACTER(lc) ::   clname      ! clname description (default length, lc, is 256, see par_kind.F90)
+      INTEGER       ::   nfreqh      ! nfreqh description 
+   END TYPE FLD_E 
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   var1         !: var1 description. CAUTION always use !: to describe
+   !                                                          !  a PUBLIC variable: simplify its search : 
+   !                                                          !  grep var1 *90 | grep '!:'
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   var2, var2   !: several variable on a same line OK, but 
+   !                                                          !  DO NOT use continuation lines in declaration
+
+   !                               !!* namelist nam_xxx *
+   LOGICAL   ::   ln_opt = .TRUE.   ! give the default value of each namelist parameter
+   CHARACTER ::   cn_tex = 'T'      ! short description  of the variable
+   INTEGER   ::   nn_opt = 1        ! please respect the DOCTOR norm for namelist variable
+   REAL(wp)  ::   rn_var = 2._wp    ! (it becomes easy to identify them in the code)
+   TYPE(FLD) ::   sn_ex             ! structure
+
+   INTEGER                          ::   nint    ! nint  description (local permanent variable)
+   REAL(wp)                         ::   var     ! var         -                -
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   array   ! array       -                -
+
+   !! * Substitutions
+   ! for DO macro
+#  include "do_loop_substitute.h90"
+   !for other substitutions
+#  include "exampl_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION exa_mpl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION exa_mpl_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( array(jpi,jpj,jpk) , STAT= exa_mpl_alloc )   ! Module array                                                                
+      !
+      CALL mpp_sum ( 'module_example', exa_mpl_alloc )
+      IF( exa_mpl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'exa_mpl_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION exa_mpl_alloc
+   
+
+   SUBROUTINE exa_mpl( kt, pvar1, pvar2, ptab )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE exa_mpl  ***
+      !!
+      !! ** Purpose :   Brief description of the routine
+      !!
+      !! ** Method  :   description of the methodoloy used to achieve the
+      !!                objectives of the routine. Be as clear as possible!
+      !!
+      !! ** Action  : - first action (share memory array/varible modified
+      !!                in this routine
+      !!              - second action .....
+      !!              - .....
+      !!
+      !! References :   Author et al., Short_name_review, Year
+      !!                Give references if exist otherwise suppress these lines
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in   )                     ::   kt      ! short description 
+      INTEGER , INTENT(inout)                     ::   pvar1   !   -         -
+      REAL(wp), INTENT(  out)                     ::   pvar2   !   -         -
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   pvar2   !   -         -
+      !!
+      INTEGER  ::   ji, jj, jk       ! dummy loop arguments  (DOCTOR : start with j, but not jp)
+      INTEGER  ::   itoto, itata     ! temporary integers    (DOCTOR : start with i
+      REAL(wp) ::   zmlmin, zbbrho   ! temporary scalars     (DOCTOR : start with z)
+      REAL(wp) ::   zfact1, zfact2   ! do not use continuation lines in declaration
+      REAL(wp), DIMENSION(A2D(nn_hls))     ::   zwrk_2d   ! 2D workspace
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::   zwrk_3d   ! 3D workspace
+      !!--------------------------------------------------------------------
+      !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+         IF( kt == nit000  )   CALL exa_mpl_init    ! Initialization (first time-step only)
+
+         zmlmin = 1.e-8                             ! Local constant initialization
+         zbbrho =  .5 * ebb / rho0
+         zfact1 = -.5 * rdt * efave
+         zfact2 = 1.5 * rdt * ediss
+      ENDIF
+	  
+      SELECT CASE ( npdl )                       ! short description of the action
+      !
+      CASE ( 0 )                                      ! describe case 1
+         DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 1, jpkm1 )
+            avm(ji,jj,jk) = ....
+         END_3D
+         !
+      CASE ( 1 )                                      ! describe case 2
+         DO_3D( nn_hls-1, nn_hls-1, nn_hls-1, nn_hls-1, 1, jpkm1 )
+            avm(ji,jj,jk) = ....
+         END_3D
+         !
+      END SELECT
+      !
+      ! WARNING! the lbc_lnk call could not be compatible with the tiling approach
+      ! please refer to the manual for how to adapt your code
+      CALL lbc_lnk( 'module_example', avm, 'T', 1., ncsten=true )     ! Lateral boundary conditions (unchanged sign)
+      !                                                                ! ncsten=false for 5-points stencil communication
+      !                                                                ! ncsten=true (default)  for 9-points stencil communication
+      !
+   END SUBROUTINE exa_mpl
+
+
+   SUBROUTINE exa_mpl_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE exa_mpl_init  ***
+      !!                   
+      !! ** Purpose :   initialization of ....
+      !!
+      !! ** Method  :   blah blah blah ...
+      !!
+      !! ** input   :   Namlist namexa
+      !!
+      !! ** Action  :   ...  
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk, jit   ! dummy loop indices
+      INTEGER  ::   ios              ! Local integer output status for namelist read
+      !!
+      NAMELIST/namexa/ exa_v1, exa_v2, nexa_0, sn_ex     
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namexa in reference namelist : Example
+      READ  ( numnam_ref, namexa, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namexa in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namexa in configuration namelist : Example
+      READ  ( numnam_cfg, namexa, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namexa in configuration namelist' )
+   ! Output namelist for control
+      WRITE ( numond, namexa )
+      !
+      IF(lwp) THEN                              ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'exa_mpl_init : example '
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namexa : set example parameters'
+         WRITE(numout,*) '      brief desciption               exa_v1  = ', exa_v1
+         WRITE(numout,*) '      brief desciption               exa_v2  = ', exa_v2
+         WRITE(numout,*) '      brief desciption               nexa_0  = ', nexa_0
+         WRITE(numout,*) '      brief desciption          sn_ex%clname = ', sn_ex%clname
+         WRITE(numout,*) '      brief desciption          sn_ex%nfreqh = ', sn_ex%nfreqh
+      ENDIF
+      !
+      !                              ! allocate exa_mpl arrays      
+      IF( exa_mpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'exa_mpl_init : unable to allocate arrays' )
+      !                              ! Parameter control
+      IF( ln_tile .AND. ntile > 0 ) CALL ctl_stop( 'exa_mpl_init: tiling is not supported in this module by default, see manual for how to adapt your code' )
+      IF( ln_opt      )   CALL ctl_stop( 'exa_mpl_init: this work and option xxx are incompatible'   )
+      IF( nn_opt == 2 )   CALL ctl_stop( 'STOP',  'exa_mpl_init: this work and option yyy may cause problems'  )
+      !
+   END SUBROUTINE exa_mpl_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :                                         NO example
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE exa_mpl( kt, pvar1, pvar2, ptab )              ! Empty routine
+      REAL::   ptab(:,:)
+      WRITE(*,*) 'exa_mpl: You should not have seen this print! error?', kt, pvar1, pvar2, ptab(1,1)
+   END SUBROUTINE exa_mpl
+#endif
+
+   !!======================================================================
+END MODULE exampl
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/nemogcm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/nemogcm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/nemogcm.F90	(revision 14055)
@@ -439,5 +439,5 @@
      CALL Agrif_Declare_Var_ini   !  "      "   "   "      "  DOM
 #endif
-                           CALL     dom_init( Nbb, Nnn, Naa, "OPA") ! Domain
+                           CALL     dom_init( Nbb, Nnn, Naa ) ! Domain
       IF( ln_crs       )   CALL     crs_init(      Nnn )       ! coarsened grid: domain initialization 
       IF( sn_cfctl%l_prtctl )   &
@@ -492,4 +492,9 @@
                            CALL dyn_spg_init         ! surface pressure gradient
 
+      !                                      ! Icebergs
+                           CALL icb_init( rn_Dt, nit000)   ! initialise icebergs instance
+
+                                                ! ice shelf
+                           CALL isf_init( Nbb, Nnn, Naa )
 #if defined key_top
       !                                      ! Passive tracers
@@ -497,10 +502,4 @@
 #endif
       IF( l_ldfslp     )   CALL ldf_slp_init    ! slope of lateral mixing
-
-      !                                      ! Icebergs
-                           CALL icb_init( rn_Dt, nit000)   ! initialise icebergs instance
-
-                                                ! ice shelf
-                           CALL isf_init( Nbb, Nnn, Naa )
 
       !                                      ! Misc. options
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/par_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/par_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/par_oce.F90	(revision 14055)
@@ -65,4 +65,12 @@
    INTEGER, PUBLIC ::   jpjmax! = ( Nj0glo + jpnj-1 ) / jpnj + 2*nn_hls            !: maximum jpj
 
+   ! Domain tiling
+   INTEGER, PUBLIC ::   nijtile    !: number of tiles in total
+   INTEGER, PUBLIC ::   ntile      !: current tile number
+   INTEGER, PUBLIC ::   ntsi       !: start of internal part of tile domain
+   INTEGER, PUBLIC ::   ntsj       !
+   INTEGER, PUBLIC ::   ntei       !: end of internal part of tile domain
+   INTEGER, PUBLIC ::   ntej       !
+
    !!---------------------------------------------------------------------
    !! Active tracer parameters
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/step.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/step.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/step.F90	(revision 14055)
@@ -55,4 +55,6 @@
    INTEGER, PUBLIC :: Nbb, Nnn, Naa, Nrhs          !! used by nemo_init
 
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
    !!----------------------------------------------------------------------
    !! NEMO/OCE 4.0 , NEMO Consortium (2018)
@@ -85,5 +87,5 @@
       !!              -8- Outputs and diagnostics
       !!----------------------------------------------------------------------
-      INTEGER ::   ji, jj, jk   ! dummy loop indice
+      INTEGER ::   ji, jj, jk, jtile   ! dummy loop indice
 !!gm kcall can be removed, I guess
       INTEGER ::   kcall        ! optional integer argument (dom_vvl_sf_nxt)
@@ -124,4 +126,21 @@
          IF( ln_crs      )   CALL iom_init( TRIM(cxios_context)//"_crs" )  ! for coarse grid
       ENDIF
+      IF((kstp == nitrst) .AND. lwxios) THEN
+         CALL iom_swap(      cw_ocerst_cxt          )
+         CALL iom_init_closedef(cw_ocerst_cxt)
+         CALL iom_setkt( kstp - nit000 + 1,      cw_ocerst_cxt          )
+#if defined key_top
+         CALL iom_swap(      cw_toprst_cxt          )
+         CALL iom_init_closedef(cw_toprst_cxt)
+         CALL iom_setkt( kstp - nit000 + 1,      cw_toprst_cxt          )
+#endif
+      ENDIF
+#if defined key_si3
+      IF(((kstp + nn_fsbc - 1) == nitrst) .AND. lwxios) THEN
+         CALL iom_swap(      cw_icerst_cxt          )
+         CALL iom_init_closedef(cw_icerst_cxt)
+         CALL iom_setkt( kstp - nit000 + 1,      cw_icerst_cxt          )
+      ENDIF
+#endif
       IF( kstp /= nit000 )   CALL day( kstp )         ! Calendar (day was already called at nit000 in day_init)
                              CALL iom_setkt( kstp - nit000 + 1,      cxios_context          )   ! tell IOM we are at time step kstp
@@ -246,28 +265,46 @@
       ! Active tracers                              
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                         ts(:,:,:,:,Nrhs) = 0._wp         ! set tracer trends to zero
-
-      IF(  lk_asminc .AND. ln_asmiau .AND. &
-         & ln_trainc )   CALL tra_asm_inc( kstp, Nbb, Nnn, ts, Nrhs )  ! apply tracer assimilation increment
-                         CALL tra_sbc    ( kstp,      Nnn, ts, Nrhs )  ! surface boundary condition
-      IF( ln_traqsr  )   CALL tra_qsr    ( kstp,      Nnn, ts, Nrhs )  ! penetrative solar radiation qsr
-      IF( ln_isf     )   CALL tra_isf    ( kstp,      Nnn, ts, Nrhs )  ! ice shelf heat flux
-      IF( ln_trabbc  )   CALL tra_bbc    ( kstp,      Nnn, ts, Nrhs )  ! bottom heat flux
-      IF( ln_trabbl  )   CALL tra_bbl    ( kstp, Nbb, Nnn, ts, Nrhs )  ! advective (and/or diffusive) bottom boundary layer scheme
-      IF( ln_tradmp  )   CALL tra_dmp    ( kstp, Nbb, Nnn, ts, Nrhs )  ! internal damping trends
-      IF( ln_bdy     )   CALL bdy_tra_dmp( kstp, Nbb,      ts, Nrhs )  ! bdy damping trends
-#if defined key_agrif
-      IF(.NOT. Agrif_Root())  & 
-               &         CALL Agrif_Sponge_tra        ! tracers sponge
-#endif
-                         CALL tra_adv    ( kstp, Nbb, Nnn, ts, Nrhs )  ! hor. + vert. advection	==> RHS
-      IF( ln_zdfosm  )   CALL tra_osm    ( kstp,      Nnn, ts, Nrhs )  ! OSMOSIS non-local tracer fluxes ==> RHS
-      IF( lrst_oce .AND. ln_zdfosm ) &
-           &             CALL osm_rst    ( kstp,      Nnn, 'WRITE'  )  ! write OSMOSIS outputs + ww (so must do here) to restarts
-                         CALL tra_ldf    ( kstp, Nbb, Nnn, ts, Nrhs )  ! lateral mixing
-
-                         CALL tra_zdf    ( kstp, Nbb, Nnn, Nrhs, ts, Naa  )  ! vertical mixing and after tracer fields
-      IF( ln_zdfnpc  )   CALL tra_npc    ( kstp,      Nnn, Nrhs, ts, Naa  )  ! update after fields by non-penetrative convection
-
+      ! Loop over tile domains
+      DO jtile = 1, nijtile
+         IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = jtile )
+
+         DO_3D( 0, 0, 0, 0, 1, jpk )
+            ts(ji,jj,jk,:,Nrhs) = 0._wp                                         ! set tracer trends to zero
+         END_3D
+
+         IF(  lk_asminc .AND. ln_asmiau .AND. &
+            & ln_trainc )   CALL tra_asm_inc( kstp, Nbb, Nnn, ts, Nrhs )  ! apply tracer assimilation increment
+                            CALL tra_sbc    ( kstp,      Nnn, ts, Nrhs )  ! surface boundary condition
+         IF( ln_traqsr  )   CALL tra_qsr    ( kstp,      Nnn, ts, Nrhs )  ! penetrative solar radiation qsr
+         IF( ln_isf     )   CALL tra_isf    ( kstp,      Nnn, ts, Nrhs )  ! ice shelf heat flux
+         IF( ln_trabbc  )   CALL tra_bbc    ( kstp,      Nnn, ts, Nrhs )  ! bottom heat flux
+         IF( ln_trabbl  )   CALL tra_bbl    ( kstp, Nbb, Nnn, ts, Nrhs )  ! advective (and/or diffusive) bottom boundary layer scheme
+         IF( ln_tradmp  )   CALL tra_dmp    ( kstp, Nbb, Nnn, ts, Nrhs )  ! internal damping trends
+         IF( ln_bdy     )   CALL bdy_tra_dmp( kstp, Nbb,      ts, Nrhs )  ! bdy damping trends
+      END DO
+
+#if defined key_agrif
+         IF(.NOT. Agrif_Root()) THEN
+            IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )
+            CALL Agrif_Sponge_tra        ! tracers sponge
+         ENDIF
+#endif
+
+      ! TEMP: [tiling] Separate loop over tile domains (due to tra_adv workarounds for tiling)
+      DO jtile = 1, nijtile
+         IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = jtile )
+
+                            CALL tra_adv    ( kstp, Nbb, Nnn, ts, Nrhs )  ! hor. + vert. advection	==> RHS
+         IF( ln_zdfmfc  )   CALL tra_mfc    ( kstp, Nbb,      ts, Nrhs )  ! Mass Flux Convection 
+         IF( ln_zdfosm  )   CALL tra_osm    ( kstp,      Nnn, ts, Nrhs )  ! OSMOSIS non-local tracer fluxes ==> RHS
+         IF( lrst_oce .AND. ln_zdfosm ) &
+              &             CALL osm_rst    ( kstp,      Nnn, 'WRITE'  )  ! write OSMOSIS outputs + ww (so must do here) to restarts
+                            CALL tra_ldf    ( kstp, Nbb, Nnn, ts, Nrhs )  ! lateral mixing
+
+                            CALL tra_zdf    ( kstp, Nbb, Nnn, Nrhs, ts, Naa  )  ! vertical mixing and after tracer fields
+         IF( ln_zdfnpc  )   CALL tra_npc    ( kstp,      Nnn, Nrhs, ts, Naa  )  ! update after fields by non-penetrative convection
+      END DO
+
+      IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 ) ! Revert to tile over full domain
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Set boundary conditions, time filter and swap time levels
@@ -338,4 +375,5 @@
       IF( kstp == nit000 ) THEN                          ! 1st time step only
                                         CALL iom_close( numror )   ! close input  ocean restart file
+         IF( lrxios )                   CALL iom_context_finalize(      cr_ocerst_cxt         )
          IF(lwm)                        CALL FLUSH    ( numond )   ! flush output namelist oce
          IF(lwm .AND. numoni /= -1 )    CALL FLUSH    ( numoni )   ! flush output namelist ice (if exist)
@@ -353,5 +391,4 @@
       IF( kstp == nitend .OR. nstop > 0 ) THEN 
                       CALL iom_context_finalize(      cxios_context          ) ! needed for XIOS+AGRIF
-         IF( lrxios ) CALL iom_context_finalize(      crxios_context         )
          IF( ln_crs ) CALL iom_context_finalize( trim(cxios_context)//"_crs" ) ! 
       ENDIF
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/step_oce.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/step_oce.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/step_oce.F90	(revision 14055)
@@ -9,4 +9,5 @@
    USE oce             ! ocean dynamics and tracers variables
    USE dom_oce         ! ocean space and time domain variables
+   USE domain, ONLY : dom_tile
    USE zdf_oce         ! ocean vertical physics variables
    USE zdfdrg  ,  ONLY : ln_drgimp   ! implicit top/bottom friction
@@ -69,4 +70,5 @@
    USE zdfphy          ! vertical physics manager      (zdf_phy_init routine)
    USE zdfosm  , ONLY : osm_rst, dyn_osm, tra_osm      ! OSMOSIS routines used in step.F90
+   USE zdfmfc          ! Mass FLux Convection routine used in step.F90
 
    USE diu_layers      ! diurnal SST bulk and coolskin routines
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/stpMLF.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/stpMLF.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/stpMLF.F90	(revision 14055)
@@ -364,5 +364,5 @@
       IF( kstp == nitend .OR. indic < 0 ) THEN
                       CALL iom_context_finalize(      cxios_context          ) ! needed for XIOS+AGRIF
-         IF(lrxios) CALL iom_context_finalize(      crxios_context          )
+         IF(lrxios) CALL iom_context_finalize(      cr_ocerst_cxt          )
          IF( ln_crs ) CALL iom_context_finalize( trim(cxios_context)//"_crs" ) !
       ENDIF
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/timing.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/timing.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OCE/timing.F90	(revision 14055)
@@ -109,5 +109,5 @@
 
       s_timer%l_tdone = .FALSE.
-      s_timer%niter = s_timer%niter + 1
+      IF( ntile == 0 .OR. ntile == 1 ) s_timer%niter = s_timer%niter + 1      ! All tiles count as one iteration
       s_timer%t_cpu = 0.
       s_timer%t_clock = 0.
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OFF/dtadyn.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OFF/dtadyn.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OFF/dtadyn.F90	(revision 14055)
@@ -46,5 +46,5 @@
    USE fldread         ! read input fields 
    USE timing          ! Timing
-   USE trc, ONLY : ln_rsttr, numrtr, numrtw, lrst_trc
+   USE trc, ONLY : ln_rsttr, lrst_trc
 
    IMPLICIT NONE
@@ -795,5 +795,5 @@
       !!---------------------------------------------------------------------
       INTEGER ,                              INTENT(in ) :: kt       ! time step
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in ) :: pts      ! temperature/salinity
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(inout) :: pts      ! temperature/salinity
       REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(out) :: puslp    ! zonal isopycnal slopes
       REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(out) :: pvslp    ! meridional isopycnal slopes
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OFF/nemogcm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OFF/nemogcm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/OFF/nemogcm.F90	(revision 14055)
@@ -126,4 +126,10 @@
          ENDIF
          !
+      IF((istp == nitrst) .AND. lwxios) THEN
+         CALL iom_swap(      cw_toprst_cxt          )
+         CALL iom_init_closedef(cw_toprst_cxt)
+         CALL iom_setkt( istp - nit000 + 1,      cw_toprst_cxt          )
+      ENDIF
+
          IF( istp /= nit000 )   CALL day        ( istp )         ! Calendar (day was already called at nit000 in day_init)
                                 CALL iom_setkt  ( istp - nit000 + 1, cxios_context )   ! say to iom that we are at time step kstp
@@ -340,5 +346,5 @@
                            CALL     eos_init        ! Equation of state
       IF( lk_c1d       )   CALL     c1d_init        ! 1D column configuration
-                           CALL     dom_init( Nbb, Nnn, Naa, "OPA") ! Domain
+                           CALL     dom_init( Nbb, Nnn, Naa ) ! Domain
       IF( sn_cfctl%l_prtctl )   &
          &                 CALL prt_ctl_init        ! Print control
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAO/nemogcm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAO/nemogcm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAO/nemogcm.F90	(revision 14055)
@@ -235,5 +235,5 @@
                            CALL phy_cst            ! Physical constants
                            CALL eos_init           ! Equation of state
-                           CALL dom_init( Nbb, Nnn, Naa, 'SAO')    ! Domain
+                           CALL dom_init( Nbb, Nnn, Naa )    ! Domain
 
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/nemogcm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/nemogcm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/nemogcm.F90	(revision 14055)
@@ -34,4 +34,5 @@
    USE diu_layers     ! diurnal bulk SST and coolskin
    USE step_diu       ! diurnal bulk SST timestepping (called from here if run offline)
+   USE icb_oce        ! icebergs
    !
    USE prtctl         ! Print control
@@ -374,5 +375,5 @@
      CALL Agrif_Declare_Var_ini   !  "      "   "   "      "  DOM
 #endif
-                           CALL dom_init( Nbb, Nnn, Naa, 'SAS') ! Domain
+                           CALL dom_init( Nbb, Nnn, Naa ) ! Domain
       IF( sn_cfctl%l_prtctl )   &
          &                 CALL prt_ctl_init        ! Print control
@@ -393,4 +394,10 @@
       ! ==>
                            CALL icb_init( rn_Dt, nit000)   ! initialise icebergs instance
+
+      ! compatibility check
+      IF( ln_icebergs .AND. ln_M2016 ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   ln_iceberg and ln_M2016 not compatible with SAS (need 3d data)'
+         CALL ctl_stop('ln_iceberg and ln_M2016 not compatible with SAS (need 3d data)')
+      END IF
       !
       IF(lwp) WRITE(numout,cform_aaa)           ! Flag AAAAAAA
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/sbcssm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/sbcssm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/sbcssm.F90	(revision 14055)
@@ -21,4 +21,5 @@
    USE zpshde         ! z-coord. with partial steps: horizontal derivatives
    USE closea         ! for ln_closea
+   USE icb_oce        ! for icebergs
    !
    USE in_out_manager ! I/O manager
@@ -226,5 +227,8 @@
          ln_closea = .false.
       ENDIF
-
+      IF( ln_icebergs .AND. ln_M2016 ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   ln_iceberg and ln_M2016 not compatible with SAS (need 3d data)'
+         CALL ctl_stop('ln_iceberg and ln_M2016 not compatible with SAS (need 3d data)')
+      END IF
       !
       IF( l_sasread ) THEN                       ! store namelist information in an array
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/step.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/step.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SAS/step.F90	(revision 14055)
@@ -89,6 +89,24 @@
 #endif   
       IF( kstp == nit000 )   CALL iom_init( cxios_context ) ! iom_put initialization (must be done after nemo_init for AGRIF+XIOS+OASIS)
+                             CALL iom_setkt( kstp - nit000 + 1, cxios_context )   ! tell iom we are at time step kstp
+      IF((kstp == nitrst) .AND. lwxios) THEN
+         CALL iom_swap(      cw_ocerst_cxt          )
+         CALL iom_init_closedef(cw_ocerst_cxt)
+         CALL iom_setkt( kstp - nit000 + 1,      cw_ocerst_cxt          )
+#if defined key_top
+         CALL iom_swap(      cw_toprst_cxt          )
+         CALL iom_init_closedef(cw_toprst_cxt)
+         CALL iom_setkt( kstp - nit000 + 1,      cw_toprst_cxt          )
+#endif
+      ENDIF
       IF( kstp /= nit000 )   CALL day( kstp )             ! Calendar (day was already called at nit000 in day_init)
-                             CALL iom_setkt( kstp - nit000 + 1, cxios_context )   ! tell iom we are at time step kstp
+
+#if defined key_si3
+      IF(((kstp + nn_fsbc - 1) == nitrst) .AND. lwxios) THEN
+         CALL iom_swap(      cw_icerst_cxt          )
+         CALL iom_init_closedef(cw_icerst_cxt)
+         CALL iom_setkt( kstp - nit000 + 1,      cw_icerst_cxt          )
+      ENDIF
+#endif
 
       ! ==> clem: open boundaries is mandatory for sea-ice because ice BDY is not decoupled from  
@@ -128,5 +146,8 @@
       ! File manipulation at the end of the first time step
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
-      IF( kstp == nit000   ) CALL iom_close( numror )                          ! close input  ocean restart file
+      IF( kstp == nit000   ) THEN
+            CALL iom_close( numror )                          ! close input  ocean restart file
+            IF( lrxios )     CALL iom_context_finalize(      cr_ocerst_cxt      )
+      ENDIF
       
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -140,5 +161,7 @@
             CALL iom_close( numrow )     
          ELSE
-            CALL iom_context_finalize( cwxios_context )
+            CALL iom_context_finalize( cw_ocerst_cxt )
+            iom_file(numrow)%nfid       = 0
+            numrow = 0
          ENDIF
          lrst_oce = .FALSE.
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/domain.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/domain.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/domain.F90	(revision 14055)
@@ -66,5 +66,5 @@
 CONTAINS
 
-   SUBROUTINE dom_init( Kbb, Kmm, Kaa, cdstr )
+   SUBROUTINE dom_init( Kbb, Kmm, Kaa )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE dom_init  ***
@@ -82,5 +82,4 @@
       !!----------------------------------------------------------------------
       INTEGER          , INTENT(in) :: Kbb, Kmm, Kaa          ! ocean time level indices
-      CHARACTER (len=*), INTENT(in) :: cdstr                  ! model: NEMO or SAS. Determines core restart variables
       !
 !!st6
@@ -135,17 +134,4 @@
       CALL dom_nam                     ! read namelist ( namrun, namdom )
       !
-      IF( lwxios ) THEN
-!define names for restart write and set core output (restart.F90)
-         CALL iom_set_rst_vars(rst_wfields)
-         CALL iom_set_rstw_core(cdstr)
-      ENDIF
-!reset namelist for SAS
-      IF(cdstr == 'SAS') THEN
-         IF(lrxios) THEN
-               IF(lwp) write(numout,*) 'Disable reading restart file using XIOS for SAS'
-               lrxios = .FALSE.
-         ENDIF
-      ENDIF
-      !
       CALL dom_hgr                      ! Horizontal mesh
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/domvvl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/domvvl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/domvvl.F90	(revision 14055)
@@ -1105,5 +1105,5 @@
          IF( ln_rstart ) THEN                   !* Read the restart file
             CALL rst_read_open                  !  open the restart file if necessary
-            CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm), ldxios = lrxios    )
+            CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm)    )
             !
             id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
@@ -1118,6 +1118,6 @@
             !
             IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb) )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm) )
                ! needed to restart if land processor not computed 
                IF(lwp) write(numout,*) 'dom_vvl_rst : e3t(:,:,:,Kbb) and e3t(:,:,:,Kmm) found in restart files'
@@ -1133,5 +1133,5 @@
                IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb) )
                e3t(:,:,:,Kmm) = e3t(:,:,:,Kbb)
                l_1st_euler = .true.
@@ -1140,5 +1140,5 @@
                IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm) )
                e3t(:,:,:,Kbb) = e3t(:,:,:,Kmm)
                l_1st_euler = .true.
@@ -1165,6 +1165,6 @@
                !                          ! ----------------------- !
                IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:) )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:) )
                ELSE                            ! one at least array is missing
                   tilde_e3t_b(:,:,:) = 0.0_wp
@@ -1175,5 +1175,5 @@
                   !                       ! ------------ !
                   IF( id5 > 0 ) THEN  ! required array exists
-                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:) )
                   ELSE                ! array is missing
                      hdiv_lf(:,:,:) = 0.0_wp
@@ -1251,23 +1251,21 @@
          !                                   ! ===================
          IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
          !                                           ! --------- !
          !                                           ! all cases !
          !                                           ! --------- !
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb) )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm) )
          !                                           ! ----------------------- !
          IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
             !                                        ! ----------------------- !
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:))
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:))
          END IF
          !                                           ! -------------!    
          IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
             !                                        ! ------------ !
-            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:))
          ENDIF
          !
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/nemogcm.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/nemogcm.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/nemogcm.F90	(revision 14055)
@@ -383,5 +383,5 @@
                            CALL     phy_cst         ! Physical constants
                            
-                           CALL     dom_init( Nbb, Nnn, Naa, "OPA") ! Domain
+                           CALL     dom_init( Nbb, Nnn, Naa ) ! Domain
 
       IF( sn_cfctl%l_prtctl )   &
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/step.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/step.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/step.F90	(revision 14055)
@@ -304,5 +304,5 @@
       IF( kstp == nitend .OR. indic < 0 ) THEN 
                       CALL iom_context_finalize(      cxios_context          ) ! needed for XIOS+AGRIF
-                      IF(lrxios) CALL iom_context_finalize(      crxios_context          )
+                      IF(lrxios) CALL iom_context_finalize(      cr_ocerst_cxt          )
       ENDIF
 #endif
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/stepLF.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/stepLF.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/stepLF.F90	(revision 14055)
@@ -318,5 +318,5 @@
       IF( kstp == nitend .OR. indic < 0 ) THEN 
                       CALL iom_context_finalize(      cxios_context          ) ! needed for XIOS+AGRIF
-                      IF(lrxios) CALL iom_context_finalize(      crxios_context          )
+                      IF(lrxios) CALL iom_context_finalize(      cr_ocerst_cxt          )
       ENDIF
 #endif
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/stpRK3.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/stpRK3.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/SWE/stpRK3.F90	(revision 14055)
@@ -361,5 +361,5 @@
       IF( kstp == nitend .OR. indic < 0 ) THEN 
                       CALL iom_context_finalize(      cxios_context          ) ! needed for XIOS+AGRIF
-                      IF(lrxios) CALL iom_context_finalize(      crxios_context          )
+                      IF(lrxios) CALL iom_context_finalize(      cr_ocerst_cxt          )
       ENDIF
 #endif
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/C14/trcsms_c14.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/C14/trcsms_c14.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/C14/trcsms_c14.F90	(revision 14055)
@@ -144,9 +144,9 @@
          IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
          !
-         CALL iom_rstput( kt, nitrst, numrtw, 'co2sbc', co2sbc )       ! These five need      &
-         CALL iom_rstput( kt, nitrst, numrtw, 'c14sbc', c14sbc )     ! &    to be written   &
+         CALL iom_rstput( kt, nitrst, numrtw, 'co2sbc', co2sbc ) ! These five need      &
+         CALL iom_rstput( kt, nitrst, numrtw, 'c14sbc', c14sbc ) ! &    to be written   &
          CALL iom_rstput( kt, nitrst, numrtw, 'exch_co2', exch_co2 ) ! &    for temporal    &
          CALL iom_rstput( kt, nitrst, numrtw, 'exch_c14', exch_c14 ) ! &    averages        &
-         CALL iom_rstput( kt, nitrst, numrtw, 'qtr_c14', qtr_c14 )   ! &    to be coherent.
+         CALL iom_rstput( kt, nitrst, numrtw, 'qtr_c14', qtr_c14   ) ! &    to be coherent.
          CALL iom_rstput( kt, nitrst, numrtw, 'qint_c14', qint_c14 ) ! Cumulative
          !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/P4Z/p4zsms.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/P4Z/p4zsms.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/P4Z/p4zsms.F90	(revision 14055)
@@ -368,6 +368,6 @@
             IF(lwp) WRITE(numout,*) '~~~~~~~'
          ENDIF
-         CALL iom_rstput( kt, nitrst, numrtw, 'PH', hi(:,:,:) )
-         CALL iom_rstput( kt, nitrst, numrtw, 'Silicalim', xksi(:,:) )
+         CALL iom_rstput( kt, nitrst, numrtw, 'PH', hi(:,:,:)           )
+         CALL iom_rstput( kt, nitrst, numrtw, 'Silicalim', xksi(:,:)    )
          CALL iom_rstput( kt, nitrst, numrtw, 'Silicamax', xksimax(:,:) )
          CALL iom_rstput( kt, nitrst, numrtw, 'tcflxcum', t_oce_co2_flx_cum )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sed.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sed.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sed.F90	(revision 14055)
@@ -43,5 +43,4 @@
    REAL    , PUBLIC               ::  sedmask
    REAL(wp), PUBLIC               ::  denssol                !: density of solid material
-   INTEGER , PUBLIC               ::  numrsr, numrsw   !: logical unit for sed restart (read and write)
    LOGICAL , PUBLIC               ::  lrst_sed       !: logical to control the trc restart write
    LOGICAL , PUBLIC               ::  ln_rst_sed  = .TRUE.     !: initialisation from a restart file or not
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sedrst.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sedrst.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sedrst.F90	(revision 14055)
@@ -42,4 +42,5 @@
       CHARACTER(LEN=50)   ::   clname   ! trc output restart file name
       CHARACTER(LEN=256)  ::   clpath   ! full path to ocean output restart file
+      CHARACTER(LEN=52)   ::   clpname   ! trc output restart file name including AGRIF
       !!----------------------------------------------------------------------
       !
@@ -80,5 +81,21 @@
          IF(lwp) WRITE(numsed,*) &
              '             open sed restart.output NetCDF file: ',TRIM(clpath)//clname
-         CALL iom_open( TRIM(clpath)//TRIM(clname), numrsw, ldwrt = .TRUE., kdlev = jpksed, cdcomp = 'SED' )
+         IF(.NOT.lwxios) THEN
+            CALL iom_open( TRIM(clpath)//TRIM(clname), numrsw, ldwrt = .TRUE., kdlev = jpksed, cdcomp = 'SED' )
+         ELSE
+#if defined key_iomput
+            cw_sedrst_cxt = "rstws_"//TRIM(ADJUSTL(clkt))
+            IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+               clpname = clname
+            ELSE
+               clpname = TRIM(Agrif_CFixed())//"_"//clname
+            ENDIF
+            numrsw = iom_xios_setid(TRIM(clpath)//TRIM(clpname))
+            CALL iom_init( cw_sedrst_cxt, kdid = numrsw, ld_closedef = .FALSE. )
+#else
+            CALL ctl_stop( 'Can not use XIOS in trc_rst_opn' )
+#endif
+         ENDIF
+
          lrst_sed = .TRUE.
       ENDIF
@@ -196,5 +213,4 @@
       CALL pack_arr( jpoce, sedligand(1:jpoce,1:jpksed), &
          &             zdta2(1:jpi,1:jpj,1:jpksed), iarroce(1:jpoce) )
-
       IF( ln_timing )  CALL timing_stop('sed_rst_read')
      
@@ -240,7 +256,6 @@
       !! 1. WRITE in nutwrs
       !! ------------------
-
-      zinfo(1) = REAL( kt)
-      CALL iom_rstput( kt, nitrst, numrsw, 'kt', zinfo  )
+!     zinfo(1) = REAL( kt)
+      CALL iom_rstput( kt, nitrst, numrsw, 'kt', REAL( kt    , wp) )
 
       ! Back to 2D geometry
@@ -299,5 +314,11 @@
 
       IF( kt == nitrst ) THEN
-          CALL iom_close( numrsw )     ! close the restart file (only at last time step)
+          IF(.NOT.lwxios) THEN
+             CALL iom_close( numrsw )     ! close the restart file (only at last time step)
+          ELSE
+             CALL iom_context_finalize( cw_sedrst_cxt ) 
+             iom_file(numrsw)%nfid       = 0
+             numrsw = 0
+          ENDIF
           IF( l_offline .AND. ln_rst_list ) THEN
              nrst_lst = nrst_lst + 1
@@ -342,4 +363,5 @@
       REAL(wp) ::  zkt, zrdttrc1
       REAL(wp) ::  zndastp
+      CHARACTER(len = 82) :: clpname
 
       ! Time domain : restart
@@ -353,7 +375,18 @@
 
          IF( ln_rst_sed ) THEN
+            lxios_sini = .FALSE.
             CALL iom_open( TRIM(cn_sedrst_indir)//'/'//cn_sedrst_in, numrsr )
+
+            IF( lrxios) THEN
+                cr_sedrst_cxt = 'sed_rst'
+                IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS for SED'
+!               IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+!                  clpname = cn_sedrst_in
+!               ELSE
+!                  clpname = TRIM(Agrif_CFixed())//"_"//cn_sedrst_in   
+!               ENDIF
+                CALL iom_init( cr_sedrst_cxt, kdid = numrsr, ld_closedef = .TRUE. )
+            ENDIF
             CALL iom_get ( numrsr, 'kt', zkt )   ! last time-step of previous run
-
             IF(lwp) THEN
                WRITE(numsed,*) ' *** Info read in restart : '
@@ -402,9 +435,10 @@
             IF(lwp) WRITE(numsed,*) 'trc_wri : write the TOP restart file (NetCDF) at it= ', kt, ' date= ', ndastp
             IF(lwp) WRITE(numsed,*) '~~~~~~~'
+            IF( lwxios ) CALL iom_init_closedef(cw_sedrst_cxt)
          ENDIF
          CALL iom_rstput( kt, nitrst, numrsw, 'kt'     , REAL( kt    , wp) )   ! time-step
          CALL iom_rstput( kt, nitrst, numrsw, 'ndastp' , REAL( ndastp, wp) )   ! date
-         CALL iom_rstput( kt, nitrst, numrsw, 'adatrj' , adatrj            )   ! number of elapsed days since
-         !                                                                     ! the begining of the run [s]
+         CALL iom_rstput( kt, nitrst, numrsw, 'adatrj' , adatrj )   ! number of elapsed days since
+         !                                                                                      ! the begining of the run [s]
       ENDIF
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sedstp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sedstp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/PISCES/SED/sedstp.F90	(revision 14055)
@@ -86,5 +86,6 @@
       IF( kt == nitsed000 ) THEN
           CALL iom_close( numrsr )       ! close input tracer restart file
-!          IF(lwm) CALL FLUSH( numont )   ! flush namelist output
+          IF(lrxios) CALL iom_context_finalize(      cr_sedrst_cxt  )
+!         IF(lwm) CALL FLUSH( numont )   ! flush namelist output
       ENDIF
       IF( lrst_sed )            CALL sed_rst_wri( kt )   ! restart file output
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trcadv.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trcadv.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trcadv.F90	(revision 14055)
@@ -23,5 +23,7 @@
    USE traadv_cen     ! centered scheme           (tra_adv_cen  routine)
    USE traadv_fct     ! FCT      scheme           (tra_adv_fct  routine)
+   USE traadv_fct_lf  ! FCT      scheme           (tra_adv_fct  routine - loop fusion version)
    USE traadv_mus     ! MUSCL    scheme           (tra_adv_mus  routine)
+   USE traadv_mus_lf  ! MUSCL    scheme           (tra_adv_mus  routine - loop fusion version)
    USE traadv_ubs     ! UBS      scheme           (tra_adv_ubs  routine)
    USE traadv_qck     ! QUICKEST scheme           (tra_adv_qck  routine)
@@ -125,12 +127,37 @@
       !
       CASE ( np_CEN )                                 ! Centered : 2nd / 4th order
+         IF (nn_hls.EQ.2) CALL lbc_lnk( 'trcadv', ptr(:,:,:,:,Kmm), 'T', 1.)
          CALL tra_adv_cen( kt, nittrc000,'TRC',          zuu, zvv, zww,      Kmm, ptr, jptra, Krhs, nn_cen_h, nn_cen_v )
       CASE ( np_FCT )                                 ! FCT      : 2nd / 4th order
-         CALL tra_adv_fct( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, nn_fct_h, nn_fct_v )
+         IF (nn_hls.EQ.2) THEN
+            CALL lbc_lnk_multi( 'trcadv', ptr(:,:,:,:,Kbb), 'T', 1., ptr(:,:,:,:,Kmm), 'T', 1.)
+            CALL lbc_lnk_multi( 'traadv', zuu(:,:,:), 'U', -1., zvv(:,:,:), 'V', -1., zww(:,:,:), 'W', 1.)
+#if defined key_loop_fusion
+            CALL tra_adv_fct_lf( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, nn_fct_h, nn_fct_v )
+#else
+            CALL tra_adv_fct( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, nn_fct_h, nn_fct_v )
+#endif
+         ELSE
+            CALL tra_adv_fct( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, nn_fct_h, nn_fct_v )
+         END IF
       CASE ( np_MUS )                                 ! MUSCL
-         CALL tra_adv_mus( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, ln_mus_ups         ) 
+         IF (nn_hls.EQ.2) THEN
+            IF (nn_hls.EQ.2) CALL lbc_lnk( 'trcadv', ptr(:,:,:,:,Kbb), 'T', 1.)
+#if defined key_loop_fusion
+            CALL tra_adv_mus_lf( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, ln_mus_ups ) 
+#else
+            CALL tra_adv_mus( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, ln_mus_ups ) 
+#endif
+         ELSE
+            CALL tra_adv_mus( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, ln_mus_ups ) 
+         END IF
       CASE ( np_UBS )                                 ! UBS
+         IF (nn_hls.EQ.2) CALL lbc_lnk( 'trcadv', ptr(:,:,:,:,Kbb), 'T', 1.)
          CALL tra_adv_ubs( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs, nn_ubs_v           )
       CASE ( np_QCK )                                 ! QUICKEST
+         IF (nn_hls.EQ.2) THEN
+            CALL lbc_lnk_multi( 'trcadv', zuu(:,:,:), 'U', -1., zvv(:,:,:), 'V', -1.)
+            CALL lbc_lnk( 'traadv', ptr(:,:,:,:,Kbb), 'T', 1.)
+         END IF
          CALL tra_adv_qck( kt, nittrc000,'TRC', rDt_trc, zuu, zvv, zww, Kbb, Kmm, ptr, jptra, Krhs                     )
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trcldf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trcldf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trcldf.F90	(revision 14055)
@@ -102,4 +102,5 @@
            &                     ptr(:,:,:,:,Kbb), ptr(:,:,:,:,Kbb), ptr(:,:,:,:,Krhs), jptra, 1 )
       CASE ( np_blp , np_blp_i , np_blp_it )                                                               ! bilaplacian: all operator (iso-level, -neutral)
+         IF(nn_hls.EQ.2) CALL lbc_lnk( 'trc_ldf', ptr(:,:,:,:,Kbb), 'T',1.)
          CALL tra_ldf_blp  ( kt, Kmm, nittrc000,'TRC', zahu, zahv, gtru, gtrv, gtrui, gtrvi,            &
            &                     ptr(:,:,:,:,Kbb) , ptr(:,:,:,:,Krhs),                 jptra, nldf_trc )
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trctrp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trctrp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/TRP/trctrp.F90	(revision 14055)
@@ -25,4 +25,5 @@
    USE trcsbc          ! surface boundary condition          (trc_sbc routine)
    USE trcbc           ! Tracers boundary condtions          ( trc_bc routine)
+   USE trcais          ! Antarctic Ice Sheet tracers         (trc_ais routine)
    USE zpshde          ! partial step: hor. derivative       (zps_hde routine)
    USE bdy_oce   , ONLY: ln_bdy
@@ -74,4 +75,5 @@
          IF( ln_trcbc .AND. lltrcbc .AND. kt /= nit000 )  &
                                 CALL trc_bc     ( kt,      Kmm, tr, Krhs )      ! tracers: surface and lateral Boundary Conditions 
+         IF( ln_trcais )        CALL trc_ais    ( kt,      Kmm, tr, Krhs )      ! tracers from Antarctic Ice Sheet (icb, isf)               
          IF( ln_trabbl )        CALL trc_bbl    ( kt, Kbb, Kmm, tr, Krhs )      ! advective (and/or diffusive) bottom boundary layer scheme
          IF( ln_trcdmp )        CALL trc_dmp    ( kt, Kbb, Kmm, tr, Krhs )      ! internal damping trends
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trc.F90	(revision 14055)
@@ -21,6 +21,4 @@
    INTEGER, PUBLIC ::   numonr     = -1   !: reference passive tracer namelist output output.namelist.top
    INTEGER, PUBLIC ::   numstr            !: tracer statistics
-   INTEGER, PUBLIC ::   numrtr     = -1   !: trc restart (read )
-   INTEGER, PUBLIC ::   numrtw            !: trc restart ( write )
    CHARACTER(:), ALLOCATABLE, PUBLIC ::   numnat_ref   !: character buffer for reference passive tracer namelist_top_ref
    CHARACTER(:), ALLOCATABLE, PUBLIC ::   numnat_cfg   !: character buffer for configuration specific passive tracer namelist_top_cfg
@@ -40,4 +38,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:  ) ::  trc_o          !: prescribed tracer concentration in ocean for SBC
    INTEGER             , PUBLIC                            ::  nn_ice_tr      !: handling of sea ice tracers
+   INTEGER             , PUBLIC                            ::  nn_ais_tr      !: handling of Antarctic Ice Sheet tracers
 
    !! interpolated gradient
@@ -65,4 +64,5 @@
    LOGICAL             , PUBLIC ::   ln_trcdta          !: Read inputs data from files
    LOGICAL             , PUBLIC ::   ln_trcbc           !: Enable surface, lateral or open boundaries conditions
+   LOGICAL             , PUBLIC ::   ln_trcais          !: Enable Antarctic Ice Sheet nutrient supply
    LOGICAL             , PUBLIC ::   ln_trcdmp          !: internal damping flag
    LOGICAL             , PUBLIC ::   ln_trcdmp_clo      !: internal damping flag on closed seas
@@ -93,4 +93,5 @@
       LOGICAL           ::   llcbc     ! read in a file or not
       LOGICAL           ::   llobc     ! read in a file or not
+      LOGICAL           ::   llais     ! read in a file or not
    END TYPE PTRACER
    !
@@ -114,4 +115,5 @@
    LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_sbc    !: Use surface boundary condition data
    LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_cbc    !: Use coastal boundary condition data
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_ais    !: Use Antarctic Ice Sheet boundary condition data
    LOGICAL , PUBLIC                                  ::   ln_rnf_ctl    !: remove runoff dilution on tracers
    REAL(wp), PUBLIC                                  ::   rn_sbc_time   !: Time scaling factor for SBC data (seconds in a day)
@@ -159,4 +161,5 @@
          &      ln_trc_ini(jptra)     ,                                                       &
          &      ln_trc_sbc(jptra)     , ln_trc_cbc(jptra)     , ln_trc_obc(jptra)     ,       &
+         &      ln_trc_ais(jptra)     ,                                                       &
          &      STAT = ierr(1)  )
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcais.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcais.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcais.F90	(revision 14055)
@@ -0,0 +1,281 @@
+MODULE trcais
+   !!======================================================================
+   !!                         ***  MODULE trcais  ***
+   !!  Module for passive tracers in Antarctic ice sheet
+   !!  delivered by iceberg and ice shelf freshwater fluxes
+   !!======================================================================
+   !! History :  1.0  ! 2020    (R. Person, O. Aumont, C. Ethe),
+   !!======================================================================
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP model
+   !!----------------------------------------------------------------------
+   !!   trc_ais       : external source of tracers from Antarctic ice sheet
+   !!----------------------------------------------------------------------
+   USE par_trc        !  passive tracers parameters
+   USE oce_trc        !  shared variables between ocean and passive tracers
+   USE trc            !  passive tracers common variables
+   USE iom            !  I/O manager
+   USE lib_mpp        !  MPP library
+   USE sbc_oce        !
+   USE isf_oce        ! ice shelf melting contribution
+   USE sbcrnf         ! iceberg freshwater flux
+   USE trcnam         ! Namelist read
+   USE prtctl         ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ais         ! called in trcstp.F90 or within TOP modules
+   PUBLIC   trc_ais_ini     ! called in trcini.F90
+
+   INTEGER  , SAVE, PUBLIC                              :: nb_trcais    ! number of tracers in AIS
+   REAL(wp) , SAVE, PUBLIC                              :: rn_icbdep    ! mean underwater depth of iceberg (in meters)
+   INTEGER  , SAVE, PUBLIC                              :: icblev       ! mean underwater depth of iceberg (in level depth)
+   INTEGER  , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)   :: n_trc_indais ! index of tracer with AIS freswater flux
+   REAL(wp) , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)   :: rf_trafac    ! multiplicative factor for AIS tracer values
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ais_ini
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ais_ini ***
+      !!
+      !! ** Purpose :   Initialization of passive tracers from the Antartic
+      !!                Ice Sheet delivered by iceberg and ice shelf
+      !!                freshwater flux
+      !!
+      !! ** Method  : - Read namtsd namelist
+      !!              
+      !!---------------------------------------------------------------------
+      INTEGER            :: jl, jn, jk                     ! dummy loop indices
+      INTEGER            :: ierr0, ierr1, ierr2, ierr3     ! temporary integers
+      INTEGER            :: ios                            ! Local integer output status for namelist read
+      REAL(wp)   , DIMENSION(jpmaxtrc) :: rn_trafac    ! multiplicative factor for tracer values
+      !!
+      NAMELIST/namtrc_ais/ nn_ais_tr, rn_trafac, rn_icbdep
+      !!----------------------------------------------------------------------
+      !
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_ais_ini : Antarctic ice sheet tracer initialization'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      ! 
+      IF (.NOT. ln_rnf_icb) THEN
+         CALL ctl_stop( 'trc_ais_ini: no iceberg freswater flux in runoff file' )   ;  RETURN
+      ENDIF
+      !
+      ! Compute the number of tracers to be initialised in iceberg and ice
+      ! shelf freshwater flux
+      ALLOCATE( n_trc_indais(jptra), STAT=ierr0 )
+      IF( ierr0 > 0 ) THEN
+         CALL ctl_stop( 'trc_ais_ini: unable to allocate n_trc_indais' )   ;  RETURN
+      ENDIF
+      nb_trcais       = 0
+      n_trc_indais(:) = 0
+      !
+      ! Read Antarctic Ice Sheet Namelist
+      READ  ( numnat_ref, namtrc_ais, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_ais in reference namelist' )
+      READ  ( numnat_cfg, namtrc_ais, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_ais in configuration namelist' )
+      IF(lwm) WRITE ( numont, namtrc_ais )
+      ! 
+      IF( lwp ) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) '   Namelist : namtrc_ais'
+         WRITE(numout,*) '   Antarctic Ice Sheet tracers option (nn_ais_tr) : ', nn_ais_tr
+      ENDIF
+      ! compose AIS data indexes
+      DO jn = 1, jptra
+         IF( ln_trc_ais(jn) ) THEN
+             nb_trcais       = nb_trcais + 1   ;   n_trc_indais(jn) = nb_trcais
+         ENDIF
+      END DO
+
+      ! Print summmary of Antarctic Ice Sheet tracers supply
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,'(a,i3)') '   Total tracers to be initialized with AIS freshwater fluxes:', nb_trcais
+      ENDIF
+      !
+      IF( nb_trcais > 0 ) THEN
+         ALLOCATE( rf_trafac(nb_trcais), STAT=ierr0 )
+         DO jn = 1, jptra
+            IF( ln_trc_ais(jn) ) THEN
+                jl = n_trc_indais(jn)
+                rf_trafac(jl) = rn_trafac(jn)
+                IF(lwp) WRITE(numout, 9001) jn, ctrcnm(jn), 'AIS', rn_trafac(jn), rf_trafac(jl)
+            ENDIF
+         END DO
+      ENDIF
+9001  FORMAT(2x,i5, 8x, a15, 3x, a3, 5x, e11.3, 5x, e11.3)
+
+      ! 
+      icblev = 1        !  compute last level where depth less than rn_icbdep (120 m)
+         DO jk = jpkm1, 1, -1
+            IF( gdept_1d(jk) > rn_icbdep )   icblev = jk - 1
+         END DO
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' Level corresponding to iceberg depth ',  icblev,' ', gdept_1d(icblev+1)
+      !
+   END SUBROUTINE trc_ais_ini
+
+   SUBROUTINE trc_ais(kt, Kmm, ptr, Krhs)
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_ais  ***
+      !!
+      !! ** Purpose :  Apply Antarctic Ice Sheet inputs to tracers
+      !!
+      !! ** Method  :  Read freswater flux from iceberg and ice shelf 
+      !!               and update data 
+      !!                
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER                                   , INTENT(in)           ::   kt ! ocean time-step index
+      INTEGER                                   , INTENT(in)           ::   Kmm, Krhs ! time level indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jptra,jpt), INTENT(inout)        ::   ptr ! passive tracers and RHS of tracer equation
+      !!
+      INTEGER  :: ji, jj, jk, jn, jl             ! Loop index
+      INTEGER  :: ikt, ikb  ! top and bottom level of the tbl
+      CHARACTER (len=22) :: charout
+      REAL(wp) :: zfact, zcalv, zfrac
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_ais')
+
+      IF( kt == nit000 .AND. lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_ais : passive tracers from Antarctic Ice Sheet'
+         WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+
+
+      ! 0. initialization
+      SELECT CASE ( nn_ais_tr )
+
+      CASE ( 0 ) ! No tracers in Antarctic Ice Sheet (null concentration in AIS)
+         !
+         ! Iceberg freshwater dilution for tracers with absent iceberg load
+         IF( ln_rnf_icb ) THEN
+            DO jn = 1, jptra
+               IF( ln_trc_ais(jn) ) THEN
+                  jl = n_trc_indais(jn)
+                  DO_2D( 1, 1, 1, 1 )
+                     zfact = 1. / e3t(ji,jj,1,Kmm)
+                     ptr(ji,jj,jk,jn,Krhs) = ptr(ji,jj,1,jn,Krhs) + fwficb(ji,jj) * r1_rho0 * ptr(ji,jj,1,jn,Kmm) * zfact
+                  END_2D
+               END IF
+            END DO   
+         END IF   
+         ! Ice shelf freshwater dilution for tracers with absent ice shelf load
+         IF( ln_isf ) THEN
+            DO jn = 1, jptra
+               IF( ln_trc_ais(jn) ) THEN
+                  jl = n_trc_indais(jn)
+                  DO_2D( 1, 1, 1, 1 )
+                     IF( ln_isfpar_mlt ) THEN
+                        zcalv = - fwfisf_par(ji,jj) * r1_rho0 / rhisf_tbl_par(ji,jj)
+                        ikt = misfkt_par(ji,jj)
+                        ikb = misfkb_par(ji,jj)
+                        zfrac = rfrac_tbl_par(ji,jj)
+                     END IF   
+                     IF( ln_isfcav_mlt ) THEN
+                        zcalv = - fwfisf_cav(ji,jj) * r1_rho0 / rhisf_tbl_cav(ji,jj)
+                        ikt = misfkt_cav(ji,jj)
+                        ikb = misfkb_cav(ji,jj)
+                        zfrac = rfrac_tbl_cav(ji,jj)
+                     END IF   
+                     ! level fully include in the ice shelf boundary layer
+                     DO jk = ikt, ikb - 1
+                        ptr(ji,jj,jk,jn,Krhs) = ptr(ji,jj,jk,jn,Krhs) + zcalv * ptr(ji,jj,jk,jn,Kmm)
+                     END DO
+                     ! level partially include in ice shelf boundary layer
+                     ptr(ji,jj,ikb,jn,Krhs) = ptr(ji,jj,ikb,jn,Krhs) +  zcalv * ptr(ji,jj,ikb,jn,Kmm) * zfrac 
+                  END_2D
+               ENDIF   
+            END DO
+         END IF
+         !
+      CASE ( 1 )  ! Specific treatment  with an imposed concentration in AIS
+         !
+         ! source of bgc tracers from iceberg in Southern Ocean
+         ! distributed along the water column until 120 m depth (Person et al., 2019)
+         IF( ln_rnf_icb ) THEN
+            DO jn = 1, jptra
+               IF( ln_trc_ais(jn) ) THEN
+                  jl = n_trc_indais(jn)
+                  DO_2D( 1, 1, 1, 1 )
+                     DO jk = 1, icblev
+                        zcalv  =  fwficb(ji,jj) * r1_rho0 
+                        ptr(ji,jj,jk,jn,Krhs) = ptr(ji,jj,jk,jn,Krhs) + rf_trafac(jl) * zcalv / gdepw(ji,jj,icblev+1,Kmm)
+                     END DO   
+                  END_2D
+                END IF  
+            END DO   
+         END IF   
+         ! source of bgc tracers from ice shelf in the Southern Ocean 
+         ! with tbl treated as in Mathiot et al. (2017)
+         IF( ln_isf ) THEN
+            DO jn = 1, jptra
+               IF( ln_trc_ais(jn) ) THEN
+                  jl = n_trc_indais(jn)
+                  DO_2D( 1, 1, 1, 1 )
+                     IF( ln_isfpar_mlt ) THEN
+                        zcalv = - fwfisf_par(ji,jj) * r1_rho0 / rhisf_tbl_par(ji,jj)
+                        ikt = misfkt_par(ji,jj)
+                        ikb = misfkb_par(ji,jj)
+                        zfrac = rfrac_tbl_par(ji,jj)
+                     END IF
+                     IF( ln_isfcav_mlt ) THEN
+                        zcalv = - fwfisf_cav(ji,jj) * r1_rho0 / rhisf_tbl_cav(ji,jj)
+                        ikt = misfkt_cav(ji,jj)
+                        ikb = misfkb_cav(ji,jj)
+                        zfrac = rfrac_tbl_cav(ji,jj)
+                     END IF
+                     ! level fully include in the ice shelf boundary layer
+                     DO jk = ikt, ikb - 1
+                        ptr(ji,jj,jk,jn,Krhs) = ptr(ji,jj,jk,jn,Krhs) + rf_trafac(jl) * zcalv
+                     END DO
+                     ! level partially include in ice shelf boundary layer
+                     ptr(ji,jj,ikb,jn,Krhs) = ptr(ji,jj,ikb,jn,Krhs) + rf_trafac(jl) * zcalv * zfrac
+                  END_2D
+               ENDIF
+            END DO
+         END IF
+      END SELECT
+      !
+
+      IF( ln_timing )   CALL timing_stop('trc_ais')
+      !
+      ! for debugging
+!      IF( sn_cfctl%l_prttrc ) THEN ! print mean trends (used for debugging)
+!         WRITE(charout, FMT="('ais ')")
+!         CALL prt_ctl_trc_info(charout)
+!         CALL prt_ctl_trc( tab4d=ptr(:,:,:,:,Krhs), mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+!      ENDIF
+      !
+   END SUBROUTINE trc_ais
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                              NO 3D passive tracer data
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ais_ini   ! Empty routine
+   END SUBROUTINE trc_ais_ini
+   SUBROUTINE trc_ais( kt, Kmm, Krhs )        ! Empty routine
+      INTEGER, INTENT(in) :: kt, Kmm, Krhs ! time level indices
+      WRITE(*,*) 'trc_ais: You should not have seen this print! error?', kt, Kmm, Krhs
+   END SUBROUTINE trc_ais
+#endif
+
+   !!======================================================================
+END MODULE trcais
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcini.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcini.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcini.F90	(revision 14055)
@@ -26,4 +26,5 @@
    USE trcice          ! tracers in sea ice
    USE trcbc           ! generalized Boundary Conditions
+   USE trcais          ! tracers from Antartic Ice Sheet
  
    IMPLICIT NONE
@@ -161,4 +162,5 @@
          ln_trc_cbc(jn) =       sn_tracer(jn)%llcbc
          ln_trc_obc(jn) =       sn_tracer(jn)%llobc
+         ln_trc_ais(jn) =       sn_tracer(jn)%llais
       END DO
       !
@@ -183,7 +185,7 @@
          WRITE(numout,*) 'trc_init_sms : Summary for selected passive tracers'
          WRITE(numout,*) '~~~~~~~~~~~~'
-         WRITE(numout,*) '    ID     NAME     INI  SBC  CBC  OBC'
+         WRITE(numout,*) '    ID     NAME     INI  SBC  CBC  OBC  AIS'
          DO jn = 1, jptra
-            WRITE(numout,9001) jn, TRIM(ctrcnm(jn)), ln_trc_ini(jn), ln_trc_sbc(jn),ln_trc_cbc(jn),ln_trc_obc(jn)
+            WRITE(numout,9001) jn, TRIM(ctrcnm(jn)), ln_trc_ini(jn),ln_trc_sbc(jn),ln_trc_cbc(jn),ln_trc_obc(jn),ln_trc_ais(jn)
          END DO
       ENDIF
@@ -192,6 +194,11 @@
          WRITE(numout,*) ' Applying tracer boundary conditions '
       ENDIF
+      !
+      IF( lwp .AND. ln_trcais ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' Applying tracer from Antarctic Ice Sheet '
+      ENDIF
      
-9001  FORMAT(3x,i3,1x,a10,3x,l2,3x,l2,3x,l2,3x,l2)
+9001  FORMAT(3x,i3,1x,a10,3x,l2,3x,l2,3x,l2,3x,l2,3x,l2)
       !
    END SUBROUTINE trc_ini_sms
@@ -243,4 +250,5 @@
       ENDIF
       !
+      IF( ln_trcais ) CALL trc_ais_ini   ! set tracers from Antarctic Ice Sheet
       !
       IF( ln_rsttr ) THEN              ! restart from a file
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcnam.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcnam.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcnam.F90	(revision 14055)
@@ -137,9 +137,10 @@
       !!
       NAMELIST/namtrc/jp_bgc, ln_pisces, ln_my_trc, ln_age, ln_cfc11, ln_cfc12, ln_sf6, ln_c14, &
-         &            sn_tracer, ln_trcdta, ln_trcbc, ln_trcdmp, ln_trcdmp_clo, jp_dia3d, jp_dia2d
+         &            sn_tracer, ln_trcdta, ln_trcbc, ln_trcdmp, ln_trcdmp_clo, jp_dia3d, jp_dia2d, &
+         &            ln_trcais
       !!---------------------------------------------------------------------
       ! Dummy settings to fill tracers data structure
-      !                  !   name   !   title   !   unit   !   init  !   sbc   !   cbc   !   obc  !
-      sn_tracer = PTRACER( 'NONAME' , 'NOTITLE' , 'NOUNIT' , .false. , .false. , .false. , .false.)
+      !                  !   name   !   title   !   unit   !   init  !   sbc   !   cbc   !   obc   !   ais   !
+      sn_tracer = PTRACER( 'NONAME' , 'NOTITLE' , 'NOUNIT' , .false. , .false. , .false. , .false. , .false. )
       !
       IF(lwp) WRITE(numout,*)
@@ -210,4 +211,5 @@
          WRITE(numout,*) '      Read inputs data from file (y/n)             ln_trcdta     = ', ln_trcdta
          WRITE(numout,*) '      Enable surface, lateral or open boundaries conditions (y/n)  ln_trcbc  = ', ln_trcbc
+         WRITE(numout,*) '      Enable Antarctic Ice Sheet nutrient supply   ln_trcais     = ', ln_trcais
          WRITE(numout,*) '      Damping of passive tracer (y/n)              ln_trcdmp     = ', ln_trcdmp
          WRITE(numout,*) '      Restoring of tracer on closed seas           ln_trcdmp_clo = ', ln_trcdmp_clo
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcrst.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcrst.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcrst.F90	(revision 14055)
@@ -53,4 +53,5 @@
       CHARACTER(LEN=50)   ::   clname   ! trc output restart file name
       CHARACTER(LEN=256)  ::   clpath   ! full path to ocean output restart file
+      CHARACTER(LEN=50)   ::   clpname  ! trc output restart file name including AGRIF
       !!----------------------------------------------------------------------
       !
@@ -92,5 +93,20 @@
          IF(lwp) WRITE(numout,*) &
              '             open trc restart.output NetCDF file: ',TRIM(clpath)//clname
-         CALL iom_open( TRIM(clpath)//TRIM(clname), numrtw, ldwrt = .TRUE. )
+         IF(.NOT.lwxios) THEN
+            CALL iom_open( TRIM(clpath)//TRIM(clname), numrtw, ldwrt = .TRUE. )
+         ELSE
+#if defined key_iomput
+            cw_toprst_cxt = "rstwt_"//TRIM(ADJUSTL(clkt))
+            IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+               clpname = clname
+            ELSE
+               clpname = TRIM(Agrif_CFixed())//"_"//clname
+            ENDIF
+            numrtw = iom_xios_setid(TRIM(clpath)//TRIM(clpname))
+            CALL iom_init( cw_toprst_cxt, kdid = numrtw, ld_closedef = .FALSE. )
+#else
+            CALL ctl_stop( 'Can not use XIOS in trc_rst_opn' )
+#endif
+         ENDIF
          lrst_trc = .TRUE.
       ENDIF
@@ -122,6 +138,5 @@
       END DO
       !
-      CALL iom_delay_rst( 'READ', 'TOP', numrtr )   ! read only TOP delayed global communication variables
-      
+      IF(.NOT.lrxios) CALL iom_delay_rst( 'READ', 'TOP', numrtr )   ! read only TOP delayed global communication variables
    END SUBROUTINE trc_rst_read
 
@@ -148,10 +163,16 @@
          CALL iom_rstput( kt, nitrst, numrtw, 'TRB'//ctrcnm(jn), tr(:,:,:,jn,Kbb) )
       END DO
-      !
-      CALL iom_delay_rst( 'WRITE', 'TOP', numrtw )   ! save only TOP delayed global communication variables
+
+      IF( .NOT. lwxios ) CALL iom_delay_rst( 'WRITE', 'TOP', numrtw )   ! save only TOP delayed global communication variables
     
       IF( kt == nitrst ) THEN
           CALL trc_rst_stat( Kmm, Krhs )             ! statistics
-          CALL iom_close( numrtw )     ! close the restart file (only at last time step)
+          IF(lwxios) THEN
+             CALL iom_context_finalize(      cw_toprst_cxt          )
+             iom_file(numrtw)%nfid       = 0
+             numrtw = 0
+          ELSE
+             CALL iom_close( numrtw )     ! close the restart file (only at last time step)
+          ENDIF
 #if ! defined key_trdmxl_trc
           lrst_trc = .FALSE.
@@ -197,4 +218,5 @@
       REAL(wp) ::  zrdttrc1, zkt, zndastp, zdayfrac, ksecs, ktime
       INTEGER  ::   ihour, iminute
+      CHARACTER(len=82) :: clpname
 
       ! Time domain : restart
@@ -208,5 +230,17 @@
 
          IF( ln_rsttr ) THEN
+            lxios_sini = .FALSE.
             CALL iom_open( TRIM(cn_trcrst_indir)//'/'//cn_trcrst_in, numrtr )
+            IF( lrxios) THEN
+                cr_toprst_cxt = 'top_rst'
+                IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS for TOP'
+!               IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+!                  clpname = cn_trcrst_in
+!               ELSE
+!                  clpname = TRIM(Agrif_CFixed())//"_"//cn_trcrst_in   
+!               ENDIF
+                CALL iom_init( cr_toprst_cxt, kdid = numrtr, ld_closedef = .TRUE. )
+            ENDIF
+
             CALL iom_get ( numrtr, 'kt', zkt )   ! last time-step of previous run
 
@@ -294,9 +328,9 @@
             IF(lwp) WRITE(numout,*) '~~~~~~~'
          ENDIF
-         CALL iom_rstput( kt, nitrst, numrtw, 'kt'     , REAL( kt    , wp) )   ! time-step
-         CALL iom_rstput( kt, nitrst, numrtw, 'ndastp' , REAL( ndastp, wp) )   ! date
-         CALL iom_rstput( kt, nitrst, numrtw, 'adatrj' , adatrj            )   ! number of elapsed days since
+         CALL iom_rstput( kt, nitrst, numrtw, 'kt'     , REAL( kt    , wp)   )   ! time-step
+         CALL iom_rstput( kt, nitrst, numrtw, 'ndastp' , REAL( ndastp, wp)   )   ! date
+         CALL iom_rstput( kt, nitrst, numrtw, 'adatrj' , adatrj              )   ! number of elapsed days since
          !                                                                     ! the begining of the run [s]
-         CALL iom_rstput( kt, nitrst, numrtw, 'ntime'  , REAL( nn_time0, wp)) ! time
+         CALL iom_rstput( kt, nitrst, numrtw, 'ntime'  , REAL( nn_time0, wp) ) ! time
       ENDIF
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcstp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcstp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/src/TOP/trcstp.F90	(revision 14055)
@@ -111,4 +111,5 @@
       IF( kt == nittrc000 ) THEN
          CALL iom_close( numrtr )                         ! close input tracer restart file
+         IF(lrxios) CALL iom_context_finalize(      cr_toprst_cxt          )
          IF(lwm) CALL FLUSH( numont )                     ! flush namelist output
       ENDIF
@@ -197,5 +198,4 @@
            &                              .AND. iom_varid( numrtr, 'ktdcy'    , ldstop = .FALSE. ) > 0  &
            &                              .AND. iom_varid( numrtr, 'nrdcy'    , ldstop = .FALSE. ) > 0  ) THEN
-
             CALL iom_get( numrtr, 'ktdcy', zkt )  
             rsecfst = INT( zkt ) * rn_Dt
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/axis_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/axis_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/axis_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/context_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/context_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/context_nemo.xml	(revision 14055)
@@ -0,0 +1,25 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/domain_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/domain_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/domain_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/field_def_nemo-oce.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/field_def_nemo-oce.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/file_def_nemo-oce.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/file_def_nemo-oce.xml	(revision 14055)
@@ -0,0 +1,104 @@
+<?xml version="1.0"?>
+
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1h" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."> <!-- 6h files -->     
+        <file id="file61" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"                           />
+          <field field_ref="toce"         name="votemper"     operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"                       />
+          <field field_ref="mldr10_1"                     />
+          <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="qsr_oce"      name="qsr_oce"  />
+          <field field_ref="qns_oce"      name="qns_oce"  />
+          <field field_ref="qt_oce"       name="qt_oce"   />
+          <field field_ref="saltflx"      name="sfx"      />
+          <field field_ref="taum"         name="taum"     />
+          <field field_ref="wspd"         name="windsp"   />
+          <field field_ref="precip"       name="precip"   />
+        </file>
+      </file_group>
+
+
+      <file_group id="12h" output_freq="12h"  output_level="10" enabled=".TRUE."> <!-- 1d files -->
+
+        <file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"                           />
+          <field field_ref="toce"         name="votemper"     operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"                       />
+          <field field_ref="mldr10_1"                     />
+          <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="qsr_oce"      name="qsr_oce"  />
+          <field field_ref="qns_oce"      name="qns_oce"  />
+          <field field_ref="qt_oce"       name="qt_oce"   />
+          <field field_ref="saltflx"      name="sfx"      />
+          <field field_ref="taum"         name="taum"     />
+          <field field_ref="wspd"         name="windsp"   />
+          <field field_ref="precip"       name="precip"   />
+        </file>
+
+       <file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="uo"       operation="instant" freq_op="1d" > @uoce_e3u / @e3u </field>
+          <field field_ref="utau"         name="tauuo"    />
+        </file>
+
+       <file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vo"       operation="instant" freq_op="1d" > @voce_e3v / @e3v </field>
+          <field field_ref="vtau"         name="tauvo"    />
+        </file>
+
+        <file id="file4" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="e3w" />
+          <field field_ref="avt"          name="difvho"   />
+        </file>
+
+      </file_group>
+
+      
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."> <!-- 1d files -->
+        <file id="file60" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"                           />
+          <field field_ref="toce"         name="votemper"     operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"                       />
+          <field field_ref="mldr10_1"                     />
+          <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="qsr_oce"      name="qsr_oce"  />
+          <field field_ref="qns_oce"      name="qns_oce"  />
+          <field field_ref="qt_oce"       name="qt_oce"   />
+          <field field_ref="saltflx"      name="sfx"      />
+          <field field_ref="taum"         name="taum"     />
+          <field field_ref="wspd"         name="windsp"   />
+          <field field_ref="precip"       name="precip"   />
+        </file>
+      </file_group>
+
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/> <!-- 5d files -->   
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/file_def_nemo-oce.xml_ori
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/file_def_nemo-oce.xml_ori	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/file_def_nemo-oce.xml_ori	(revision 14055)
@@ -0,0 +1,141 @@
+<?xml version="1.0"?>
+
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."> <!-- 1 time step files -->
+      </file_group>
+
+
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."> <!-- 1h files -->
+      </file_group>
+
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->  
+
+   
+      <file_group id="12h" output_freq="12h"  output_level="10" enabled=".TRUE."> <!-- 6h files -->  
+
+        <file id="file105" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"                           />
+          <field field_ref="toce"         name="votemper"     operation="instant" freq_op="12h" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="12h" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"                       />
+          <field field_ref="mldr10_1"                     />
+          <field field_ref="mlddzt"                     />
+          <field field_ref="mldr0_1"                     />
+          <field field_ref="tinv"                     />
+          <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="qsr_oce"      name="qsr_oce"  />
+          <field field_ref="qns_oce"      name="qns_oce"  />
+          <field field_ref="qt_oce"       name="qt_oce"   />
+          <field field_ref="saltflx"      name="sfx"      />
+          <field field_ref="taum"         name="taum"     />
+          <field field_ref="wspd"         name="windsp"   />
+          <field field_ref="precip"       name="precip"   />
+          <field field_ref="mf_Tp"         />
+          <field field_ref="mf_Sp"         />
+          <field field_ref="mf_epsT"         />
+          <field field_ref="mf_epsW"         />
+          <field field_ref="mf_edmf" />
+          <field field_ref="mf_FT" />
+          <field field_ref="mf_FS" />
+        </file>
+
+       <file id="file106" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="uo"       operation="instant" freq_op="12h" > @uoce_e3u / @e3u </field>
+          <field field_ref="utau"         name="tauuo"    />
+        </file>
+
+       <file id="file107" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vo"       operation="instant" freq_op="12h" > @voce_e3v / @e3v </field>
+          <field field_ref="vtau"         name="tauvo"    />
+        </file>
+
+        <file id="file108" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="e3w" />
+          <field field_ref="woce"         name="wo"       />
+          <field field_ref="avt"          name="difvho"   />
+          <field field_ref="mf_wp" />
+          <field field_ref="mf_wp0" />
+          <field field_ref="mf_app" />
+          <field field_ref="KZ_FT" />
+          <field field_ref="KZ_FS" />
+        </file>
+
+      </file_group>
+
+   
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."> <!-- 1d files -->
+
+        <file id="file5" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"                           />
+          <field field_ref="toce"         name="votemper"     operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"                       />
+          <field field_ref="mldr10_1"                     />
+          <field field_ref="mlddzt"                     />
+          <field field_ref="mldr0_1"                     />
+          <field field_ref="tinv"                     />
+          <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="qsr_oce"      name="qsr_oce"  />
+          <field field_ref="qns_oce"      name="qns_oce"  />
+          <field field_ref="qt_oce"       name="qt_oce"   />
+          <field field_ref="saltflx"      name="sfx"      />
+          <field field_ref="taum"         name="taum"     />
+          <field field_ref="wspd"         name="windsp"   />
+          <field field_ref="precip"       name="precip"   />
+          <field field_ref="mf_Tp"         />
+          <field field_ref="mf_Sp"         />
+          <field field_ref="mf_epsT"         />
+          <field field_ref="mf_epsW"         />
+          <field field_ref="mf_edmf" />
+          <field field_ref="mf_FT" />
+          <field field_ref="mf_FS" />
+        </file>
+
+       <file id="file6" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="uo"       operation="instant" freq_op="1d" > @uoce_e3u / @e3u </field>
+          <field field_ref="utau"         name="tauuo"    />
+        </file>
+
+       <file id="file7" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vo"       operation="instant" freq_op="1d" > @voce_e3v / @e3v </field>
+          <field field_ref="vtau"         name="tauvo"    />
+        </file>
+
+        <file id="file8" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="e3w" />
+          <field field_ref="woce"         name="wo"       />
+          <field field_ref="avt"          name="difvho"   />
+          <field field_ref="mf_wp" />
+          <field field_ref="mf_wp0" />
+          <field field_ref="mf_app" />
+          <field field_ref="KZ_FT" />
+          <field field_ref="KZ_FS" />
+        </file>
+
+      </file_group>
+
+      
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/> <!-- 5d files -->   
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/grid_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/grid_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/grid_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/iodef.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/iodef.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/iodef.xml	(revision 14055)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/namelist_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/namelist_cfg	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/namelist_cfg	(revision 14055)
@@ -0,0 +1,506 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE :   Reference namelist_ref                                !!
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  :  1 - Domain & run manager (namrun, namcfg, namdom, namtsd, namcrs, namc1d, namc1d_uvd)
+!! namelists    2 - Surface boundary (namsbc, namsbc_flx, namsbc_blk, namsbc_cpl,
+!!                                    namsbc_sas, namtra_qsr, namsbc_rnf,
+!!                                    namsbc_isf, namsbc_iscpl, namsbc_apr, 
+!!                                    namsbc_ssr, namsbc_wave, namberg)
+!!              3 - lateral boundary (namlbc, namagrif, nambdy, nambdy_tide)
+!!              4 - top/bot boundary (namdrg, namdrg_top, namdrg_bot, nambbc, nambbl)
+!!              5 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_eiv, namtra_dmp)
+!!              6 - dynamics         (namdyn_adv, namdyn_vor, namdyn_hpg, namdyn_spg, namdyn_ldf)
+!!              7 - Vertical physics (namzdf, namzdf_ric, namzdf_tke, namzdf_gls, namzdf_iwm)
+!!              8 - diagnostics      (namnc4, namtrd, namspr, namflo, namhsb)
+!!              9 - Obs & Assim      (namobs, nam_asminc)
+!!             10 - miscellaneous    (nammpp, namctl, namsto)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   C1D user defined namelist
+!-----------------------------------------------------------------------
+   rn_bathy    =  2380.   ! depth in meters
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      = "C1D_ASICS"!  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   17040   !  last  time step (std 5475)
+   nn_date0    = 20130115  !  date at nit_0000 (format yyyymmdd) used if ln_rstart=F or (ln_rstart=T and nn_rstctl=0 or 1)
+   nn_stock    =   17040   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   17040   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_Dt      =  360.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   
+   cn_dir      = './'      !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem      = 'init_ASICS'       ,         24.       ,'votemper',  .false.     , .true.,  'daily'  ,    ''            ,    ''    ,    ''
+   sn_sal      = 'init_ASICS'       ,         24.       ,'vosaline',  .false.     , .true.,  'daily'  ,    ''            ,    ''    ,    ''
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+   rn_lat1d    =      30   !  Column latitude
+   rn_lon1d    =      15   !  Column longitude
+   ln_c1d_locpt =  .true.  ! Localization of 1D config in a grid (T) or independant point (F)
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   !                       !  =T read U-V fields for:
+   ln_uvd_init   = .false.       !  ocean initialisation
+   ln_uvd_dyndmp = .false.       !  U-V restoring
+
+   cn_dir      = './'      !  root directory for the U-V data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_ucur     = 'ucurrent'              ,         -1.       ,'u_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Ume'   , ''
+   sn_vcur     = 'vcurrent'              ,         -1.       ,'v_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Vme'   , ''
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_flx      = .true.    !  flux formulation                          (T => fill namsbc_flx )
+      !              ! Type of coupling (Ocean/Ice/Atmosphere) :
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+   sn_utau     = 'forc_ASICS' ,        1         , 'TAUX2'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
+   sn_vtau     = 'forc_ASICS' ,        1         , 'TAUY2'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
+   sn_qtot     = 'forc_ASICS' ,        1         , 'FNET2'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
+   sn_qsr      = 'forc_ASICS' ,        1         , 'FSOL2'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
+   sn_emp      = 'forc_ASICS' ,        1         , 'EMP2'     , .false.      , .false., 'yearly'  , ''       , ''       , ''
+   !
+   cn_dir      = './'      !  root directory for the location of the flux files
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+   
+   cn_dir      = './'      !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+
+   sn_chl      ='chlorophyll',         -1.       , 'CHLA'    ,   .true.     , .true. , 'yearly'  ,        ''       ,    ''    , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =  0.   !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin  = .true.   !  non-linear  drag: Cd = Cd0 |U|
+   ln_drgimp   = .false.  !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_drg_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.         !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF = .true. !  No tracer advection
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   = .true.   !  No explicit diffusion
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true. !  energy    conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+    ln_dynspg_ts   = .false.   ! split-explicit free surface
+       ln_bt_fw      = .false.     ! Forward integration of barotropic Eqs.
+       ln_bt_av      = .true.     ! Time filtering of barotropic variables
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfmfc   = .true.       !  Mass Flux Convection
+   ln_zdfiwm   = .true.       ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_mfc     !   Mass Flux Convection
+!-----------------------------------------------------------------------
+   ln_edmfuv  = .false.        ! Activate on velocity fields (Not available yet)
+   rn_cemf    =  1.            ! entrain/detrain coef. (<0 => cte; >0 % depending on dW/dz
+   rn_cwmf    = -0.            ! entrain/detrain coef. (<0 => cte; >0 % depending on dW/dz
+   rn_cent    = 2.e-5          ! entrain of convective area
+   rn_cdet    = 3.e-5          ! detrain of convective area
+   rn_cap     = 0.9            ! Coef. for CAP estimation
+   App_max    = 0.1            ! Maximum convection area (% of the cell)
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+   nn_zpyc     = 1         !  pycnocline-intensified dissipation scales as N (=1) or N^2 (=2)
+   ln_mevar    = .true.    !  variable (T) or constant (F) mixing efficiency
+   ln_tsdiff   = .true.    !  account for differential T/S mixing (T) or not (F)
+
+   cn_dir      = './'      !  root directory for the iwm data location                                                                  
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_mpb      = 'forcing_iwm_ASICSstation' , -12.           , 'mixing_power_bot' , .false.  , .true. , 'yearly' , '' , ''  , ''
+   sn_mpp      = 'forcing_iwm_ASICSstation' , -12.           , 'mixing_power_pyc' , .false.  , .true. , 'yearly' , '' , ''  , ''
+   sn_mpc      = 'forcing_iwm_ASICSstation' , -12.           , 'mixing_power_cri' , .false.  , .true. , 'yearly' , '' , ''  , ''
+   sn_dsb      = 'forcing_iwm_ASICSstation' , -12.           , 'decay_scale_bot'  , .false.  , .true. , 'yearly' , '' , ''  , ''
+   sn_dsc      = 'forcing_iwm_ASICSstation' , -12.           , 'decay_scale_cri'  , .false.  , .true. , 'yearly' , '' , ''  , ''
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diadct    ! transports through some sections                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc    !   assimilation increments                              ('key_asminc')
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/namelist_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/namelist_ref	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/EXP00/namelist_ref	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_hgr.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_hgr.F90	(revision 14055)
@@ -0,0 +1,108 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                     ***  MODULE usrdef_hgr   ***
+   !!
+   !!                     ===  C1D_ASICS configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  4.0 ! 2016-03  (S. Flavoni) 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp, njmpp        ! ocean space and time domain
+   USE c1d      ,  ONLY: rn_lon1d, rn_lat1d ! ocean lon/lat define by namelist
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE usrdef_nam     !
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called in domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_hgr.F90 10072 2018-08-28 15:21:50Z nicolasmartin $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!
+      !!                Here C1D_ASICS configuration :
+      !!          Rectangular 3x3 domain 
+      !!          - Located at 10E-42N
+      !!          - a constant horizontal resolution  
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj               ! dummy loop indices
+      REAL(wp) ::   zlam1, zlam0, zcos_alpha, zim1 , zjm1 , ze1  , ze1deg, zf0   ! local scalars
+      REAL(wp) ::   zphi1, zphi0, zsin_alpha, zim05, zjm05, zbeta, znorme, zfact !   -      -
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : C1D configuration'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   uniform grid spacing WITH Coriolis force'
+      !
+      !                       !==  grid point position  ==!   (Special case of 1D config: all lon/lat are the same)
+      !                       ! longitude
+      plamt(:,:) = rn_lon1d
+      plamu(:,:) = rn_lon1d 
+      plamv(:,:) = rn_lon1d
+      plamf(:,:) = rn_lon1d
+      !                       ! latitude
+      pphit(:,:) = rn_lat1d
+      pphiu(:,:) = rn_lat1d
+      pphiv(:,:) = rn_lat1d
+      pphif(:,:) = rn_lat1d
+      !                       !== Horizontal scale factors ==! (in meters)
+      !                     
+      !                                         ! constant grid spacing
+      pe1t(:,:) = 100.  ;   pe2t(:,:) = 100.
+      pe1u(:,:) = 100.  ;   pe2u(:,:) = 100.
+      pe1v(:,:) = 100.  ;   pe2v(:,:) = 100.
+      pe1f(:,:) = 100.  ;   pe2f(:,:) = 100.
+      !
+      !                                         ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                              !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp                       !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp                       !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 0                 !  indicate to compute Coriolis parameter afterward
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_nam.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_nam.F90	(revision 14055)
@@ -0,0 +1,99 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                     ***  MODULE usrdef_nam   ***
+   !!
+   !!                     ===  C1D_ASICS configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp, njmpp             ! ocean space and time domain
+   USE dom_oce  , ONLY: ln_zco, ln_zps, ln_sco   ! flag of type of coordinate
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called in nemogcm.F90 module
+
+   !                              !!* namusr_def namelist *!!
+   LOGICAL, PUBLIC ::   ln_bench   ! =T benchmark test with gyre: the gridsize is constant (no need to adjust timestep or viscosity)
+   INTEGER, PUBLIC ::   nn_GYRE    ! 1/nn_GYRE = the resolution chosen in degrees and thus defining the horizontal domain size
+   REAL(wp), PUBLIC::   rn_bathy   ! Depth in meters for 1D configuration
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_nam.F90 12377 2020-02-12 14:39:06Z acc $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here C1D configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ rn_bathy
+      !!----------------------------------------------------------------------
+      !
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'C1D'               ! name & resolution (not used)
+      kk_cfg = 0
+
+      ! Global Domain size:  C1D domain is 3 x 3 grid-points x 75 or vertical levels
+      kpi = 3
+      kpj = 3
+      kpk = 75 
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio =  7                   ! C1D configuration : 3x3 basin with cyclic Est-West and Norht-South condition
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : C1 case'
+         WRITE(numout,*) '      type of vertical coordinate : '
+         WRITE(numout,*) '         z-coordinate flag                     ln_zco = ', ln_zco
+         WRITE(numout,*) '         z-partial-step coordinate flag        ln_zps = ', ln_zps
+         WRITE(numout,*) '         s-coordinate flag                     ln_sco = ', ln_sco
+         WRITE(numout,*) '      C1D domain = 3 x 3 x75 grid-points                '
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      C1D : closed basin                       jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_zgr.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/MY_SRC/usrdef_zgr.F90	(revision 14055)
@@ -0,0 +1,184 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                       ===  C1D_ASICS configuration  ===
+   !!
+   !! User defined : vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-06  (R. Bourdalle-Badie)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system
+   !!      zgr_z      : reference 1D z-coordinate 
+   !!      zgr_top_bot: ocean top and bottom level indices
+   !!      zgr_zco    : 3D verticl coordinate in pure z-coordinate case
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE depth_e3       ! depth <=> e3
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_zgr.F90 13295 2020-07-10 18:24:21Z acc $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   ji, jj, jk        ! dummy indices
+      INTEGER  ::   ik                ! local integers
+      REAL(wp) ::   zfact, z1_jpkm1   ! local scalar
+      REAL(wp) ::   ze3min            ! local scalar
+      REAL(wp) ::   zt, zw            ! local scalars
+      REAL(wp) ::   zsur, za0, za1, zkth, zacr        ! Values for the Madec & Imbard (1996) function
+      REAL(wp) ::   za2, zkth2, zacr2                 ! Values for optional double tanh function set from parameters
+      REAL(wp), DIMENSION(jpi,jpj) ::   zht, zhu, z2d ! 2D workspace
+
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : C1D configuration (zps-coordinate closed box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ld_zco    = .FALSE.         ! C1D case:  z-coordinate without ocean cavities
+      ld_zps    = .TRUE.
+      ld_sco    = .FALSE.
+      ld_isfcav = .FALSE.
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      ! Set parameters of z(k) function
+      ! -------------------------------
+      zsur =   -3958.95137127683
+      za0  =    103.953009600000
+      za1  =    2.41595126900000
+      zkth =    15.3510137000000
+      zacr =    7.00000000000000
+      za2  =    100.760928500000
+      zkth2=    48.0298937200000
+      zacr2=    13.0000000000000
+      !
+      IF(lwp) THEN            ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '     zgr_z75L   : Reference vertical z-coordinates '
+         WRITE(numout,*) '     ~~~~~~~'
+         WRITE(numout,*) '       C1D case : L75 function with the following coefficients :'
+         WRITE(numout,*) '                 zsur = ', zsur
+         WRITE(numout,*) '                 za0  = ', za0
+         WRITE(numout,*) '                 za1  = ', za1
+         WRITE(numout,*) '                 zkth = ', zkth
+         WRITE(numout,*) '                 zacr = ', zacr
+         WRITE(numout,*) '                 za2  = ', za2
+         WRITE(numout,*) '                 zkth2= ', zkth2
+         WRITE(numout,*) '                 zacr2= ', zacr2
+      ENDIF
+
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      zht(:,:) = rn_bathy
+      !
+      DO jk = 1, jpk          ! depth at T and W-points
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) = ( zsur + za0 * zw + za1 * zacr * LOG ( COSH( (zw-zkth ) / zacr  ) )    &
+                  &                    + za2 * zacr2* LOG ( COSH( (zw-zkth2) / zacr2 ) )  )
+         pdept_1d(jk) = ( zsur + za0 * zt + za1 * zacr * LOG ( COSH( (zt-zkth ) / zacr  ) )    &
+                  &                    + za2 * zacr2* LOG ( COSH( (zt-zkth2) / zacr2 ) )  )
+      END DO
+      !
+      !                       ! e3t and e3w from depth
+      CALL depth_to_e3( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d )
+      !
+      !                       ! recompute depths from SUM(e3)  <== needed
+      CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d )
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      k_top(:,:) = 1 
+      !                                   !* bottom ocean compute from the depth of grid-points
+      k_bot(:,:) = jpkm1
+      DO jk = jpkm1, 1, -1
+        ze3min = 0.1_wp * pe3t_1d (jk)
+         WHERE( zht(:,:) < pdepw_1d(jk) + ze3min )   k_bot(:,:) = jk-1
+      END DO
+      !
+      !                                !* vertical coordinate system
+      DO jk = 1, jpk                      ! initialization to the reference z-coordinate
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      ! bottom scale factors and depth at T- and W-points
+      DO_2D( 1, 1, 1, 1 )
+         ik = k_bot(ji,jj)
+         pdepw(ji,jj,ik+1) = MIN( zht(ji,jj) , pdepw_1d(ik+1) )
+         pe3t (ji,jj,ik  ) = pdepw(ji,jj,ik+1) - pdepw(ji,jj,ik)
+         pe3t (ji,jj,ik+1) = pe3t (ji,jj,ik  ) 
+         !
+         pdept(ji,jj,ik  ) = pdepw(ji,jj,ik  ) + pe3t (ji,jj,ik  ) * 0.5_wp
+         pdept(ji,jj,ik+1) = pdepw(ji,jj,ik+1) + pe3t (ji,jj,ik+1) * 0.5_wp
+         pe3w (ji,jj,ik+1) = pdept(ji,jj,ik+1) - pdept(ji,jj,ik)              ! = pe3t (ji,jj,ik  )
+      END_2D        
+      !                                   ! bottom scale factors and depth at  U-, V-, UW and VW-points
+      !                                   ! usually Computed as the minimum of neighbooring scale factors
+      pe3u (:,:,:) = pe3t(:,:,:)          ! HERE C1D configuration : 
+      pe3v (:,:,:) = pe3t(:,:,:)          !    e3 increases with k-index 
+      pe3f (:,:,:) = pe3t(:,:,:)          !    so e3 minimum of (i,i+1) points is (i) point
+      pe3uw(:,:,:) = pe3w(:,:,:)          !    in j-direction e3v=e3t and e3f=e3v
+      pe3vw(:,:,:) = pe3w(:,:,:)          !    ==>>  no need of lbc_lnk calls
+      !      
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/cpp_C1D_ASICS.fcm
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/cpp_C1D_ASICS.fcm	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/C1D_ASICS/cpp_C1D_ASICS.fcm	(revision 14055)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_c1d key_mpp_mpi key_iomput
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/CANAL/MY_SRC/domvvl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/CANAL/MY_SRC/domvvl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/CANAL/MY_SRC/domvvl.F90	(revision 14055)
@@ -282,22 +282,4 @@
       ENDIF
       !
-      IF(lwxios) THEN
-! define variables in restart file when writing with XIOS
-         CALL iom_set_rstw_var_active('e3t_b')
-         CALL iom_set_rstw_var_active('e3t_n')
-         !                                           ! ----------------------- !
-         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
-            !                                        ! ----------------------- !
-            CALL iom_set_rstw_var_active('tilde_e3t_b')
-            CALL iom_set_rstw_var_active('tilde_e3t_n')
-         END IF
-         !                                           ! -------------!    
-         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
-            !                                        ! ------------ !
-            CALL iom_set_rstw_var_active('hdiv_lf')
-         ENDIF
-         !
-      ENDIF
-      !
    END SUBROUTINE dom_vvl_zgr
 
@@ -803,5 +785,5 @@
          IF( ln_rstart ) THEN                   !* Read the restart file
             CALL rst_read_open                  !  open the restart file if necessary
-            CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm), ldxios = lrxios    )
+            CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm)    )
             !
             id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
@@ -816,6 +798,6 @@
             !
             IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb) )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm) )
                ! needed to restart if land processor not computed 
                IF(lwp) write(numout,*) 'dom_vvl_rst : e3t(:,:,:,Kbb) and e3t(:,:,:,Kmm) found in restart files'
@@ -831,5 +813,5 @@
                IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb) )
                e3t(:,:,:,Kmm) = e3t(:,:,:,Kbb)
                l_1st_euler = .true.
@@ -838,5 +820,5 @@
                IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm) )
                e3t(:,:,:,Kbb) = e3t(:,:,:,Kmm)
                l_1st_euler = .true.
@@ -863,6 +845,6 @@
                !                          ! ----------------------- !
                IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:) )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:) )
                ELSE                            ! one at least array is missing
                   tilde_e3t_b(:,:,:) = 0.0_wp
@@ -873,5 +855,5 @@
                   !                       ! ------------ !
                   IF( id5 > 0 ) THEN  ! required array exists
-                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:) )
                   ELSE                ! array is missing
                      hdiv_lf(:,:,:) = 0.0_wp
@@ -947,23 +929,21 @@
          !                                   ! ===================
          IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
          !                                           ! --------- !
          !                                           ! all cases !
          !                                           ! --------- !
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb) )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm) )
          !                                           ! ----------------------- !
          IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
             !                                        ! ----------------------- !
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:))
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:))
          END IF
          !                                           ! -------------!    
          IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
             !                                        ! ------------ !
-            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:))
          ENDIF
          !
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/CANAL/MY_SRC/trazdf.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/CANAL/MY_SRC/trazdf.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/CANAL/MY_SRC/trazdf.F90	(revision 14055)
@@ -54,5 +54,5 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts,jpt), INTENT(inout) :: pts                 ! active tracers and RHS of tracer equation
       !
-      INTEGER  ::   jk   ! Dummy loop indices
+      INTEGER  ::   ji, jj, jk   ! Dummy loop indices
       REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds   ! 3D workspace
       !!---------------------------------------------------------------------
@@ -61,7 +61,9 @@
       !
       IF( kt == nit000 )  THEN
-         IF(lwp)WRITE(numout,*)
-         IF(lwp)WRITE(numout,*) 'tra_zdf : implicit vertical mixing on T & S'
-         IF(lwp)WRITE(numout,*) '~~~~~~~ '
+         IF( ntile == 0 .OR. ntile == 1 )  THEN                   ! Do only on the first tile
+            IF(lwp)WRITE(numout,*)
+            IF(lwp)WRITE(numout,*) 'tra_zdf : implicit vertical mixing on T & S'
+            IF(lwp)WRITE(numout,*) '~~~~~~~ '
+         ENDIF
       ENDIF
       !
@@ -83,9 +85,13 @@
 
       IF( l_trdtra )   THEN                      ! save the vertical diffusive trends for further diagnostics
-         DO jk = 1, jpkm1
-            ztrdt(:,:,jk) = ( ( pts(:,:,jk,jp_tem,Kaa)*e3t(:,:,jk,Kaa) - pts(:,:,jk,jp_tem,Kbb)*e3t(:,:,jk,Kbb) ) &
-               &          / (e3t(:,:,jk,Kmm)*rDt) ) - ztrdt(:,:,jk)
-            ztrds(:,:,jk) = ( ( pts(:,:,jk,jp_sal,Kaa)*e3t(:,:,jk,Kaa) - pts(:,:,jk,jp_sal,Kbb)*e3t(:,:,jk,Kbb) ) &
-              &           / (e3t(:,:,jk,Kmm)*rDt) ) - ztrds(:,:,jk)
+         DO jk = 1, jpk
+            ztrdt(:,:,jk) = (   (  pts(:,:,jk,jp_tem,Kaa)*e3t(:,:,jk,Kaa)     &
+               &                 - pts(:,:,jk,jp_tem,Kbb)*e3t(:,:,jk,Kbb)  )  &
+               &              / (  e3t(:,:,jk,Kmm)*rDt  )   )                 &
+               &          - ztrdt(:,:,jk)
+            ztrds(:,:,jk) = (   (  pts(:,:,jk,jp_sal,Kaa)*e3t(:,:,jk,Kaa)     &
+               &                 - pts(:,:,jk,jp_sal,Kbb)*e3t(:,:,jk,Kbb)  )  &
+               &             / (   e3t(:,:,jk,Kmm)*rDt  )   )                 &
+               &          - ztrds(:,:,jk)
          END DO
 !!gm this should be moved in trdtra.F90 and done on all trends
@@ -135,5 +141,5 @@
       INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
       REAL(wp) ::  zrhs, zzwi, zzws ! local scalars
-      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zwi, zwt, zwd, zws
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk) ::  zwi, zwt, zwd, zws
       !!---------------------------------------------------------------------
       !
@@ -149,6 +155,12 @@
             !
             ! vertical mixing coef.: avt for temperature, avs for salinity and passive tracers
-            IF( cdtype == 'TRA' .AND. jn == jp_tem ) THEN   ;   zwt(:,:,2:jpk) = avt(:,:,2:jpk)
-            ELSE                                            ;   zwt(:,:,2:jpk) = avs(:,:,2:jpk)
+            IF( cdtype == 'TRA' .AND. jn == jp_tem ) THEN
+               DO_3D( 1, 1, 1, 1, 2, jpk )
+                  zwt(ji,jj,jk) = avt(ji,jj,jk)
+               END_3D
+            ELSE
+               DO_3D( 1, 1, 1, 1, 2, jpk )
+                  zwt(ji,jj,jk) = avs(ji,jj,jk)
+               END_3D
             ENDIF
             zwt(:,:,1) = 0._wp
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/axis_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/axis_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/context_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/context_nemo.xml	(revision 14055)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/domain_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/domain_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/field_def_nemo-oce.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/field_def_nemo-oce.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/file_def_nemo-oce.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/file_def_nemo-oce.xml	(revision 14055)
@@ -0,0 +1,58 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."> <!-- 1 time step files -->
+	<file id="file11" output_freq="1ts" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="empmr"        name="soemp"     />
+	  <field field_ref="berg_buoy_melt"  name="sobergbuoy"  />
+	  <field field_ref="berg_eros_melt"  name="sobergeros"  />
+	  <field field_ref="berg_conv_melt"  name="sobergconv"  />
+        </file>
+      </file_group>
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."> <!-- 1h files -->
+	<file id="file1" output_freq="1h" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="toce"         name="votemper"  />
+	  <field field_ref="soce"         name="vosaline"  />
+	  <field field_ref="ssh"          name="sossheig"  />
+	  <field field_ref="empmr"        name="soemp"     />
+	  <field field_ref="berg_buoy_melt"  name="sobergbuoy"  />
+	  <field field_ref="berg_eros_melt"  name="sobergeros"  />
+	  <field field_ref="berg_conv_melt"  name="sobergconv"  />
+        </file>
+	<file id="file2" output_freq="1h" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="vozocrtx"  />
+        </file>
+	<file id="file3" output_freq="1h" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vomecrty"  /> 
+        </file>
+      </file_group>
+
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->
+     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d files -->  
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/grid_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/grid_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/iodef.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/iodef.xml	(revision 14055)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/namelist_cfg	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/namelist_cfg	(revision 14055)
@@ -0,0 +1,484 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                         ISOMIP configuration                       !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "ICB" !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =     480   !  last  time step
+   nn_leapy    =       0   !  Leap year calendar (1) or not (0)
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =  99999999 !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =      48   !  frequency of write in the output file   (modulo referenced to nn_it000)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   ISOMIP user defined namelist  
+!-----------------------------------------------------------------------
+   ln_zps      = .false.   ! z-partial-step coordinate
+   ln_zco      = .true.    ! z-full-step coordinate
+   ln_sco      = .false.   ! s-coordinate
+   rn_dx       =   1000    !  zonal      grid-spacing (degrees)
+   rn_dy       =   1000    !  meridional grid-spacing (degrees)
+   rn_e3       =   10.     !  vertical resolution
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_Dt       =  180.     !  time step for the dynamics (and tracer if nn_acc=0)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+   ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&namisf       !  Top boundary layer (ISF)                               (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+   ln_icebergs = .true.       ! activate iceberg floats (force =F with "key_agrif")
+   !                          ! diagnostics:
+   ln_bergdia        = .true.        ! Calculate budgets
+   nn_verbose_level  = 0             ! Turn on more verbose output if level > 0
+   nn_verbose_write  = 15            ! Timesteps between verbose messages
+   nn_sample_rate    = 1             ! Timesteps between sampling for trajectory storage
+   !
+   !                          ! iceberg setting:
+   !                                 ! Initial mass required for an iceberg of each class
+   rn_initial_mass   = 8.8e7, 4.1e8, 3.3e9, 1.8e10, 3.8e10, 7.5e10, 1.2e11, 2.2e11, 3.9e11, 7.4e11
+   !                                 ! Proportion of calving mass to apportion to each class
+   rn_distribution   = 0.24, 0.12, 0.15, 0.18, 0.12, 0.07, 0.03, 0.03, 0.03, 0.02
+   !                                 ! Ratio between effective and real iceberg mass (non-dim)
+   !                                 ! i.e. number of icebergs represented at a point
+   rn_mass_scaling   = 2000., 200., 50., 20., 10., 5., 2., 1., 1., 1.
+                                     ! thickness of newly calved bergs (m)
+   rn_initial_thickness     = 40., 67., 133., 175., 250., 250., 250., 250., 250., 100.
+   !
+   rn_rho_bergs            = 1025.    ! Density of icebergs
+   rn_LoW_ratio            = 1.5     ! Initial ratio L/W for newly calved icebergs
+   ln_operator_splitting   = .true.  ! Use first order operator splitting for thermodynamics
+   rn_bits_erosion_fraction = 0.     ! Fraction of erosion melt flux to divert to bergy bits
+   rn_sicn_shift           = 0.      ! Shift of sea-ice concn in erosion flux (0<sicn_shift<1)
+   ln_passive_mode         = .false. ! iceberg - ocean decoupling
+   nn_test_icebergs        =  10     ! Create test icebergs of this class (-1 = no)
+   !                                 ! Put a test iceberg at each gridpoint in box (lon1,lon2,lat1,lat2)
+   rn_test_box             = 1500.0,  39500.0, 9500.0, 10500.0
+   !
+   ln_M2016                = .false. ! use Merino et al. (2016) modification (use of 3d ocean data instead of only sea surface data)
+      ln_icb_grd           = .false.
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF     = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_OFF =F)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF = .true. !  No tracer advection
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_OFF   = .true.    !  No explicit diffusion
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true.  !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  energy conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.    !  s-coordinate adapted for isf (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+   rn_evd      =  0.1         ! mixing coefficient [m2/s]
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-3      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst)
+   rn_avt0     =   5.e-5      !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst)
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namptr        !   Poleward Transport Diagnostic                        (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     ("key_float")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents              ("key_diaharm")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdct        ! transports through some sections                       ("key_diadct")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diatmb    !  Top Middle Bottom Output                              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc    !   assimilation increments                              ('key_asminc')
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   sn_cfctl%l_oceout  = .TRUE.
+   ln_timing   = .true.           !  timing by routine write out in timing.output file
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/namelist_ref	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/namelist_ref	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/run_job.sh
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/run_job.sh	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/EXPREF/run_job.sh	(revision 14055)
@@ -0,0 +1,59 @@
+#!/bin/bash 
+#OAR -n nemo_sette
+#OAR -l core=2,walltime=00:05:00
+#OAR -O nemo_sette.o%jobid%
+#OAR -E nemo_sette.e%jobid%
+#OAR --project tipaccs
+
+. ~/bin/load_intelmodule.bash
+
+  export PBS_O_WORKDIR=$(readlink -f $PBS_O_WORKDIR)
+  export OMP_NUM_THREADS=1
+  cd $PBS_O_WORKDIR
+  export XIO_HOME=$xios_path
+#
+  echo " ";
+  export OMP_NUM_THREADS=1
+  O_PER_NODE=2
+  X_PER_NODE=2
+  OCORES=2
+  XCORES=0
+  if [ $OCORES -le 32 ] ; then O_PER_NODE=$OCORES; fi
+  export SETTE_DIR=/bettik/mathiotp/NEMO/NEMO_dev/branches/2020/tickets_icb_1900/sette
+
+  export EXE_DIR=/bettik/mathiotp/NEMO/NEMO_dev/branches/2020/tickets_icb_1900/tests/ICB/EXP00/
+  ulimit -c unlimited
+  ulimit -s unlimited
+#
+# end of set up
+###############################################################
+#
+# change to the working directory 
+#
+  cd $EXE_DIR
+  echo Directory is `pwd`
+  
+  if [ $XCORES -gt 0 ]; then
+#
+#  Run MPMD case
+#
+     #XIOS will run on a separate node so will run in parallel queue
+     if [ ! -f ./xios_server.exe ] && [ -f ${XIO_HOME}/bin/xios_server.exe ]; then
+        cp ${XIO_HOME}/bin/xios_server.exe .
+     fi
+     if [ ! -f ./xios_server.exe ]; then
+        echo "./xios_server.exe not found"
+        echo "run aborted"
+        exit
+     fi
+       echo time aprun -b -n $XCORES -N $X_PER_NODE ./xios_server.exe : -n $OCORES -N $O_PER_NODE ./nemo
+            time aprun -b -n $XCORES -N $X_PER_NODE ./xios_server.exe : -n $OCORES -N $O_PER_NODE ./nemo
+#
+  else
+#
+# Run SPMD case
+#
+    echo time mpirun -n $OCORES ./nemo
+         time mpirun -n $OCORES ./nemo
+  fi
+#
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/step.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/step.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/step.F90	(revision 14055)
@@ -0,0 +1,175 @@
+MODULE step
+   !!======================================================================
+   !!                       ***  MODULE step  ***
+   !! Time-stepping   : manager of the ocean, tracer and ice time stepping
+   !!======================================================================
+   !! History :  OPA  !  1991-03  (G. Madec)  Original code
+   !!             -   !  1991-11  (G. Madec)
+   !!             -   !  1992-06  (M. Imbard)  add a first output record
+   !!             -   !  1996-04  (G. Madec)  introduction of dynspg
+   !!             -   !  1996-04  (M.A. Foujols)  introduction of passive tracer
+   !!            8.0  !  1997-06  (G. Madec)  new architecture of call
+   !!            8.2  !  1997-06  (G. Madec, M. Imbard, G. Roullet)  free surface
+   !!             -   !  1999-02  (G. Madec, N. Grima)  hpg implicit
+   !!             -   !  2000-07  (J-M Molines, M. Imbard)  Open Bondary Conditions
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  free form, suppress macro-tasking
+   !!             -   !  2004-08  (C. Talandier) New trends organization
+   !!             -   !  2005-01  (C. Ethe) Add the KPP closure scheme
+   !!             -   !  2005-11  (G. Madec)  Reorganisation of tra and dyn calls
+   !!             -   !  2006-01  (L. Debreu, C. Mazauric)  Agrif implementation
+   !!             -   !  2006-07  (S. Masson)  restart using iom
+   !!            3.2  !  2009-02  (G. Madec, R. Benshila)  reintroduicing z*-coordinate
+   !!             -   !  2009-06  (S. Masson, G. Madec)  TKE restart compatible with key_cpl
+   !!            3.3  !  2010-05  (K. Mogensen, A. Weaver, M. Martin, D. Lea) Assimilation interface
+   !!             -   !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase + merge TRC-TRA
+   !!            3.4  !  2011-04  (G. Madec, C. Ethe) Merge of dtatem and dtasal
+   !!            3.6  !  2012-07  (J. Simeon, G. Madec. C. Ethe)  Online coarsening of outputs
+   !!            3.6  !  2014-04  (F. Roquet, G. Madec) New equations of state
+   !!            3.6  !  2014-10  (E. Clementi, P. Oddo) Add Qiao vertical mixing in case of waves
+   !!            3.7  !  2014-10  (G. Madec)  LDF simplication 
+   !!             -   !  2014-12  (G. Madec) remove KPP scheme
+   !!             -   !  2015-11  (J. Chanut) free surface simplification (remove filtered free surface)
+   !!            4.0  !  2017-05  (G. Madec)  introduction of the vertical physics manager (zdfphy)
+   !!            4.1  !  2019-08  (A. Coward, D. Storkey) rewrite in preparation for new timestepping scheme
+   !!----------------------------------------------------------------------
+#if defined key_qco
+   !!----------------------------------------------------------------------
+   !!   'key_qco'      EMPTY MODULE      Quasi-Eulerian vertical coordonate
+   !!----------------------------------------------------------------------
+#else
+   !!----------------------------------------------------------------------
+   !!   stp             : OPA system time-stepping
+   !!----------------------------------------------------------------------
+   USE step_oce         ! time stepping definition modules
+   !
+   USE iom              ! xIOs server
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   stp   ! called by nemogcm.F90
+
+   !!----------------------------------------------------------------------
+   !! time level indices
+   !!----------------------------------------------------------------------
+   INTEGER, PUBLIC :: Nbb, Nnn, Naa, Nrhs          !! used by nemo_init
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: step.F90 13237 2020-07-03 09:12:53Z smasson $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if defined key_agrif
+   RECURSIVE SUBROUTINE stp( )
+      INTEGER             ::   kstp   ! ocean time-step index
+#else
+   SUBROUTINE stp( kstp )
+      INTEGER, INTENT(in) ::   kstp   ! ocean time-step index
+#endif
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE stp  ***
+      !!
+      !! ** Purpose : - Time stepping of OPA  (momentum and active tracer eqs.)
+      !!              - Time stepping of SI3 (dynamic and thermodynamic eqs.)
+      !!              - Time stepping of TRC  (passive tracer eqs.)
+      !!
+      !! ** Method  : -1- Update forcings and data
+      !!              -2- Update ocean physics
+      !!              -3- Compute the t and s trends
+      !!              -4- Update t and s
+      !!              -5- Compute the momentum trends
+      !!              -6- Update the horizontal velocity
+      !!              -7- Compute the diagnostics variables (rd,N2, hdiv,w)
+      !!              -8- Outputs and diagnostics
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk   ! dummy loop indice
+!!gm kcall can be removed, I guess
+      INTEGER ::   kcall        ! optional integer argument (dom_vvl_sf_nxt)
+      !! ---------------------------------------------------------------------
+#if defined key_agrif
+      IF( nstop > 0 ) RETURN   ! avoid to go further if an error was detected during previous time step (child grid)
+      kstp = nit000 + Agrif_Nb_Step()
+      Kbb_a = Nbb; Kmm_a = Nnn; Krhs_a = Nrhs   ! agrif_oce module copies of time level indices
+      IF( lk_agrif_debug ) THEN
+         IF( Agrif_Root() .and. lwp)   WRITE(*,*) '---'
+         IF(lwp)   WRITE(*,*) 'Grid Number', Agrif_Fixed(),' time step ', kstp, 'int tstep', Agrif_NbStepint()
+      ENDIF
+      IF( kstp == nit000 + 1 )   lk_agrif_fstep = .FALSE.
+# if defined key_iomput
+      IF( Agrif_Nbstepint() == 0 )   CALL iom_swap( cxios_context )
+# endif
+#endif
+      !
+      IF( ln_timing )   CALL timing_start('stp')
+      !
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! model timestep
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !
+      IF( l_1st_euler ) THEN  
+         ! start or restart with Euler 1st time-step
+         rDt =  rn_Dt   
+         r1_Dt = 1._wp / rDt
+      ENDIF
+      !
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! update I/O and calendar 
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( kstp == nit000 ) THEN                       ! initialize IOM context (must be done after nemo_init for AGRIF+XIOS+OASIS)
+                             CALL iom_init( cxios_context, ld_closedef=.FALSE. )   ! for model grid (including possible AGRIF zoom)
+         IF( lk_diamlr   )   CALL dia_mlr_iom_init    ! with additional setup for multiple-linear-regression analysis
+                             CALL iom_init_closedef
+         IF( ln_crs      )   CALL iom_init( TRIM(cxios_context)//"_crs" )  ! for coarse grid
+      ENDIF
+      IF( kstp /= nit000 )   CALL day( kstp )         ! Calendar (day was already called at nit000 in day_init)
+                             CALL iom_setkt( kstp - nit000 + 1,      cxios_context          )   ! tell IOM we are at time step kstp
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Update external forcing (tides, open boundaries, ice shelf interaction and surface boundary condition (including sea-ice)
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         CALL sbc     ( kstp, Nbb, Nnn )              ! Sea Boundary Condition (including sea-ice)
+
+                         CALL dia_wri   ( kstp,      Nnn )      ! ocean model: outputs
+
+!!gm : This does not only concern the dynamics ==>>> add a new title
+!!gm2: why ouput restart before AGRIF update?
+!!
+!!jc: That would be better, but see comment above
+!!
+      IF( lrst_oce   )   CALL rst_write    ( kstp, Nbb, Nnn )   ! write output ocean restart file
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! File manipulation at the end of the first time step
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
+      IF( kstp == nit000 ) THEN                          ! 1st time step only
+                                        CALL iom_close( numror )   ! close input  ocean restart file
+         IF(lwm)                        CALL FLUSH    ( numond )   ! flush output namelist oce
+         IF(lwm .AND. numoni /= -1 )    CALL FLUSH    ( numoni )   ! flush output namelist ice (if exist)
+      ENDIF
+      !
+#if defined key_iomput
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Finalize contextes if end of simulation or error detected
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
+      IF( kstp == nitend .OR. nstop > 0 ) THEN 
+                      CALL iom_context_finalize(      cxios_context          ) ! needed for XIOS+AGRIF
+         IF( lrxios ) CALL iom_context_finalize(      crxios_context         )
+         IF( ln_crs ) CALL iom_context_finalize( trim(cxios_context)//"_crs" ) ! 
+      ENDIF
+#endif
+      !
+      IF( l_1st_euler ) THEN         ! recover Leap-frog timestep
+         rDt = 2._wp * rn_Dt   
+         r1_Dt = 1._wp / rDt
+         l_1st_euler = .FALSE.      
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('stp')
+      !
+   END SUBROUTINE stp
+   !
+#endif
+   !!======================================================================
+END MODULE step
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_hgr.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_hgr.F90	(revision 14055)
@@ -0,0 +1,122 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE usrdef_hgr   ***
+   !!
+   !!                  ===  LOCK_EXCHANGE configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)   Original code
+   !!                  ! 2017-02  (P. Mathiot, S. Flavoni) Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for ISOMIP configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce  ,  ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_hgr.F90 12740 2020-04-12 09:03:06Z smasson $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                ISOMIP configuration
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zfact, zlam0, zphi0, zti, zui, zvi, zfi, ztj, zuj, zvj, zfj      ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'usr_def_hgr : ISOMIP configuration'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*)
+         WRITE(numout,*) '   ===>>  geographical mesh on the sphere with regular grid-spacing'
+         WRITE(numout,*) '          given by rn_e1deg and rn_e2deg'
+      ENDIF
+      !
+      zlam0 = 0.0
+      zphi0 = 0.0
+      DO_2D (1,1,1,1)
+         zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+         zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+         
+         plamt(ji,jj) = zlam0 + rn_dx * zti
+         plamu(ji,jj) = zlam0 + rn_dx * zui
+         plamv(ji,jj) = plamt(ji,jj) 
+         plamf(ji,jj) = plamu(ji,jj) 
+         
+         pphit(ji,jj) = zphi0 + rn_dy * ztj
+         pphiv(ji,jj) = zphi0 + rn_dy * zvj
+         pphiu(ji,jj) = pphit(ji,jj) 
+         pphif(ji,jj) = pphiv(ji,jj) 
+      END_2D
+      !
+      !                       !==  Horizontal scale factors  ==!   (in meters)
+      DO_2D (1,1,1,1)
+         !                       ! e1   (zonal)
+         pe1t(ji,jj) = rn_dx
+         pe1u(ji,jj) = rn_dx
+         pe1v(ji,jj) = rn_dx
+         pe1f(ji,jj) = rn_dx
+         !                       ! e2   (meridional)
+         pe2t(ji,jj) = rn_dy
+         pe2u(ji,jj) = rn_dy
+         pe2v(ji,jj) = rn_dy
+         pe2f(ji,jj) = rn_dy
+      END_2D
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v    = 0               !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       ! Coriolis parameter set to 0
+      pff_f(:,:) = 0._wp            ! CAUTION: set to zero to avoid error with some compilers that
+      pff_t(:,:) = 0._wp            !             require an initialization of INTENT(out) arguments
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_istate.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_istate.F90	(revision 14055)
@@ -0,0 +1,73 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                  ===  ISOMIP configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-11 (S. Flavoni)             Original code
+   !!                 ! 2017-02 (P. Mathiot, S. Flavoni) Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_istate.F90 10074 2018-08-28 16:15:49Z nicolasmartin $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here ISOMIP configuration 
+      !!
+      !! ** Method  : - set temperature field
+      !!              - set salinity    field
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER  ::   jk     ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : ISOMIP configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   Ocean at rest, with a constant salinity and temperature.      '
+      pu  (:,:,:) = 1._wp * umask(:,:,:)       ! ocean at rest
+      pv  (:,:,:) = 0._wp * vmask(:,:,:) 
+      pu  (:,:,3:jpkm1) = 0._wp * umask(:,:,3:jpkm1)        ! ocean at rest
+      pv  (:,:,3:jpkm1) = 1._wp * vmask(:,:,3:jpkm1)
+      pssh(:,:)   = 0._wp
+      !
+      !                          ! T & S profiles
+      pts(:,:,:,jp_tem) = 2  * ptmask(:,:,:)          ! ISOMIP configuration : start from constant T+S fields
+      pts(:,:,:,jp_sal) = 34 * ptmask(:,:,:)
+
+      pts(:,:,3:jpkm1,jp_tem) = 1  * ptmask(:,:,3:jpkm1)          ! ISOMIP configuration : start from constant T+S fields
+      !   
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_nam.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_nam.F90	(revision 14055)
@@ -0,0 +1,108 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                     ===  ISOMIP configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)   Original code
+   !!                 ! 2017-02  (P. Mathiot, S. Flavoni) Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE dom_oce  , ONLY: ln_zco, ln_zps, ln_sco   ! flag of type of coordinate
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                                         !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx, rn_dy         !: horizontal resolution   [degrees]
+   REAL(wp), PUBLIC ::   rn_e3                !: vertical   resolution         [m]
+   
+   REAL(wp), PARAMETER, PUBLIC ::   rbathy = 100._wp   !: depth of the seafloor   [m]
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_nam.F90 12377 2020-02-12 14:39:06Z acc $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here ISOMIP configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ ln_zco, ln_zps, ln_sco, rn_dx, rn_dy, rn_e3
+      !!----------------------------------------------------------------------
+      !
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'ISOMIP'           ! name & resolution (not used)
+      kk_cfg = INT( rn_e3 )
+      !
+      ! Global Domain size:  ICB domain is  15° x 10° x 900 m
+      kpi = 40 + 2     ! add 2 for t-point in the east  & west  coasts
+      kpj = 40 + 2     !     -        -           north & south   -
+      kpk = INT( rbathy / rn_e3    ) + 1     ! add 1 for t-point in the seafloor
+      !
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! ICB configuration : box
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : ISOMIP test case'
+         WRITE(numout,*) '      type of vertical coordinate : '
+         WRITE(numout,*) '         z-coordinate flag                     ln_zco   = ', ln_zco
+         WRITE(numout,*) '         z-partial-step coordinate flag        ln_zps   = ', ln_zps
+         WRITE(numout,*) '         s-coordinate flag                     ln_sco   = ', ln_sco
+         WRITE(numout,*) '      resolution'
+         WRITE(numout,*) '         zonal      resolution                 rn_dx    = ', rn_dx   , ' meters '
+         WRITE(numout,*) '         meridional resolution                 rn_dy    = ', rn_dy   , ' meters '
+         WRITE(numout,*) '         vertical   resolution                 rn_e3    = ', rn_e3   , ' meters'
+         WRITE(numout,*) '      ICB domain = 15° x 10° x 900 m'
+         WRITE(numout,*) '         resulting global domain size :        jpiglo   = ', kpi
+         WRITE(numout,*) '                                               jpjglo   = ', kpj
+         WRITE(numout,*) '                                               jpkglo   = ', kpk
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      ICB : closed basin                    jperio   = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_sbc.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_sbc.F90	(revision 14055)
@@ -0,0 +1,91 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                     ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                  ===  ISOMIP configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)   user defined interface
+   !!                  ! 2017-02  (P. Mathiot, S. Flavoni) adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in ISOMIP case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_sbc.F90 12377 2020-02-12 14:39:06Z acc $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt, Kbb )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for ISOMIP case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      INTEGER, INTENT(in) ::   Kbb  ! ocean time index
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : ISOMIP case: NO surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   utau = vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+      ENDIF
+      !
+      utau(:,:) = 0._wp
+      vtau(:,:) = 0._wp
+      taum(:,:) = 0._wp
+      wndm(:,:) = 0._wp
+      !
+      emp (:,:) = 0._wp
+      sfx (:,:) = 0._wp
+      qns (:,:) = 0._wp
+      qsr (:,:) = 0._wp
+      !         
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phi    ! ice thickness
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_zgr.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/MY_SRC/usrdef_zgr.F90	(revision 14055)
@@ -0,0 +1,116 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===      ICE_AGRIF case     ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_zgr.F90 12597 2020-03-25 08:57:21Z smasson $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   jk, k_dz  ! dummy indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : ICE_AGRIF configuration '
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   (slab ocean - advection of an ice patch in a biperiodic square box domain)'
+      !
+      !
+      ! type of vertical coordinate  ==>>>   here ICE_AGRIF : slab ocean always
+      ! ---------------------------
+      ld_zco    = .TRUE.       ! z-full-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .FALSE.      ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! 
+      k_dz = 10
+      pdepw_1d(1) = 0.0
+      pdept_1d(1) = k_dz / 2.0
+      pe3w_1d = k_dz
+      pe3t_1d = k_dz
+      !
+      DO jk = 2, jpk
+         pdepw_1d(jk) = pdepw_1d(jk-1) +   k_dz
+         pdept_1d(jk) = pdept_1d(jk-1) +   k_dz
+      END DO
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      k_top(:,:) = 1
+      !
+      !                       !==  z-coordinate  ==!   (step-like topography)
+      !                                !* bottom ocean compute from the depth of grid-points
+      jpkm1 = jpk-1
+      k_bot(:,:) = 10         ! here use k_top as a land mask
+      WHERE (( glamt < 10000 .OR. glamt > 30000 ))
+         k_bot(:,:) = 4
+      END WHERE
+      !                                !* horizontally uniform coordinate (reference z-co everywhere)
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/README
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/README	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/README	(revision 14055)
@@ -0,0 +1,38 @@
+ICB 
+---
+
+ICB is a very idealized configuration used to test and debug the icb module.
+The configuration is box with a shallow shelf (40m) on the east and west part of the domain with a deep central trough (> 100m).
+ICB are generating using the test capability of the icb model along a E-W line (this can easily be tuned).
+
+In this configuration, ONLY the ICB module is activated. It means that:
+- SI3 is OFF
+- NO atmospheric fluxes. See usr routine in MY_SRC.
+- NO time variation of ocean properties. T, S, U, V, ssh (...) are intialized and never changed in time. This is achieved by simplifying the step.F90 routine in MY_SRC.
+
+Resolution and Initial condition are:
+- Homogeneous S (34)
+- Spatially constant T     set to 2     over the first 2 levels and 1     below
+- Spatially constant (U,V) set to (1,0) over the first 2 levels and (0,1) below
+- e3 is set to 10m
+- iceberg thicness is set to 100 in the class tested (10 level affected).
+- iceberg density is set to 1026 as the ocean reference density => icb tikness = icb draft (easier to evaluate the output)
+
+Results expected are:
+- ln_M2016 = F => icb moving along the W direction only and pilling up on the W side of the domain.
+- ln_M2016 = T => icb on shallow bank move at 45 degrees (NW) and 76 degrees (NNNNW) in the deeper through. 
+- ln_M2016 = T and ln_icb_grd = T => as before but now icb cannot move onto the shallow bank on the W and migrate northward along the shelf break. Some get stuck at specific point because of the grounding law (they always get back to there intial position at every time step).
+
+This set up allow us to easily test various option of the ICB code as:
+- ln_M2016   (use properties in depth to compute dyn and thd)
+- ln_icb_grd (use icb bottom level of the icb (tail) to ground the icb or not)
+
+It can also help us to:
+- reproduce bugs (interpolation issue for example)
+- develop and test new functionalities (new grounding scheme for exemple)
+- evaluate ICB performance alone
+
+The side effect of the implementation is that:
+- the run.stat (if produced) is meaningless as NEMO tracer and dynamics are not computed
+
+
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/cpp_ICB.fcm
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/cpp_ICB.fcm	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICB/cpp_ICB.fcm	(revision 14055)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_iomput key_mpp_mpi 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_ADV2D/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_ADV2D/MY_SRC/usrdef_sbc.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_ADV2D/MY_SRC/usrdef_sbc.F90	(revision 14055)
@@ -18,5 +18,5 @@
    USE sbc_ice         ! Surface boundary condition: ice fields
    USE phycst          ! physical constants
-   USE ice, ONLY       : at_i_b, a_i_b
+   USE ice, ONLY       : jpl, at_i_b, a_i_b
    USE icethd_dh       ! for CALL ice_thd_snwblow
    !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/README
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/README	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/README	(revision 14055)
@@ -0,0 +1,54 @@
+-------
+purpose
+-------
+This demonstration case allows for examining the sea ice rheology under idealised
+forcing.  The set-up follows the paper "Stress and deformation characteristics of sea
+ice in a high-resolution, anisotropic sea ice model" by Heorton et al, Phil. Trans,
+R. Soc. 2018.
+
+-----------
+Experiments
+-----------
+A range of experiments can be configured:
+
+- The suggested experiment is to examine the different shear patterns formed
+  by different rheologies. The default set-up reproduces the leftmost panels
+  of figure 3a (ln_rhg_EAP true in namelist_ice_cfg) and 3b (ln_rhg_EVP true in
+  namelist_ice_cfg). Increase the last time step in namelist_cfg appropriately
+  to generate the other panels.
+
+- The resolution of the box can be changed analogous to figure 2 of the paper
+  (change rn_dx and rn_dy in namelist_cfg, default is 2000m)
+
+- The ratio of the windstress component can be changed to cause different modes 
+  of failure (Rwind in usrdef_sbc.F90, default is -0.8) 
+
+It takes about 10 minutes to run a simulation on 16 processors
+
+----------
+How to run
+----------
+
+a) Compile and run the model once to get mesh_mask_xxxx.nc files.
+   E.g., starting in the root NEMO directory:
+
+ ./makenemo -a ICE_RHEO -r ICE_RHEO_TEST -m X64_MOBILIS -j 4
+ cd tests/ICE_RHEO_TEST/EXP00
+ mpirun -np 1 ./nemo
+
+c) Create the initial condition file for sea-ice (initice.nc) by running
+   this python script:
+
+ python ../../ICE_RHEO/EXPREF/make_INITICE.py
+
+d) Run the model a second time
+
+ mpirun -np 16 ./nemo
+
+---------------
+What to look at
+---------------
+EVP rheology has less defined shear strain maxima (linear kinematic
+features). If the model is run longer one can see that the LKFs appearing
+with EVP rheology intersect at a different angle than with EAP rheology
+
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/context_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/context_nemo.xml	(revision 14055)
@@ -0,0 +1,47 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+<!-- $id$ -->
+    <variable_definition>
+    <!-- Year of time origin for NetCDF files; defaults to 1800 -->
+       <variable id="ref_year" type="int"   > 1800 </variable>
+       <variable id="rau0"     type="float" > 1026.0 </variable>
+       <variable id="cpocean"  type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu" type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"    type="float" > 917.0 </variable>
+       <variable id="rhosn"    type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>
+    </variable_definition>
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+    <!-- 
+============================================================================================================
+= grid definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+    
+    <axis_definition>
+      <axis id="deptht"  long_name="Vertical T levels"  unit="m" positive="down" />
+      <axis id="depthu"  long_name="Vertical U levels"  unit="m" positive="down" />
+      <axis id="depthv"  long_name="Vertical V levels"  unit="m" positive="down" />
+      <axis id="depthw"  long_name="Vertical W levels"  unit="m" positive="down" />
+      <axis id="nfloat"  long_name="Float number"       unit="-"                 />
+      <axis id="icbcla"  long_name="Iceberg class"      unit="1"                 />
+      <axis id="ncatice" long_name="Ice category"       unit="1"                 />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"              />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"              />
+    </axis_definition>
+ 
+    <domain_definition src="./domain_def_nemo.xml"/>
+  
+    <grid_definition src="./grid_def_nemo.xml"/>
+
+</context>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/domain_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/domain_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/field_def_nemo-ice.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/field_def_nemo-ice.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/field_def_nemo-oce.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/field_def_nemo-oce.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/file_def_nemo-ice.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/file_def_nemo-ice.xml	(revision 14055)
@@ -0,0 +1,58 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+============================================================================================================
+  -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    
+    
+      <file_group id="5ts" output_freq="5ts"  output_level="10" enabled=".TRUE."/>  <!-- 1 day files -->   	
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."> <!-- 1h files -->
+	<file id="file1" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+        <!-- ice mask -->
+        <field field_ref="icemask"          name="simsk"   />
+
+        <!-- general -->
+        <field field_ref="snwvolu"          name="snvolu" />
+        <field field_ref="icethic"          name="sithic" />
+        <field field_ref="iceconc"          name="siconc" />
+
+        <!-- momentum -->
+        <field field_ref="uice"             name="sivelu"  />
+        <field field_ref="vice"             name="sivelv"  />
+        <field field_ref="icevel"           name="sivelo"  />
+        <field field_ref="utau_ai"          name="utau_ai" />
+        <field field_ref="vtau_ai"          name="vtau_ai" />
+
+        <!-- rheology -->
+        <field field_ref="icediv"           name="sidive"  />
+        <field field_ref="iceshe"           name="sishea"  />
+        <field field_ref="icestr"           name="sistre"  />
+        <field field_ref="normstr"          name="normstr" />
+        <field field_ref="sheastr"          name="sheastr" />
+        <field field_ref="aniso"            name="aniso"   />
+
+        </file>
+      </file_group>
+
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->        
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d files -->   	
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/file_def_nemo-oce.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/file_def_nemo-oce.xml	(revision 14055)
@@ -0,0 +1,44 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+   
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    
+
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."> <!-- 1h files -->
+        <file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="vozocrtx"  />
+          <field field_ref="utau"         name="sozotaux"  />
+        </file>
+
+        <file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vomecrty"  />
+          <field field_ref="vtau"         name="sometauy"  />
+        </file>
+      </file_group>
+
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->     
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d files -->   
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
+
+
+
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/grid_def_nemo.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/grid_def_nemo.xml	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/iodef.xml	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/iodef.xml	(revision 14055)
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+	  <!--
+          <variable id="optimal_buffer_size"       type="string">memory</variable>
+          <variable id="buffer_size_factor"        type="double">1.0</variable>
+	  -->
+	  <variable id="info_level"                type="int">10</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/make_INITICE.py
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/make_INITICE.py	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/make_INITICE.py	(revision 14055)
@@ -0,0 +1,91 @@
+#!/usr/bin/python
+
+import os,sys
+from netCDF4 import Dataset as netcdf
+import numpy as np
+
+resname=''
+
+# input file
+fcoord='mesh_mask.nc'
+
+# output file
+fflx='initice.nc'
+
+print '   creating init ice file  ' +fflx
+
+# Reading coordinates file
+nccoord=netcdf(fcoord,'r')
+nav_lon=nccoord.variables['glamt'][0,:,:]
+nav_lat=nccoord.variables['gphit'][0,:,:]
+time_counter=1
+LON1= nav_lon.shape[1]
+LAT1= nav_lon.shape[0]
+print 'nav_lon.shape[1]' ,nav_lon.shape[1]
+print 'LON1 ', LON1
+print 'LAT1 ', LAT1
+
+# Creating INITICE netcdf file
+nc=netcdf(fflx,'w')
+nc.createDimension('y',LAT1)
+nc.createDimension('x',LON1)
+nc.createDimension('time_counter',None)    # Setting dimension size to 0 or None makes it unlimited. 
+
+cdflon=nc.createVariable('nav_lon','f',('y','x'))
+cdflat=nc.createVariable('nav_lat','f',('y','x'))
+cdftimecounter=nc.createVariable('time_counter','f',('time_counter'))
+
+# ati : Fraction of open waters in sea ice - units %
+# hti : Sea ice thickness - units m
+# hts : Snow thickness - units m
+# smi : Sea ice salinity:
+# tmi : Sea ice internal temperature - units K
+# tsu : Sea ice surface temperature - units K
+#
+# Take constant values from namelist &namiceini of NEMO
+rn_hti_ini=2.0
+rn_hts_ini=0.1            #  initial real snow thickness (m)
+rn_ati_ini=0.99           #  initial ice concentration   (-)
+rn_smi_ini=6.3            #  initial ice salinity     (g/kg)
+rn_tmi_ini=270.           #  initial ice/snw temperature (K)
+rn_tsu_ini=270.           #  initial sea ice temperature (K)
+#
+cdfati=nc.createVariable('ati','f',('time_counter','y','x'))
+cdfati.units='Percentage'
+cdfati.long_name='Sea ice concentration'
+cdfhti=nc.createVariable('hti','f',('time_counter','y','x'))
+cdfhti.long_name='Sea ice thickness'
+cdfhti.units='m'
+cdfhts=nc.createVariable('hts','f',('time_counter','y','x'))
+cdfhts.long_name='Snow thickness'
+cdfhts.units='m'
+cdfsmi=nc.createVariable('smi','f',('time_counter','y','x'))
+cdfsmi.long_name='Sea ice salinity'
+cdfsmi.units='pss'
+cdftmi=nc.createVariable('tmi','f',('time_counter','y','x'))
+cdftmi.long_name='Sea ice internal temperature'
+cdftmi.units='Kelvin'
+cdftsu=nc.createVariable('tsu','f',('time_counter','y','x'))
+cdftsu.long_name='Sea ice surface temperature'
+cdftsu.units='Kelvin'
+
+cdflon[:,:]=nav_lon[:,:]
+cdflat[:,:]=nav_lat[:,:]
+cdftimecounter[0]=1
+
+cdfati[:,:,:]=rn_ati_ini
+cdfhts[:,:,:]=rn_hts_ini
+cdfsmi[:,:,:]=rn_smi_ini
+cdftmi[:,:,:]=rn_tmi_ini
+cdftsu[:,:,:]=rn_tsu_ini
+
+# --- add noise in initial thickness to help nucleation of deformation ---
+#for y in np.arange(1,1000,1) :
+#    for x in np.arange(1,1000,1) :
+#        cdfhti[:,y,x] = rn_hti_ini+0.02*rn_hti_ini*np.random.uniform(-1,1)
+cdfhti[:,:,:]=rn_hti_ini
+
+nc.close()
+nccoord.close()
+
+#sys.exit()
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_cfg	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_cfg	(revision 14055)
@@ -0,0 +1,263 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_RHEO configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_RHEO user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    2000.   ! horizontal resolution in meters
+   rn_dy       =    2000.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  90.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_RHEO"  !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =     720     !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_Dt      = 30.       !  time step for the dynamics and tracer
+   !
+   ln_meshmask = .true.    !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_flx      = .false.   !  flux formulation                          (T => fill namsbc_flx )
+   ln_blk      = .false.    !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1        !  frequency of surface boundary condition computation
+   nn_ice      =  2        !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula          (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR      = .true.    ! "NCAR"      algorithm   (Large and Yeager 2008)
+   ln_COARE_3p0 = .false.   ! "COARE 3.0" algorithm   (Fairall et al. 2003)
+   ln_COARE_3p6 = .false.   ! "COARE 3.6" algorithm   (Edson et al. 2013)
+   ln_ECMWF     = .false.   ! "ECMWF"     algorithm   (IFS cycle 45r1)
+      !
+      rn_zqt      = 10.       !  Air temperature & humidity reference height (m)
+      rn_zu       = 10.       !  Wind vector reference height (m)
+      ln_Cd_L12   = .false.   !  air-ice drags = F(ice conc.) (Lupkes et al. 2012)
+      ln_Cd_L15   = .false.   !  air-ice drags = F(ice conc.) (Lupkes et al. 2015)
+      rn_pfac     = 1.        !  multiplicative factor for precipitation (total & snow)
+      rn_efac     = 1.        !  multiplicative factor for evaporation (0. or 1.)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !       weights filename               ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    3.        , 'U_10_MOD',   .true.    , .true. , 'yearly'  , ''                                   , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    3.        , 'V_10_MOD',   .true.    , .true. , 'yearly'  , ''                                   , 'Vwnd'   , ''
+   sn_qsr      = ''                           ,    0.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+   sn_qlw      = ''                           ,    0.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+   sn_tair     = ''                           ,    0.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+   sn_humi     = ''                           ,    0.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+   sn_prec     = ''                           ,    0.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+   sn_snow     = ''                           ,    0.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+   sn_slp      = ''                           ,    0.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , ''                                   , ''       , ''
+
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF  = .false.   !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .true.          !  = Use TEOS-10
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ice_cfg	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ice_cfg	(revision 14055)
@@ -0,0 +1,131 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   1             !  number of ice  categories
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .true.          !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .false.         !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+   ln_str_H79       = .true.          !  ice strength param.: Hibler_79   => P = pstar*<h>*exp(-c_rhg*A)
+      rn_pstar      =   2700          !     ice strength thickness parameter [N/m2]
+      rn_crhg       =   20.0          !     ice strength conc. parameter (-)
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+   ln_rhg_EVP       = .false.         !  EVP rheology
+      ln_aEVP       = .false.         !     adaptive rheology (Kimmritz et al. 2016 & 2017)
+      rn_creepl     =   2.0e-9        !     creep limit [1/s]
+      rn_ecc        =   2.0           !     eccentricity of the elliptical yield curve          
+      nn_nevp       =   200           !     number of EVP subcycles                             
+      rn_relast     =   0.333         !     ratio of elastic timescale to ice time step: Telast = dt_ice * rn_relast 
+                                      !        advised value: 1/3 (rn_nevp=120) or 1/9 (rn_nevp=300)
+   ln_rhg_EAP       = .true.          !  EAP rheology
+   nn_rhg_chkcvg    =   0             !  check convergence of rheology
+                                      !     = 0  no check
+                                      !     = 1  check at the main time step (output xml: uice_cvg)
+                                      !     = 2  check at both main and rheology time steps (additional output: ice_cvg.nc)
+                                      !          this option 2 asks a lot of communications between cpu
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .true.          !  Advection scheme (Prather)
+   ln_adv_UMx       = .false.         !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =   1             !     0 = Initialise sea ice based on SSTs
+                                      !     1 = Initialise sea ice from single category netcdf file
+                                      !     2 = Initialise sea ice from multi category restart file
+   rn_thres_sst     =   2.0           !  max temp. above Tfreeze with initial ice = (sst - tfreeze)
+   rn_hti_ini_n     =   3.0           !  initial ice thickness       (m), North
+   rn_hts_ini_n     =   0.1           !  initial snow thickness      (m), North
+   rn_ati_ini_n     =   0.99          !  initial ice concentration   (-), North
+   rn_smi_ini_n     =   6.3           !  initial ice salinity     (g/kg), North
+   rn_tmi_ini_n     = 270.            !  initial ice temperature     (K), North
+   rn_tsu_ini_n     = 270.            !  initial surface temperature (K), North
+   rn_tms_ini_n     = 270.            !  initial snw temperature     (K), North
+   rn_apd_ini_n     =   0.0           !  initial pond fraction       (-), North
+   rn_hpd_ini_n     =   0.0           !  initial pond depth          (m), North
+   sn_hti = 'initice'                 , -12. ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice'                 , -12. ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice'                 , -12. ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice'                 , -12. ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice'                 , -12. ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice'                 , -12. ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ice_ref	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ice_ref	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ice_ref
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ref	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/EXPREF/namelist_ref	(revision 14055)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/icedyn_rhg_eap.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/icedyn_rhg_eap.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/icedyn_rhg_eap.F90	(revision 14055)
@@ -0,0 +1,2002 @@
+MODULE icedyn_rhg_eap
+   !!======================================================================
+   !!                     ***  MODULE  icedyn_rhg_eap  ***
+   !!   Sea-Ice dynamics : rheology Elasto-Viscous-Plastic
+   !!======================================================================
+   !! History :   -   !  2007-03  (M.A. Morales Maqueda, S. Bouillon) Original code
+   !!            3.0  !  2008-03  (M. Vancoppenolle) adaptation to new model
+   !!             -   !  2008-11  (M. Vancoppenolle, S. Bouillon, Y. Aksenov) add surface tilt in ice rheolohy 
+   !!            3.3  !  2009-05  (G.Garric)    addition of the evp case
+   !!            3.4  !  2011-01  (A. Porter)   dynamical allocation 
+   !!            3.5  !  2012-08  (R. Benshila) AGRIF
+   !!            3.6  !  2016-06  (C. Rousset)  Rewriting + landfast ice + mEVP (Bouillon 2013)
+   !!            3.7  !  2017     (C. Rousset)  add aEVP (Kimmritz 2016-2017)
+   !!            4.0  !  2018     (many people) SI3 [aka Sea Ice cube]
+   !!                 !  2019     (S. Rynders, Y. Aksenov, C. Rousset)  change into eap rheology from
+   !!                                           CICE code (Tsamados, Heorton) 
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_rhg_eap : computes ice velocities from EVP rheology
+   !!   rhg_eap_rst     : read/write EVP fields in ice restart
+   !!----------------------------------------------------------------------
+   USE phycst         ! Physical constant
+   USE dom_oce        ! Ocean domain
+   USE sbc_oce , ONLY : ln_ice_embd, nn_fsbc, ssh_m
+   USE sbc_ice , ONLY : utau_ice, vtau_ice, snwice_mass, snwice_mass_b
+   USE ice            ! sea-ice: ice variables
+   USE icevar         ! ice_var_sshdyn
+   USE icedyn_rdgrft  ! sea-ice: ice strength
+   USE bdy_oce , ONLY : ln_bdy 
+   USE bdyice 
+#if defined key_agrif
+   USE agrif_ice_interp
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE prtctl         ! Print control
+
+   USE netcdf         ! NetCDF library for convergence test
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rhg_eap   ! called by icedyn_rhg.F90
+   PUBLIC   rhg_eap_rst       ! called by icedyn_rhg.F90
+
+   REAL(wp), PARAMETER ::   pphi = 3.141592653589793_wp/12._wp    ! diamond shaped floe smaller angle (default phi = 30 deg)
+
+   ! look-up table for calculating structure tensor
+   INTEGER, PARAMETER ::   nx_yield = 41
+   INTEGER, PARAMETER ::   ny_yield = 41
+   INTEGER, PARAMETER ::   na_yield = 21
+
+   REAL(wp), DIMENSION(nx_yield, ny_yield, na_yield) ::   s11r, s12r, s22r, s11s, s12s, s22s
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+#  include "domzgr_substitute.h90"
+
+   !! for convergence tests
+   INTEGER ::   ncvgid   ! netcdf file id
+   INTEGER ::   nvarid   ! netcdf variable id
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zmsk00, zmsk15
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id: icedyn_rhg_eap.F90 11536 2019-09-11 13:54:18Z smasson $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_rhg_eap( kt, Kmm, pstress1_i, pstress2_i, pstress12_i, pshear_i, pdivu_i, pdelta_i, paniso_11, paniso_12, prdg_conv )
+      !!-------------------------------------------------------------------
+      !!                 ***  SUBROUTINE ice_dyn_rhg_eap  ***
+      !!                             EAP-C-grid
+      !!
+      !! ** purpose : determines sea ice drift from wind stress, ice-ocean
+      !!  stress and sea-surface slope. Ice-ice interaction is described by 
+      !!  a non-linear elasto-anisotropic-plastic (EAP) law including shear 
+      !!  strength and a bulk rheology .	
+      !!
+      !!  The points in the C-grid look like this, dear reader
+      !!
+      !!                              (ji,jj)
+      !!                                 |
+      !!                                 |
+      !!                      (ji-1,jj)  |  (ji,jj)
+      !!                             ---------   
+      !!                            |         |
+      !!                            | (ji,jj) |------(ji,jj)
+      !!                            |         |
+      !!                             ---------   
+      !!                     (ji-1,jj-1)     (ji,jj-1)
+      !!
+      !! ** Inputs  : - wind forcing (stress), oceanic currents
+      !!                ice total volume (vt_i) per unit area
+      !!                snow total volume (vt_s) per unit area
+      !!
+      !! ** Action  : - compute u_ice, v_ice : the components of the 
+      !!                sea-ice velocity vector
+      !!              - compute delta_i, shear_i, divu_i, which are inputs
+      !!                of the ice thickness distribution
+      !!
+      !! ** Steps   : 0) compute mask at F point
+      !!              1) Compute ice snow mass, ice strength 
+      !!              2) Compute wind, oceanic stresses, mass terms and
+      !!                 coriolis terms of the momentum equation
+      !!              3) Solve the momentum equation (iterative procedure)
+      !!              4) Recompute delta, shear and divergence
+      !!                 (which are inputs of the ITD) & store stress
+      !!                 for the next time step
+      !!              5) Diagnostics including charge ellipse
+      !!
+      !! ** Notes   : There is the possibility to use aEVP from the nice work of Kimmritz et al. (2016 & 2017)
+      !!              by setting up ln_aEVP=T (i.e. changing alpha and beta parameters).
+      !!              This is an upgraded version of mEVP from Bouillon et al. 2013
+      !!              (i.e. more stable and better convergence)
+      !!
+      !! References : Hunke and Dukowicz, JPO97
+      !!              Bouillon et al., Ocean Modelling 2009
+      !!              Bouillon et al., Ocean Modelling 2013
+      !!              Kimmritz et al., Ocean Modelling 2016 & 2017
+      !!-------------------------------------------------------------------
+      INTEGER                 , INTENT(in   ) ::   kt                                    ! time step
+      INTEGER                 , INTENT(in   ) ::   Kmm                                   ! ocean time level index
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pstress1_i, pstress2_i, pstress12_i   !
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pshear_i  , pdivu_i   , pdelta_i      !
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   paniso_11 , paniso_12                 ! structure tensor components
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   prdg_conv                             ! for ridging
+      !!
+      INTEGER ::   ji, jj       ! dummy loop indices
+      INTEGER ::   jter         ! local integers
+      !
+      REAL(wp) ::   zrhoco                                              ! rau0 * rn_cio
+      REAL(wp) ::   zdtevp, z1_dtevp                                    ! time step for subcycling
+      REAL(wp) ::   ecc2, z1_ecc2                                       ! square of yield ellipse eccenticity
+      REAL(wp) ::   zalph1, z1_alph1, zalph2, z1_alph2                  ! alpha coef from Bouillon 2009 or Kimmritz 2017
+      REAl(wp) ::   zbetau, zbetav
+      REAL(wp) ::   zm1, zm2, zm3, zmassU, zmassV, zvU, zvV             ! ice/snow mass and volume
+      REAL(wp) ::   zds2, zdt, zdt2, zdiv, zdiv2, zdsT                  ! temporary scalars
+      REAL(wp) ::   zTauO, zTauB, zRHS, zvel                            ! temporary scalars
+      REAL(wp) ::   zkt                                                 ! isotropic tensile strength for landfast ice
+      REAL(wp) ::   zvCr                                                ! critical ice volume above which ice is landfast
+      !
+      REAL(wp) ::   zintb, zintn                                        ! dummy argument
+      REAL(wp) ::   zfac_x, zfac_y
+      REAL(wp) ::   zshear, zdum1, zdum2
+      REAL(wp) ::   zstressptmp, zstressmtmp, zstress12tmpF             ! anisotropic stress tensor components
+      REAL(wp) ::   zalphar, zalphas                                    ! for mechanical redistribution
+      REAL(wp) ::   zmresult11, zmresult12, z1dtevpkth, zp5kth, z1_dtevp_A  ! for structure tensor evolution
+      REAL(wp) ::   zinvw                                                ! for test case
+
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zstress12tmp                    ! anisotropic stress tensor component for regridding
+      REAL(wp), DIMENSION(jpi,jpj) ::   zyield11, zyield22, zyield12    ! yield surface tensor for history
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdelta, zp_delt                 ! delta and P/delta at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zten_i                          ! tension
+      REAL(wp), DIMENSION(jpi,jpj) ::   zbeta                           ! beta coef from Kimmritz 2017
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdt_m                           ! (dt / ice-snow_mass) on T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zaU  , zaV                      ! ice fraction on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmU_t, zmV_t                    ! (ice-snow_mass / dt) on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmf                             ! coriolis parameter at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   v_oceU, u_oceV, v_iceU, u_iceV  ! ocean/ice u/v component on V/U points                           
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zds                             ! shear
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1, zs2, zs12                  ! stress tensor components
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsshdyn                         ! array used for the calculation of ice surface slope:
+      !                                                                 !    ocean surface (ssh_m) if ice is not embedded
+      !                                                                 !    ice bottom surface if ice is embedded   
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfU  , zfV                      ! internal stresses
+      REAL(wp), DIMENSION(jpi,jpj) ::   zspgU, zspgV                    ! surface pressure gradient at U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCorU, zCorV                    ! Coriolis stress array
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_ai, ztauy_ai              ! ice-atm. stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_oi, ztauy_oi              ! ice-ocean stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_bi, ztauy_bi              ! ice-OceanBottom stress at U-V points (landfast)
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_base, ztauy_base          ! ice-bottom stress at U-V points (landfast)
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk01x, zmsk01y                ! dummy arrays
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk00x, zmsk00y                ! mask for ice presence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfmask                          ! mask at F points for the ice
+
+      REAL(wp), PARAMETER          ::   zepsi  = 1.0e-20_wp             ! tolerance parameter
+      REAL(wp), PARAMETER          ::   zmmin  = 1._wp                  ! ice mass (kg/m2)  below which ice velocity becomes very small
+      REAL(wp), PARAMETER          ::   zamin  = 0.001_wp               ! ice concentration below which ice velocity becomes very small
+      !! --- check convergence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_ice, zv_ice
+      !! --- diags
+      REAL(wp) ::   zsig1, zsig2, zsig12, zfac, z1_strength
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zsig_I, zsig_II, zsig1_p, zsig2_p         
+      !! --- SIMIP diags
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_ice ! X-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_ice ! Y-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_snw ! X-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_snw ! Y-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xatrp     ! X-component of area transport (m2/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_yatrp     ! Y-component of area transport (m2/s)      
+      !!-------------------------------------------------------------------
+
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_rhg_eap: EAP sea-ice rheology'
+      !
+      ! for diagnostics and convergence tests
+      ALLOCATE( zmsk00(jpi,jpj), zmsk15(jpi,jpj) )
+      DO_2D( 1, 1, 1, 1 )
+         zmsk00(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06  ) ) ! 1 if ice    , 0 if no ice
+         zmsk15(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.15_wp ) ) ! 1 if 15% ice, 0 if less
+      END_2D
+      !
+!!gm for Clem:  OPTIMIZATION:  I think zfmask can be computed one for all at the initialization....
+      !------------------------------------------------------------------------------!
+      ! 0) mask at F points for the ice
+      !------------------------------------------------------------------------------!
+      ! ocean/land mask
+      DO_2D( 1, 0, 1, 0 )
+         zfmask(ji,jj) = tmask(ji,jj,1) * tmask(ji+1,jj,1) * tmask(ji,jj+1,1) * tmask(ji+1,jj+1,1)
+      END_2D
+      CALL lbc_lnk( 'icedyn_rhg_eap', zfmask, 'F', 1._wp )
+
+      ! Lateral boundary conditions on velocity (modify zfmask)
+      DO_2D( 0, 0, 0, 0 )
+         IF( zfmask(ji,jj) == 0._wp ) THEN
+            zfmask(ji,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(ji,jj,1), umask(ji,jj+1,1), &
+               &                                          vmask(ji,jj,1), vmask(ji+1,jj,1) ) )
+         ENDIF
+      END_2D
+      DO jj = 2, jpjm1
+         IF( zfmask(1,jj) == 0._wp ) THEN
+            zfmask(1  ,jj) = rn_ishlat * MIN( 1._wp , MAX( vmask(2,jj,1), umask(1,jj+1,1), umask(1,jj,1) ) )
+         ENDIF
+         IF( zfmask(jpi,jj) == 0._wp ) THEN
+            zfmask(jpi,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(jpi,jj+1,1), vmask(jpim1,jj,1), umask(jpi,jj-1,1) ) )
+         ENDIF
+      END DO
+      DO ji = 2, jpim1
+         IF( zfmask(ji,1) == 0._wp ) THEN
+            zfmask(ji, 1 ) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,1,1), umask(ji,2,1), vmask(ji,1,1) ) )
+         ENDIF
+         IF( zfmask(ji,jpj) == 0._wp ) THEN
+            zfmask(ji,jpj) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,jpj,1), vmask(ji-1,jpj,1), umask(ji,jpjm1,1) ) )
+         ENDIF
+      END DO
+      CALL lbc_lnk( 'icedyn_rhg_eap', zfmask, 'F', 1.0_wp )
+
+      !------------------------------------------------------------------------------!
+      ! 1) define some variables and initialize arrays
+      !------------------------------------------------------------------------------!
+      zrhoco = rho0 * rn_cio 
+!extra code for test case boundary conditions
+      zinvw=1._wp/(zrhoco*0.5_wp)
+
+      ! ecc2: square of yield ellipse eccenticrity
+      ecc2    = rn_ecc * rn_ecc
+      z1_ecc2 = 1._wp / ecc2
+
+      ! alpha parameters (Bouillon 2009)
+      IF( .NOT. ln_aEVP ) THEN
+         zdtevp   = rDt_ice / REAL( nn_nevp )
+         zalph1 =   2._wp * rn_relast * REAL( nn_nevp )
+         zalph2 = zalph1 * z1_ecc2
+
+         z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+         z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+      ELSE
+         zdtevp   = rdt_ice
+         ! zalpha parameters set later on adaptatively
+      ENDIF
+      z1_dtevp = 1._wp / zdtevp
+         
+      ! Initialise stress tensor 
+      zs1 (:,:) = pstress1_i (:,:) 
+      zs2 (:,:) = pstress2_i (:,:)
+      zs12(:,:) = pstress12_i(:,:)
+
+      ! constants for structure tensor
+      z1_dtevp_A = z1_dtevp/10.0_wp
+      z1dtevpkth = 1._wp / (z1_dtevp_A + 0.00002_wp)
+      zp5kth = 0.5_wp * 0.00002_wp
+
+      ! Ice strength
+      CALL ice_strength
+
+      ! landfast param from Lemieux(2016): add isotropic tensile strength (following Konig Beatty and Holland, 2010)
+      IF( ln_landfast_L16 ) THEN   ;   zkt = rn_lf_tensile
+      ELSE                         ;   zkt = 0._wp
+      ENDIF
+      !
+      !------------------------------------------------------------------------------!
+      ! 2) Wind / ocean stress, mass terms, coriolis terms
+      !------------------------------------------------------------------------------!
+      ! sea surface height
+      !    embedded sea ice: compute representative ice top surface
+      !    non-embedded sea ice: use ocean surface for slope calculation
+      zsshdyn(:,:) = ice_var_sshdyn( ssh_m, snwice_mass, snwice_mass_b)
+
+      DO_2D( 0, 0, 0, 0 )
+
+         ! ice fraction at U-V points
+         zaU(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+         zaV(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+         ! Ice/snow mass at U-V points
+         zm1 = ( rhos * vt_s(ji  ,jj  ) + rhoi * vt_i(ji  ,jj  ) )
+         zm2 = ( rhos * vt_s(ji+1,jj  ) + rhoi * vt_i(ji+1,jj  ) )
+         zm3 = ( rhos * vt_s(ji  ,jj+1) + rhoi * vt_i(ji  ,jj+1) )
+         zmassU = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm2 * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+         zmassV = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm3 * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+         ! Ocean currents at U-V points
+         v_oceU(ji,jj)   = 0.25_wp * ( v_oce(ji,jj) + v_oce(ji,jj-1) + v_oce(ji+1,jj) + v_oce(ji+1,jj-1) ) * umask(ji,jj,1)
+         u_oceV(ji,jj)   = 0.25_wp * ( u_oce(ji,jj) + u_oce(ji-1,jj) + u_oce(ji,jj+1) + u_oce(ji-1,jj+1) ) * vmask(ji,jj,1)
+
+         ! Coriolis at T points (m*f)
+         zmf(ji,jj)      = zm1 * ff_t(ji,jj)
+
+         ! dt/m at T points (for alpha and beta coefficients)
+         zdt_m(ji,jj)    = zdtevp / MAX( zm1, zmmin )
+         
+         ! m/dt
+         zmU_t(ji,jj)    = zmassU * z1_dtevp
+         zmV_t(ji,jj)    = zmassV * z1_dtevp
+         
+         ! Drag ice-atm.
+         ztaux_ai(ji,jj) = zaU(ji,jj) * utau_ice(ji,jj)
+         ztauy_ai(ji,jj) = zaV(ji,jj) * vtau_ice(ji,jj)
+
+         ! Surface pressure gradient (- m*g*GRAD(ssh)) at U-V points
+         zspgU(ji,jj)    = - zmassU * grav * ( zsshdyn(ji+1,jj) - zsshdyn(ji,jj) ) * r1_e1u(ji,jj)
+         zspgV(ji,jj)    = - zmassV * grav * ( zsshdyn(ji,jj+1) - zsshdyn(ji,jj) ) * r1_e2v(ji,jj)
+
+         ! masks
+         zmsk00x(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassU ) )  ! 0 if no ice
+         zmsk00y(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassV ) )  ! 0 if no ice
+
+         ! switches
+         IF( zmassU <= zmmin .AND. zaU(ji,jj) <= zamin ) THEN   ;   zmsk01x(ji,jj) = 0._wp
+         ELSE                                                   ;   zmsk01x(ji,jj) = 1._wp   ;   ENDIF
+         IF( zmassV <= zmmin .AND. zaV(ji,jj) <= zamin ) THEN   ;   zmsk01y(ji,jj) = 0._wp
+         ELSE                                                   ;   zmsk01y(ji,jj) = 1._wp   ;   ENDIF
+
+      END_2D
+      CALL lbc_lnk_multi( 'icedyn_rhg_eap', zmf, 'T', 1.0_wp, zdt_m, 'T', 1.0_wp )
+      !
+      !                                  !== Landfast ice parameterization ==!
+      !
+      IF( ln_landfast_L16 ) THEN         !-- Lemieux 2016
+         DO_2D( 0, 0, 0, 0 )
+            ! ice thickness at U-V points
+            zvU = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            zvV = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+            ! ice-bottom stress at U points
+            zvCr = zaU(ji,jj) * rn_lf_depfra * hu(ji,jj,Kmm)
+            ztaux_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvU - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaU(ji,jj) ) )
+            ! ice-bottom stress at V points
+            zvCr = zaV(ji,jj) * rn_lf_depfra * hv(ji,jj,Kmm)
+            ztauy_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvV - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaV(ji,jj) ) )
+            ! ice_bottom stress at T points
+            zvCr = at_i(ji,jj) * rn_lf_depfra * ht(ji,jj)
+            tau_icebfr(ji,jj) = - rn_lf_bfr * MAX( 0._wp, vt_i(ji,jj) - zvCr ) * EXP( -rn_crhg * ( 1._wp - at_i(ji,jj) ) )
+         END_2D
+         CALL lbc_lnk( 'icedyn_rhg_eap', tau_icebfr(:,:), 'T', 1.0_wp )
+         !
+      ELSE                               !-- no landfast
+         DO_2D( 0, 0, 0, 0 )
+            ztaux_base(ji,jj) = 0._wp
+            ztauy_base(ji,jj) = 0._wp
+         END_2D
+      ENDIF
+
+      !------------------------------------------------------------------------------!
+      ! 3) Solution of the momentum equation, iterative procedure
+      !------------------------------------------------------------------------------!
+      !
+      !                                               ! ==================== !
+      DO jter = 1 , nn_nevp                           !    loop over jter    !
+         !                                            ! ==================== !        
+         l_full_nf_update = jter == nn_nevp   ! false: disable full North fold update (performances) for iter = 1 to nn_nevp-1
+         !
+         ! convergence test
+         IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2  ) THEN
+            DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
+               zu_ice(ji,jj) = u_ice(ji,jj) * umask(ji,jj,1) ! velocity at previous time step
+               zv_ice(ji,jj) = v_ice(ji,jj) * vmask(ji,jj,1)
+            END_2D
+         ENDIF
+
+         ! --- divergence, tension & shear (Appendix B of Hunke & Dukowicz, 2002) --- !
+         DO_2D( 1, 0, 1, 0 )
+
+            ! shear at F points
+            zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+               &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+               &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+         END_2D
+
+         DO_2D( 0, 0, 0, 0 )
+
+            ! shear**2 at T points (doc eq. A16)
+            zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+           
+            ! divergence at T points
+            zdiv  = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &    + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &    ) * r1_e1e2t(ji,jj)
+            zdiv2 = zdiv * zdiv
+            
+            ! tension at T points
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+            zdt2 = zdt * zdt
+
+            ! delta at T points
+            zdelta(ji,jj) = SQRT( zdiv2 + ( zdt2 + zds2 ) * z1_ecc2 )  
+
+         END_2D
+         CALL lbc_lnk( 'icedyn_rhg_eap', zdelta, 'T', 1.0_wp )
+               
+         ! P/delta at T points
+         DO_2D( 1, 1, 1, 1 )
+            zp_delt(ji,jj) = strength(ji,jj) / ( zdelta(ji,jj) + rn_creepl )
+         END_2D
+
+         DO_2D( 0, 1, 0, 1 )   ! loop ends at jpi,jpj so that no lbc_lnk are needed for zs1 and zs2
+
+             ! shear at T points 
+            zdsT = ( zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+            
+           ! divergence at T points (duplication to avoid communications)
+            zdiv  = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &    + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &    ) * r1_e1e2t(ji,jj)
+            
+            ! tension at T points (duplication to avoid communications)
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+
+            ! --- anisotropic stress calculation --- !
+            CALL update_stress_rdg (jter, nn_nevp, zdiv, zdt, zdsT, paniso_11(ji,jj), paniso_12(ji,jj), &
+                                    zstressptmp, zstressmtmp, zstress12tmp(ji,jj), strength(ji,jj), zalphar, zalphas)
+
+            ! structure tensor update
+               CALL calc_ffrac(zstressptmp, zstressmtmp, zstress12tmp(ji,jj), paniso_11(ji,jj), paniso_12(ji,jj), zmresult11,  zmresult12)
+
+               paniso_11(ji,jj) = (paniso_11(ji,jj)  + 0.5*2.e-5*zdtevp + zmresult11*zdtevp) / (1. + 2.e-5*zdtevp) ! implicit
+               paniso_12(ji,jj) = (paniso_12(ji,jj)                     + zmresult12*zdtevp) / (1. + 2.e-5*zdtevp) ! implicit
+
+            IF (jter == nn_nevp) THEN
+               zyield11(ji,jj) = 0.5_wp * (zstressptmp + zstressmtmp)
+               zyield22(ji,jj) = 0.5_wp * (zstressptmp - zstressmtmp)
+               zyield12(ji,jj) = zstress12tmp(ji,jj)
+               prdg_conv(ji,jj) = -min( zalphar, 0._wp)    
+            ENDIF
+
+            ! alpha for aEVP
+            !   gamma = 0.5*P/(delta+creepl) * (c*pi)**2/Area * dt/m
+            !   alpha = beta = sqrt(4*gamma)
+            IF( ln_aEVP ) THEN
+               zalph1   = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+               z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+               zalph2   = zalph1
+               z1_alph2 = z1_alph1
+               ! explicit:
+               ! z1_alph1 = 1._wp / zalph1
+               ! z1_alph2 = 1._wp / zalph1
+               ! zalph1 = zalph1 - 1._wp
+               ! zalph2 = zalph1
+            ENDIF
+
+            ! stress at T points (zkt/=0 if landfast)
+            zs1(ji,jj) = ( zs1(ji,jj) * zalph1 + zstressptmp ) * z1_alph1
+            zs2(ji,jj) = ( zs2(ji,jj) * zalph1 + zstressmtmp ) * z1_alph1
+         END_2D
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zstress12tmp, 'T', 1.0_wp , paniso_11, 'T', 1.0_wp , paniso_12, 'T', 1.0_wp)
+
+        ! Save beta at T-points for further computations
+         IF( ln_aEVP ) THEN
+            DO_2D( 1, 1, 1, 1 )
+               zbeta(ji,jj) = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+            END_2D
+         ENDIF
+
+         DO_2D( 1, 0, 1, 0 )
+            ! stress12tmp at F points 
+            zstress12tmpF = ( zstress12tmp(ji,jj+1) * e1e2t(ji,jj+1) + zstress12tmp(ji+1,jj+1) * e1e2t(ji+1,jj+1)  &
+               &            + zstress12tmp(ji,jj  ) * e1e2t(ji,jj  ) + zstress12tmp(ji+1,jj  ) * e1e2t(ji+1,jj  )  &
+               &            ) * 0.25_wp * r1_e1e2f(ji,jj)
+
+            ! alpha for aEVP
+            IF( ln_aEVP ) THEN
+               zalph2   = MAX( zbeta(ji,jj), zbeta(ji+1,jj), zbeta(ji,jj+1), zbeta(ji+1,jj+1) )
+               z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+               ! explicit:
+               ! z1_alph2 = 1._wp / zalph2
+               ! zalph2 = zalph2 - 1._wp
+            ENDIF
+            
+            ! stress at F points (zkt/=0 if landfast)
+            zs12(ji,jj) = ( zs12(ji,jj) * zalph1 + zstress12tmpF ) * z1_alph1
+
+         END_2D
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zs1, 'T', 1.0_wp, zs2, 'T', 1.0_wp, zs12, 'F', 1.0_wp )
+
+         ! --- Ice internal stresses (Appendix C of Hunke and Dukowicz, 2002) --- !
+         DO_2D( 0, 0, 0, 0 )
+            !                   !--- U points
+            zfU(ji,jj) = 0.5_wp * ( ( zs1(ji+1,jj) - zs1(ji,jj) ) * e2u(ji,jj)                                             &
+               &                  + ( zs2(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) - zs2(ji,jj) * e2t(ji,jj) * e2t(ji,jj)    &
+               &                    ) * r1_e2u(ji,jj)                                                                      &
+               &                  + ( zs12(ji,jj) * e1f(ji,jj) * e1f(ji,jj) - zs12(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1)  &
+               &                    ) * 2._wp * r1_e1u(ji,jj)                                                              &
+               &                  ) * r1_e1e2u(ji,jj)
+            !
+            !                !--- V points
+            zfV(ji,jj) = 0.5_wp * ( ( zs1(ji,jj+1) - zs1(ji,jj) ) * e1v(ji,jj)                                             &
+               &                  - ( zs2(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) - zs2(ji,jj) * e1t(ji,jj) * e1t(ji,jj)    &
+               &                    ) * r1_e1v(ji,jj)                                                                      &
+               &                  + ( zs12(ji,jj) * e2f(ji,jj) * e2f(ji,jj) - zs12(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj)  &
+               &                    ) * 2._wp * r1_e2v(ji,jj)                                                              &
+               &                  ) * r1_e1e2v(ji,jj)
+            !
+            !                !--- ice currents at U-V point
+            v_iceU(ji,jj) = 0.25_wp * ( v_ice(ji,jj) + v_ice(ji,jj-1) + v_ice(ji+1,jj) + v_ice(ji+1,jj-1) ) * umask(ji,jj,1)
+            u_iceV(ji,jj) = 0.25_wp * ( u_ice(ji,jj) + u_ice(ji-1,jj) + u_ice(ji,jj+1) + u_ice(ji-1,jj+1) ) * vmask(ji,jj,1)
+            !
+         END_2D
+         !
+         ! --- Computation of ice velocity --- !
+         !  Bouillon et al. 2013 (eq 47-48) => unstable unless alpha, beta vary as in Kimmritz 2016 & 2017
+         !  Bouillon et al. 2009 (eq 34-35) => stable
+         IF( MOD(jter,2) == 0 ) THEN ! even iterations
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(v_oce - v_ice)
+               zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                  &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/v_ice
+               zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+               zTauB = ztauy_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+               !
+               !                 !--- Coriolis at V-points (energy conserving formulation)
+               zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                  &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                  &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   & 
+                     &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetav + 1._wp )                                              &
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  v_ice(ji,jj) = ( (         rswitch   * ( zmV_t(ji,jj)  * v_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )   * zmsk00y(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  v_ice(ji,jj) = zinvw*(ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj))
+               END IF
+
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', v_ice, 'V', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(u_oce - u_ice)
+               zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                  &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/u_ice
+               zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+               zTauB = ztaux_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+               !
+               !                 !--- Coriolis at U-points (energy conserving formulation)
+               zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                  &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                  &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                     &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetau + 1._wp )                                              &
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  u_ice(ji,jj) = ( (         rswitch   * ( zmU_t(ji,jj)  * u_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &            )   * zmsk00x(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  u_ice(ji,jj) = zinvw*(ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj))
+               END IF
+
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', u_ice, 'U', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+         ELSE ! odd iterations
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(u_oce - u_ice)
+               zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                  &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/u_ice
+               zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+               zTauB = ztaux_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+               !
+               !                 !--- Coriolis at U-points (energy conserving formulation)
+               zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                  &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                  &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                     &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetau + 1._wp )                                              &
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  u_ice(ji,jj) = ( (         rswitch   * ( zmU_t(ji,jj)  * u_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )   * zmsk00x(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  u_ice(ji,jj) = zinvw*(ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj))
+               END IF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', u_ice, 'U', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(v_oce - v_ice)
+               zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                  &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/v_ice
+               zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+               zTauB = ztauy_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+               !
+               !                 !--- Coriolis at v-points (energy conserving formulation)
+               zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                  &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                  &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   &
+                     &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetav + 1._wp )                                              & 
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  v_ice(ji,jj) = ( (         rswitch   * ( zmV_t(ji,jj)  * v_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &              ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                  & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )   * zmsk00y(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  v_ice(ji,jj) = zinvw*(ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj))
+               END IF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_eap', v_ice, 'V', -1.0_wp )
+            !
+#if defined key_agrif
+!!          CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+         ENDIF
+
+         ! convergence test
+         IF( nn_rhg_chkcvg == 2 )   CALL rhg_cvg( kt, jter, nn_nevp, u_ice, v_ice, zu_ice, zv_ice )
+         !
+         !                                                ! ==================== !
+      END DO                                              !  end loop over jter  !
+      !                                                   ! ==================== !
+      IF( ln_aEVP )   CALL iom_put( 'beta_evp' , zbeta )
+      !
+      CALL lbc_lnk( 'icedyn_rhg_eap', prdg_conv, 'T', 1.0_wp )  ! only need this in ridging module after rheology completed
+      !
+      !------------------------------------------------------------------------------!
+      ! 4) Recompute delta, shear and div (inputs for mechanical redistribution) 
+      !------------------------------------------------------------------------------!
+      DO_2D( 1, 0, 1, 0 )
+
+         ! shear at F points
+         zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+            &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+            &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+      END_2D
+      
+      DO_2D( 0, 0, 0, 0 )
+         
+         ! tension**2 at T points
+         zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+            &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+            &   ) * r1_e1e2t(ji,jj)
+         zdt2 = zdt * zdt
+         
+         zten_i(ji,jj) = zdt
+
+         ! shear**2 at T points (doc eq. A16)
+         zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+            &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+            &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+         
+         ! shear at T points
+         pshear_i(ji,jj) = SQRT( zdt2 + zds2 )
+
+         ! divergence at T points
+         pdivu_i(ji,jj) = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+            &             + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+            &             ) * r1_e1e2t(ji,jj)
+         
+         ! delta at T points
+         zfac            = SQRT( pdivu_i(ji,jj) * pdivu_i(ji,jj) + ( zdt2 + zds2 ) * z1_ecc2 ) ! delta  
+         rswitch         = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zfac ) ) ! 0 if delta=0
+         pdelta_i(ji,jj) = zfac + rn_creepl * rswitch ! delta+creepl
+
+      END_2D
+      CALL lbc_lnk_multi( 'icedyn_rhg_eap', pshear_i, 'T', 1.0_wp, pdivu_i, 'T', 1.0_wp, pdelta_i, 'T', 1.0_wp, &
+         &                                    zten_i, 'T', 1.0_wp, zs1    , 'T', 1.0_wp, zs2     , 'T', 1.0_wp, &
+         &                                      zs12, 'F', 1.0_wp )
+      
+      ! --- Store the stress tensor for the next time step --- !
+      pstress1_i (:,:) = zs1 (:,:)
+      pstress2_i (:,:) = zs2 (:,:)
+      pstress12_i(:,:) = zs12(:,:)
+      !
+
+      !------------------------------------------------------------------------------!
+      ! 5) diagnostics
+      !------------------------------------------------------------------------------!
+      ! --- ice-ocean, ice-atm. & ice-oceanbottom(landfast) stresses --- !
+      IF(  iom_use('utau_oi') .OR. iom_use('vtau_oi') .OR. iom_use('utau_ai') .OR. iom_use('vtau_ai') .OR. &
+         & iom_use('utau_bi') .OR. iom_use('vtau_bi') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', ztaux_oi, 'U', -1.0_wp, ztauy_oi, 'V', -1.0_wp, ztaux_ai, 'U', -1.0_wp, &
+            &                                  ztauy_ai, 'V', -1.0_wp, ztaux_bi, 'U', -1.0_wp, ztauy_bi, 'V', -1.0_wp )
+         !
+         CALL iom_put( 'utau_oi' , ztaux_oi * zmsk00 )
+         CALL iom_put( 'vtau_oi' , ztauy_oi * zmsk00 )
+         CALL iom_put( 'utau_ai' , ztaux_ai * zmsk00 )
+         CALL iom_put( 'vtau_ai' , ztauy_ai * zmsk00 )
+         CALL iom_put( 'utau_bi' , ztaux_bi * zmsk00 )
+         CALL iom_put( 'vtau_bi' , ztauy_bi * zmsk00 )
+      ENDIF
+       
+      ! --- divergence, shear and strength --- !
+      IF( iom_use('icediv') )   CALL iom_put( 'icediv' , pdivu_i  * zmsk00 )   ! divergence
+      IF( iom_use('iceshe') )   CALL iom_put( 'iceshe' , pshear_i * zmsk00 )   ! shear
+      IF( iom_use('icedlt') )   CALL iom_put( 'icedlt' , pdelta_i * zmsk00 )   ! delta
+      IF( iom_use('icestr') )   CALL iom_put( 'icestr' , strength * zmsk00 )   ! strength
+
+      ! --- Stress tensor invariants (SIMIP diags) --- !
+      IF( iom_use('normstr') .OR. iom_use('sheastr') ) THEN
+         !
+         ALLOCATE( zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )
+         !         
+         DO_2D( 1, 1, 1, 1 )
+         
+            ! Ice stresses
+            ! sigma1, sigma2, sigma12 are some useful recombination of the stresses (Hunke and Dukowicz MWR 2002, Bouillon et al., OM2013)
+            ! These are NOT stress tensor components, neither stress invariants, neither stress principal components
+            ! I know, this can be confusing...
+            zfac             =   strength(ji,jj) / ( pdelta_i(ji,jj) + rn_creepl ) 
+            zsig1            =   zfac * ( pdivu_i(ji,jj) - pdelta_i(ji,jj) )
+            zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+            zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            
+            ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008)
+            zsig_I (ji,jj)   =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+            zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+            
+         END_2D
+         !
+         ! Stress tensor invariants (normal and shear stress N/m) - SIMIP diags - definitions following Coon (1974) and Feltham (2008)
+         IF( iom_use('normstr') )   CALL iom_put( 'normstr', zsig_I (:,:) * zmsk00(:,:) ) ! Normal stress
+         IF( iom_use('sheastr') )   CALL iom_put( 'sheastr', zsig_II(:,:) * zmsk00(:,:) ) ! Maximum shear stress
+         
+         DEALLOCATE ( zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- Normalized stress tensor principal components --- !
+      ! This are used to plot the normalized yield curve, see Lemieux & Dupont, 2020
+      ! Recommendation 1 : we use ice strength, not replacement pressure
+      ! Recommendation 2 : need to use deformations at PREVIOUS iterate for viscosities
+      IF( iom_use('sig1_pnorm') .OR. iom_use('sig2_pnorm') ) THEN
+         !
+         ALLOCATE( zsig1_p(jpi,jpj) , zsig2_p(jpi,jpj) , zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )         
+         !         
+         DO_2D( 1, 1, 1, 1 )
+         
+            ! Ice stresses computed with **viscosities** (delta, p/delta) at **previous** iterates 
+            !                        and **deformations** at current iterates
+            !                        following Lemieux & Dupont (2020)
+            zfac             =   zp_delt(ji,jj)
+            zsig1            =   zfac * ( pdivu_i(ji,jj) - ( zdelta(ji,jj) + rn_creepl ) )
+            zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+            zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            
+            ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008), T-point
+            zsig_I(ji,jj)    =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+            zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+   
+            ! Normalized  principal stresses (used to display the ellipse)
+            z1_strength      =   1._wp / MAX( 1._wp, strength(ji,jj) )
+            zsig1_p(ji,jj)   =   ( zsig_I(ji,jj) + zsig_II(ji,jj) ) * z1_strength
+            zsig2_p(ji,jj)   =   ( zsig_I(ji,jj) - zsig_II(ji,jj) ) * z1_strength
+         END_2D
+         !
+         CALL iom_put( 'sig1_pnorm' , zsig1_p ) 
+         CALL iom_put( 'sig2_pnorm' , zsig2_p ) 
+      
+         DEALLOCATE( zsig1_p , zsig2_p , zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- yieldcurve --- !
+      IF( iom_use('yield11') .OR. iom_use('yield12') .OR. iom_use('yield22')) THEN
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zyield11, 'T', 1.0_wp, zyield22, 'T', 1.0_wp, zyield12, 'T', 1.0_wp )
+
+         CALL iom_put( 'yield11', zyield11 * zmsk00 )
+         CALL iom_put( 'yield22', zyield22 * zmsk00 )
+         CALL iom_put( 'yield12', zyield12 * zmsk00 )
+      ENDIF
+
+      ! --- anisotropy tensor --- !
+      IF( iom_use('aniso') ) THEN       
+         CALL lbc_lnk( 'icedyn_rhg_eap', paniso_11, 'T', 1.0_wp ) 
+         CALL iom_put( 'aniso' , paniso_11 * zmsk00 )
+      ENDIF
+      
+      ! --- SIMIP --- !
+      IF(  iom_use('dssh_dx') .OR. iom_use('dssh_dy') .OR. &
+         & iom_use('corstrx') .OR. iom_use('corstry') .OR. iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zspgU, 'U', -1.0_wp, zspgV, 'V', -1.0_wp, &
+            &                                  zCorU, 'U', -1.0_wp, zCorV, 'V', -1.0_wp, &
+            &                                    zfU, 'U', -1.0_wp,   zfV, 'V', -1.0_wp )
+
+         CALL iom_put( 'dssh_dx' , zspgU * zmsk00 )   ! Sea-surface tilt term in force balance (x)
+         CALL iom_put( 'dssh_dy' , zspgV * zmsk00 )   ! Sea-surface tilt term in force balance (y)
+         CALL iom_put( 'corstrx' , zCorU * zmsk00 )   ! Coriolis force term in force balance (x)
+         CALL iom_put( 'corstry' , zCorV * zmsk00 )   ! Coriolis force term in force balance (y)
+         CALL iom_put( 'intstrx' , zfU   * zmsk00 )   ! Internal force term in force balance (x)
+         CALL iom_put( 'intstry' , zfV   * zmsk00 )   ! Internal force term in force balance (y)
+      ENDIF
+
+      IF(  iom_use('xmtrpice') .OR. iom_use('ymtrpice') .OR. &
+         & iom_use('xmtrpsnw') .OR. iom_use('ymtrpsnw') .OR. iom_use('xatrp') .OR. iom_use('yatrp') ) THEN
+         !
+         ALLOCATE( zdiag_xmtrp_ice(jpi,jpj) , zdiag_ymtrp_ice(jpi,jpj) , &
+            &      zdiag_xmtrp_snw(jpi,jpj) , zdiag_ymtrp_snw(jpi,jpj) , zdiag_xatrp(jpi,jpj) , zdiag_yatrp(jpi,jpj) )
+         !
+         DO_2D( 0, 0, 0, 0 )
+            ! 2D ice mass, snow mass, area transport arrays (X, Y)
+            zfac_x = 0.5 * u_ice(ji,jj) * e2u(ji,jj) * zmsk00(ji,jj)
+            zfac_y = 0.5 * v_ice(ji,jj) * e1v(ji,jj) * zmsk00(ji,jj)
+
+            zdiag_xmtrp_ice(ji,jj) = rhoi * zfac_x * ( vt_i(ji+1,jj) + vt_i(ji,jj) ) ! ice mass transport, X-component
+            zdiag_ymtrp_ice(ji,jj) = rhoi * zfac_y * ( vt_i(ji,jj+1) + vt_i(ji,jj) ) !        ''           Y-   ''
+
+            zdiag_xmtrp_snw(ji,jj) = rhos * zfac_x * ( vt_s(ji+1,jj) + vt_s(ji,jj) ) ! snow mass transport, X-component
+            zdiag_ymtrp_snw(ji,jj) = rhos * zfac_y * ( vt_s(ji,jj+1) + vt_s(ji,jj) ) !          ''          Y-   ''
+
+            zdiag_xatrp(ji,jj)     = zfac_x * ( at_i(ji+1,jj) + at_i(ji,jj) )        ! area transport,      X-component
+            zdiag_yatrp(ji,jj)     = zfac_y * ( at_i(ji,jj+1) + at_i(ji,jj) )        !        ''            Y-   ''
+
+         END_2D
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_eap', zdiag_xmtrp_ice, 'U', -1.0_wp, zdiag_ymtrp_ice, 'V', -1.0_wp, &
+            &                                  zdiag_xmtrp_snw, 'U', -1.0_wp, zdiag_ymtrp_snw, 'V', -1.0_wp, &
+            &                                  zdiag_xatrp    , 'U', -1.0_wp, zdiag_yatrp    , 'V', -1.0_wp )
+
+         CALL iom_put( 'xmtrpice' , zdiag_xmtrp_ice )   ! X-component of sea-ice mass transport (kg/s)
+         CALL iom_put( 'ymtrpice' , zdiag_ymtrp_ice )   ! Y-component of sea-ice mass transport 
+         CALL iom_put( 'xmtrpsnw' , zdiag_xmtrp_snw )   ! X-component of snow mass transport (kg/s)
+         CALL iom_put( 'ymtrpsnw' , zdiag_ymtrp_snw )   ! Y-component of snow mass transport
+         CALL iom_put( 'xatrp'    , zdiag_xatrp     )   ! X-component of ice area transport
+         CALL iom_put( 'yatrp'    , zdiag_yatrp     )   ! Y-component of ice area transport
+
+         DEALLOCATE( zdiag_xmtrp_ice , zdiag_ymtrp_ice , &
+            &        zdiag_xmtrp_snw , zdiag_ymtrp_snw , zdiag_xatrp , zdiag_yatrp )
+
+      ENDIF
+      !
+      ! --- convergence tests --- !
+      IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2 ) THEN
+         IF( iom_use('uice_cvg') ) THEN
+            IF( ln_aEVP ) THEN   ! output: beta * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * zbeta(:,:) * umask(:,:,1) , &
+                  &                           ABS( v_ice(:,:) - zv_ice(:,:) ) * zbeta(:,:) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ELSE                 ! output: nn_nevp * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', REAL( nn_nevp ) * MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * umask(:,:,1) , &
+                  &                                             ABS( v_ice(:,:) - zv_ice(:,:) ) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ENDIF
+         ENDIF
+      ENDIF      
+      !
+      DEALLOCATE( zmsk00, zmsk15 )
+      !
+   END SUBROUTINE ice_dyn_rhg_eap
+
+   
+   SUBROUTINE rhg_cvg( kt, kiter, kitermax, pu, pv, pub, pvb )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE rhg_cvg  ***
+      !!                     
+      !! ** Purpose :   check convergence of oce rheology
+      !!
+      !! ** Method  :   create a file ice_cvg.nc containing the convergence of ice velocity
+      !!                during the sub timestepping of rheology so as:
+      !!                  uice_cvg = MAX( u(t+1) - u(t) , v(t+1) - v(t) )
+      !!                This routine is called every sub-iteration, so it is cpu expensive
+      !!
+      !! ** Note    :   for the first sub-iteration, uice_cvg is set to 0 (too large otherwise)   
+      !!----------------------------------------------------------------------
+      INTEGER ,                 INTENT(in) ::   kt, kiter, kitermax       ! ocean time-step index
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pu, pv, pub, pvb          ! now and before velocities
+      !!
+      INTEGER           ::   it, idtime, istatus
+      INTEGER           ::   ji, jj          ! dummy loop indices
+      REAL(wp)          ::   zresm           ! local real 
+      CHARACTER(len=20) ::   clname
+      REAL(wp), DIMENSION(jpi,jpj) ::   zres           ! check convergence
+      !!----------------------------------------------------------------------
+
+      ! create file
+      IF( kt == nit000 .AND. kiter == 1 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'rhg_cvg : ice rheology convergence control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !
+         IF( lwm ) THEN
+            clname = 'ice_cvg.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, ncvgid )
+            istatus = NF90_DEF_DIM( ncvgid, 'time'  , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( ncvgid, 'uice_cvg', NF90_DOUBLE   , (/ idtime /), nvarid )
+            istatus = NF90_ENDDEF(ncvgid)
+         ENDIF
+         !
+      ENDIF
+
+      ! time
+      it = ( kt - 1 ) * kitermax + kiter
+      
+      ! convergence
+      IF( kiter == 1 ) THEN ! remove the first iteration for calculations of convergence (always very large)
+         zresm = 0._wp
+      ELSE
+         DO_2D( 1, 1, 1, 1 )
+            zres(ji,jj) = MAX( ABS( pu(ji,jj) - pub(ji,jj) ) * umask(ji,jj,1), &
+               &               ABS( pv(ji,jj) - pvb(ji,jj) ) * vmask(ji,jj,1) ) * zmsk15(ji,jj)
+         END_2D
+
+         ! cut of the boundary of the box (forced velocities)
+         IF (mjg(jj)<=30 .or. mjg(jj)>970 .or. mig(ji)<=30 .or. mig(ji)>970) THEN
+            zres(ji,jj) = 0._wp
+         END IF
+         zresm = MAXVAL( zres )
+         CALL mpp_max( 'icedyn_rhg_evp', zresm )   ! max over the global domain
+      ENDIF
+
+      IF( lwm ) THEN
+         ! write variables
+         istatus = NF90_PUT_VAR( ncvgid, nvarid, (/zresm/), (/it/), (/1/) )
+         ! close file
+         IF( kt == nitend )   istatus = NF90_CLOSE(ncvgid)
+      ENDIF
+      
+   END SUBROUTINE rhg_cvg
+
+
+   SUBROUTINE update_stress_rdg( ksub, kndte, pdivu, ptension, pshear, pa11, pa12, &
+      &                          pstressp,  pstressm, pstress12, pstrength, palphar, palphas )
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE update_stress_rdg  ***
+      !!                     
+      !! ** Purpose :   Updates the stress depending on values of strain rate and structure
+      !!                tensor and for the last subcycle step it computes closing and sliding rate
+      !!---------------------------------------------------------------------
+      INTEGER,  INTENT(in   ) ::   ksub, kndte
+      REAL(wp), INTENT(in   ) ::   pstrength
+      REAL(wp), INTENT(in   ) ::   pdivu, ptension, pshear
+      REAL(wp), INTENT(in   ) ::   pa11, pa12
+      REAL(wp), INTENT(  out) ::   pstressp, pstressm, pstress12
+      REAL(wp), INTENT(  out) ::   palphar, palphas
+
+      INTEGER  ::   kx ,ky, ka
+
+      REAL(wp) ::   zstemp11r, zstemp12r, zstemp22r   
+      REAL(wp) ::   zstemp11s, zstemp12s, zstemp22s 
+      REAL(wp) ::   za22, zQd11Qd11, zQd11Qd12, zQd12Qd12 
+      REAL(wp) ::   zQ11Q11, zQ11Q12, zQ12Q12 
+      REAL(wp) ::   zdtemp11, zdtemp12, zdtemp22 
+      REAL(wp) ::   zrotstemp11r, zrotstemp12r, zrotstemp22r   
+      REAL(wp) ::   zrotstemp11s, zrotstemp12s, zrotstemp22s
+      REAL(wp) ::   zsig11, zsig12, zsig22 
+      REAL(wp) ::   zsgprm11, zsgprm12, zsgprm22 
+      REAL(wp) ::   zinvstressconviso 
+      REAL(wp) ::   zAngle_denom_gamma,  zAngle_denom_alpha 
+      REAL(wp) ::   zTany_1, zTany_2 
+      REAL(wp) ::   zx, zy, zdx, zdy, zda, zkxw, kyw, kaw
+      REAL(wp) ::   zinvdx, zinvdy, zinvda   
+      REAL(wp) ::   zdtemp1, zdtemp2, zatempprime, zinvsin
+
+      REAL(wp), PARAMETER ::   kfriction = 0.45_wp
+      !!---------------------------------------------------------------------
+      ! Factor to maintain the same stress as in EVP (see Section 3)
+      ! Can be set to 1 otherwise
+!      zinvstressconviso = 1._wp/(1._wp+kfriction*kfriction)
+      zinvstressconviso = 1._wp
+ 
+      zinvsin = 1._wp/sin(2._wp*pphi) * zinvstressconviso 
+      !now uses phi as set in higher code
+       
+      ! compute eigenvalues, eigenvectors and angles for structure tensor, strain
+      ! rates
+
+      ! 1) structure tensor
+      za22 = 1._wp-pa11
+      zQ11Q11 = 1._wp
+      zQ12Q12 = rsmall
+      zQ11Q12 = rsmall
+ 
+      ! gamma: angle between general coordiantes and principal axis of A 
+      ! here Tan2gamma = 2 a12 / (a11 - a22) 
+      IF((ABS(pa11 - za22) > rsmall).OR.(ABS(pa12) > rsmall)) THEN      
+         zAngle_denom_gamma = 1._wp/sqrt( ( pa11 - za22 )*( pa11 - za22) + &
+                              4._wp*pa12*pa12 )
+   
+         zQ11Q11 = 0.5_wp + ( pa11 - za22 )*0.5_wp*zAngle_denom_gamma   !Cos^2 
+         zQ12Q12 = 0.5_wp - ( pa11 - za22 )*0.5_wp*zAngle_denom_gamma   !Sin^2
+         zQ11Q12 = pa12*zAngle_denom_gamma                     !CosSin 
+      ENDIF
+ 
+      ! rotation Q*atemp*Q^T
+      zatempprime = zQ11Q11*pa11 + 2.0_wp*zQ11Q12*pa12 + zQ12Q12*za22 
+      
+      ! make first principal value the largest
+      zatempprime = max(zatempprime, 1.0_wp - zatempprime)
+ 
+      ! 2) strain rate
+      zdtemp11 = 0.5_wp*(pdivu + ptension)
+      zdtemp12 = pshear*0.5_wp
+      zdtemp22 = 0.5_wp*(pdivu - ptension)
+
+      ! here Tan2alpha = 2 dtemp12 / (dtemp11 - dtemp22) 
+
+      zQd11Qd11 = 1.0_wp
+      zQd12Qd12 = rsmall
+      zQd11Qd12 = rsmall
+
+      IF((ABS( zdtemp11 - zdtemp22) > rsmall).OR. (ABS(zdtemp12) > rsmall)) THEN
+
+         zAngle_denom_alpha = 1.0_wp/sqrt( ( zdtemp11 - zdtemp22 )* &
+                             ( zdtemp11 - zdtemp22 ) + 4.0_wp*zdtemp12*zdtemp12)
+
+         zQd11Qd11 = 0.5_wp + ( zdtemp11 - zdtemp22 )*0.5_wp*zAngle_denom_alpha !Cos^2 
+         zQd12Qd12 = 0.5_wp - ( zdtemp11 - zdtemp22 )*0.5_wp*zAngle_denom_alpha !Sin^2
+         zQd11Qd12 = zdtemp12*zAngle_denom_alpha !CosSin
+      ENDIF
+
+      zdtemp1 = zQd11Qd11*zdtemp11 + 2.0_wp*zQd11Qd12*zdtemp12 + zQd12Qd12*zdtemp22
+      zdtemp2 = zQd12Qd12*zdtemp11 - 2.0_wp*zQd11Qd12*zdtemp12 + zQd11Qd11*zdtemp22
+      ! In cos and sin values
+      zx = 0._wp
+      IF ((ABS(zdtemp1) > rsmall).OR.(ABS(zdtemp2) > rsmall)) THEN
+         zx = atan2(zdtemp2,zdtemp1)
+      ENDIF      
+               
+      ! to ensure the angle lies between pi/4 and 9 pi/4 
+      IF (zx < rpi*0.25_wp) zx = zx + rpi*2.0_wp
+      
+      ! y: angle between major principal axis of strain rate and structure
+      ! tensor
+      ! y = gamma - alpha 
+      ! Expressesed componently with
+      ! Tany = (Singamma*Cosgamma - Sinalpha*Cosgamma)/(Cos^2gamma - Sin^alpha)
+      
+      zTany_1 = zQ11Q12 - zQd11Qd12
+      zTany_2 = zQ11Q11 - zQd12Qd12
+      
+      zy = 0._wp
+      
+      IF ((ABS(zTany_1) > rsmall).OR.(ABS(zTany_2) > rsmall)) THEN
+         zy = atan2(zTany_1,zTany_2)
+      ENDIF
+      
+      ! to make sure y is between 0 and pi
+      IF (zy > rpi) zy = zy - rpi
+      IF (zy < 0)  zy = zy + rpi
+
+      ! 3) update anisotropic stress tensor 
+      zdx   = rpi/real(nx_yield-1,kind=wp)
+      zdy   = rpi/real(ny_yield-1,kind=wp)
+      zda   = 0.5_wp/real(na_yield-1,kind=wp)
+      zinvdx = 1._wp/zdx
+      zinvdy = 1._wp/zdy
+      zinvda = 1._wp/zda
+
+      ! % need 8 coords and 8 weights
+      ! % range in kx
+      kx  = int((zx-rpi*0.25_wp-rpi)*zinvdx) + 1
+      !!clem kx  = MAX( 1, MIN( nx_yield-1, INT((zx-rpi*0.25_wp-rpi)*zinvdx) + 1  ) )
+      zkxw = kx - (zx-rpi*0.25_wp-rpi)*zinvdx  
+      
+      ky  = int(zy*zinvdy) + 1
+      !!clem ky  = MAX( 1, MIN( ny_yield-1, INT(zy*zinvdy) + 1 ) )
+      kyw = ky - zy*zinvdy 
+      
+      ka  = int((zatempprime-0.5_wp)*zinvda) + 1
+      !!clem ka  = MAX( 1, MIN( na_yield-1, INT((zatempprime-0.5_wp)*zinvda) + 1 ) )
+      kaw = ka - (zatempprime-0.5_wp)*zinvda
+      
+      ! % Determine sigma_r(A1,Zeta,y) and sigma_s (see Section A1 of Tsamados 2013)
+!!$      zstemp11r =  zkxw  * kyw         * kaw         * s11r(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s11r(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s11r(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s11r(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s11r(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s11r(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s11r(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s11r(kx+1,ky+1,ka+1)
+!!$      zstemp12r =  zkxw  * kyw         * kaw         * s12r(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s12r(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s12r(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s12r(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s12r(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s12r(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s12r(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s12r(kx+1,ky+1,ka+1)
+!!$      zstemp22r =  zkxw  * kyw         * kaw         * s22r(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s22r(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s22r(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s22r(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s22r(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s22r(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s22r(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s22r(kx+1,ky+1,ka+1)
+!!$      
+!!$      zstemp11s =  zkxw  * kyw         * kaw         * s11s(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s11s(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s11s(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s11s(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s11s(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s11s(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s11s(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s11s(kx+1,ky+1,ka+1)
+!!$      zstemp12s =  zkxw  * kyw         * kaw         * s12s(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s12s(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s12s(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s12s(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s12s(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s12s(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s12s(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s12s(kx+1,ky+1,ka+1)
+!!$      zstemp22s =  zkxw  * kyw         * kaw         * s22s(kx  ,ky  ,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * kaw         * s22s(kx+1,ky  ,ka  ) &
+!!$        & + zkxw         * (1._wp-kyw) * kaw         * s22s(kx  ,ky+1,ka  ) &
+!!$        & + zkxw         * kyw         * (1._wp-kaw) * s22s(kx  ,ky  ,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * kaw         * s22s(kx+1,ky+1,ka  ) &
+!!$        & + (1._wp-zkxw) * kyw         * (1._wp-kaw) * s22s(kx+1,ky  ,ka+1) &
+!!$        & + zkxw         * (1._wp-kyw) * (1._wp-kaw) * s22s(kx  ,ky+1,ka+1) &
+!!$        & + (1._wp-zkxw) * (1._wp-kyw) * (1._wp-kaw) * s22s(kx+1,ky+1,ka+1)
+
+      zstemp11r = s11r(kx,ky,ka)
+      zstemp12r = s12r(kx,ky,ka)
+      zstemp22r = s22r(kx,ky,ka)
+      zstemp11s = s11s(kx,ky,ka)
+      zstemp12s = s12s(kx,ky,ka)
+      zstemp22s = s22s(kx,ky,ka)
+      
+      
+      ! Calculate mean ice stress over a collection of floes (Equation 3 in
+      ! Tsamados 2013)
+
+      zsig11  = pstrength*(zstemp11r + kfriction*zstemp11s) * zinvsin
+      zsig12  = pstrength*(zstemp12r + kfriction*zstemp12s) * zinvsin
+      zsig22  = pstrength*(zstemp22r + kfriction*zstemp22s) * zinvsin
+
+      ! Back - rotation of the stress from principal axes into general coordinates
+
+      ! Update stress
+      zsgprm11 = zQ11Q11*zsig11 + zQ12Q12*zsig22 -      2._wp*zQ11Q12 *zsig12
+      zsgprm12 = zQ11Q12*zsig11 - zQ11Q12*zsig22 + (zQ11Q11 - zQ12Q12)*zsig12
+      zsgprm22 = zQ12Q12*zsig11 + zQ11Q11*zsig22 +      2._wp*zQ11Q12 *zsig12
+
+      pstressp  = zsgprm11 + zsgprm22
+      pstress12 = zsgprm12
+      pstressm  = zsgprm11 - zsgprm22
+
+      ! Compute ridging and sliding functions in general coordinates 
+      ! (Equation 11 in Tsamados 2013)
+      IF (ksub == kndte) THEN
+         zrotstemp11r = zQ11Q11*zstemp11r - 2._wp*zQ11Q12* zstemp12r &
+                      + zQ12Q12*zstemp22r
+         zrotstemp12r = zQ11Q11*zstemp12r +       zQ11Q12*(zstemp11r-zstemp22r) &
+                      - zQ12Q12*zstemp12r
+         zrotstemp22r = zQ12Q12*zstemp11r + 2._wp*zQ11Q12* zstemp12r & 
+                      + zQ11Q11*zstemp22r
+
+         zrotstemp11s = zQ11Q11*zstemp11s - 2._wp*zQ11Q12* zstemp12s &
+                      + zQ12Q12*zstemp22s
+         zrotstemp12s = zQ11Q11*zstemp12s +       zQ11Q12*(zstemp11s-zstemp22s) &
+                      - zQ12Q12*zstemp12s
+         zrotstemp22s = zQ12Q12*zstemp11s + 2._wp*zQ11Q12* zstemp12s & 
+                      + zQ11Q11*zstemp22s
+
+         palphar =  zrotstemp11r*zdtemp11 + 2._wp*zrotstemp12r*zdtemp12 &
+                  + zrotstemp22r*zdtemp22
+         palphas =  zrotstemp11s*zdtemp11 + 2._wp*zrotstemp12s*zdtemp12 &
+                  + zrotstemp22s*zdtemp22
+      ENDIF
+   END SUBROUTINE update_stress_rdg 
+
+!=======================================================================
+
+
+   SUBROUTINE calc_ffrac( pstressp, pstressm, pstress12, pa11, pa12, &
+      &                   pmresult11, pmresult12 )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE calc_ffrac  ***
+      !!                     
+      !! ** Purpose :   Computes term in evolution equation for structure tensor
+      !!                which determines the ice floe re-orientation due to fracture
+      !! ** Method :    Eq. 7: Ffrac = -kf(A-S) or = 0 depending on sigma_1 and sigma_2
+      !!---------------------------------------------------------------------
+      REAL (wp), INTENT(in)  ::   pstressp, pstressm, pstress12, pa11, pa12
+      REAL (wp), INTENT(out) ::   pmresult11, pmresult12
+
+      ! local variables
+
+      REAL (wp) ::   zsigma11, zsigma12, zsigma22  ! stress tensor elements
+      REAL (wp) ::   zAngle_denom        ! angle with principal component axis
+      REAL (wp) ::   zsigma_1, zsigma_2   ! principal components of stress
+      REAL (wp) ::   zQ11, zQ12, zQ11Q11, zQ11Q12, zQ12Q12
+
+!!$      REAL (wp), PARAMETER ::   kfrac = 0.0001_wp   ! rate of fracture formation 
+      REAL (wp), PARAMETER ::   kfrac = 1.e-3_wp   ! rate of fracture formation 
+      REAL (wp), PARAMETER ::   threshold = 0.3_wp  ! critical confinement ratio 
+      !!---------------------------------------------------------------
+      !
+      zsigma11 = 0.5_wp*(pstressp+pstressm) 
+      zsigma12 = pstress12 
+      zsigma22 = 0.5_wp*(pstressp-pstressm) 
+
+      ! Here's the change - no longer calculate gamma,
+      ! use trig formulation, angle signs are kept correct, don't worry
+   
+      ! rotate tensor to get into sigma principal axis
+   
+      ! here Tan2gamma = 2 sig12 / (sig11 - sig12) 
+      ! add rsmall to the denominator to stop 1/0 errors, makes very little 
+      ! error to the calculated angles < rsmall
+
+      zQ11Q11 = 0.1_wp
+      zQ12Q12 = rsmall
+      zQ11Q12 = rsmall
+
+      IF((ABS( zsigma11 - zsigma22) > rsmall).OR.(ABS(zsigma12) > rsmall)) THEN
+
+         zAngle_denom = 1.0_wp/sqrt( ( zsigma11 - zsigma22 )*( zsigma11 - &
+                       zsigma22 ) + 4.0_wp*zsigma12*zsigma12)
+
+         zQ11Q11 = 0.5_wp + ( zsigma11 - zsigma22 )*0.5_wp*zAngle_denom   !Cos^2 
+         zQ12Q12 = 0.5_wp - ( zsigma11 - zsigma22 )*0.5_wp*zAngle_denom   !Sin^2
+         zQ11Q12 = zsigma12*zAngle_denom                      !CosSin 
+      ENDIF
+
+      zsigma_1 = zQ11Q11*zsigma11 + 2.0_wp*zQ11Q12*zsigma12 + zQ12Q12*zsigma22 ! S(1,1)
+      zsigma_2 = zQ12Q12*zsigma11 - 2.0_wp*zQ11Q12*zsigma12 + zQ11Q11*zsigma22 ! S(2,2)
+
+      ! Pure divergence
+      IF ((zsigma_1 >= 0.0_wp).AND.(zsigma_2 >= 0.0_wp))  THEN
+         pmresult11 = 0.0_wp
+         pmresult12 = 0.0_wp
+
+      ! Unconfined compression: cracking of blocks not along the axial splitting
+      ! direction
+      ! which leads to the loss of their shape, so we again model it through diffusion
+      ELSEIF ((zsigma_1 >= 0.0_wp).AND.(zsigma_2 < 0.0_wp))  THEN
+         pmresult11 = - kfrac * (pa11 - zQ12Q12)
+         pmresult12 = - kfrac * (pa12 + zQ11Q12)
+
+      ! Shear faulting
+      ELSEIF (zsigma_2 == 0.0_wp) THEN
+         pmresult11 = 0.0_wp
+         pmresult12 = 0.0_wp
+      ELSEIF ((zsigma_1 <= 0.0_wp).AND.(zsigma_1/zsigma_2 <= threshold)) THEN
+         pmresult11 = - kfrac * (pa11 - zQ12Q12)
+         pmresult12 = - kfrac * (pa12 + zQ11Q12)
+
+      ! Horizontal spalling
+      ELSE 
+         pmresult11 = 0.0_wp
+         pmresult12 = 0.0_wp
+      ENDIF
+
+   END SUBROUTINE calc_ffrac
+
+
+   SUBROUTINE rhg_eap_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rhg_eap_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write RHG file in restart file
+      !!      
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER  ::   iter                      ! local integer
+      INTEGER  ::   id1, id2, id3, id4, id5   ! local integers
+      INTEGER  ::   ix, iy, ip, iz, n, ia     ! local integers
+    
+      INTEGER, PARAMETER            ::    nz = 100
+      
+      REAL(wp) ::   ainit, xinit, yinit, pinit, zinit
+      REAL(wp) ::   da, dx, dy, dp, dz, a1
+
+      !!clem
+      REAL(wp) ::   zw1, zw2, zfac, ztemp
+      REAL(wp) ::   idx, idy, idz
+
+      REAL(wp), PARAMETER           ::   eps6 = 1.0e-6_wp
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialize
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            id1 = iom_varid( numrir, 'stress1_i' , ldstop = .FALSE. )
+            id2 = iom_varid( numrir, 'stress2_i' , ldstop = .FALSE. )
+            id3 = iom_varid( numrir, 'stress12_i', ldstop = .FALSE. )
+            id4 = iom_varid( numrir, 'aniso_11'  , ldstop = .FALSE. )
+            id5 = iom_varid( numrir, 'aniso_12'  , ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2, id3, id4, id5 ) > 0 ) THEN      ! fields exist
+               CALL iom_get( numrir, jpdom_auto, 'stress1_i' , stress1_i , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'stress2_i' , stress2_i , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'stress12_i', stress12_i, cd_type = 'F' )
+               CALL iom_get( numrir, jpdom_auto, 'aniso_11'  , aniso_11  , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'aniso_12'  , aniso_12  , cd_type = 'T' )
+            ELSE                                     ! start rheology from rest
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) '   ==>>>   previous run without rheology, set stresses to 0'
+               stress1_i (:,:) = 0._wp
+               stress2_i (:,:) = 0._wp
+               stress12_i(:,:) = 0._wp
+               aniso_11  (:,:) = 0.5_wp
+               aniso_12  (:,:) = 0._wp
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>>   start from rest: set stresses to 0'
+            stress1_i (:,:) = 0._wp
+            stress2_i (:,:) = 0._wp
+            stress12_i(:,:) = 0._wp
+            aniso_11  (:,:) = 0.5_wp
+            aniso_12  (:,:) = 0._wp
+         ENDIF
+         !
+
+         da = 0.5_wp/real(na_yield-1,kind=wp)
+         ainit = 0.5_wp - da
+         dx = rpi/real(nx_yield-1,kind=wp)
+         xinit = rpi + 0.25_wp*rpi - dx
+         dz = rpi/real(nz,kind=wp)
+         zinit = -rpi*0.5_wp
+         dy = rpi/real(ny_yield-1,kind=wp)
+         yinit = -dy
+
+         s11r(:,:,:) = 0._wp
+         s12r(:,:,:) = 0._wp
+         s22r(:,:,:) = 0._wp
+         s11s(:,:,:) = 0._wp
+         s12s(:,:,:) = 0._wp
+         s22s(:,:,:) = 0._wp
+
+!!$         DO ia=1,na_yield
+!!$            DO ix=1,nx_yield
+!!$               DO iy=1,ny_yield
+!!$                  s11r(ix,iy,ia) = 0._wp
+!!$                  s12r(ix,iy,ia) = 0._wp
+!!$                  s22r(ix,iy,ia) = 0._wp
+!!$                  s11s(ix,iy,ia) = 0._wp
+!!$                  s12s(ix,iy,ia) = 0._wp
+!!$                  s22s(ix,iy,ia) = 0._wp
+!!$                  IF (ia <= na_yield-1) THEN
+!!$                     DO iz=1,nz
+!!$                        s11r(ix,iy,ia) = s11r(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s11kr(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s12r(ix,iy,ia) = s12r(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s12kr(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s22r(ix,iy,ia) = s22r(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s22kr(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi) 
+!!$                        s11s(ix,iy,ia) = s11s(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s11ks(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s12s(ix,iy,ia) = s12s(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s12ks(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                        s22s(ix,iy,ia) = s22s(ix,iy,ia) + 1*w1(ainit+ia*da)* &
+!!$                           exp(-w2(ainit+ia*da)*(zinit+iz*dz)*(zinit+iz*dz))* &
+!!$                           s22ks(xinit+ix*dx,yinit+iy*dy,zinit+iz*dz)*dz/sin(2._wp*pphi)
+!!$                     ENDDO
+!!$                     IF (abs(s11r(ix,iy,ia)) < eps6) s11r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12r(ix,iy,ia)) < eps6) s12r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22r(ix,iy,ia)) < eps6) s22r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s11s(ix,iy,ia)) < eps6) s11s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12s(ix,iy,ia)) < eps6) s12s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22s(ix,iy,ia)) < eps6) s22s(ix,iy,ia) = 0._wp
+!!$                  ELSE
+!!$                     s11r(ix,iy,ia) = 0.5_wp*s11kr(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s12r(ix,iy,ia) = 0.5_wp*s12kr(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s22r(ix,iy,ia) = 0.5_wp*s22kr(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s11s(ix,iy,ia) = 0.5_wp*s11ks(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s12s(ix,iy,ia) = 0.5_wp*s12ks(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     s22s(ix,iy,ia) = 0.5_wp*s22ks(xinit+ix*dx,yinit+iy*dy,0._wp)/sin(2._wp*pphi)
+!!$                     IF (abs(s11r(ix,iy,ia)) < eps6) s11r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12r(ix,iy,ia)) < eps6) s12r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22r(ix,iy,ia)) < eps6) s22r(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s11s(ix,iy,ia)) < eps6) s11s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s12s(ix,iy,ia)) < eps6) s12s(ix,iy,ia) = 0._wp
+!!$                     IF (abs(s22s(ix,iy,ia)) < eps6) s22s(ix,iy,ia) = 0._wp
+!!$                  ENDIF
+!!$               ENDDO
+!!$            ENDDO
+!!$         ENDDO
+
+         !! faster but still very slow => to be improved         
+         zfac = dz/sin(2._wp*pphi)
+         DO ia = 1, na_yield-1
+            zw1 = w1(ainit+ia*da)
+            zw2 = w2(ainit+ia*da)
+            DO iz = 1, nz
+               idz = zinit+iz*dz
+               ztemp = zw1 * EXP(-zw2*(zinit+iz*dz)*(zinit+iz*dz))
+               DO iy = 1, ny_yield
+                  idy = yinit+iy*dy
+                  DO ix = 1, nx_yield
+                     idx = xinit+ix*dx
+                     s11r(ix,iy,ia) = s11r(ix,iy,ia) + ztemp * s11kr(idx,idy,idz)*zfac
+                     s12r(ix,iy,ia) = s12r(ix,iy,ia) + ztemp * s12kr(idx,idy,idz)*zfac
+                     s22r(ix,iy,ia) = s22r(ix,iy,ia) + ztemp * s22kr(idx,idy,idz)*zfac 
+                     s11s(ix,iy,ia) = s11s(ix,iy,ia) + ztemp * s11ks(idx,idy,idz)*zfac
+                     s12s(ix,iy,ia) = s12s(ix,iy,ia) + ztemp * s12ks(idx,idy,idz)*zfac
+                     s22s(ix,iy,ia) = s22s(ix,iy,ia) + ztemp * s22ks(idx,idy,idz)*zfac
+                  END DO
+               END DO
+            END DO
+         END DO
+
+         zfac = 1._wp/sin(2._wp*pphi)
+         ia = na_yield
+         DO iy = 1, ny_yield
+            idy = yinit+iy*dy
+            DO ix = 1, nx_yield
+               idx = xinit+ix*dx                  
+               s11r(ix,iy,ia) = 0.5_wp*s11kr(idx,idy,0._wp)*zfac
+               s12r(ix,iy,ia) = 0.5_wp*s12kr(idx,idy,0._wp)*zfac
+               s22r(ix,iy,ia) = 0.5_wp*s22kr(idx,idy,0._wp)*zfac
+               s11s(ix,iy,ia) = 0.5_wp*s11ks(idx,idy,0._wp)*zfac
+               s12s(ix,iy,ia) = 0.5_wp*s12ks(idx,idy,0._wp)*zfac
+               s22s(ix,iy,ia) = 0.5_wp*s22ks(idx,idy,0._wp)*zfac
+            ENDDO
+         ENDDO
+         WHERE (ABS(s11r(:,:,:)) < eps6) s11r(:,:,:) = 0._wp
+         WHERE (ABS(s12r(:,:,:)) < eps6) s12r(:,:,:) = 0._wp
+         WHERE (ABS(s22r(:,:,:)) < eps6) s22r(:,:,:) = 0._wp
+         WHERE (ABS(s11s(:,:,:)) < eps6) s11s(:,:,:) = 0._wp
+         WHERE (ABS(s12s(:,:,:)) < eps6) s12s(:,:,:) = 0._wp
+         WHERE (ABS(s22s(:,:,:)) < eps6) s22s(:,:,:) = 0._wp
+
+
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- rhg-rst ----'
+         iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         CALL iom_rstput( iter, nitrst, numriw, 'stress1_i' , stress1_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress2_i' , stress2_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress12_i', stress12_i )
+         CALL iom_rstput( iter, nitrst, numriw, 'aniso_11'  , aniso_11   )
+         CALL iom_rstput( iter, nitrst, numriw, 'aniso_12'  , aniso_12   )
+         !
+      ENDIF
+      !
+   END SUBROUTINE rhg_eap_rst
+
+
+   FUNCTION w1(pa)
+      !!-------------------------------------------------------------------
+      !! Function : w1 (see Gaussian function psi in Tsamados et al 2013)
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   pa
+      REAL(wp) ::   w1
+      !!-------------------------------------------------------------------
+   
+      w1 = -   223.87569446_wp &
+       &   +  2361.21986630_wp*pa &
+       &   - 10606.56079975_wp*pa*pa &
+       &   + 26315.50025642_wp*pa*pa*pa &
+       &   - 38948.30444297_wp*pa*pa*pa*pa &
+       &   + 34397.72407466_wp*pa*pa*pa*pa*pa &
+       &   - 16789.98003081_wp*pa*pa*pa*pa*pa*pa &
+       &   +  3495.82839237_wp*pa*pa*pa*pa*pa*pa*pa
+   
+   END FUNCTION w1
+
+
+   FUNCTION w2(pa)
+      !!-------------------------------------------------------------------
+      !! Function : w2 (see Gaussian function psi in Tsamados et al 2013)
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   pa
+      REAL(wp) ::   w2
+      !!-------------------------------------------------------------------
+   
+      w2 = -    6670.68911883_wp &
+       &   +   70222.33061536_wp*pa &
+       &   -  314871.71525448_wp*pa*pa &
+       &   +  779570.02793492_wp*pa*pa*pa &
+       &   - 1151098.82436864_wp*pa*pa*pa*pa &
+       &   + 1013896.59464498_wp*pa*pa*pa*pa*pa &
+       &   -  493379.44906738_wp*pa*pa*pa*pa*pa*pa &
+       &   +  102356.55151800_wp*pa*pa*pa*pa*pa*pa*pa
+   
+   END FUNCTION w2
+
+   FUNCTION s11kr(px,py,pz) 
+      !!-------------------------------------------------------------------
+      !! Function : s11kr
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+   
+      REAL(wp) ::   s11kr, zpih
+   
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+   
+      zpih = 0.5_wp*rpi
+   
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+   ! In expression of tensor d, with this formulatin d(x)=-d(x+pi)
+   ! Solution, when diagonalizing always check sgn(a11-a22) if > then keep x else
+   ! x=x-pi/2
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+   
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+   
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+   
+      s11kr = (- zHen1t2 * zn1t2i11 - zHen2t1 * zn2t1i11)
+
+   END FUNCTION s11kr
+
+   FUNCTION s12kr(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s12kr
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s12kr, zs12r0, zs21r0, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+   
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+   
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+   
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+   
+      zs12r0 = (- zHen1t2 * zn1t2i12 - zHen2t1 * zn2t1i12)
+      zs21r0 = (- zHen1t2 * zn1t2i21 - zHen2t1 * zn2t1i21)
+      s12kr=0.5_wp*(zs12r0+zs21r0)
+   
+   END FUNCTION s12kr
+
+   FUNCTION s22kr(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s22kr
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s22kr, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      s22kr = (- zHen1t2 * zn1t2i22 - zHen2t1 * zn2t1i22)
+
+   END FUNCTION s22kr
+
+   FUNCTION s11ks(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s11ks
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s11ks, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      s11ks = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i11 + zHen2t1 * zt2t1i11)
+
+   END FUNCTION s11ks
+
+   FUNCTION s12ks(px,py,pz)
+      !!-------------------------------------------------------------------
+      !! Function : s12ks
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s12ks, zs12s0, zs21s0, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      zs12s0 = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i12 + zHen2t1 * zt2t1i12)
+      zs21s0 = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i21 + zHen2t1 * zt2t1i21)
+      s12ks=0.5_wp*(zs12s0+zs21s0)
+
+   END FUNCTION s12ks
+
+   FUNCTION s22ks(px,py,pz) 
+      !!-------------------------------------------------------------------
+      !! Function : s22ks
+      !!-------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   px,py,pz
+
+      REAL(wp) ::   s22ks, zpih
+
+      REAL(wp) ::   zn1t2i11, zn1t2i12, zn1t2i21, zn1t2i22
+      REAL(wp) ::   zn2t1i11, zn2t1i12, zn2t1i21, zn2t1i22
+      REAL(wp) ::   zt1t2i11, zt1t2i12, zt1t2i21, zt1t2i22
+      REAL(wp) ::   zt2t1i11, zt2t1i12, zt2t1i21, zt2t1i22
+      REAL(wp) ::   zd11, zd12, zd22
+      REAL(wp) ::   zIIn1t2, zIIn2t1, zIIt1t2
+      REAL(wp) ::   zHen1t2, zHen2t1
+      !!-------------------------------------------------------------------
+      zpih = 0.5_wp*rpi
+
+      zn1t2i11 = cos(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i12 = cos(pz+zpih-pphi) * sin(pz+pphi)
+      zn1t2i21 = sin(pz+zpih-pphi) * cos(pz+pphi)
+      zn1t2i22 = sin(pz+zpih-pphi) * sin(pz+pphi)
+      zn2t1i11 = cos(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i12 = cos(pz-zpih+pphi) * sin(pz-pphi)
+      zn2t1i21 = sin(pz-zpih+pphi) * cos(pz-pphi)
+      zn2t1i22 = sin(pz-zpih+pphi) * sin(pz-pphi)
+      zt1t2i11 = cos(pz-pphi) * cos(pz+pphi)
+      zt1t2i12 = cos(pz-pphi) * sin(pz+pphi)
+      zt1t2i21 = sin(pz-pphi) * cos(pz+pphi)
+      zt1t2i22 = sin(pz-pphi) * sin(pz+pphi)
+      zt2t1i11 = cos(pz+pphi) * cos(pz-pphi)
+      zt2t1i12 = cos(pz+pphi) * sin(pz-pphi)
+      zt2t1i21 = sin(pz+pphi) * cos(pz-pphi)
+      zt2t1i22 = sin(pz+pphi) * sin(pz-pphi)
+      zd11 = cos(py)*cos(py)*(cos(px)+sin(px)*tan(py)*tan(py))
+      zd12 = cos(py)*cos(py)*tan(py)*(-cos(px)+sin(px))
+      zd22 = cos(py)*cos(py)*(sin(px)+cos(px)*tan(py)*tan(py))
+      zIIn1t2 = zn1t2i11 * zd11 + (zn1t2i12 + zn1t2i21) * zd12 + zn1t2i22 * zd22
+      zIIn2t1 = zn2t1i11 * zd11 + (zn2t1i12 + zn2t1i21) * zd12 + zn2t1i22 * zd22
+      zIIt1t2 = zt1t2i11 * zd11 + (zt1t2i12 + zt1t2i21) * zd12 + zt1t2i22 * zd22
+
+      IF (-zIIn1t2>=rsmall) THEN
+      zHen1t2 = 1._wp
+      ELSE
+      zHen1t2 = 0._wp
+      ENDIF
+
+      IF (-zIIn2t1>=rsmall) THEN
+      zHen2t1 = 1._wp
+      ELSE
+      zHen2t1 = 0._wp
+      ENDIF
+
+      s22ks = sign(1._wp,zIIt1t2+rsmall)*(zHen1t2 * zt1t2i22 + zHen2t1 * zt2t1i22)
+
+   END FUNCTION s22ks
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!==============================================================================
+END MODULE icedyn_rhg_eap
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/icedyn_rhg_evp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/icedyn_rhg_evp.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/icedyn_rhg_evp.F90	(revision 14055)
@@ -0,0 +1,1077 @@
+MODULE icedyn_rhg_evp
+   !!======================================================================
+   !!                     ***  MODULE  icedyn_rhg_evp  ***
+   !!   Sea-Ice dynamics : rheology Elasto-Viscous-Plastic
+   !!======================================================================
+   !! History :   -   !  2007-03  (M.A. Morales Maqueda, S. Bouillon) Original code
+   !!            3.0  !  2008-03  (M. Vancoppenolle) adaptation to new model
+   !!             -   !  2008-11  (M. Vancoppenolle, S. Bouillon, Y. Aksenov) add surface tilt in ice rheolohy 
+   !!            3.3  !  2009-05  (G.Garric)    addition of the evp case
+   !!            3.4  !  2011-01  (A. Porter)   dynamical allocation 
+   !!            3.5  !  2012-08  (R. Benshila) AGRIF
+   !!            3.6  !  2016-06  (C. Rousset)  Rewriting + landfast ice + mEVP (Bouillon 2013)
+   !!            3.7  !  2017     (C. Rousset)  add aEVP (Kimmritz 2016-2017)
+   !!            4.0  !  2018     (many people) SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_rhg_evp : computes ice velocities from EVP rheology
+   !!   rhg_evp_rst     : read/write EVP fields in ice restart
+   !!----------------------------------------------------------------------
+   USE phycst         ! Physical constant
+   USE dom_oce        ! Ocean domain
+   USE sbc_oce , ONLY : ln_ice_embd, nn_fsbc, ssh_m
+   USE sbc_ice , ONLY : utau_ice, vtau_ice, snwice_mass, snwice_mass_b
+   USE ice            ! sea-ice: ice variables
+   USE icevar         ! ice_var_sshdyn
+   USE icedyn_rdgrft  ! sea-ice: ice strength
+   USE bdy_oce , ONLY : ln_bdy 
+   USE bdyice 
+#if defined key_agrif
+   USE agrif_ice_interp
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE prtctl         ! Print control
+
+   USE netcdf         ! NetCDF library for convergence test
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rhg_evp   ! called by icedyn_rhg.F90
+   PUBLIC   rhg_evp_rst       ! called by icedyn_rhg.F90
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+#  include "domzgr_substitute.h90"
+
+   !! for convergence tests
+   INTEGER ::   ncvgid   ! netcdf file id
+   INTEGER ::   nvarid   ! netcdf variable id
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zmsk00, zmsk15
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id: icedyn_rhg_evp.F90 13612 2020-10-14 17:18:19Z clem $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_rhg_evp( kt, Kmm, pstress1_i, pstress2_i, pstress12_i, pshear_i, pdivu_i, pdelta_i )
+      !!-------------------------------------------------------------------
+      !!                 ***  SUBROUTINE ice_dyn_rhg_evp  ***
+      !!                             EVP-C-grid
+      !!
+      !! ** purpose : determines sea ice drift from wind stress, ice-ocean
+      !!  stress and sea-surface slope. Ice-ice interaction is described by 
+      !!  a non-linear elasto-viscous-plastic (EVP) law including shear 
+      !!  strength and a bulk rheology (Hunke and Dukowicz, 2002).	
+      !!
+      !!  The points in the C-grid look like this, dear reader
+      !!
+      !!                              (ji,jj)
+      !!                                 |
+      !!                                 |
+      !!                      (ji-1,jj)  |  (ji,jj)
+      !!                             ---------   
+      !!                            |         |
+      !!                            | (ji,jj) |------(ji,jj)
+      !!                            |         |
+      !!                             ---------   
+      !!                     (ji-1,jj-1)     (ji,jj-1)
+      !!
+      !! ** Inputs  : - wind forcing (stress), oceanic currents
+      !!                ice total volume (vt_i) per unit area
+      !!                snow total volume (vt_s) per unit area
+      !!
+      !! ** Action  : - compute u_ice, v_ice : the components of the 
+      !!                sea-ice velocity vector
+      !!              - compute delta_i, shear_i, divu_i, which are inputs
+      !!                of the ice thickness distribution
+      !!
+      !! ** Steps   : 0) compute mask at F point
+      !!              1) Compute ice snow mass, ice strength 
+      !!              2) Compute wind, oceanic stresses, mass terms and
+      !!                 coriolis terms of the momentum equation
+      !!              3) Solve the momentum equation (iterative procedure)
+      !!              4) Recompute delta, shear and divergence
+      !!                 (which are inputs of the ITD) & store stress
+      !!                 for the next time step
+      !!              5) Diagnostics including charge ellipse
+      !!
+      !! ** Notes   : There is the possibility to use aEVP from the nice work of Kimmritz et al. (2016 & 2017)
+      !!              by setting up ln_aEVP=T (i.e. changing alpha and beta parameters).
+      !!              This is an upgraded version of mEVP from Bouillon et al. 2013
+      !!              (i.e. more stable and better convergence)
+      !!
+      !! References : Hunke and Dukowicz, JPO97
+      !!              Bouillon et al., Ocean Modelling 2009
+      !!              Bouillon et al., Ocean Modelling 2013
+      !!              Kimmritz et al., Ocean Modelling 2016 & 2017
+      !!-------------------------------------------------------------------
+      INTEGER                 , INTENT(in   ) ::   kt                                    ! time step
+      INTEGER                 , INTENT(in   ) ::   Kmm                                   ! ocean time level index
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pstress1_i, pstress2_i, pstress12_i   !
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pshear_i  , pdivu_i   , pdelta_i      !
+      !!
+      INTEGER ::   ji, jj       ! dummy loop indices
+      INTEGER ::   jter         ! local integers
+      !
+      REAL(wp) ::   zrhoco                                              ! rho0 * rn_cio
+      REAL(wp) ::   zdtevp, z1_dtevp                                    ! time step for subcycling
+      REAL(wp) ::   ecc2, z1_ecc2                                       ! square of yield ellipse eccenticity
+      REAL(wp) ::   zalph1, z1_alph1, zalph2, z1_alph2                  ! alpha coef from Bouillon 2009 or Kimmritz 2017
+      REAl(wp) ::   zbetau, zbetav
+      REAL(wp) ::   zm1, zm2, zm3, zmassU, zmassV, zvU, zvV             ! ice/snow mass and volume
+      REAL(wp) ::   zp_delf, zds2, zdt, zdt2, zdiv, zdiv2               ! temporary scalars
+      REAL(wp) ::   zTauO, zTauB, zRHS, zvel                            ! temporary scalars
+      REAL(wp) ::   zkt                                                 ! isotropic tensile strength for landfast ice
+      REAL(wp) ::   zvCr                                                ! critical ice volume above which ice is landfast
+      !
+      REAL(wp) ::   zintb, zintn                                        ! dummy argument
+      REAL(wp) ::   zfac_x, zfac_y
+      REAL(wp) ::   zshear, zdum1, zdum2
+      REAL(wp) ::   zinvw                                                ! for test case
+
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdelta, zp_delt                 ! delta and P/delta at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zbeta                           ! beta coef from Kimmritz 2017
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdt_m                           ! (dt / ice-snow_mass) on T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zaU  , zaV                      ! ice fraction on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmU_t, zmV_t                    ! (ice-snow_mass / dt) on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmf                             ! coriolis parameter at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   v_oceU, u_oceV, v_iceU, u_iceV  ! ocean/ice u/v component on V/U points
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zds                             ! shear
+      REAL(wp), DIMENSION(jpi,jpj) ::   zten_i                          ! tension
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1, zs2, zs12                  ! stress tensor components
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsshdyn                         ! array used for the calculation of ice surface slope:
+      !                                                                 !    ocean surface (ssh_m) if ice is not embedded
+      !                                                                 !    ice bottom surface if ice is embedded   
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfU  , zfV                      ! internal stresses
+      REAL(wp), DIMENSION(jpi,jpj) ::   zspgU, zspgV                    ! surface pressure gradient at U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCorU, zCorV                    ! Coriolis stress array
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_ai, ztauy_ai              ! ice-atm. stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_oi, ztauy_oi              ! ice-ocean stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_bi, ztauy_bi              ! ice-OceanBottom stress at U-V points (landfast)
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_base, ztauy_base          ! ice-bottom stress at U-V points (landfast)
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk01x, zmsk01y                ! dummy arrays
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk00x, zmsk00y                ! mask for ice presence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfmask                          ! mask at F points for the ice
+
+      REAL(wp), PARAMETER          ::   zepsi  = 1.0e-20_wp             ! tolerance parameter
+      REAL(wp), PARAMETER          ::   zmmin  = 1._wp                  ! ice mass (kg/m2)  below which ice velocity becomes very small
+      REAL(wp), PARAMETER          ::   zamin  = 0.001_wp               ! ice concentration below which ice velocity becomes very small
+      !! --- check convergence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_ice, zv_ice
+      !! --- diags
+      REAL(wp) ::   zsig1, zsig2, zsig12, zfac, z1_strength
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zsig_I, zsig_II, zsig1_p, zsig2_p         
+      !! --- SIMIP diags
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_ice ! X-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_ice ! Y-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_snw ! X-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_snw ! Y-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xatrp     ! X-component of area transport (m2/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_yatrp     ! Y-component of area transport (m2/s)      
+      !!-------------------------------------------------------------------
+
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_rhg_evp: EVP sea-ice rheology'
+      !
+      ! for diagnostics and convergence tests
+      ALLOCATE( zmsk00(jpi,jpj), zmsk15(jpi,jpj) )
+      DO_2D( 1, 1, 1, 1 )
+         zmsk00(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06  ) ) ! 1 if ice    , 0 if no ice
+         zmsk15(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.15_wp ) ) ! 1 if 15% ice, 0 if less
+      END_2D
+      !
+      !!gm for Clem:  OPTIMIZATION:  I think zfmask can be computed one for all at the initialization....
+      !------------------------------------------------------------------------------!
+      ! 0) mask at F points for the ice
+      !------------------------------------------------------------------------------!
+      ! ocean/land mask
+      DO_2D( 1, 0, 1, 0 )
+         zfmask(ji,jj) = tmask(ji,jj,1) * tmask(ji+1,jj,1) * tmask(ji,jj+1,1) * tmask(ji+1,jj+1,1)
+      END_2D
+      CALL lbc_lnk( 'icedyn_rhg_evp', zfmask, 'F', 1._wp )
+
+      ! Lateral boundary conditions on velocity (modify zfmask)
+      DO_2D( 0, 0, 0, 0 )
+         IF( zfmask(ji,jj) == 0._wp ) THEN
+            zfmask(ji,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(ji,jj,1), umask(ji,jj+1,1), &
+               &                                          vmask(ji,jj,1), vmask(ji+1,jj,1) ) )
+         ENDIF
+      END_2D
+      DO jj = 2, jpjm1
+         IF( zfmask(1,jj) == 0._wp ) THEN
+            zfmask(1  ,jj) = rn_ishlat * MIN( 1._wp , MAX( vmask(2,jj,1), umask(1,jj+1,1), umask(1,jj,1) ) )
+         ENDIF
+         IF( zfmask(jpi,jj) == 0._wp ) THEN
+            zfmask(jpi,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(jpi,jj+1,1), vmask(jpim1,jj,1), umask(jpi,jj-1,1) ) )
+        ENDIF
+      END DO
+      DO ji = 2, jpim1
+         IF( zfmask(ji,1) == 0._wp ) THEN
+            zfmask(ji, 1 ) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,1,1), umask(ji,2,1), vmask(ji,1,1) ) )
+         ENDIF
+         IF( zfmask(ji,jpj) == 0._wp ) THEN
+            zfmask(ji,jpj) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,jpj,1), vmask(ji-1,jpj,1), umask(ji,jpjm1,1) ) )
+         ENDIF
+      END DO
+      CALL lbc_lnk( 'icedyn_rhg_evp', zfmask, 'F', 1._wp )
+
+      !------------------------------------------------------------------------------!
+      ! 1) define some variables and initialize arrays
+      !------------------------------------------------------------------------------!
+      zrhoco = rho0 * rn_cio 
+!extra code for test case boundary conditions
+      zinvw=1._wp/(zrhoco*0.5_wp)
+
+      ! ecc2: square of yield ellipse eccenticrity
+      ecc2    = rn_ecc * rn_ecc
+      z1_ecc2 = 1._wp / ecc2
+
+      ! alpha parameters (Bouillon 2009)
+      IF( .NOT. ln_aEVP ) THEN
+         zdtevp   = rDt_ice / REAL( nn_nevp )
+         zalph1 =   2._wp * rn_relast * REAL( nn_nevp )
+         zalph2 = zalph1 * z1_ecc2
+
+         z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+         z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+      ELSE
+         zdtevp   = rdt_ice
+         ! zalpha parameters set later on adaptatively
+      ENDIF
+      z1_dtevp = 1._wp / zdtevp
+         
+      ! Initialise stress tensor 
+      zs1 (:,:) = pstress1_i (:,:) 
+      zs2 (:,:) = pstress2_i (:,:)
+      zs12(:,:) = pstress12_i(:,:)
+
+      ! Ice strength
+      CALL ice_strength
+
+      ! landfast param from Lemieux(2016): add isotropic tensile strength (following Konig Beatty and Holland, 2010)
+      IF( ln_landfast_L16 ) THEN   ;   zkt = rn_lf_tensile
+      ELSE                         ;   zkt = 0._wp
+      ENDIF
+      !
+      !------------------------------------------------------------------------------!
+      ! 2) Wind / ocean stress, mass terms, coriolis terms
+      !------------------------------------------------------------------------------!
+      ! sea surface height
+      !    embedded sea ice: compute representative ice top surface
+      !    non-embedded sea ice: use ocean surface for slope calculation
+      zsshdyn(:,:) = ice_var_sshdyn( ssh_m, snwice_mass, snwice_mass_b)
+
+      DO_2D( 0, 0, 0, 0 )
+
+         ! ice fraction at U-V points
+         zaU(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+         zaV(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+         ! Ice/snow mass at U-V points
+         zm1 = ( rhos * vt_s(ji  ,jj  ) + rhoi * vt_i(ji  ,jj  ) )
+         zm2 = ( rhos * vt_s(ji+1,jj  ) + rhoi * vt_i(ji+1,jj  ) )
+         zm3 = ( rhos * vt_s(ji  ,jj+1) + rhoi * vt_i(ji  ,jj+1) )
+         zmassU = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm2 * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+         zmassV = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm3 * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+         ! Ocean currents at U-V points
+         v_oceU(ji,jj)   = 0.25_wp * ( v_oce(ji,jj) + v_oce(ji,jj-1) + v_oce(ji+1,jj) + v_oce(ji+1,jj-1) ) * umask(ji,jj,1)
+         u_oceV(ji,jj)   = 0.25_wp * ( u_oce(ji,jj) + u_oce(ji-1,jj) + u_oce(ji,jj+1) + u_oce(ji-1,jj+1) ) * vmask(ji,jj,1)
+
+         ! Coriolis at T points (m*f)
+         zmf(ji,jj)      = zm1 * ff_t(ji,jj)
+
+         ! dt/m at T points (for alpha and beta coefficients)
+         zdt_m(ji,jj)    = zdtevp / MAX( zm1, zmmin )
+         
+         ! m/dt
+         zmU_t(ji,jj)    = zmassU * z1_dtevp
+         zmV_t(ji,jj)    = zmassV * z1_dtevp
+         
+         ! Drag ice-atm.
+         ztaux_ai(ji,jj) = zaU(ji,jj) * utau_ice(ji,jj)
+         ztauy_ai(ji,jj) = zaV(ji,jj) * vtau_ice(ji,jj)
+
+         ! Surface pressure gradient (- m*g*GRAD(ssh)) at U-V points
+         zspgU(ji,jj)    = - zmassU * grav * ( zsshdyn(ji+1,jj) - zsshdyn(ji,jj) ) * r1_e1u(ji,jj)
+         zspgV(ji,jj)    = - zmassV * grav * ( zsshdyn(ji,jj+1) - zsshdyn(ji,jj) ) * r1_e2v(ji,jj)
+
+         ! masks
+         zmsk00x(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassU ) )  ! 0 if no ice
+         zmsk00y(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassV ) )  ! 0 if no ice
+
+         ! switches
+         IF( zmassU <= zmmin .AND. zaU(ji,jj) <= zamin ) THEN   ;   zmsk01x(ji,jj) = 0._wp
+         ELSE                                                   ;   zmsk01x(ji,jj) = 1._wp   ;   ENDIF
+         IF( zmassV <= zmmin .AND. zaV(ji,jj) <= zamin ) THEN   ;   zmsk01y(ji,jj) = 0._wp
+         ELSE                                                   ;   zmsk01y(ji,jj) = 1._wp   ;   ENDIF
+
+      END_2D
+      CALL lbc_lnk_multi( 'icedyn_rhg_evp', zmf, 'T', 1.0_wp, zdt_m, 'T', 1.0_wp )
+      !
+      !                                  !== Landfast ice parameterization ==!
+      !
+      IF( ln_landfast_L16 ) THEN         !-- Lemieux 2016
+         DO_2D( 0, 0, 0, 0 )
+            ! ice thickness at U-V points
+            zvU = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            zvV = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+            ! ice-bottom stress at U points
+            zvCr = zaU(ji,jj) * rn_lf_depfra * hu(ji,jj,Kmm)
+            ztaux_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvU - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaU(ji,jj) ) )
+            ! ice-bottom stress at V points
+            zvCr = zaV(ji,jj) * rn_lf_depfra * hv(ji,jj,Kmm)
+            ztauy_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvV - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaV(ji,jj) ) )
+            ! ice_bottom stress at T points
+            zvCr = at_i(ji,jj) * rn_lf_depfra * ht(ji,jj)
+            tau_icebfr(ji,jj) = - rn_lf_bfr * MAX( 0._wp, vt_i(ji,jj) - zvCr ) * EXP( -rn_crhg * ( 1._wp - at_i(ji,jj) ) )
+         END_2D
+         CALL lbc_lnk( 'icedyn_rhg_evp', tau_icebfr(:,:), 'T', 1.0_wp )
+         !
+      ELSE                               !-- no landfast
+         DO_2D( 0, 0, 0, 0 )
+            ztaux_base(ji,jj) = 0._wp
+            ztauy_base(ji,jj) = 0._wp
+         END_2D
+      ENDIF
+
+      !------------------------------------------------------------------------------!
+      ! 3) Solution of the momentum equation, iterative procedure
+      !------------------------------------------------------------------------------!
+      !
+      !                                               ! ==================== !
+      DO jter = 1 , nn_nevp                           !    loop over jter    !
+         !                                            ! ==================== !        
+         l_full_nf_update = jter == nn_nevp   ! false: disable full North fold update (performances) for iter = 1 to nn_nevp-1
+         !
+         ! convergence test
+         IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2  ) THEN
+            DO_2D( nn_hls, nn_hls, nn_hls, nn_hls )
+               zu_ice(ji,jj) = u_ice(ji,jj) * umask(ji,jj,1) ! velocity at previous time step
+               zv_ice(ji,jj) = v_ice(ji,jj) * vmask(ji,jj,1)
+            END_2D
+         ENDIF
+
+         ! --- divergence, tension & shear (Appendix B of Hunke & Dukowicz, 2002) --- !
+         DO_2D( 1, 0, 1, 0 )
+
+            ! shear at F points
+            zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+               &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+               &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+         END_2D
+
+         DO_2D( 0, 0, 0, 0 )
+
+            ! shear**2 at T points (doc eq. A16)
+            zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+           
+            ! divergence at T points
+            zdiv  = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &    + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &    ) * r1_e1e2t(ji,jj)
+            zdiv2 = zdiv * zdiv
+            
+            ! tension at T points
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+            zdt2 = zdt * zdt
+            
+            ! delta at T points
+            zdelta(ji,jj) = SQRT( zdiv2 + ( zdt2 + zds2 ) * z1_ecc2 )  
+
+         END_2D
+         CALL lbc_lnk( 'icedyn_rhg_evp', zdelta, 'T', 1.0_wp )
+
+         ! P/delta at T points
+         DO_2D( 1, 1, 1, 1 )
+            zp_delt(ji,jj) = strength(ji,jj) / ( zdelta(ji,jj) + rn_creepl )
+         END_2D
+
+         DO_2D( 0, 1, 0, 1 )   ! loop ends at jpi,jpj so that no lbc_lnk are needed for zs1 and zs2
+
+            ! divergence at T points (duplication to avoid communications)
+            zdiv  = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+               &    + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+               &    ) * r1_e1e2t(ji,jj)
+            
+            ! tension at T points (duplication to avoid communications)
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+            
+            ! alpha for aEVP
+            !   gamma = 0.5*P/(delta+creepl) * (c*pi)**2/Area * dt/m
+            !   alpha = beta = sqrt(4*gamma)
+            IF( ln_aEVP ) THEN
+               zalph1   = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+               z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+               zalph2   = zalph1
+               z1_alph2 = z1_alph1
+               ! explicit:
+               ! z1_alph1 = 1._wp / zalph1
+               ! z1_alph2 = 1._wp / zalph1
+               ! zalph1 = zalph1 - 1._wp
+               ! zalph2 = zalph1
+            ENDIF
+            
+            ! stress at T points (zkt/=0 if landfast)
+            zs1(ji,jj) = ( zs1(ji,jj)*zalph1 + zp_delt(ji,jj) * ( zdiv*(1._wp + zkt) - zdelta(ji,jj)*(1._wp - zkt) ) ) * z1_alph1
+            zs2(ji,jj) = ( zs2(ji,jj)*zalph2 + zp_delt(ji,jj) * ( zdt * z1_ecc2 * (1._wp + zkt) ) ) * z1_alph2
+          
+         END_2D
+
+         ! Save beta at T-points for further computations
+         IF( ln_aEVP ) THEN
+            DO_2D( 1, 1, 1, 1 )
+               zbeta(ji,jj) = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+            END_2D
+         ENDIF
+         
+         DO_2D( 1, 0, 1, 0 )
+
+            ! alpha for aEVP
+            IF( ln_aEVP ) THEN
+               zalph2   = MAX( zbeta(ji,jj), zbeta(ji+1,jj), zbeta(ji,jj+1), zbeta(ji+1,jj+1) )
+               z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+               ! explicit:
+               ! z1_alph2 = 1._wp / zalph2
+               ! zalph2 = zalph2 - 1._wp
+            ENDIF
+            
+            ! P/delta at F points
+            zp_delf = 0.25_wp * ( zp_delt(ji,jj) + zp_delt(ji+1,jj) + zp_delt(ji,jj+1) + zp_delt(ji+1,jj+1) )
+            
+            ! stress at F points (zkt/=0 if landfast)
+            zs12(ji,jj)= ( zs12(ji,jj) * zalph2 + zp_delf * ( zds(ji,jj) * z1_ecc2 * (1._wp + zkt) ) * 0.5_wp ) * z1_alph2
+
+         END_2D
+
+         ! --- Ice internal stresses (Appendix C of Hunke and Dukowicz, 2002) --- !
+         DO_2D( 0, 0, 0, 0 )
+            !                   !--- U points
+            zfU(ji,jj) = 0.5_wp * ( ( zs1(ji+1,jj) - zs1(ji,jj) ) * e2u(ji,jj)                                             &
+               &                  + ( zs2(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) - zs2(ji,jj) * e2t(ji,jj) * e2t(ji,jj)    &
+               &                    ) * r1_e2u(ji,jj)                                                                      &
+               &                  + ( zs12(ji,jj) * e1f(ji,jj) * e1f(ji,jj) - zs12(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1)  &
+               &                    ) * 2._wp * r1_e1u(ji,jj)                                                              &
+               &                  ) * r1_e1e2u(ji,jj)
+            !
+            !                !--- V points
+            zfV(ji,jj) = 0.5_wp * ( ( zs1(ji,jj+1) - zs1(ji,jj) ) * e1v(ji,jj)                                             &
+               &                  - ( zs2(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) - zs2(ji,jj) * e1t(ji,jj) * e1t(ji,jj)    &
+               &                    ) * r1_e1v(ji,jj)                                                                      &
+               &                  + ( zs12(ji,jj) * e2f(ji,jj) * e2f(ji,jj) - zs12(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj)  &
+               &                    ) * 2._wp * r1_e2v(ji,jj)                                                              &
+               &                  ) * r1_e1e2v(ji,jj)
+            !
+            !                !--- ice currents at U-V point
+            v_iceU(ji,jj) = 0.25_wp * ( v_ice(ji,jj) + v_ice(ji,jj-1) + v_ice(ji+1,jj) + v_ice(ji+1,jj-1) ) * umask(ji,jj,1)
+            u_iceV(ji,jj) = 0.25_wp * ( u_ice(ji,jj) + u_ice(ji-1,jj) + u_ice(ji,jj+1) + u_ice(ji-1,jj+1) ) * vmask(ji,jj,1)
+            !
+         END_2D
+         !
+         ! --- Computation of ice velocity --- !
+         !  Bouillon et al. 2013 (eq 47-48) => unstable unless alpha, beta vary as in Kimmritz 2016 & 2017
+         !  Bouillon et al. 2009 (eq 34-35) => stable
+         IF( MOD(jter,2) == 0 ) THEN ! even iterations
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(v_oce - v_ice)
+               zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                  &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/v_ice
+               zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+               zTauB = ztauy_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+               !
+               !                 !--- Coriolis at V-points (energy conserving formulation)
+               zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                  &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                  &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   & 
+                     &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetav + 1._wp )                                              &
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * v_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &            )  * zmsk00y(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  v_ice(ji,jj) = zinvw*(ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj))
+               END IF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_evp', v_ice, 'V', -1.0_wp )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(u_oce - u_ice)
+               zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                  &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/u_ice
+               zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+               zTauB = ztaux_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+               !
+               !                 !--- Coriolis at U-points (energy conserving formulation)
+               zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                  &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                  &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                     &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetau + 1._wp )                                              &
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * u_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  u_ice(ji,jj) = zinvw*(ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj))
+               END IF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_evp', u_ice, 'U', -1.0_wp )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+         ELSE ! odd iterations
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(u_oce - u_ice)
+               zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                  &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/u_ice
+               zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+               zTauB = ztaux_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+               !
+               !                 !--- Coriolis at U-points (energy conserving formulation)
+               zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                  &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                  &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                     &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetau + 1._wp )                                              &
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                     &           )   * zmsk00x(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * u_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00x(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  u_ice(ji,jj) = zinvw*(ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj))
+               END IF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_evp', u_ice, 'U', -1.0_wp )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+            DO_2D( 0, 0, 0, 0 )
+               !                 !--- tau_io/(v_oce - v_ice)
+               zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                  &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+               !                 !--- Ocean-to-Ice stress
+               ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+               !
+               !                 !--- tau_bottom/v_ice
+               zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+               zTauB = ztauy_base(ji,jj) / zvel
+               !                 !--- OceanBottom-to-Ice stress
+               ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+               !
+               !                 !--- Coriolis at v-points (energy conserving formulation)
+               zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                  &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                  &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+               !
+               !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+               zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+               !
+               !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+               !                                         1 = sliding friction : TauB < RHS
+               rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+               !
+               IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                  zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   &
+                     &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                     &                                    ) / ( zbetav + 1._wp )                                              & 
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                  v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * v_ice(ji,jj)                                       & ! previous velocity
+                     &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                     &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                     &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                     &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                     &           )   * zmsk00y(ji,jj)
+               ENDIF
+!extra code for test case boundary conditions
+               IF (mjg(jj)<25 .or. mjg(jj)>975 .or. mig(ji)<25 .or. mig(ji)>975) THEN
+                  v_ice(ji,jj) = zinvw*(ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj))
+               END IF
+            END_2D
+            CALL lbc_lnk( 'icedyn_rhg_evp', v_ice, 'V', -1.0_wp )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+         ENDIF
+
+         ! convergence test
+         IF( nn_rhg_chkcvg == 2 )   CALL rhg_cvg( kt, jter, nn_nevp, u_ice, v_ice, zu_ice, zv_ice )
+         !
+         !                                                ! ==================== !
+      END DO                                              !  end loop over jter  !
+      !                                                   ! ==================== !
+      IF( ln_aEVP )   CALL iom_put( 'beta_evp' , zbeta )
+      !
+      !------------------------------------------------------------------------------!
+      ! 4) Recompute delta, shear and div (inputs for mechanical redistribution) 
+      !------------------------------------------------------------------------------!
+      DO_2D( 1, 0, 1, 0 )
+
+         ! shear at F points
+         zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+            &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+            &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+      END_2D
+      
+      DO_2D( 0, 0, 0, 0 )   ! no vector loop
+         
+         ! tension**2 at T points
+         zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+            &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+            &   ) * r1_e1e2t(ji,jj)
+         zdt2 = zdt * zdt
+
+         zten_i(ji,jj) = zdt
+         
+         ! shear**2 at T points (doc eq. A16)
+         zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+            &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+            &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+         
+         ! shear at T points
+         pshear_i(ji,jj) = SQRT( zdt2 + zds2 )
+
+         ! divergence at T points
+         pdivu_i(ji,jj) = ( e2u(ji,jj) * u_ice(ji,jj) - e2u(ji-1,jj) * u_ice(ji-1,jj)   &
+            &             + e1v(ji,jj) * v_ice(ji,jj) - e1v(ji,jj-1) * v_ice(ji,jj-1)   &
+            &             ) * r1_e1e2t(ji,jj)
+         
+         ! delta at T points
+         zfac            = SQRT( pdivu_i(ji,jj) * pdivu_i(ji,jj) + ( zdt2 + zds2 ) * z1_ecc2 ) ! delta  
+         rswitch         = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zfac ) ) ! 0 if delta=0
+         pdelta_i(ji,jj) = zfac + rn_creepl * rswitch ! delta+creepl
+
+      END_2D
+      CALL lbc_lnk_multi( 'icedyn_rhg_evp', pshear_i, 'T', 1._wp, pdivu_i, 'T', 1._wp, pdelta_i, 'T', 1._wp, zten_i, 'T', 1._wp, &
+         &                                  zs1     , 'T', 1._wp, zs2    , 'T', 1._wp, zs12    , 'F', 1._wp )
+      
+      ! --- Store the stress tensor for the next time step --- !
+      pstress1_i (:,:) = zs1 (:,:)
+      pstress2_i (:,:) = zs2 (:,:)
+      pstress12_i(:,:) = zs12(:,:)
+      !
+
+      !------------------------------------------------------------------------------!
+      ! 5) diagnostics
+      !------------------------------------------------------------------------------!
+      ! --- ice-ocean, ice-atm. & ice-oceanbottom(landfast) stresses --- !
+      IF(  iom_use('utau_oi') .OR. iom_use('vtau_oi') .OR. iom_use('utau_ai') .OR. iom_use('vtau_ai') .OR. &
+         & iom_use('utau_bi') .OR. iom_use('vtau_bi') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_evp', ztaux_oi, 'U', -1.0_wp, ztauy_oi, 'V', -1.0_wp, ztaux_ai, 'U', -1.0_wp, ztauy_ai, 'V', -1.0_wp, &
+            &                                  ztaux_bi, 'U', -1.0_wp, ztauy_bi, 'V', -1.0_wp )
+         !
+         CALL iom_put( 'utau_oi' , ztaux_oi * zmsk00 )
+         CALL iom_put( 'vtau_oi' , ztauy_oi * zmsk00 )
+         CALL iom_put( 'utau_ai' , ztaux_ai * zmsk00 )
+         CALL iom_put( 'vtau_ai' , ztauy_ai * zmsk00 )
+         CALL iom_put( 'utau_bi' , ztaux_bi * zmsk00 )
+         CALL iom_put( 'vtau_bi' , ztauy_bi * zmsk00 )
+      ENDIF
+       
+      ! --- divergence, shear and strength --- !
+      IF( iom_use('icediv') )   CALL iom_put( 'icediv' , pdivu_i  * zmsk00 )   ! divergence
+      IF( iom_use('iceshe') )   CALL iom_put( 'iceshe' , pshear_i * zmsk00 )   ! shear
+      IF( iom_use('icestr') )   CALL iom_put( 'icestr' , strength * zmsk00 )   ! strength
+
+      ! --- Stress tensor invariants (SIMIP diags) --- !
+      IF( iom_use('normstr') .OR. iom_use('sheastr') ) THEN
+         !
+         ALLOCATE( zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )
+         !         
+         DO_2D( 1, 1, 1, 1 )
+            
+            ! Ice stresses
+            ! sigma1, sigma2, sigma12 are some useful recombination of the stresses (Hunke and Dukowicz MWR 2002, Bouillon et al., OM2013)
+            ! These are NOT stress tensor components, neither stress invariants, neither stress principal components
+            ! I know, this can be confusing...
+            zfac             =   strength(ji,jj) / ( pdelta_i(ji,jj) + rn_creepl ) 
+            zsig1            =   zfac * ( pdivu_i(ji,jj) - pdelta_i(ji,jj) )
+            zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+            zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            
+            ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008)
+            zsig_I (ji,jj)   =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+            zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+               
+         END_2D         
+         !
+         ! Stress tensor invariants (normal and shear stress N/m) - SIMIP diags - definitions following Coon (1974) and Feltham (2008)
+         IF( iom_use('normstr') )   CALL iom_put( 'normstr', zsig_I (:,:) * zmsk00(:,:) ) ! Normal stress
+         IF( iom_use('sheastr') )   CALL iom_put( 'sheastr', zsig_II(:,:) * zmsk00(:,:) ) ! Maximum shear stress
+         
+         DEALLOCATE ( zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- Normalized stress tensor principal components --- !
+      ! This are used to plot the normalized yield curve, see Lemieux & Dupont, 2020
+      ! Recommendation 1 : we use ice strength, not replacement pressure
+      ! Recommendation 2 : need to use deformations at PREVIOUS iterate for viscosities
+      IF( iom_use('sig1_pnorm') .OR. iom_use('sig2_pnorm') ) THEN
+         !
+         ALLOCATE( zsig1_p(jpi,jpj) , zsig2_p(jpi,jpj) , zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )         
+         !         
+         DO_2D( 1, 1, 1, 1 )
+            
+            ! Ice stresses computed with **viscosities** (delta, p/delta) at **previous** iterates 
+            !                        and **deformations** at current iterates
+            !                        following Lemieux & Dupont (2020)
+            zfac             =   zp_delt(ji,jj)
+            zsig1            =   zfac * ( pdivu_i(ji,jj) - ( zdelta(ji,jj) + rn_creepl ) )
+            zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+            zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+            
+            ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008), T-point
+            zsig_I(ji,jj)    =   zsig1 * 0.5_wp                                            ! 1st stress invariant, aka average normal stress, aka negative pressure
+            zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )   ! 2nd  ''       '', aka maximum shear stress
+            
+            ! Normalized  principal stresses (used to display the ellipse)
+            z1_strength      =   1._wp / MAX( 1._wp, strength(ji,jj) )
+            zsig1_p(ji,jj)   =   ( zsig_I(ji,jj) + zsig_II(ji,jj) ) * z1_strength
+            zsig2_p(ji,jj)   =   ( zsig_I(ji,jj) - zsig_II(ji,jj) ) * z1_strength
+         END_2D              
+         !
+         CALL iom_put( 'sig1_pnorm' , zsig1_p ) 
+         CALL iom_put( 'sig2_pnorm' , zsig2_p ) 
+
+         DEALLOCATE( zsig1_p , zsig2_p , zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- SIMIP --- !
+      IF(  iom_use('dssh_dx') .OR. iom_use('dssh_dy') .OR. &
+         & iom_use('corstrx') .OR. iom_use('corstry') .OR. iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_evp', zspgU, 'U', -1.0_wp, zspgV, 'V', -1.0_wp, &
+            &                                  zCorU, 'U', -1.0_wp, zCorV, 'V', -1.0_wp, zfU, 'U', -1.0_wp, zfV, 'V', -1.0_wp )
+
+         CALL iom_put( 'dssh_dx' , zspgU * zmsk00 )   ! Sea-surface tilt term in force balance (x)
+         CALL iom_put( 'dssh_dy' , zspgV * zmsk00 )   ! Sea-surface tilt term in force balance (y)
+         CALL iom_put( 'corstrx' , zCorU * zmsk00 )   ! Coriolis force term in force balance (x)
+         CALL iom_put( 'corstry' , zCorV * zmsk00 )   ! Coriolis force term in force balance (y)
+         CALL iom_put( 'intstrx' , zfU   * zmsk00 )   ! Internal force term in force balance (x)
+         CALL iom_put( 'intstry' , zfV   * zmsk00 )   ! Internal force term in force balance (y)
+      ENDIF
+
+      IF(  iom_use('xmtrpice') .OR. iom_use('ymtrpice') .OR. &
+         & iom_use('xmtrpsnw') .OR. iom_use('ymtrpsnw') .OR. iom_use('xatrp') .OR. iom_use('yatrp') ) THEN
+         !
+         ALLOCATE( zdiag_xmtrp_ice(jpi,jpj) , zdiag_ymtrp_ice(jpi,jpj) , &
+            &      zdiag_xmtrp_snw(jpi,jpj) , zdiag_ymtrp_snw(jpi,jpj) , zdiag_xatrp(jpi,jpj) , zdiag_yatrp(jpi,jpj) )
+         !
+         DO_2D( 0, 0, 0, 0 )
+            ! 2D ice mass, snow mass, area transport arrays (X, Y)
+            zfac_x = 0.5 * u_ice(ji,jj) * e2u(ji,jj) * zmsk00(ji,jj)
+            zfac_y = 0.5 * v_ice(ji,jj) * e1v(ji,jj) * zmsk00(ji,jj)
+
+            zdiag_xmtrp_ice(ji,jj) = rhoi * zfac_x * ( vt_i(ji+1,jj) + vt_i(ji,jj) ) ! ice mass transport, X-component
+            zdiag_ymtrp_ice(ji,jj) = rhoi * zfac_y * ( vt_i(ji,jj+1) + vt_i(ji,jj) ) !        ''           Y-   ''
+
+            zdiag_xmtrp_snw(ji,jj) = rhos * zfac_x * ( vt_s(ji+1,jj) + vt_s(ji,jj) ) ! snow mass transport, X-component
+            zdiag_ymtrp_snw(ji,jj) = rhos * zfac_y * ( vt_s(ji,jj+1) + vt_s(ji,jj) ) !          ''          Y-   ''
+
+            zdiag_xatrp(ji,jj)     = zfac_x * ( at_i(ji+1,jj) + at_i(ji,jj) )        ! area transport,      X-component
+            zdiag_yatrp(ji,jj)     = zfac_y * ( at_i(ji,jj+1) + at_i(ji,jj) )        !        ''            Y-   ''
+
+         END_2D
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_evp', zdiag_xmtrp_ice, 'U', -1.0_wp, zdiag_ymtrp_ice, 'V', -1.0_wp, &
+            &                                  zdiag_xmtrp_snw, 'U', -1.0_wp, zdiag_ymtrp_snw, 'V', -1.0_wp, &
+            &                                  zdiag_xatrp    , 'U', -1.0_wp, zdiag_yatrp    , 'V', -1.0_wp )
+
+         CALL iom_put( 'xmtrpice' , zdiag_xmtrp_ice )   ! X-component of sea-ice mass transport (kg/s)
+         CALL iom_put( 'ymtrpice' , zdiag_ymtrp_ice )   ! Y-component of sea-ice mass transport 
+         CALL iom_put( 'xmtrpsnw' , zdiag_xmtrp_snw )   ! X-component of snow mass transport (kg/s)
+         CALL iom_put( 'ymtrpsnw' , zdiag_ymtrp_snw )   ! Y-component of snow mass transport
+         CALL iom_put( 'xatrp'    , zdiag_xatrp     )   ! X-component of ice area transport
+         CALL iom_put( 'yatrp'    , zdiag_yatrp     )   ! Y-component of ice area transport
+
+         DEALLOCATE( zdiag_xmtrp_ice , zdiag_ymtrp_ice , &
+            &        zdiag_xmtrp_snw , zdiag_ymtrp_snw , zdiag_xatrp , zdiag_yatrp )
+
+      ENDIF
+      !
+      ! --- convergence tests --- !
+      IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2 ) THEN
+         IF( iom_use('uice_cvg') ) THEN
+            IF( ln_aEVP ) THEN   ! output: beta * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * zbeta(:,:) * umask(:,:,1) , &
+                  &                           ABS( v_ice(:,:) - zv_ice(:,:) ) * zbeta(:,:) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ELSE                 ! output: nn_nevp * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', REAL( nn_nevp ) * MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * umask(:,:,1) , &
+                  &                                             ABS( v_ice(:,:) - zv_ice(:,:) ) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ENDIF
+         ENDIF
+      ENDIF      
+      !
+      DEALLOCATE( zmsk00, zmsk15 )
+      !
+   END SUBROUTINE ice_dyn_rhg_evp
+
+
+   SUBROUTINE rhg_cvg( kt, kiter, kitermax, pu, pv, pub, pvb )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE rhg_cvg  ***
+      !!                     
+      !! ** Purpose :   check convergence of oce rheology
+      !!
+      !! ** Method  :   create a file ice_cvg.nc containing the convergence of ice velocity
+      !!                during the sub timestepping of rheology so as:
+      !!                  uice_cvg = MAX( u(t+1) - u(t) , v(t+1) - v(t) )
+      !!                This routine is called every sub-iteration, so it is cpu expensive
+      !!
+      !! ** Note    :   for the first sub-iteration, uice_cvg is set to 0 (too large otherwise)   
+      !!----------------------------------------------------------------------
+      INTEGER ,                 INTENT(in) ::   kt, kiter, kitermax       ! ocean time-step index
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pu, pv, pub, pvb          ! now and before velocities
+      !!
+      INTEGER           ::   it, idtime, istatus
+      INTEGER           ::   ji, jj          ! dummy loop indices
+      REAL(wp)          ::   zresm           ! local real 
+      CHARACTER(len=20) ::   clname
+      REAL(wp), DIMENSION(jpi,jpj) ::   zres           ! check convergence
+      !!----------------------------------------------------------------------
+
+      ! create file
+      IF( kt == nit000 .AND. kiter == 1 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'rhg_cvg : ice rheology convergence control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !
+         IF( lwm ) THEN
+            clname = 'ice_cvg.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, ncvgid )
+            istatus = NF90_DEF_DIM( ncvgid, 'time'  , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( ncvgid, 'uice_cvg', NF90_DOUBLE   , (/ idtime /), nvarid )
+            istatus = NF90_ENDDEF(ncvgid)
+         ENDIF
+         !
+      ENDIF
+
+      ! time
+      it = ( kt - 1 ) * kitermax + kiter
+      
+      ! convergence
+      IF( kiter == 1 ) THEN ! remove the first iteration for calculations of convergence (always very large)
+         zresm = 0._wp
+      ELSE
+         DO_2D( 1, 1, 1, 1 )
+            zres(ji,jj) = MAX( ABS( pu(ji,jj) - pub(ji,jj) ) * umask(ji,jj,1), &
+               &               ABS( pv(ji,jj) - pvb(ji,jj) ) * vmask(ji,jj,1) ) * zmsk15(ji,jj)
+         END_2D
+
+         ! cut of the boundary of the box (forced velocities)
+         IF (mjg(jj)<=30 .or. mjg(jj)>970 .or. mig(ji)<=30 .or. mig(ji)>970) THEN
+            zres(ji,jj) = 0._wp
+         END IF
+
+         zresm = MAXVAL( zres )
+         CALL mpp_max( 'icedyn_rhg_evp', zresm )   ! max over the global domain
+      ENDIF
+
+      IF( lwm ) THEN
+         ! write variables
+         istatus = NF90_PUT_VAR( ncvgid, nvarid, (/zresm/), (/it/), (/1/) )
+         ! close file
+         IF( kt == nitend - nn_fsbc + 1 )   istatus = NF90_CLOSE(ncvgid)
+      ENDIF
+      
+   END SUBROUTINE rhg_cvg
+
+
+   SUBROUTINE rhg_evp_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rhg_evp_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write RHG file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER  ::   iter            ! local integer
+      INTEGER  ::   id1, id2, id3   ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialize
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            id1 = iom_varid( numrir, 'stress1_i' , ldstop = .FALSE. )
+            id2 = iom_varid( numrir, 'stress2_i' , ldstop = .FALSE. )
+            id3 = iom_varid( numrir, 'stress12_i', ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2, id3 ) > 0 ) THEN      ! fields exist
+               CALL iom_get( numrir, jpdom_auto, 'stress1_i' , stress1_i , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'stress2_i' , stress2_i , cd_type = 'T' )
+               CALL iom_get( numrir, jpdom_auto, 'stress12_i', stress12_i, cd_type = 'F' )
+            ELSE                                     ! start rheology from rest
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) '   ==>>>   previous run without rheology, set stresses to 0'
+               stress1_i (:,:) = 0._wp
+               stress2_i (:,:) = 0._wp
+               stress12_i(:,:) = 0._wp
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>>   start from rest: set stresses to 0'
+            stress1_i (:,:) = 0._wp
+            stress2_i (:,:) = 0._wp
+            stress12_i(:,:) = 0._wp
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- rhg-rst ----'
+         iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         CALL iom_rstput( iter, nitrst, numriw, 'stress1_i' , stress1_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress2_i' , stress2_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress12_i', stress12_i )
+         !
+      ENDIF
+      !
+   END SUBROUTINE rhg_evp_rst
+
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!==============================================================================
+END MODULE icedyn_rhg_evp
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_hgr.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_hgr.F90	(revision 14055)
@@ -0,0 +1,147 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  ICE_RHEO configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for ICE_RHEO configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy, ln_corio, rn_ppgphi0   ! horizontal resolution in meters
+   !                                                            coriolis and reference latitude
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_hgr.F90 10074 2018-08-28 16:15:49Z nicolasmartin $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                ICE_RHEO configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zphi0, zlam0, zbeta, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : ICE_RHEO configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          f-plane with regular gridcell size'
+
+      !                          ==========
+      zlam0 = -(jpiglo-1)/2 * 1.e-3 * rn_dx
+      zphi0 = -(jpjglo-1)/2 * 1.e-3 * rn_dy
+
+
+      DO_2D( 1, 1, 1, 1 )
+         zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+         zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+
+         plamt(ji,jj) = zlam0 + rn_dx * 1.e-3 * zti
+         plamu(ji,jj) = zlam0 + rn_dx * 1.e-3 * zui
+         plamv(ji,jj) = plamt(ji,jj) 
+         plamf(ji,jj) = plamu(ji,jj) 
+  
+         pphit(ji,jj) = zphi0 + rn_dy * 1.e-3 * ztj
+         pphiv(ji,jj) = zphi0 + rn_dy * 1.e-3 * zvj
+         pphiu(ji,jj) = pphit(ji,jj) 
+         pphif(ji,jj) = pphiv(ji,jj) 
+      END_2D
+         
+         ! Horizontal scale factors (in meters)
+         !                              ======
+!! ==> EITHER 1) variable scale factors
+!! clem: This can be used with a 1proc simulation but I think it breaks repro when >1procs are used      
+!!         DO_2D( 1, 1, 1, 1 )
+!!               !!pe1t(ji,jj) = rn_dx * EXP( -0.8/REAL(jpiglo**2) * (mi0(ji)-REAL(jpiglo+1)*0.5)**2 )  ! gaussian shape
+!!               !!pe2t(ji,jj) = rn_dy * EXP( -0.8/REAL(jpjglo**2) * (mj0(jj)-REAL(jpjglo+1)*0.5)**2 )  ! gaussian shape
+!!               pe1t(ji,jj) = rn_dx * ( 1. -0.1 * ABS(REAL(mi0(ji))-REAL(jpiglo+1)*0.5) / (1.-REAL(jpiglo+1)*0.5) ) ! linear shape
+!!               pe2t(ji,jj) = rn_dy * ( 1. -0.1 * ABS(REAL(mj0(jj))-REAL(jpjglo+1)*0.5) / (1.-REAL(jpjglo+1)*0.5) ) ! linear shape
+!!         END_2D
+!!#if defined key_agrif 
+!!         IF( .NOT. Agrif_Root() ) THEN ! only works if the zoom is positioned at the center of the parent grid
+!!            DO_2D( 1, 1, 1, 1 )
+!!                  pe1t(ji,jj) = rn_dx * ( 1. -0.1 * ABS(REAL(mi0(ji))-REAL(jpiglo+1)*0.5) / (1.-REAL(jpiglo+1)*0.5)  &
+!!                     &                            * REAL(jpiglo) / REAL(Agrif_Parent(jpiglo) * Agrif_Rhox()) )       ! factor to match parent grid
+!!                  pe2t(ji,jj) = rn_dy * ( 1. -0.1 * ABS(REAL(mj0(jj))-REAL(jpjglo+1)*0.5) / (1.-REAL(jpjglo+1)*0.5)  &
+!!                     &                            * REAL(jpjglo) / REAL(Agrif_Parent(jpjglo) * Agrif_Rhoy()) )       ! factor to match parent grid
+!!            END_2D
+!!         ENDIF
+!!#endif
+!! ==> OR 2) constant scale factors
+         pe1t(:,:) = rn_dx
+         pe2t(:,:) = rn_dy
+!! ==> END
+         
+      pe1u(:,:) = pe1t(:,:)      ;      pe2u(:,:) = pe2t(:,:)
+      pe1v(:,:) = pe1t(:,:)      ;      pe2v(:,:) = pe2t(:,:)
+      pe1f(:,:) = pe1t(:,:)      ;      pe2f(:,:) = pe2t(:,:)
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      IF( ln_corio ) THEN
+         zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         pff_f(:,:) = zf0 + zbeta * pphif(:,:) * 1.e+3
+         pff_t(:,:) = zf0 + zbeta * pphit(:,:) * 1.e+3
+      ELSE
+         pff_f(:,:) = 0.
+         pff_t(:,:) = 0.
+      ENDIF
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_nam.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_nam.F90	(revision 14055)
@@ -0,0 +1,107 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  ICE_RHEO configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp , Agrif_Root           ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                               !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dy      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_ppgphi0 ! reference latitude for beta-plane 
+   LOGICAL , PUBLIC ::   ln_corio   ! set coriolis at 0 (ln_corio=F) or not 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_nam.F90 10161 2018-10-01 09:48:55Z clem $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here ICE_RHEO configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios       ! Local integer
+      REAL(wp)::   zlx, zly  ! Local scalars
+      !!
+      NAMELIST/namusr_def/ rn_dx, rn_dy, ln_corio, rn_ppgphi0
+      !!----------------------------------------------------------------------
+      !
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'ICE_RHEO'           ! name & resolution (not used)
+      kk_cfg = NINT( rn_dx )
+      !
+      ! Global Domain size:  domain is  2000 km x 2000 Km x 10 m
+         kpi = NINT( 2000.e3 / rn_dx ) 
+         kpj = NINT( 2000.e3 / rn_dy ) 
+      kpk = 1
+      !
+!!      zlx = (kpi-2)*rn_dx*1.e-3
+!!      zly = (kpj-2)*rn_dy*1.e-3
+      zlx = kpi*rn_dx*1.e-3
+      zly = kpj*rn_dy*1.e-3
+      !
+      kperio = 0     ! closed periodicity for the zoom
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : ICE_RHEO test case'
+         WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+         WRITE(numout,*) '      horizontal resolution                    rn_dy  = ', rn_dy, ' meters'
+         WRITE(numout,*) '      ICE_RHEO domain = 2000 km x 2000 km'
+         WRITE(numout,*) '         LX [km]: ', zlx
+         WRITE(numout,*) '         LY [km]: ', zly
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '         Coriolis:', ln_corio
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      ICE_RHEO closed basin                    jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_sbc.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_sbc.F90	(revision 14055)
@@ -0,0 +1,220 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  ICE_RHEO configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in ICE_RHEO case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   USE ice, ONLY       : at_i_b, a_i_b, at_i, u_ice, v_ice
+   USE icethd_dh       ! for CALL ice_thd_snwblow
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called by sbcmod.F90 for sbc ocean
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "do_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_sbc.F90 10074 2018-08-28 16:15:49Z nicolasmartin $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt, Kbb )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for ICE_RHEO case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      INTEGER, INTENT(in) ::   Kbb  ! ocean time index
+      INTEGER ::    ij0, ij1, ii0, ii1, jj, ji   ! loop indices
+      REAL(wp) ::   zrhoco          ! ocean density and drag coefficient product
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         !IF(lwp)   WRITE(numout,*)' usrdef_sbc_oce : ICE_RHEO case: ocean boudary conditions'
+
+         utau(:,:) = 0._wp
+         utau(:,:) = 0._wp
+
+         !ij0 = 1   ;   ij1 = 25                       ! set boundary condition
+         !ii0 = 975   ;   ii1 = 1000
+         !DO jj = mj0(ij0), mj1(ij1)
+         !   DO ji = mi0(ii0), mi1(ii1)
+         !      utau(ji,jj) = -utau_ice(ji,jj) 
+         !      vtau(ji,jj) = -vtau_ice(ji,jj)
+         !   END DO
+         !END DO
+
+         taum(:,:) = 0._wp   ! assume these are not used
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !
+         utau_b(:,:) = 0._wp 
+         vtau_b(:,:) = 0._wp
+         emp_b (:,:) = 0._wp
+         sfx_b (:,:) = 0._wp
+         qns_b (:,:) = 0._wp
+         !
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (momentum) condition over
+      !sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      INTEGER ::   jj, ji   ! loop indices
+
+      REAL(wp) ::   zwndi_f , zwndj_f, zwnorm_f       ! relative wind module and components at F-point
+      REAL(wp) ::   zwndi_t , zwndj_t                 ! relative wind components at T-point
+      REAL(wp), DIMENSION(jpi,jpj) ::   windu, windv  ! wind components (idealised forcing)
+      REAL(wp), PARAMETER ::   r_vfac = 1._wp         ! relative velocity (make 0 for absolute velocity) 
+      REAL(wp), PARAMETER ::   Rwind = -0.8_wp        ! ratio of wind components
+      REAL(wp), PARAMETER ::   Umax = 15._wp          ! maximum wind speed (m/s)
+      REAL(wp), PARAMETER ::   d = 2000._wp           ! size of the domain (km)
+      REAL(wp), PARAMETER ::   res = 2._wp            ! gridcell size
+      REAL(wp), PARAMETER ::   zrhoa  = 1.22          ! Air density kg/m3
+      REAL(wp), PARAMETER ::   Cd_atm =  1.4e-3       ! transfer coefficient over ice
+      !!---------------------------------------------------------------------
+      ! extra code for test case
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_RHEO case: analytical stress forcing'
+
+      DO_2D( 0, 0, 0, 0 )
+         ! wind spins up over 6 hours, factor 1000 to balance the units
+         windu(ji,jj) = Umax/sqrt(d*1000)*(d-2*mig(ji)*res)/((d-2*mig(ji)*res)**2+(d-2*mjg(jj)*res)**2*Rwind**2)**(1/4)*min(kt*30./21600,1.)
+         windv(ji,jj) = Umax/sqrt(d*1000)*(d-2*mjg(jj)*res)/((d-2*mig(ji)*res)**2+(d-2*mjg(jj)*res)**2*Rwind**2)**(1/4)*Rwind*min(kt*30./21600,1.)
+      END_2D
+      CALL lbc_lnk_multi( 'usrdef_sbc', windu, 'U', -1., windv, 'V', -1. )
+
+      wndm_ice(:,:) = 0._wp      !!gm brutal....
+
+      ! ------------------------------------------------------------ !
+      !    Wind module relative to the moving ice ( U10m - U_ice )   !
+      ! ------------------------------------------------------------ !
+      ! C-grid ice dynamics :   U & V-points (same as ocean)
+      DO_2D( 0, 0, 0, 0 )
+         zwndi_t = (  windu(ji,jj) - r_vfac * 0.5 * ( u_ice(ji-1,jj  ) + u_ice(ji,jj) )  )
+         zwndj_t = (  windv(ji,jj) - r_vfac * 0.5 * ( v_ice(ji,jj-1) + v_ice(ji,jj) )  )
+         wndm_ice(ji,jj) = SQRT( zwndi_t * zwndi_t + zwndj_t * zwndj_t ) * tmask(ji,jj,1)
+      END_2D
+      CALL lbc_lnk( 'usrdef_sbc', wndm_ice, 'T',  1. )
+
+      !!gm brutal....
+      utau_ice  (:,:) = 0._wp
+      vtau_ice  (:,:) = 0._wp
+      !!gm end
+
+      ! ------------------------------------------------------------ !
+      !    Wind stress relative to the moving ice ( U10m - U_ice )   !
+      ! ------------------------------------------------------------ !
+      ! C-grid ice dynamics :   U & V-points (same as ocean)
+      DO_2D( 0, 0, 0, 0 )
+         utau_ice(ji,jj) = 0.5 * zrhoa * Cd_atm * ( wndm_ice(ji+1,jj  ) + wndm_ice(ji,jj) )            &
+            &          * ( 0.5 * (windu(ji+1,jj) + windu(ji,jj) ) - r_vfac * u_ice(ji,jj) )
+         vtau_ice(ji,jj) = 0.5 * zrhoa * Cd_atm * ( wndm_ice(ji,jj+1  ) + wndm_ice(ji,jj) )            &
+            &          * ( 0.5 * (windv(ji,jj+1) + windv(ji,jj) ) - r_vfac * v_ice(ji,jj) )
+      END_2D
+      CALL lbc_lnk_multi( 'usrdef_sbc', utau_ice, 'U', -1., vtau_ice, 'V', -1. )
+      !
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (flux) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   phi    ! ice thickness
+      !!
+      REAL(wp) ::   zfr1, zfr2                 ! local variables
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsnw   ! snw distribution after wind blowing
+      !!---------------------------------------------------------------------
+      !
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_RHEO case: NO flux forcing'
+      !
+      ! ocean variables (renaming)
+      emp_oce (:,:)   = 0._wp   ! uniform value for freshwater budget (E-P)
+      qsr_oce (:,:)   = 0._wp   ! uniform value for     solar radiation
+      qns_oce (:,:)   = 0._wp   ! uniform value for non-solar radiation
+
+      ! ice variables
+      alb_ice (:,:,:) = 0.7_wp  ! useless
+      qsr_ice (:,:,:) = 0._wp   ! uniform value for     solar radiation
+      qns_ice (:,:,:) = 0._wp   ! uniform value for non-solar radiation
+      sprecip (:,:)   = 0._wp   ! uniform value for snow precip
+      evap_ice(:,:,:) = 0._wp   ! uniform value for sublimation
+
+      ! ice fields deduced from above
+      zsnw(:,:) = 1._wp
+      !!CALL lim_thd_snwblow( at_i_b, zsnw )  ! snow distribution over ice after wind blowing 
+      emp_ice  (:,:)   = SUM( a_i_b(:,:,:) * evap_ice(:,:,:), dim=3 ) - sprecip(:,:) * zsnw(:,:)
+      emp_oce  (:,:)   = emp_oce(:,:) - sprecip(:,:) * (1._wp - zsnw(:,:) )
+      qevap_ice(:,:,:) =   0._wp
+      qprec_ice(:,:)   =   rhos * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) !  in J/m3
+      qemp_oce (:,:)   = - emp_oce(:,:) * sst_m(:,:) * rcp
+      qemp_ice (:,:)   =   sprecip(:,:) * zsnw * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) ! solid precip (only)
+
+      ! total fluxes
+      emp_tot (:,:) = emp_ice  + emp_oce
+      qns_tot (:,:) = at_i_b(:,:) * qns_oce(:,:) + SUM( a_i_b(:,:,:) * qns_ice(:,:,:), dim=3 ) + qemp_ice(:,:) + qemp_oce(:,:)
+      qsr_tot (:,:) = at_i_b(:,:) * qsr_oce(:,:) + SUM( a_i_b(:,:,:) * qsr_ice(:,:,:), dim=3 )
+
+      ! --- shortwave radiation transmitted below the surface (W/m2, see Grenfell Maykut 77) --- !
+      zfr1 = ( 0.18 * ( 1.0 - pp_cldf ) + 0.35 * pp_cldf )            ! transmission when hi>10cm
+      zfr2 = ( 0.82 * ( 1.0 - pp_cldf ) + 0.65 * pp_cldf )            ! zfr2 such that zfr1 + zfr2 to equal 1
+      !
+      WHERE    ( phs(:,:,:) <= 0._wp .AND. phi(:,:,:) <  0.1_wp )       ! linear decrease from hi=0 to 10cm  
+         qtr_ice_top(:,:,:) = qsr_ice(:,:,:) * ( zfr1 + zfr2 * ( 1._wp - phi(:,:,:) * 10._wp ) )
+      ELSEWHERE( phs(:,:,:) <= 0._wp .AND. phi(:,:,:) >= 0.1_wp )       ! constant (zfr1) when hi>10cm
+         qtr_ice_top(:,:,:) = qsr_ice(:,:,:) * zfr1
+      ELSEWHERE                                                         ! zero when hs>0
+         qtr_ice_top(:,:,:) = 0._wp 
+      END WHERE
+          
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_zgr.F90	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/MY_SRC/usrdef_zgr.F90	(revision 14055)
@@ -0,0 +1,109 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===      ICE_RHEO case     ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: usrdef_zgr.F90 10074 2018-08-28 16:15:49Z nicolasmartin $
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   jk, k_dz  ! dummy indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : ICE_RHEO configuration '
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   (slab ocean - ice cover in square box domain)'
+      !
+      !
+      ! type of vertical coordinate  ==>>>   here ICE_RHEO : slab ocean always
+      ! ---------------------------
+      ld_zco    = .TRUE.       ! z-full-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .FALSE.      ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! 
+      k_dz = 1
+      DO jk = 1, jpk
+         pdepw_1d(jk) =    k_dz
+         pdept_1d(jk) =    k_dz
+         pe3w_1d (jk) =    k_dz
+         pe3t_1d (jk) =    k_dz
+      END DO
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      k_top(:,:) = 1
+      !
+      !                       !==  z-coordinate  ==!   (step-like topography)
+      !                                !* bottom ocean compute from the depth of grid-points
+      jpkm1 = jpk
+      k_bot(:,:) = 1    ! here use k_top as a land mask
+      !                                !* horizontally uniform coordinate (reference z-co everywhere)
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/cpp_ICE_RHEO.fcm
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/cpp_ICE_RHEO.fcm	(revision 14055)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ICE_RHEO/cpp_ICE_RHEO.fcm	(revision 14055)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys key_si3 key_mpp_mpi key_nosignedzero key_iomput
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/dtatsd.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/dtatsd.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/dtatsd.F90	(revision 14055)
@@ -18,4 +18,5 @@
    USE phycst          ! physical constants
    USE dom_oce         ! ocean space and time domain
+   USE domain, ONLY : dom_tile
    USE fldread         ! read input fields
    !
@@ -163,21 +164,40 @@
       INTEGER                              , INTENT(in   ) ::   kt     ! ocean time-step
       CHARACTER(LEN=3)                     , INTENT(in   ) ::   cddta  ! dmp or ini
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   ptsd   ! T & S data
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk,jpts), INTENT(  out) ::   ptsd   ! T & S data
       !
       INTEGER ::   ji, jj, jk, jl, jkk   ! dummy loop indicies
       INTEGER ::   ik, il0, il1, ii0, ii1, ij0, ij1   ! local integers
+      INTEGER ::   itile
       REAL(wp)::   zl, zi                             ! local scalars
       REAL(wp), DIMENSION(jpk) ::  ztp, zsp   ! 1D workspace
       !!----------------------------------------------------------------------
       !
+      IF( ntile == 0 .OR. ntile == 1 )  THEN                                         ! Do only for the full domain
+         itile = ntile
+         IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = 0 )            ! Use full domain
+
+         SELECT CASE(cddta)
+         CASE('ini')
+            CALL fld_read( kt, 1, sf_tsdini ) !==   read T & S data at kt time step   ==!
+         CASE('dmp')
+            CALL fld_read( kt, 1, sf_tsddmp ) !==   read T & S data at kt time step   ==!
+         CASE DEFAULT
+            CALL ctl_stop('STOP', 'dta_tsd: cddta case unknown')
+         END SELECT
+
+         IF( ln_tile ) CALL dom_tile( ntsi, ntsj, ntei, ntej, ktile = itile )            ! Revert to tile domain
+      ENDIF
+      !
       SELECT CASE(cddta)
-      CASE('ini') 
-         CALL fld_read( kt, 1, sf_tsdini ) !==   read T & S data at kt time step   ==!
-         ptsd(:,:,:,jp_tem) = sf_tsdini(jp_tem)%fnow(:,:,:)    ! NO mask
-         ptsd(:,:,:,jp_sal) = sf_tsdini(jp_sal)%fnow(:,:,:) 
+      CASE('ini')
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpk )
+            ptsd(ji,jj,jk,jp_tem) = sf_tsdini(jp_tem)%fnow(ji,jj,jk)    ! NO mask
+            ptsd(ji,jj,jk,jp_sal) = sf_tsdini(jp_sal)%fnow(ji,jj,jk)
+         END_3D
       CASE('dmp')
-         CALL fld_read( kt, 1, sf_tsddmp ) !==   read T & S data at kt time step   ==!
-         ptsd(:,:,:,jp_tem) = sf_tsddmp(jp_tem)%fnow(:,:,:)    ! NO mask
-         ptsd(:,:,:,jp_sal) = sf_tsddmp(jp_sal)%fnow(:,:,:) 
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpk )
+            ptsd(ji,jj,jk,jp_tem) = sf_tsddmp(jp_tem)%fnow(ji,jj,jk)    ! NO mask
+            ptsd(ji,jj,jk,jp_sal) = sf_tsddmp(jp_sal)%fnow(ji,jj,jk)
+         END_3D
       CASE DEFAULT
          CALL ctl_stop('STOP', 'dta_tsd: cddta case unknown')
@@ -186,7 +206,9 @@
       IF( ln_sco ) THEN                   !==   s- or mixed s-zps-coordinate   ==!
          !
-         IF( kt == nit000 .AND. lwp )THEN
-            WRITE(numout,*)
-            WRITE(numout,*) 'dta_tsd: interpolates T & S data onto the s- or mixed s-z-coordinate mesh'
+         IF( ntile == 0 .OR. ntile == 1 )  THEN                       ! Do only on the first tile
+            IF( kt == nit000 .AND. lwp )THEN
+               WRITE(numout,*)
+               WRITE(numout,*) 'dta_tsd: interpolates T & S data onto the s- or mixed s-z-coordinate mesh'
+            ENDIF
          ENDIF
          !
@@ -220,6 +242,8 @@
       ELSE                                !==   z- or zps- coordinate   ==!
          !                             
-         ptsd(:,:,:,jp_tem) = ptsd(:,:,:,jp_tem) * tmask(:,:,:)    ! Mask
-         ptsd(:,:,:,jp_sal) = ptsd(:,:,:,jp_sal) * tmask(:,:,:)
+         DO_3D( nn_hls, nn_hls, nn_hls, nn_hls, 1, jpk )
+            ptsd(ji,jj,jk,jp_tem) = ptsd(ji,jj,jk,jp_tem) * tmask(ji,jj,jk)    ! Mask
+            ptsd(ji,jj,jk,jp_sal) = ptsd(ji,jj,jk,jp_sal) * tmask(ji,jj,jk)
+         END_3D
          !
          IF( ln_zps ) THEN                      ! zps-coordinate (partial steps) interpolation at the last ocean level
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/eosbn2.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/eosbn2.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/eosbn2.F90	(revision 14055)
@@ -39,4 +39,5 @@
    !!----------------------------------------------------------------------
    USE dom_oce        ! ocean space and time domain
+   USE domutl, ONLY : is_tile
    USE phycst         ! physical constants
    USE stopar         ! Stochastic T/S fluctuations
@@ -55,5 +56,5 @@
    !                  !! * Interface
    INTERFACE eos
-      MODULE PROCEDURE eos_insitu, eos_insitu_pot, eos_insitu_2d
+      MODULE PROCEDURE eos_insitu, eos_insitu_pot, eos_insitu_2d, eos_insitu_pot_2d
    END INTERFACE
    !
@@ -191,4 +192,14 @@
 
    SUBROUTINE eos_insitu( pts, prd, pdep )
+      !!
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                      ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prd   ! in situ density            [-]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pdep  ! depth                      [m]
+      !!
+      CALL eos_insitu_t( pts, is_tile(pts), prd, is_tile(prd), pdep, is_tile(pdep) )
+   END SUBROUTINE eos_insitu
+
+   SUBROUTINE eos_insitu_t( pts, ktts, prd, ktrd, pdep, ktdep )
       !!----------------------------------------------------------------------
       !!                   ***  ROUTINE eos_insitu  ***
@@ -228,8 +239,9 @@
       !!                TEOS-10 Manual, 2010
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      INTEGER                                 , INTENT(in   ) ::   ktts, ktrd, ktdep
+      REAL(wp), DIMENSION(A2D_T(ktts) ,JPK,JPTS), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
       !                                                               ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd   ! in situ density            [-]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep  ! depth                      [m]
+      REAL(wp), DIMENSION(A2D_T(ktrd) ,JPK     ), INTENT(  out) ::   prd   ! in situ density            [-]
+      REAL(wp), DIMENSION(A2D_T(ktdep),JPK     ), INTENT(in   ) ::   pdep  ! depth                      [m]
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -312,8 +324,20 @@
       IF( ln_timing )   CALL timing_stop('eos-insitu')
       !
-   END SUBROUTINE eos_insitu
+   END SUBROUTINE eos_insitu_t
 
 
    SUBROUTINE eos_insitu_pot( pts, prd, prhop, pdep )
+      !!
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      !                                                       ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prd    ! in situ density            [-]
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pdep   ! depth                      [m]
+      !!
+      CALL eos_insitu_pot_t( pts, is_tile(pts), prd, is_tile(prd), prhop, is_tile(prhop), pdep, is_tile(pdep) )
+   END SUBROUTINE eos_insitu_pot
+
+
+   SUBROUTINE eos_insitu_pot_t( pts, ktts, prd, ktrd, prhop, ktrhop, pdep, ktdep )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE eos_insitu_pot  ***
@@ -328,9 +352,10 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      INTEGER                                  , INTENT(in   ) ::   ktts, ktrd, ktrhop, ktdep
+      REAL(wp), DIMENSION(A2D_T(ktts)  ,JPK,JPTS), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
       !                                                                ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd    ! in situ density            [-]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep   ! depth                      [m]
+      REAL(wp), DIMENSION(A2D_T(ktrd)  ,JPK     ), INTENT(  out) ::   prd    ! in situ density            [-]
+      REAL(wp), DIMENSION(A2D_T(ktrhop),JPK     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      REAL(wp), DIMENSION(A2D_T(ktdep) ,JPK     ), INTENT(in   ) ::   pdep   ! depth                      [m]
       !
       INTEGER  ::   ji, jj, jk, jsmp             ! dummy loop indices
@@ -482,8 +507,19 @@
       IF( ln_timing )   CALL timing_stop('eos-pot')
       !
-   END SUBROUTINE eos_insitu_pot
+   END SUBROUTINE eos_insitu_pot_t
 
 
    SUBROUTINE eos_insitu_2d( pts, pdep, prd )
+      !!
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                    ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pdep  ! depth                      [m]
+      REAL(wp), DIMENSION(:,:)  , INTENT(  out) ::   prd   ! in situ density
+      !!
+      CALL eos_insitu_2d_t( pts, is_tile(pts), pdep, is_tile(pdep), prd, is_tile(prd) )
+   END SUBROUTINE eos_insitu_2d
+
+
+   SUBROUTINE eos_insitu_2d_t( pts, ktts, pdep, ktdep, prd, ktrd )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE eos_insitu_2d  ***
@@ -496,8 +532,9 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      INTEGER                            , INTENT(in   ) ::   ktts, ktdep, ktrd
+      REAL(wp), DIMENSION(A2D_T(ktts),JPTS), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
       !                                                           ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(in   ) ::   pdep  ! depth                      [m]
-      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(  out) ::   prd   ! in situ density
+      REAL(wp), DIMENSION(A2D_T(ktdep)    ), INTENT(in   ) ::   pdep  ! depth                      [m]
+      REAL(wp), DIMENSION(A2D_T(ktrd)     ), INTENT(  out) ::   prd   ! in situ density
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -584,8 +621,104 @@
       IF( ln_timing )   CALL timing_stop('eos2d')
       !
-   END SUBROUTINE eos_insitu_2d
+   END SUBROUTINE eos_insitu_2d_t
+
+
+   SUBROUTINE eos_insitu_pot_2d( pts, prhop )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE eos_insitu_pot  ***
+      !!
+      !! ** Purpose :   Compute the in situ density (ratio rho/rho0) and the
+      !!      potential volumic mass (Kg/m3) from potential temperature and
+      !!      salinity fields using an equation of state selected in the
+      !!     namelist.
+      !!
+      !! ** Action  :
+      !!              - prhop, the potential volumic mass (Kg/m3)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      !                                                                ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(jpi,jpj     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      !
+      INTEGER  ::   ji, jj, jk, jsmp             ! dummy loop indices
+      INTEGER  ::   jdof
+      REAL(wp) ::   zt , zh , zstemp, zs , ztm   ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3      !   -      -
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: zn0_sto, zn_sto, zsign    ! local vectors
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('eos-pot')
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+            DO_2D( 1, 1, 1, 1 )
+               !
+               zt  = pts (ji,jj,jp_tem) * r1_T0                           ! temperature
+               zs  = SQRT( ABS( pts(ji,jj,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+               ztm = tmask(ji,jj,1)                                         ! tmask
+               !
+               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
+                  !
+               !
+               prhop(ji,jj) = zn0 * ztm                           ! potential density referenced at the surface
+               !
+            END_2D
+
+      CASE( np_seos )                !==  simplified EOS  ==!
+         !
+         DO_2D( 1, 1, 1, 1 )
+            zt  = pts  (ji,jj,jp_tem) - 10._wp
+            zs  = pts  (ji,jj,jp_sal) - 35._wp
+            ztm = tmask(ji,jj,1)
+            !                                                     ! potential density referenced at the surface
+            zn =  - rn_a0 * ( 1._wp + 0.5_wp*rn_lambda1*zt ) * zt   &
+               &  + rn_b0 * ( 1._wp - 0.5_wp*rn_lambda2*zs ) * zs   &
+               &  - rn_nu * zt * zs
+            prhop(ji,jj) = ( rho0 + zn ) * ztm
+            !
+         END_2D
+         !
+      CASE( np_leos )                !==  ISOMIP EOS  ==!
+         !
+         DO_2D( 1, 1, 1, 1 )
+            !
+            zt    = pts  (ji,jj,jp_tem)  - (-1._wp)
+            zs    = pts  (ji,jj,jp_sal)  - 34.2_wp
+            !zh    = pdep (ji,jj)                         ! depth at the partial step level
+            !
+            zn =  rho0 * ( - rn_a0 * zt + rn_b0 * zs )
+            !
+            prhop(ji,jj) = zn * r1_rho0               ! unmasked in situ density anomaly
+            !
+         END_2D
+         !
+      END SELECT
+      !
+      IF(sn_cfctl%l_prtctl)   CALL prt_ctl( tab2d_1=prhop, clinfo1=' eos-pot: ' )
+      !
+      IF( ln_timing )   CALL timing_stop('eos-pot')
+      !
+   END SUBROUTINE eos_insitu_pot_2d
 
 
    SUBROUTINE rab_3d( pts, pab, Kmm )
+      !!
+      INTEGER                     , INTENT(in   ) ::   Kmm   ! time level index
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts   ! pot. temperature & salinity
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
+      !!
+      CALL rab_3d_t( pts, is_tile(pts), pab, is_tile(pab), Kmm )
+   END SUBROUTINE rab_3d
+
+
+   SUBROUTINE rab_3d_t( pts, ktts, pab, ktab, Kmm )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE rab_3d  ***
@@ -598,6 +731,7 @@
       !!----------------------------------------------------------------------
       INTEGER                              , INTENT(in   ) ::   Kmm   ! time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! pot. temperature & salinity
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
+      INTEGER                                , INTENT(in   ) ::   ktts, ktab
+      REAL(wp), DIMENSION(A2D_T(ktts),JPK,JPTS), INTENT(in   ) ::   pts   ! pot. temperature & salinity
+      REAL(wp), DIMENSION(A2D_T(ktab),JPK,JPTS), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -706,8 +840,19 @@
       IF( ln_timing )   CALL timing_stop('rab_3d')
       !
-   END SUBROUTINE rab_3d
+   END SUBROUTINE rab_3d_t
 
 
    SUBROUTINE rab_2d( pts, pdep, pab, Kmm )
+      !!
+      INTEGER                   , INTENT(in   ) ::   Kmm   ! time level index
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pts    ! pot. temperature & salinity
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pdep   ! depth                  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pab    ! thermal/haline expansion ratio
+      !!
+      CALL rab_2d_t(pts, is_tile(pts), pdep, is_tile(pdep), pab, is_tile(pab), Kmm)
+   END SUBROUTINE rab_2d
+
+
+   SUBROUTINE rab_2d_t( pts, ktts, pdep, ktdep, pab, ktab, Kmm )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE rab_2d  ***
@@ -718,7 +863,8 @@
       !!----------------------------------------------------------------------
       INTEGER                              , INTENT(in   ) ::   Kmm   ! time level index
-      REAL(wp), DIMENSION(jpi,jpj,jpts)    , INTENT(in   ) ::   pts    ! pot. temperature & salinity
-      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(in   ) ::   pdep   ! depth                  [m]
-      REAL(wp), DIMENSION(jpi,jpj,jpts)    , INTENT(  out) ::   pab    ! thermal/haline expansion ratio
+      INTEGER                            , INTENT(in   ) ::   ktts, ktdep, ktab
+      REAL(wp), DIMENSION(A2D_T(ktts),JPTS), INTENT(in   ) ::   pts    ! pot. temperature & salinity
+      REAL(wp), DIMENSION(A2D_T(ktdep)    ), INTENT(in   ) ::   pdep   ! depth                  [m]
+      REAL(wp), DIMENSION(A2D_T(ktab),JPTS), INTENT(  out) ::   pab    ! thermal/haline expansion ratio
       !
       INTEGER  ::   ji, jj, jk                ! dummy loop indices
@@ -829,5 +975,5 @@
       IF( ln_timing )   CALL timing_stop('rab_2d')
       !
-   END SUBROUTINE rab_2d
+   END SUBROUTINE rab_2d_t
 
 
@@ -942,4 +1088,15 @@
 
    SUBROUTINE bn2( pts, pab, pn2, Kmm )
+      !!
+      INTEGER                              , INTENT(in   ) ::  Kmm   ! time level index
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celsius,psu]
+      REAL(wp), DIMENSION(:,:,:,:)         , INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-1,psu-1]
+      REAL(wp), DIMENSION(:,:,:)           , INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
+      !!
+      CALL bn2_t( pts, pab, is_tile(pab), pn2, is_tile(pn2), Kmm )
+   END SUBROUTINE bn2
+
+
+   SUBROUTINE bn2_t( pts, pab, ktab, pn2, ktn2, Kmm )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE bn2  ***
@@ -956,7 +1113,8 @@
       !!----------------------------------------------------------------------
       INTEGER                              , INTENT(in   ) ::   Kmm   ! time level index
+      INTEGER                                , INTENT(in   ) ::  ktab, ktn2
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celsius,psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-1,psu-1]
-      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
+      REAL(wp), DIMENSION(A2D_T(ktab),JPK,JPTS), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-1,psu-1]
+      REAL(wp), DIMENSION(A2D_T(ktn2),JPK     ), INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
       !
       INTEGER  ::   ji, jj, jk      ! dummy loop indices
@@ -982,5 +1140,5 @@
       IF( ln_timing )   CALL timing_stop('bn2')
       !
-   END SUBROUTINE bn2
+   END SUBROUTINE bn2_t
 
 
@@ -1043,4 +1201,14 @@
 
    SUBROUTINE  eos_fzp_2d( psal, ptf, pdep )
+      !!
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   )           ::   psal   ! salinity   [psu]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
+      REAL(wp), DIMENSION(:,:)    , INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
+      !!
+      CALL eos_fzp_2d_t( psal, ptf, is_tile(ptf), pdep )
+   END SUBROUTINE eos_fzp_2d
+
+
+   SUBROUTINE  eos_fzp_2d_t( psal, ptf, kttf, pdep )
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE eos_fzp  ***
@@ -1054,7 +1222,8 @@
       !! Reference  :   UNESCO tech. papers in the marine science no. 28. 1978
       !!----------------------------------------------------------------------
+      INTEGER                       , INTENT(in   )           ::   kttf
       REAL(wp), DIMENSION(jpi,jpj), INTENT(in   )           ::   psal   ! salinity   [psu]
       REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
+      REAL(wp), DIMENSION(A2D_T(kttf)), INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
       !
       INTEGER  ::   ji, jj          ! dummy loop indices
@@ -1089,5 +1258,5 @@
       END SELECT      
       !
-  END SUBROUTINE eos_fzp_2d
+  END SUBROUTINE eos_fzp_2d_t
 
 
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/tradmp.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/tradmp.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/ISOMIP+/MY_SRC/tradmp.F90	(revision 14055)
@@ -95,5 +95,5 @@
       !
       INTEGER ::   ji, jj, jk, jn   ! dummy loop indices
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts)     ::  zts_dta
+      REAL(wp), DIMENSION(A2D(nn_hls),jpk,jpts)     ::  zts_dta
       REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE ::  ztrdts
       !!----------------------------------------------------------------------
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/VORTEX/MY_SRC/domvvl.F90
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/VORTEX/MY_SRC/domvvl.F90	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/VORTEX/MY_SRC/domvvl.F90	(revision 14055)
@@ -287,22 +287,4 @@
       ENDIF
       !
-      IF(lwxios) THEN
-! define variables in restart file when writing with XIOS
-         CALL iom_set_rstw_var_active('e3t_b')
-         CALL iom_set_rstw_var_active('e3t_n')
-         !                                           ! ----------------------- !
-         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
-            !                                        ! ----------------------- !
-            CALL iom_set_rstw_var_active('tilde_e3t_b')
-            CALL iom_set_rstw_var_active('tilde_e3t_n')
-         END IF
-         !                                           ! -------------!    
-         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
-            !                                        ! ------------ !
-            CALL iom_set_rstw_var_active('hdiv_lf')
-         ENDIF
-         !
-      ENDIF
-      !
    END SUBROUTINE dom_vvl_zgr
 
@@ -815,5 +797,5 @@
 #endif
                CALL rst_read_open                  !  open the restart file if necessary
-               CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm), ldxios = lrxios    )
+               CALL iom_get( numror, jpdom_auto, 'sshn'   , ssh(:,:,Kmm) )
                !
                id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
@@ -830,6 +812,6 @@
             !
             IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb))
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm))
                ! needed to restart if land processor not computed 
                IF(lwp) write(numout,*) 'dom_vvl_rst : e3t(:,:,:,Kbb) and e3t(:,:,:,Kmm) found in restart files'
@@ -845,5 +827,5 @@
                IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_b', e3t(:,:,:,Kbb))
                e3t(:,:,:,Kmm) = e3t(:,:,:,Kbb)
                l_1st_euler = .true.
@@ -852,5 +834,5 @@
                IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
                IF(lwp) write(numout,*) 'l_1st_euler is forced to true'
-               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_auto, 'e3t_n', e3t(:,:,:,Kmm))
                e3t(:,:,:,Kbb) = e3t(:,:,:,Kmm)
                l_1st_euler = .true.
@@ -877,6 +859,6 @@
                !                          ! ----------------------- !
                IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
-                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_b', tilde_e3t_b(:,:,:))
+                  CALL iom_get( numror, jpdom_auto, 'tilde_e3t_n', tilde_e3t_n(:,:,:))
                ELSE                            ! one at least array is missing
                   tilde_e3t_b(:,:,:) = 0.0_wp
@@ -887,5 +869,5 @@
                   !                       ! ------------ !
                   IF( id5 > 0 ) THEN  ! required array exists
-                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                     CALL iom_get( numror, jpdom_auto, 'hdiv_lf', hdiv_lf(:,:,:))
                   ELSE                ! array is missing
                      hdiv_lf(:,:,:) = 0.0_wp
@@ -975,23 +957,21 @@
          !                                   ! ===================
          IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
-         IF( lwxios ) CALL iom_swap(      cwxios_context          )
          !                                           ! --------- !
          !                                           ! all cases !
          !                                           ! --------- !
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb), ldxios = lwxios )
-         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t(:,:,:,Kbb))
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t(:,:,:,Kmm))
          !                                           ! ----------------------- !
          IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
             !                                        ! ----------------------- !
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
-            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:))
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:))
          END IF
          !                                           ! -------------!    
          IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
             !                                        ! ------------ !
-            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:))
          ENDIF
          !
-         IF( lwxios ) CALL iom_swap(      cxios_context          )
       ENDIF
       !
Index: NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/demo_cfgs.txt
===================================================================
--- NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/demo_cfgs.txt	(revision 14048)
+++ NEMO/branches/2020/dev_r13312_AGRIF-03-04_jchanut_vinterp_tstep/tests/demo_cfgs.txt	(revision 14055)
@@ -13,2 +13,4 @@
 CPL_OASIS  OCE TOP ICE NST
 DOME OCE NST
+C1D_ASICS OCE
+ICE_RHEO OCE SAS ICE
