Index: NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/diawri.F90
===================================================================
--- NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/diawri.F90	(revision 12587)
+++ NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/diawri.F90	(revision 13159)
@@ -99,5 +99,5 @@
       ! Output the initial state and forcings
       IF( ninist == 1 ) THEN
-         CALL dia_wri_state( 'output.init', Kmm )
+         CALL dia_wri_state( Kmm, 'output.init' )
          ninist = 0
       ENDIF
@@ -126,5 +126,5 @@
    END FUNCTION dia_wri_alloc_abl
   
-   SUBROUTINE dia_wri( kt )
+   SUBROUTINE dia_wri( kt, Kmm )
       !!---------------------------------------------------------------------
       !!                  ***  ROUTINE dia_wri  ***
@@ -138,6 +138,6 @@
       !!      Each nn_write time step, output the instantaneous or mean fields
       !!----------------------------------------------------------------------
-      !!
       INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      INTEGER, INTENT( in ) ::   Kmm     ! ocean time level index
       !!
       LOGICAL ::   ll_print = .FALSE.                        ! =T print and flush numout
@@ -154,5 +154,5 @@
       ! Output the initial state and forcings
       IF( ninist == 1 ) THEN                       
-         CALL dia_wri_state( 'output.init' )
+         CALL dia_wri_state( Kmm, 'output.init' )
          ninist = 0
       ENDIF
@@ -257,5 +257,5 @@
          IF( ln_abl ) THEN 
          ! Define the ABL grid FILE ( nid_A )
-            CALL dia_nam( clhstnam, nwrite, 'grid_ABL' )
+            CALL dia_nam( clhstnam, nn_write, 'grid_ABL' )
             IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
             CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,           &  ! Horizontal grid: glamt and gphit
@@ -414,5 +414,5 @@
 #endif
 
-   SUBROUTINE dia_wri_state( cdfile_name, Kmm )
+   SUBROUTINE dia_wri_state( Kmm, cdfile_name )
       !!---------------------------------------------------------------------
       !!                 ***  ROUTINE dia_wri_state  ***
@@ -427,6 +427,6 @@
       !!      File 'output.abort.nc' is created in case of abnormal job end
       !!----------------------------------------------------------------------
+      INTEGER           , INTENT( in ) ::   Kmm              ! ocean time levelindex
       CHARACTER (len=* ), INTENT( in ) ::   cdfile_name      ! name of the file created
-      INTEGER           , INTENT( in ) ::   Kmm              ! ocean time levelindex
       !!
       INTEGER :: inum
@@ -437,11 +437,7 @@
       IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~   and forcing fields file created '
       IF(lwp) WRITE(numout,*) '                and named :', cdfile_name, '...nc'
-
-#if defined key_si3
-     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE., kdlev = jpl )
-#else
-     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE. )
-#endif
-
+      !
+      CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE. )
+      !
       CALL iom_rstput( 0, 0, inum, 'votemper', ts (:,:,:,jp_tem,Kmm) )    ! now temperature
       CALL iom_rstput( 0, 0, inum, 'vosaline', ts (:,:,:,jp_sal,Kmm) )    ! now salinity
@@ -456,13 +452,15 @@
       CALL iom_rstput( 0, 0, inum, 'sozotaux', utau                  )    ! i-wind stress
       CALL iom_rstput( 0, 0, inum, 'sometauy', vtau                  )    ! j-wind stress
- 
+      !
+      CALL iom_close( inum )
+      !
 #if defined key_si3
       IF( nn_ice == 2 ) THEN   ! condition needed in case agrif + ice-model but no-ice in child grid
+         CALL iom_open( TRIM(cdfile_name)//'_ice', inum, ldwrt = .TRUE., kdlev = jpl, cdcomp = 'ICE' )
          CALL ice_wri_state( inum )
-      ENDIF
-#endif
-      !
-      CALL iom_close( inum )
-      !
+         CALL iom_close( inum )
+      ENDIF
+      !
+#endif
    END SUBROUTINE dia_wri_state
 
Index: NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/nemogcm.F90
===================================================================
--- NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/nemogcm.F90	(revision 12587)
+++ NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/nemogcm.F90	(revision 13159)
@@ -35,4 +35,5 @@
    USE step_diu       ! diurnal bulk SST timestepping (called from here if run offline)
    !
+   USE in_out_manager ! I/O manager
    USE lib_mpp        ! distributed memory computing
    USE mppini         ! shared/distributed memory setting (mpp_init routine)
@@ -125,10 +126,4 @@
       END DO
       !
-      IF( .NOT. Agrif_Root() ) THEN
-         CALL Agrif_ParentGrid_To_ChildGrid()
-         IF( ln_timing )   CALL timing_finalize
-         CALL Agrif_ChildGrid_To_ParentGrid()
-      ENDIF
-      !
 #else
       !
@@ -165,5 +160,13 @@
       IF( nstop /= 0 .AND. lwp ) THEN        ! error print
          WRITE(ctmp1,*) '   ==>>>   nemo_gcm: a total of ', nstop, ' errors have been found'
-         CALL ctl_stop( ctmp1 )
+         IF( ngrdstop > 0 ) THEN
+            WRITE(ctmp9,'(i2)') ngrdstop
+            WRITE(ctmp2,*) '           E R R O R detected in Agrif grid '//TRIM(ctmp9)
+            WRITE(ctmp3,*) '           Look for "E R R O R" messages in all existing '//TRIM(ctmp9)//'_ocean_output* files'
+            CALL ctl_stop( ' ', ctmp1, ' ', ctmp2, ' ', ctmp3 )
+         ELSE
+            WRITE(ctmp2,*) '           Look for "E R R O R" messages in all existing ocean_output* files'
+            CALL ctl_stop( ' ', ctmp1, ' ', ctmp2 )
+         ENDIF
       ENDIF
       !
@@ -256,5 +259,11 @@
       ENDIF
       ! open /dev/null file to be able to supress output write easily
+      IF( Agrif_Root() ) THEN
                      CALL ctl_opn(     numnul,               '/dev/null', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+#ifdef key_agrif
+      ELSE
+                  numnul = Agrif_Parent(numnul)   
+#endif
+      ENDIF
       !
       !                             !--------------------!
@@ -268,20 +277,6 @@
       !
       ! finalize the definition of namctl variables
-      IF( sn_cfctl%l_allon ) THEN
-         ! Turn on all options.
-         CALL nemo_set_cfctl( sn_cfctl, .TRUE., .TRUE. )
-         ! Ensure all processors are active
-         sn_cfctl%procmin = 0 ; sn_cfctl%procmax = 1000000 ; sn_cfctl%procincr = 1
-      ELSEIF( sn_cfctl%l_config ) THEN
-         ! Activate finer control of report outputs
-         ! optionally switch off output from selected areas (note this only
-         ! applies to output which does not involve global communications)
-         IF( ( narea < sn_cfctl%procmin .OR. narea > sn_cfctl%procmax  ) .OR. &
-           & ( MOD( narea - sn_cfctl%procmin, sn_cfctl%procincr ) /= 0 ) )    &
-           &   CALL nemo_set_cfctl( sn_cfctl, .FALSE., .FALSE. )
-      ELSE
-         ! turn off all options.
-         CALL nemo_set_cfctl( sn_cfctl, .FALSE., .TRUE. )
-      ENDIF
+      IF( narea < sn_cfctl%procmin .OR. narea > sn_cfctl%procmax .OR. MOD( narea - sn_cfctl%procmin, sn_cfctl%procincr ) /= 0 )   &
+         &   CALL nemo_set_cfctl( sn_cfctl, .FALSE. )
       !
       lwp = (narea == 1) .OR. sn_cfctl%l_oceout    ! control of all listing output print
@@ -401,7 +396,4 @@
          WRITE(numout,*) '~~~~~~~~'
          WRITE(numout,*) '   Namelist namctl'
-         WRITE(numout,*) '                              sn_cfctl%l_glochk  = ', sn_cfctl%l_glochk
-         WRITE(numout,*) '                              sn_cfctl%l_allon   = ', sn_cfctl%l_allon
-         WRITE(numout,*) '       finer control over o/p sn_cfctl%l_config  = ', sn_cfctl%l_config
          WRITE(numout,*) '                              sn_cfctl%l_runstat = ', sn_cfctl%l_runstat
          WRITE(numout,*) '                              sn_cfctl%l_trcstat = ', sn_cfctl%l_trcstat
@@ -545,25 +537,18 @@
    END SUBROUTINE nemo_alloc
 
-   SUBROUTINE nemo_set_cfctl(sn_cfctl, setto, for_all )
+   SUBROUTINE nemo_set_cfctl(sn_cfctl, setto )
       !!----------------------------------------------------------------------
       !!                     ***  ROUTINE nemo_set_cfctl  ***
       !!
       !! ** Purpose :   Set elements of the output control structure to setto.
-      !!                for_all should be .false. unless all areas are to be
-      !!                treated identically.
       !!
       !! ** Method  :   Note this routine can be used to switch on/off some
-      !!                types of output for selected areas but any output types
-      !!                that involve global communications (e.g. mpp_max, glob_sum)
-      !!                should be protected from selective switching by the
-      !!                for_all argument
-      !!----------------------------------------------------------------------
-      LOGICAL :: setto, for_all
-      TYPE(sn_ctl) :: sn_cfctl
-      !!----------------------------------------------------------------------
-      IF( for_all ) THEN
-         sn_cfctl%l_runstat = setto
-         sn_cfctl%l_trcstat = setto
-      ENDIF
+      !!                types of output for selected areas.
+      !!----------------------------------------------------------------------
+      TYPE(sn_ctl), INTENT(inout) :: sn_cfctl
+      LOGICAL     , INTENT(in   ) :: setto
+      !!----------------------------------------------------------------------
+      sn_cfctl%l_runstat = setto
+      sn_cfctl%l_trcstat = setto
       sn_cfctl%l_oceout  = setto
       sn_cfctl%l_layout  = setto
Index: NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/sbcssm.F90
===================================================================
--- NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/sbcssm.F90	(revision 12587)
+++ NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/sbcssm.F90	(revision 13159)
@@ -26,5 +26,5 @@
    USE lib_mpp        ! distributed memory computing library
    USE prtctl         ! print control
-   USE fldread        ! read input fields 
+   USE fldread        ! read input fields
    USE timing         ! Timing
 
@@ -38,5 +38,5 @@
    LOGICAL            ::   ln_3d_uve     ! specify whether input velocity data is 3D
    LOGICAL            ::   ln_read_frq   ! specify whether we must read frq or not
-   
+
    LOGICAL            ::   l_sasread     ! Ice intilisation: =T read a file ; =F anaytical initilaistion
    LOGICAL            ::   l_initdone = .false.
@@ -69,10 +69,10 @@
       !!               for an off-line simulation using surface processes only
       !!
-      !! ** Method : calculates the position of data 
+      !! ** Method : calculates the position of data
       !!             - interpolates data if needed
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       INTEGER, INTENT(in) ::   Kbb, Kmm   ! ocean time level indices
-                          ! (not needed for SAS but needed to keep a consistent interface in sbcmod.F90)
+      ! (not needed for SAS but needed to keep a consistent interface in sbcmod.F90)
       !
       INTEGER  ::   ji, jj     ! dummy loop indices
@@ -82,25 +82,25 @@
       !
       IF( ln_timing )   CALL timing_start( 'sbc_ssm')
-     
+
       IF ( l_sasread ) THEN
          IF( nfld_3d > 0 ) CALL fld_read( kt, 1, sf_ssm_3d )      !==   read data at kt time step   ==!
          IF( nfld_2d > 0 ) CALL fld_read( kt, 1, sf_ssm_2d )      !==   read data at kt time step   ==!
-         ! 
+         !
          IF( ln_3d_uve ) THEN
             IF( .NOT. ln_linssh ) THEN
-               e3t_m(:,:) = sf_ssm_3d(jf_e3t)%fnow(:,:,1) * tmask(:,:,1) ! vertical scale factor 
+               e3t_m(:,:) = sf_ssm_3d(jf_e3t)%fnow(:,:,1) * tmask(:,:,1) ! vertical scale factor
             ELSE
                e3t_m(:,:) = e3t_0(:,:,1)                                 ! vertical scale factor
             ENDIF
             ssu_m(:,:) = sf_ssm_3d(jf_usp)%fnow(:,:,1) * umask(:,:,1)    ! u-velocity
-            ssv_m(:,:) = sf_ssm_3d(jf_vsp)%fnow(:,:,1) * vmask(:,:,1)    ! v-velocity 
+            ssv_m(:,:) = sf_ssm_3d(jf_vsp)%fnow(:,:,1) * vmask(:,:,1)    ! v-velocity
          ELSE
             IF( .NOT. ln_linssh ) THEN
-               e3t_m(:,:) = sf_ssm_2d(jf_e3t)%fnow(:,:,1) * tmask(:,:,1) ! vertical scale factor 
+               e3t_m(:,:) = sf_ssm_2d(jf_e3t)%fnow(:,:,1) * tmask(:,:,1) ! vertical scale factor
             ELSE
                e3t_m(:,:) = e3t_0(:,:,1)                                 ! vertical scale factor
             ENDIF
             ssu_m(:,:) = sf_ssm_2d(jf_usp)%fnow(:,:,1) * umask(:,:,1)    ! u-velocity
-            ssv_m(:,:) = sf_ssm_2d(jf_vsp)%fnow(:,:,1) * vmask(:,:,1)    ! v-velocity 
+            ssv_m(:,:) = sf_ssm_2d(jf_vsp)%fnow(:,:,1) * vmask(:,:,1)    ! v-velocity
          ENDIF
          !
@@ -123,5 +123,5 @@
          ssh  (:,:,Kmm) = 0._wp                              !              - -
       ENDIF
-      
+
       IF ( nn_ice == 1 ) THEN
          ts(:,:,1,jp_tem,Kmm) = sst_m(:,:)
@@ -132,5 +132,5 @@
       uu (:,:,1,Kbb) = ssu_m(:,:)
       vv (:,:,1,Kbb) = ssv_m(:,:)
- 
+
       IF(sn_cfctl%l_prtctl) THEN            ! print control
          CALL prt_ctl(tab2d_1=sst_m, clinfo1=' sst_m   - : ', mask1=tmask   )
@@ -162,8 +162,8 @@
       !!                  ***  ROUTINE sbc_ssm_init  ***
       !!
-      !! ** Purpose :   Initialisation of sea surface mean data     
-      !!----------------------------------------------------------------------
-      INTEGER, INTENT(in) ::   Kbb, Kmm   ! ocean time level indices 
-                          ! (not needed for SAS but needed to keep a consistent interface in sbcmod.F90)
+      !! ** Purpose :   Initialisation of sea surface mean data
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   Kbb, Kmm   ! ocean time level indices
+      ! (not needed for SAS but needed to keep a consistent interface in sbcmod.F90)
       INTEGER  :: ierr, ierr0, ierr1, ierr2, ierr3   ! return error code
       INTEGER  :: ifpr                               ! dummy loop indice
@@ -195,8 +195,8 @@
 902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_sas in configuration namelist' )
       IF(lwm) WRITE ( numond, namsbc_sas )
-      !           
+      !
       IF(lwp) THEN                              ! Control print
          WRITE(numout,*) '   Namelist namsbc_sas'
-         WRITE(numout,*) '      Initialisation using an input file                                 l_sasread   = ', l_sasread 
+         WRITE(numout,*) '      Initialisation using an input file                                 l_sasread   = ', l_sasread
          WRITE(numout,*) '      Are we supplying a 3D u,v and e3 field                             ln_3d_uve   = ', ln_3d_uve
          WRITE(numout,*) '      Are we reading frq (fraction of qsr absorbed in the 1st T level)   ln_read_frq = ', ln_read_frq
@@ -226,8 +226,8 @@
          ln_closea = .false.
       ENDIF
-      
-      !                  
+
+      !
       IF( l_sasread ) THEN                       ! store namelist information in an array
-         ! 
+         !
          !! following code is a bit messy, but distinguishes between when u,v are 3d arrays and
          !! when we have other 3d arrays that we need to read in
@@ -275,5 +275,5 @@
          ENDIF
          !
-         ierr1 = 0    ! default definition if slf_?d(ifpr)%ln_tint = .false. 
+         ierr1 = 0    ! default definition if slf_?d(ifpr)%ln_tint = .false.
          IF( nfld_3d > 0 ) THEN
             ALLOCATE( sf_ssm_3d(nfld_3d), STAT=ierr )         ! set sf structure
@@ -282,5 +282,5 @@
             ENDIF
             DO ifpr = 1, nfld_3d
-                                            ALLOCATE( sf_ssm_3d(ifpr)%fnow(jpi,jpj,jpk)    , STAT=ierr0 )
+               ALLOCATE( sf_ssm_3d(ifpr)%fnow(jpi,jpj,jpk)    , STAT=ierr0 )
                IF( slf_3d(ifpr)%ln_tint )   ALLOCATE( sf_ssm_3d(ifpr)%fdta(jpi,jpj,jpk,2)  , STAT=ierr1 )
                IF( ierr0 + ierr1 > 0 ) THEN
@@ -298,5 +298,5 @@
             ENDIF
             DO ifpr = 1, nfld_2d
-                                            ALLOCATE( sf_ssm_2d(ifpr)%fnow(jpi,jpj,1)    , STAT=ierr0 )
+               ALLOCATE( sf_ssm_2d(ifpr)%fnow(jpi,jpj,1)    , STAT=ierr0 )
                IF( slf_2d(ifpr)%ln_tint )   ALLOCATE( sf_ssm_2d(ifpr)%fdta(jpi,jpj,1,2)  , STAT=ierr1 )
                IF( ierr0 + ierr1 > 0 ) THEN
Index: NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/step.F90
===================================================================
--- NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/step.F90	(revision 12587)
+++ NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/step.F90	(revision 13159)
@@ -74,23 +74,18 @@
       !!              -2- Outputs and diagnostics
       !!----------------------------------------------------------------------
-      INTEGER ::   indic    ! error indicator if < 0
-      !! ---------------------------------------------------------------------
 
 #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()
+      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( kstp == nit000 + 1 )   lk_agrif_fstep = .FALSE.
 # if defined key_iomput
       IF( Agrif_Nbstepint() == 0 )   CALL iom_swap( cxios_context )
 # endif   
 #endif   
-                             indic = 0                    ! although indic is not changed in stp_ctl
-                                                          ! need to keep the same interface 
       IF( kstp == nit000 )   CALL iom_init( cxios_context ) ! iom_put initialization (must be done after nemo_init for AGRIF+XIOS+OASIS)
       IF( kstp /= nit000 )   CALL day( kstp )             ! Calendar (day was already called at nit000 in day_init)
@@ -109,29 +104,34 @@
 #if defined key_agrif
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! AGRIF
+      ! AGRIF recursive integration
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
-                             CALL Agrif_Integrate_ChildGrids( stp )  
+                             CALL Agrif_Integrate_ChildGrids( stp )
+                             
+#endif                             
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Control
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                             CALL stp_ctl( kstp, Nnn )
 
-      IF( Agrif_NbStepint() == 0 ) THEN               ! AGRIF Update from zoom N to zoom 1 then to Parent 
+#if defined key_agrif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! AGRIF update
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+      IF( Agrif_NbStepint() == 0 .AND. nstop == 0 ) THEN                       ! AGRIF Update from zoom N to zoom 1 then to Parent 
 #if defined key_si3
                              CALL Agrif_Update_ice( )   ! update sea-ice
 #endif
       ENDIF
+
 #endif
-                             
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! Control
-      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                             CALL stp_ctl( kstp, indic )
-      IF( indic < 0  )  THEN
-                             CALL ctl_stop( 'step: indic < 0' )
-                             CALL dia_wri_state( 'output.abort', Nnn )
-      ENDIF
-      IF( kstp == nit000   ) CALL iom_close( numror )           ! close input  ocean restart file
+      ! File manipulation at the end of the first time step
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
+      IF( kstp == nit000   ) CALL iom_close( numror )                          ! close input  ocean restart file
       
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Coupled mode
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-      IF( lk_oasis    )  CALL sbc_cpl_snd( kstp, Nbb, Nnn )     ! coupled mode : field exchanges if OASIS-coupled ice
+      IF( lk_oasis .AND. nstop == 0 ) CALL sbc_cpl_snd( kstp, Nbb, Nnn )       ! coupled mode : field exchanges if OASIS-coupled ice
 
 #if defined key_iomput
@@ -144,6 +144,6 @@
          lrst_oce = .FALSE.
       ENDIF
-      IF( kstp == nitend .OR. indic < 0 ) THEN
-                             CALL iom_context_finalize( cxios_context ) ! needed for XIOS+AGRIF
+      IF( kstp == nitend .OR. nstop > 0 ) THEN
+         CALL iom_context_finalize( cxios_context ) ! needed for XIOS+AGRIF
       ENDIF
 #endif
Index: NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/stpctl.F90
===================================================================
--- NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/stpctl.F90	(revision 12587)
+++ NEMO/branches/2020/dev_r12563_ASINTER-06_ABL_improvement/src/SAS/stpctl.F90	(revision 13159)
@@ -21,8 +21,9 @@
    USE ice      , ONLY : vt_i, u_ice, tm_i
    !
+   USE diawri          ! Standard run outputs       (dia_wri_state routine)
    USE in_out_manager  ! I/O manager
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE lib_mpp         ! distributed memory computing
-
+   !
    USE netcdf          ! NetCDF library
    IMPLICIT NONE
@@ -31,6 +32,6 @@
    PUBLIC stp_ctl           ! routine called by step.F90
 
-   INTEGER  ::   idrun, idtime, idssh, idu, ids, istatus
-   LOGICAL  ::   lsomeoce
+   INTEGER                ::   nrunid   ! netcdf file id
+   INTEGER, DIMENSION(3)  ::   nvarid   ! netcdf variable id
    !!----------------------------------------------------------------------
    !! NEMO/SAS 4.0 , NEMO Consortium (2018)
@@ -38,8 +39,7 @@
    !! Software governed by the CeCILL license (see ./LICENSE)
    !!----------------------------------------------------------------------
-
 CONTAINS
 
-   SUBROUTINE stp_ctl( kt, kindic )
+   SUBROUTINE stp_ctl( kt, Kmm )
       !!----------------------------------------------------------------------
       !!                    ***  ROUTINE stp_ctl  ***
@@ -49,66 +49,217 @@
       !! ** Method  : - Save the time step in numstp
       !!              - Print it each 50 time steps
+      !!              - Stop the run IF problem encountered by setting nstop > 0
+      !!                Problems checked: ice thickness maximum > 100 m
+      !!                                  ice velocity  maximum > 10 m/s 
+      !!                                  min ice temperature   < -100 degC
       !!
       !! ** Actions :   "time.step" file = last ocean time-step
       !!                "run.stat"  file = run statistics
-      !!                
-      !!----------------------------------------------------------------------
-      INTEGER, INTENT( in    ) ::   kt       ! ocean time-step index
-      INTEGER, INTENT( inout ) ::   kindic   ! indicator of solver convergence
-      !!
-      REAL(wp), DIMENSION(3) ::   zmax
-      LOGICAL                ::   ll_wrtstp, ll_colruns, ll_wrtruns
-      CHARACTER(len=20) :: clname
-      !!----------------------------------------------------------------------
-      !
-      ll_wrtstp  = ( MOD( kt, sn_cfctl%ptimincr ) == 0 ) .OR. ( kt == nitend )
-      ll_colruns = ll_wrtstp .AND. ( sn_cfctl%l_runstat )
-      ll_wrtruns = ll_colruns .AND. lwm
-      IF( kt == nit000 .AND. lwp ) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) 'stp_ctl : time-stepping control'
-         WRITE(numout,*) '~~~~~~~'
-         !                                ! open time.step file
-         IF( lwm ) CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
-         !                                ! open run.stat file(s) at start whatever
-         !                                ! the value of sn_cfctl%ptimincr
-         IF( lwm .AND. ( sn_cfctl%l_runstat ) ) THEN
+      !!                 nstop indicator sheared among all local domain
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt       ! ocean time-step index
+      INTEGER, INTENT(in   ) ::   Kmm      ! ocean time level index
+      !!
+      INTEGER                         ::   ji                                    ! dummy loop indices
+      INTEGER                         ::   idtime, istatus
+      INTEGER , DIMENSION(4)          ::   iareasum, iareamin, iareamax
+      INTEGER , DIMENSION(3,3)        ::   iloc                                  ! min/max loc indices
+      REAL(wp)                        ::   zzz                                   ! local real 
+      REAL(wp), DIMENSION(4)          ::   zmax, zmaxlocal
+      LOGICAL                         ::   ll_wrtstp, ll_colruns, ll_wrtruns
+      LOGICAL, DIMENSION(jpi,jpj)     ::   llmsk
+      CHARACTER(len=20)               ::   clname
+      !!----------------------------------------------------------------------
+      IF( nstop > 0 .AND. ngrdstop > -1 )   RETURN   !   stpctl was already called by a child grid
+      !
+      ll_wrtstp  = ( MOD( kt-nit000, sn_cfctl%ptimincr ) == 0 ) .OR. ( kt == nitend )
+      ll_colruns = ll_wrtstp .AND. sn_cfctl%l_runstat .AND. jpnij > 1 
+      ll_wrtruns = ( ll_colruns .OR. jpnij == 1 ) .AND. lwm
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'stp_ctl : time-stepping control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !                                ! open time.step    ascii file, done only by 1st subdomain
+         IF( lwm )   CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+         !
+         IF( ll_wrtruns ) THEN
+            !                             ! open run.stat     ascii file, done only by 1st subdomain
             CALL ctl_opn( numrun, 'run.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            !                             ! open run.stat.nc netcdf file, done only by 1st subdomain
             clname = 'run.stat.nc'
             IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
-            istatus = NF90_CREATE( 'run.stat.nc', NF90_CLOBBER, idrun )
-            istatus = NF90_DEF_DIM( idrun, 'time'     , NF90_UNLIMITED, idtime )
-            istatus = NF90_DEF_VAR( idrun, 'vt_i_max' , NF90_DOUBLE, (/ idtime /), idssh )
-            istatus = NF90_DEF_VAR( idrun, 'abs_u_max', NF90_DOUBLE, (/ idtime /), idu )
-            istatus = NF90_DEF_VAR( idrun, 'tm_i_min' , NF90_DOUBLE, (/ idtime /), ids )
-            istatus = NF90_ENDDEF(idrun)
-         ENDIF
-      ENDIF
-      IF( kt == nit000 )   lsomeoce = COUNT( ssmask(:,:) == 1._wp ) > 0
-      !
-      IF(lwm .AND. ll_wrtstp) THEN        !==  current time step  ==!   ("time.step" file)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, nrunid )
+            istatus = NF90_DEF_DIM( nrunid, 'time'     , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( nrunid, 'vt_i_max' , NF90_DOUBLE, (/ idtime /), nvarid(1) )
+            istatus = NF90_DEF_VAR( nrunid, 'abs_u_max', NF90_DOUBLE, (/ idtime /), nvarid(2) )
+            istatus = NF90_DEF_VAR( nrunid, 'tm_i_min' , NF90_DOUBLE, (/ idtime /), nvarid(3) )
+            istatus = NF90_ENDDEF(nrunid)
+         ENDIF
+         !    
+      ENDIF
+      !
+      !                                   !==              write current time step              ==!
+      !                                   !==  done only by 1st subdomain at writting timestep  ==!
+      IF( lwm .AND. ll_wrtstp ) THEN
          WRITE ( numstp, '(1x, i8)' )   kt
          REWIND( numstp )
       ENDIF
-      !                                   !==  test of extrema  ==!
+      !                                   !==            test of local extrema           ==!
+      !                                   !==  done by all processes at every time step  ==!
+      llmsk(:,:) = tmask(:,:,1) == 1._wp
+      IF( COUNT( llmsk(:,:) ) > 0 ) THEN   ! avoid huge values sent back for land processors...
+         zmax(1) = MAXVAL(      vt_i (:,:)            , mask = llmsk )   ! max ice thickness
+         zmax(2) = MAXVAL( ABS( u_ice(:,:) )          , mask = llmsk )   ! max ice velocity (zonal only)
+         zmax(3) = MAXVAL(     -tm_i (:,:) + 273.15_wp, mask = llmsk )   ! min ice temperature
+      ELSE
+         IF( ll_colruns ) THEN    ! default value: must not be kept when calling mpp_max -> must be as small as possible
+            zmax(1:3) = -HUGE(1._wp)
+         ELSE                     ! default value: must not give true for any of the tests bellow (-> avoid manipulating HUGE...)
+            zmax(1:3) = 0._wp
+         ENDIF
+      ENDIF
+      zmax(4) = REAL( nstop, wp )                                     ! stop indicator
+      !                                   !==               get global extrema             ==!
+      !                                   !==  done by all processes if writting run.stat  ==!
       IF( ll_colruns ) THEN
-         zmax(1) = MAXVAL(      vt_i (:,:) )                                           ! max ice thickness
-         zmax(2) = MAXVAL( ABS( u_ice(:,:) ) )                                         ! max ice velocity (zonal only)
-         zmax(3) = MAXVAL(     -tm_i (:,:)+273.15_wp , mask = ssmask(:,:) == 1._wp )   ! min ice temperature
-         CALL mpp_max( "stpctl", zmax )                                   ! max over the global domain
+         zmaxlocal(:) = zmax(:)
+         CALL mpp_max( "stpctl", zmax )          ! max over the global domain
+         nstop = NINT( zmax(4) )                 ! update nstop indicator (now sheared among all local domains)
+      ENDIF
+      !                                   !==              write "run.stat" files              ==!
+      !                                   !==  done only by 1st subdomain at writting timestep  ==!
+      IF( ll_wrtruns ) THEN
+         WRITE(numrun,9500) kt, zmax(1), zmax(2), -zmax(3)
+         istatus = NF90_PUT_VAR( nrunid, nvarid(1), (/ zmax(1)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( nrunid, nvarid(2), (/ zmax(2)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( nrunid, nvarid(3), (/-zmax(3)/), (/kt/), (/1/) )
+         IF( kt == nitend )   istatus = NF90_CLOSE(nrunid)
       END IF
-      !                                            !==  run statistics  ==!   ("run.stat" file)
-      IF( ll_wrtruns ) THEN
-         WRITE(numrun,9500) kt, zmax(1), zmax(2), - zmax(3)
-         istatus = NF90_PUT_VAR( idrun, idssh, (/ zmax(1)/), (/kt/), (/1/) )
-         istatus = NF90_PUT_VAR( idrun,   idu, (/ zmax(2)/), (/kt/), (/1/) )
-         istatus = NF90_PUT_VAR( idrun,   ids, (/-zmax(3)/), (/kt/), (/1/) )
-         IF( MOD( kt , 100 ) == 0 ) istatus = NF90_SYNC(idrun)
-         IF( kt == nitend         ) istatus = NF90_CLOSE(idrun)
-      END IF
+      !                                   !==               error handling               ==!
+      !                                   !==  done by all processes at every time step  ==!
+      !
+      IF(   zmax(1) >  100._wp .OR.   &                   ! too large ice thickness maximum ( > 100 m)
+         &  zmax(2) >   10._wp .OR.   &                   ! too large ice velocity ( > 10 m/s)
+         &  zmax(3) >  101._wp .OR.   &                   ! too cold ice temperature ( < -100 degC)
+         &  ISNAN( zmax(1) + zmax(2) + zmax(3) ) .OR.   &               ! NaN encounter in the tests
+         &  ABS(   zmax(1) + zmax(2) + zmax(3) ) > HUGE(1._wp) ) THEN   ! Infinity encounter in the tests
+         !
+         iloc(:,:) = 0
+         IF( ll_colruns ) THEN   ! zmax is global, so it is the same on all subdomains -> no dead lock with mpp_maxloc
+            ! first: close the netcdf file, so we can read it
+            IF( lwm .AND. kt /= nitend )   istatus = NF90_CLOSE(nrunid)
+            ! get global loc on the min/max
+            CALL mpp_maxloc( 'stpctl',      vt_i(:,:)            , tmask(:,:,1), zzz, iloc(1:2,1) )   ! mpp_maxloc ok if mask = F 
+            CALL mpp_maxloc( 'stpctl',ABS( u_ice(:,:) )          , tmask(:,:,1), zzz, iloc(1:2,2) )
+            CALL mpp_minloc( 'stpctl',      tm_i(:,:) - 273.15_wp, tmask(:,:,1), zzz, iloc(1:2,3) )
+            ! find which subdomain has the max.
+            iareamin(:) = jpnij+1   ;   iareamax(:) = 0   ;   iareasum(:) = 0
+            DO ji = 1, 4
+               IF( zmaxlocal(ji) == zmax(ji) ) THEN
+                  iareamin(ji) = narea   ;   iareamax(ji) = narea   ;   iareasum(ji) = 1
+               ENDIF
+            END DO
+            CALL mpp_min( "stpctl", iareamin )         ! min over the global domain
+            CALL mpp_max( "stpctl", iareamax )         ! max over the global domain
+            CALL mpp_sum( "stpctl", iareasum )         ! sum over the global domain
+         ELSE                    ! find local min and max locations:
+            ! if we are here, this means that the subdomain contains some oce points -> no need to test the mask used in maxloc
+            iloc(1:2,1) = MAXLOC(       vt_i(:,:)            , mask = llmsk ) + (/ nimpp - 1, njmpp - 1/)
+            iloc(1:2,2) = MAXLOC( ABS( u_ice(:,:) )          , mask = llmsk ) + (/ nimpp - 1, njmpp - 1/)
+            iloc(1:2,3) = MINLOC(       tm_i(:,:) - 273.15_wp, mask = llmsk ) + (/ nimpp - 1, njmpp - 1/)
+            iareamin(:) = narea   ;   iareamax(:) = narea   ;   iareasum(:) = 1         ! this is local information
+         ENDIF
+         !
+         WRITE(ctmp1,*) ' stp_ctl: ice_thick > 100 m or |ice_vel| > 10 m/s or ice_temp < -100 degC or NaN encounter in the tests'
+         CALL wrt_line( ctmp2, kt, 'ice_thick max',  zmax(1), iloc(:,1), iareasum(1), iareamin(1), iareamax(1) )
+         CALL wrt_line( ctmp3, kt, '|ice_vel| max',  zmax(2), iloc(:,2), iareasum(2), iareamin(2), iareamax(2) )
+         CALL wrt_line( ctmp4, kt, 'ice_temp  min', -zmax(3), iloc(:,3), iareasum(3), iareamin(3), iareamax(3) )
+         IF( Agrif_Root() ) THEN
+            WRITE(ctmp6,*) '      ===> output of last computed fields in output.abort* files'
+         ELSE
+            WRITE(ctmp6,*) '      ===> output of last computed fields in '//TRIM(Agrif_CFixed())//'_output.abort* files'
+         ENDIF
+         !
+         CALL dia_wri_state( Kmm, 'output.abort' )     ! create an output.abort file
+         !
+         IF( ll_colruns .or. jpnij == 1 ) THEN   ! all processes synchronized -> use lwp to print in opened ocean.output files
+            IF(lwp) THEN   ;   CALL ctl_stop( ctmp1, ' ', ctmp2, ctmp3, ctmp4, ctmp5, ' ', ctmp6 )
+            ELSE           ;   nstop = MAX(1, nstop)   ! make sure nstop > 0 (automatically done when calling ctl_stop)
+            ENDIF
+         ELSE                                    ! only mpi subdomains with errors are here -> STOP now
+            CALL ctl_stop( 'STOP', ctmp1, ' ', ctmp2, ctmp3, ctmp4, ctmp5, ' ', ctmp6 )
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( nstop > 0 ) THEN                                                  ! an error was detected and we did not abort yet...
+         ngrdstop = Agrif_Fixed()                                           ! store which grid got this error
+         IF( .NOT. ll_colruns .AND. jpnij > 1 )   CALL ctl_stop( 'STOP' )   ! we must abort here to avoid MPI deadlock
+      ENDIF
       !
 9500  FORMAT(' it :', i8, '    vt_i_max: ', D23.16, ' |u|_max: ', D23.16,' tm_i_min: ', D23.16)
       !
    END SUBROUTINE stp_ctl
+
+
+   SUBROUTINE wrt_line( cdline, kt, cdprefix, pval, kloc, ksum, kmin, kmax )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE wrt_line  ***
+      !!
+      !! ** Purpose :   write information line
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),      INTENT(  out) ::   cdline
+      CHARACTER(len=*),      INTENT(in   ) ::   cdprefix
+      REAL(wp),              INTENT(in   ) ::   pval
+      INTEGER, DIMENSION(3), INTENT(in   ) ::   kloc
+      INTEGER,               INTENT(in   ) ::   kt, ksum, kmin, kmax
+      !
+      CHARACTER(len=80) ::   clsuff
+      CHARACTER(len=9 ) ::   clkt, clsum, clmin, clmax
+      CHARACTER(len=9 ) ::   cli, clj, clk
+      CHARACTER(len=1 ) ::   clfmt
+      CHARACTER(len=4 ) ::   cl4   ! needed to be able to compile with Agrif, I don't know why
+      INTEGER           ::   ifmtk
+      !!----------------------------------------------------------------------
+      WRITE(clkt , '(i9)') kt
+      
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpnij  ,wp))) + 1     ! how many digits to we need to write ? (we decide max = 9)
+      !!! WRITE(clsum, '(i'//clfmt//')') ksum                   ! this is creating a compilation error with AGRIF
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clsum, cl4) ksum
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(MAX(1,jpnij-1),wp))) + 1    ! how many digits to we need to write ? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clmin, cl4) kmin-1
+                                   WRITE(clmax, cl4) kmax-1
+      !
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpiglo,wp))) + 1      ! how many digits to we need to write jpiglo? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(cli, cl4) kloc(1)      ! this is ok with AGRIF
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpjglo,wp))) + 1      ! how many digits to we need to write jpjglo? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clj, cl4) kloc(2)      ! this is ok with AGRIF
+      !
+      IF( ksum == 1 ) THEN   ;   WRITE(clsuff,9100) TRIM(clmin)
+      ELSE                   ;   WRITE(clsuff,9200) TRIM(clsum), TRIM(clmin), TRIM(clmax)
+      ENDIF
+      IF(kloc(3) == 0) THEN
+         ifmtk = INT(LOG10(REAL(jpk,wp))) + 1                   ! how many digits to we need to write jpk? (we decide max = 9)
+         clk = REPEAT(' ', ifmtk)                               ! create the equivalent in blank string
+         WRITE(cdline,9300) TRIM(ADJUSTL(clkt)), TRIM(ADJUSTL(cdprefix)), pval, TRIM(cli), TRIM(clj), clk(1:ifmtk), TRIM(clsuff)
+      ELSE
+         WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpk,wp))) + 1      ! how many digits to we need to write jpk? (we decide max = 9)
+         !!! WRITE(clk, '(i'//clfmt//')') kloc(3)               ! this is creating a compilation error with AGRIF
+         cl4 = '(i'//clfmt//')'   ;   WRITE(clk, cl4) kloc(3)   ! this is ok with AGRIF
+         WRITE(cdline,9400) TRIM(ADJUSTL(clkt)), TRIM(ADJUSTL(cdprefix)), pval, TRIM(cli), TRIM(clj),    TRIM(clk), TRIM(clsuff)
+      ENDIF
+      !
+9100  FORMAT('MPI rank ', a)
+9200  FORMAT('found in ', a, ' MPI tasks, spread out among ranks ', a, ' to ', a)
+9300  FORMAT('kt ', a, ' ', a, ' ', 1pg11.4, ' at i j   ', a, ' ', a, ' ', a, ' ', a)
+9400  FORMAT('kt ', a, ' ', a, ' ', 1pg11.4, ' at i j k ', a, ' ', a, ' ', a, ' ', a)
+      !
+   END SUBROUTINE wrt_line
+
 
    !!======================================================================
