 MODULE sedimento

#ifdef key_sedim

   !&E==========================================================================
   !&E                   ***  MODULE  sedimento  ***
   !&E
   !&E
   !&E ** Purpose : concerns all subroutines related to sediment dynamics
   !&E              to be used in MARSiAM system
   !&E              version 2 : same algorithms (sand+mud) as for Marennes-Oleron
   !&E 
   !&E ** Description :
   !&E     subroutine sed_alloc          ! allocates variables in sediment 
   !&E     subroutine sed_param          ! defines parameterization of sediment
   !&E     subroutine sed_compatibility  ! verification of compatibility between the various parameters
   !&E
   !&E     subroutine sed_init           ! initializes the sediment
   !&E     subroutine sed_init_hsed      ! initializes the sediment thickness (key_sedim_mixsed)
   !&E     subroutine sed_init_fromfile  ! reads filrepsed where all results of 
   !&E                                   ! sediment dyn. are stored
   !&E     subroutine sed_init_ws_sand   ! initializes the settling velocity of sand variables and number of sub time step
   !&E
   !&E     subroutine sed_morphoinit     !
   !&E     subroutine sed_morpho         !
   !&E
   !&E     subroutine sed_skinstress     ! computes the skin stress
   !&E     subroutine sed_settlveloc_ini ! initialisation of settling velocity (not used now)
   !&E     subroutine sed_settlveloc     ! settling velocity in the water column
   !&E
   !&E     subroutine sed_erosion        ! computes erosion thickness
   !&E     subroutine sed_comp_tocr_mixsed    ! critical shear stress for erosion (Pa)
   !&E     subroutine sed_comp_tocr_mudsand   ! critical shear stress for erosion (Pa)
   !&E     subroutine sed_erosion_flux   ! erosion flux (kg/m2/s)
   !&E
   !&E     subroutine sed_sandconcextrap ! extrapolation of sand concentration
   !&E     subroutine sed_depflx         ! computation of deposition tendancy
   !&E     subroutine sed_effdep         ! effective deposition
   !&E     subroutine sed_fusion         ! fusion of two first bottom layers
   !&E
   !&E     subroutine sed_consol_diff_bioturb   ! consolidation in sediment (si besoin) + diffusion + bioturbation
   !&E     subroutine sed_consolid       ! consolidation in sediment
   !&E     subroutine sed_diffusion      ! diffusion in sediment (not ready)
   !&E     subroutine sed_constitutivrel ! sediment permeability & effective stress
   !&E     subroutine sed_difcoef_int    ! diffusion coef at the bed/water interface
   !&E     subroutine sed_difcoef_sed    ! diffusion coef in the sediment
   !&E     subroutine sed_coefbioturb        ! bioturbation coef in the sediment
   !&E
   !&E     subroutine sed_outsaverestart ! save related field for future runs
   !&E
   !&E ** History :
   !&E     !  2009-03  (Pierre Le Hir, Florence Cayocca)
   !&E     !  2010-06  (Florence Cayocca) corrections
   !&E     !  2010-06  (F. Cayocca, V. Garnier) MPI
   !&E     !  2010-07  (B. Thouvenin) taking into account of non constitutive particulate variables
   !&E     !  2011-01 (R. Ramel Alyotech) Ionc library in fortran 90/95, netcdf4 and MPI
   !&E     !  2011-02  (B. Thouvenin) * unique dynamical allocation of raphbx, raphby, frofonx, frofony
   !&E                                * get restart file at a different date
   !&E                                * evolution of diffusion/consolidation
   !&E                                * re-estimate of ndt_part according to the real settling velocity (key_parsub_newdt)
   !&E     !  2014    (B. Thouvenin)  Evolutions, introduction of key_sand2D, introduction of initial adjustment of the sediment height 
   !&E     !  2014-05  (F. Grasso)    Modifications on consolidation subroutines based on "Grasso et al. (Ocean Dynynamics, 2014)"
   !&E                                * subroutine sed_consolid_mixsed
   !&E                                * subroutine sed_constitutivrel
   !&E     !  2014-05  (F. Cayocca) Update and modifs some names
   !&E                                * sand/mud erosion laws
   !&E                                * morpho module
   !&E     ! 2014-05  (R. Verney)  : Modification of settling velocities laws and formulations
   !&E     ! 2014-05  (F. Cayocca)   beginning of update morphodynamic (not operationnal - TO SEE LATER) -  
   !&E     ! 2014-12  (B.Thouvenin) : parallelization OMP
   !&E     ! 2015-01  (B.Thouvenin) : corrections skinstress..
   !&E     ! 2015-02  (B.Thouvenin) : add key_nosubs_Dbio_insed if using sedimento only for constitutive particules
   !&E                                (with key_biolo and key_benthos for example) 
   !&E                                (idem as key_nosedflux of Katerina Kombiadou)
   !&E     ! 2015-04  (B.Thouvenin)  settling velocity of sand variables introduce in sed_init_ws_sand  
   !&E     ! 2015-04  (B.Thouvenin  P. Le Hir) : gestion of dissolved variables in interstitial (pore) waters  
   !E      ! 2015-04  (F.Cayocca, P. Le Hir, B. Thouvenin) corrections for morphodynamic and introduction of lateral slip
   !&E     ! 2015-04  (B.Thouvenin  P. Le Hir) : gestion of dissolved variables in interstitial (pore) waters  
   !&E     ! 2015-07  (B.Thouvenin  P. Le Hir) : correction lateral erosion of dry cell  
   !&E     ! 2015-09  (B.Thouvenin  P. Le Hir) : correction consolidation+diffusion  (for key_mixsed) 
   !&E     ! 2015-11  (B.Thouvenin) : substitution key_nosubs_Dbio_insed with key_sedim_partial
   !&E     ! 2016-02  (B. Mengual, B. Thouvenin) : modification of erosion formulations - several choices
   !&E
   !&E==========================================================================

#include "toolcpp.h"

   !! * Modules used

   USE parameters,  ONLY : lchain,imin,imax,jmin,jmax,ksdmin,ksdmax,rsh,rlg,        &
                           limin,limax,ljmin,ljmax,liminp1,limaxm1,ljminp1,ljmaxm1, &
                           liminm1,ljminm1,limaxp1,ljmaxp1,limaxp2,ljmaxp2,         &
                           liminm2,ljminm2,ljminp2,riosh
   USE ionc4,       ONLY : ionc4_openr,ionc4_read_subxyt,ionc4_read_subzxyt,ionc4_close,  &
                           ionc4_createfile,ionc4_gatt,ionc4_createvar,ionc4_write_sig,&
                           ionc4_vatt_fill,ionc4_torigine,ionc4_write_time,ionc4_write_xyt,&
                           ionc4_write_zxyt,ionc4_sync

   IMPLICIT NONE

   !! * Interface

   INTERFACE sed_erosion
#ifdef key_sedim_mixsed
   MODULE PROCEDURE sed_erosion_mixsed
#endif
#ifdef key_sedim_mudsand
   MODULE PROCEDURE sed_erosion_mudsand
#endif
   END INTERFACE

   INTERFACE sed_effdep
#ifdef key_sedim_mixsed
   MODULE PROCEDURE sed_effdep_mixsed
#endif
#ifdef key_sedim_mudsand
   MODULE PROCEDURE sed_effdep_mudsand
#endif
   END INTERFACE
   
   !! * Accessibility

   ! functions & routines of this module, called outside :
   ! PUBLIC functions                                ! none ?
   PUBLIC sed_effdep,sed_erosion
   PUBLIC sed_init,sed_param,sed_alloc,sed_init_ws_sand 
   PUBLIC sed_sandconcextrap,sed_settlveloc,sed_skinstress,sed_outsaverestart
   PUBLIC sed_depflx,sed_compatibility
   !PUBLIC sed_settlveloc_ini
   PUBLIC sed_init_fromfile
   PUBLIC sed_morpho,sed_morphoinit
#ifdef key_sedim_mixsed
   PUBLIC sed_init_hsed,sed_consol_diff_bioturb
#else
   PUBLIC sed_consol_diffu_mudsand
#endif

   PRIVATE

   !! * Shared or public module variables

   !! _sed = dyn_insed : dynamique in sediment = consolidation, diffusion, bioturbation
   REAL(KIND=rlg),PUBLIC   :: tstart_sed,  &   ! time beginning consolidation/diffusion/bioturbation
                              t_sed,       &   ! time of next dynamic in sediment step
                              dt_sed           ! time step for dynamic in sediment

   LOGICAL,PUBLIC          :: l_fricwave,l_repsed,l_diffused,l_outsed_saltemp
   LOGICAL,PUBLIC          :: l_consolid,l_bioturb,l_dyn_insed
   LOGICAL,PUBLIC          :: l_morphocoupl,l_bathy_smoothing,l_erolat_wet_cell
   LOGICAL,PUBLIC          :: l_unised,l_initsed_vardiss,l_dzsmaxuni,l_init_hsed
   INTEGER,PUBLIC          :: ksmiuni,ksmauni,nk_nivsed_out,choice_nivsed_out
   INTEGER,ALLOCATABLE,DIMENSION(:,:),PUBLIC              :: ksmi,ksma

   CHARACTER(len=lchain),PUBLIC   :: filsauvsed,filrepsed,filoutsed
   CHARACTER(len=lchain),PUBLIC   :: name_out_eptot,name_out_nbniv,name_out_dzs,name_out_tenfon,&
                                     name_out_tenfonc,name_out_tenfonw

   CHARACTER(len=19),PUBLIC       :: date_start_sed
   
   REAL(kind=riosh),PUBLIC      :: riog_valid_min_eptot,riog_valid_max_eptot,riog_valid_min_nbniv, &
                                   riog_valid_max_nbniv,riog_valid_min_dzs,riog_valid_max_dzs,     &
                                   riog_valid_min_tenfon,riog_valid_max_tenfon
!cval reste local                                   riog_valid_min_cvsed,riog_valid_max_cvsed
   REAL(KIND=rsh),DIMENSION(5),PUBLIC                     :: ep_nivsed_out
#ifdef key_sand2D
   LOGICAL,DIMENSION(:),ALLOCATABLE,PUBLIC                :: l_outsandrouse
#endif
   REAL(KIND=rsh),DIMENSION(:),ALLOCATABLE,PUBLIC         :: diam_sed,cini_sed,ros,ep_nivsed_outp1
   REAL(KIND=rsh),DIMENSION(:,:,:),ALLOCATABLE  ,PUBLIC   :: c_sedtot,poro,dzs       
   REAL(KIND=rsh),DIMENSION(:,:,:),ALLOCATABLE  ,PUBLIC   :: corflux,corfluy       
   REAL(KIND=rsh),DIMENSION(:,:,:,:),ALLOCATABLE,PUBLIC   :: cv_sed
   REAL(KIND=rsh),DIMENSION(:,:),ALLOCATABLE,PUBLIC       :: hsed,z0sed,dzsmax
   REAL(KIND=rsh),DIMENSION(:,:),ALLOCATABLE,    PUBLIC   :: tenfon,tenfonc,tenfonw
   REAL(KIND=rsh),DIMENSION(:), ALLOCATABLE,    PUBLIC    :: nivsed_out
   REAL(KIND=rsh),ALLOCATABLE,DIMENSION(:,:)        :: raphbx,raphby,frofonx,frofony
   REAL(KIND=rsh),PUBLIC                 :: epmax_nivsed_out ! epaisseur max depuis la surface du sediment 
   REAL(KIND=rsh),PUBLIC                 :: aref_sand  ! parametre used in sandconcextrap
!!MC ACTIMAR 10/10/2013 
#ifdef key_sand2D
   REAL(KIND=rsh),DIMENSION(:,:,:),ALLOCATABLE,PUBLIC    :: rouse2D,sum_tmp  ! definition nombre de Rouse2D et SUM(dzcche*((htot-hzed)/hzed)**rouse) 
#endif
#ifdef key_flocmod
   REAL(KIND=rsh),DIMENSION(:),ALLOCATABLE,PUBLIC   :: f_ws
#endif
#ifdef key_sedim_mixsed
   REAL(KIND=rsh),DIMENSION(:),ALLOCATABLE,PUBLIC:: diamstar,ws_sand,rosmrowsros,      &
                                                    stresscri0,tetacri0,xnielsen
   REAL(KIND=rsh),PUBLIC     :: z0seduni,fricwav,fws2,cseduni,hseduni,                 &
                                sini_sed,tini_sed,dzsmaxuni,dzsmin,csed_mud_ini,          &
                                cfreshmud,csedmin,cmudcr,cvolmaxsort,cvolmaxmel,       &
                                xperm1,xperm2,xsigma1,xsigma1sg,xsigma2,fimpls,cimpls, &
                                xdifs1,xdifs2,xdifsi1,xdifsi2,epdifi,fexcs,cexcs,      &
                                activlayer,frmudcr2,coef_frmudcr1,x1toce_mud,          &
                                x2toce_mud,E0_sand_para,n_eros_sand,E0_mud,n_eros_mud,      &
                                corfluer1,corfluer2,MF,htncrit_eros,slopefac,          &
                                dtcal_sed,csegreg,csandseg,xexp_ero,ros_sand_homogen,&
                                xbioturbmax,xbioturbk,dbiotu0,dbiotum,frmud_db_max,frmud_db_min
   REAL(KIND=rsh),PUBLIC     :: hsed_new
   REAL(KIND=rsh),DIMENSION(:),ALLOCATABLE,PUBLIC :: cv_sedini
   REAL(KIND=rsh),PUBLIC     :: coef_erolat,coef_tenfon_lat
   REAL(KIND=rlg),DIMENSION(:,:),ALLOCATABLE,PUBLIC      ::  phieau_s2w
   INTEGER,PUBLIC            :: choice_flxdiss_diffsed,ero_option,E0_sand_option

#endif
#ifdef key_sedim_mudsand
   REAL(KIND=rsh),DIMENSION(:),ALLOCATABLE,PUBLIC:: diamstar,ws_sand
   REAL(KIND=rsh),PUBLIC     :: frmudcr1,frmudcr2,E0sable,alphavase,alphasable,        &
                                xeros,x1toce,x2toce,z0seduni,cseduni,hseduni,          &
                                sini_sed,tini_sed,fimpls,cimpls,xcvgce,                &
                                fexcs,cexcs,dzsmin,dzsmaxuni,                          &
                                cfreshmud,csmaxmel,csedmin,                            &
                                xdifs1,xdifs2,xdifsi1,xdifsi2,epdifi,poro1,            &
                                xtas11,xtas12,poro2,xtas21,xtas22,poro3,xtas31,xtas32, &
                                fricwav,fws2,sed_tocr_mudsand,sed_sedimvel,sed_eros_flx
#endif
 
#if defined key_toseelater
   ! creation des masques "mur" (10 mai 2012)
   ! cf. les routines morphoinit et morpho
   LOGICAL, ALLOCATABLE,DIMENSION(:,:)      :: mask_wallx,mask_wally 
#endif
   !---------------------------------------------------------

 
   !! * Private variables

   INTEGER, DIMENSION(:,:), ALLOCATABLE          :: dry_cell
   
   REAL(KIND=rsh),DIMENSION(:,:),ALLOCATABLE     :: epeaui,ustarbot
   REAL(KIND=rsh),DIMENSION(:,:,:),ALLOCATABLE   :: fludif,fluconsol,fluconsol_drycell,flu_dyninsed
   REAL(KIND=rsh),DIMENSION(:),ALLOCATABLE       :: alp1,alp2,alp3,alp4,alp5
   REAL(KIND=rsh),DIMENSION(:,:),ALLOCATABLE     :: morphox,morphoy,hxi,hyi,h0i,phieau_s2w_consol
   REAL(KIND=rlg),DIMENSION(:,:),ALLOCATABLE     :: phieau_s2w_drycell
#ifdef key_toseelater
   REAL(KIND=rsh),DIMENSION(:,:),ALLOCATABLE     :: hupper,dhcell
#endif
   REAL(KIND=rsh)                                :: sed_difint,sed_difsed 


 CONTAINS
 
   !!===========================================================================
 
  SUBROUTINE sed_alloc(l_filesubs)
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_alloc  ***
   !&E
   !&E ** Purpose : allocation of arrays relative to sediment
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by : main, after call traceur and sed_param 
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from traceur.F90
   !&E       !  2008-10  (F. Cayocca)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE parameters,   ONLY : l_testcase
   USE comvars2d,    ONLY : iscreenlog
   USE comsubstance, ONLY : nv_tot,nv_adv,nv_state,nvp,                     &
                            flx_s2w,flx_w2s,flx_w2s_sum,irk_fil,diam_r,cini_sed_r,      &
                            irkm_var_assoc,ros_r,unit_modif_mudbio_N2dw
#ifdef key_flocmod
   USE comsubstance, ONLY : nv_mud
#endif

   !! * Arguments
   LOGICAL, INTENT(IN), OPTIONAL :: l_filesubs

   !! * Local declarations
   INTEGER               :: iv
   CHARACTER(len=lchain) :: filepc

   !!--------------------------------------------------------------------------
   !! * Executable part
   
   ALLOCATE(ksmi(limin:limax,ljmin:ljmax))
   ALLOCATE(ksma(limin:limax,ljmin:ljmax))
   ALLOCATE(hsed(liminm1:limaxp2,ljminm1:ljmaxp2))  ! extend limits beacuse of morpho
   ALLOCATE(z0sed(limin:limax,ljmin:ljmax))
   ALLOCATE(epeaui(limin:limax,ljmin:ljmax))
   ALLOCATE(tenfon(limin:limax,ljmin:ljmax))
   ALLOCATE(tenfonc(limin:limax,ljmin:ljmax))
   ALLOCATE(tenfonw(limin:limax,ljmin:ljmax))
   ALLOCATE(ustarbot(limin:limax,ljmin:ljmax))
   ALLOCATE(dzsmax(limin:limax,ljmin:ljmax))

#ifdef key_sand2D
   ALLOCATE(rouse2D(nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(sum_tmp(nv_adv,limin:limax,ljmin:ljmax))
   rouse2D(1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   sum_tmp(1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
#endif

   ksmi(limin:limax,ljmin:ljmax)=0
   ksma(limin:limax,ljmin:ljmax)=0
   hsed(limin:limaxp1,ljmin:ljmaxp1)=0.0_rsh
   z0sed(limin:limax,ljmin:ljmax)=0.0_rsh
   epeaui(limin:limax,ljmin:ljmax)=0.0_rsh
   tenfon(limin:limax,ljmin:ljmax)=0.0_rsh
   tenfonc(limin:limax,ljmin:ljmax)=0.0_rsh
   tenfonw(limin:limax,ljmin:ljmax)=0.0_rsh
   ustarbot(limin:limax,ljmin:ljmax)=0.0_rsh

   IF(l_morphocoupl) THEN
     ALLOCATE(morphox(liminm1:limax,ljmin:ljmax))
     ALLOCATE(morphoy(limin:limax,ljminm1:ljmax))
     ALLOCATE(hxi(liminm1:limax,ljmin:ljmax))
     ALLOCATE(hyi(limin:limax,ljminm1:ljmax))
     ALLOCATE(h0i(limin:limaxp1,ljmin:ljmaxp1))
     hxi(liminm1:limax,ljmin:ljmax)=0.0_rsh
     hyi(limin:limax,ljminm1:ljmax)=0.0_rsh

#ifdef key_toseelater
     ALLOCATE(hupper(liminm1:limax,ljmin:ljmax))
     ALLOCATE(hupper(liminm1:limax,ljmin:ljmax))
   ! creation des masques "mur" (10 mai 2012)
   ! cf. les routines morphoinit et morpho
    ALLOCATE(mask_wallx(limin:limax,ljmin:ljmax))
    ALLOCATE(mask_wally(limin:limax,ljmin:ljmax))
#endif
   ENDIF

   ALLOCATE(cv_sed(-1:nv_tot,ksdmin:ksdmax,limin:limax,ljmin:ljmax))
   ALLOCATE(cini_sed(nv_state))
   ALLOCATE(c_sedtot(ksdmin:ksdmax,limin:limax,ljmin:ljmax))
   ALLOCATE(poro(ksdmin:ksdmax,limin:limax,ljmin:ljmax))
   ALLOCATE(dzs(ksdmin:ksdmax,limin:limax,ljmin:ljmax))
   ALLOCATE(ros(nvp))
   ALLOCATE(diam_sed(nvp))
   ALLOCATE(flx_s2w(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(flx_w2s(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(flx_w2s_sum(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(corflux(nv_adv,limin:limaxp1,ljmin:ljmax  ))
   ALLOCATE(corfluy(nv_adv,limin:limax  ,ljmin:ljmaxp1))
   ALLOCATE(fludif(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(fluconsol(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(fluconsol_drycell(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(flu_dyninsed(-1:nv_adv,limin:limax,ljmin:ljmax))
   ALLOCATE(alp1(nv_adv))
   ALLOCATE(alp2(nv_adv))
   ALLOCATE(alp3(nv_adv))
   ALLOCATE(alp4(nv_adv))
   ALLOCATE(alp5(nv_adv))
   cv_sed(-1:nv_tot,ksdmin:ksdmax,limin:limax,ljmin:ljmax)=0.0_rsh
   c_sedtot(ksdmin:ksdmax,limin:limax,ljmin:ljmax)=0.0_rsh
   poro(ksdmin:ksdmax,limin:limax,ljmin:ljmax)=0.0_rsh
   dzs(ksdmin:ksdmax,limin:limax,ljmin:ljmax)=0.0_rsh
   flx_s2w(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   flx_w2s(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   flx_w2s_sum(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   corflux(1:nv_adv,limin:limaxp1,ljmin:ljmax  )=1.0_rsh
   corfluy(1:nv_adv,limin:limax  ,ljmin:ljmaxp1)=1.0_rsh
   fludif(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   fluconsol(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   flu_dyninsed(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   fluconsol_drycell(-1:nv_adv,limin:limax,ljmin:ljmax)=0.0_rsh
   
   ros(1:nvp)=0.0_rsh
   diam_sed(1:nvp)=0.0_rsh
   alp1(1:nv_adv)=0.0_rsh
   alp2(1:nv_adv)=0.0_rsh
   alp3(1:nv_adv)=0.0_rsh
   alp4(1:nv_adv)=0.0_rsh
   alp5(1:nv_adv)=1.0_rsh
   
   ALLOCATE(ws_sand(nvp))        
   ALLOCATE(diamstar(nvp))
#ifdef key_sedim_mixsed    
   ALLOCATE(rosmrowsros(nvp))
   ALLOCATE(stresscri0(nvp))
   ALLOCATE(tetacri0(nvp))
   ALLOCATE(xnielsen(nvp))
   ALLOCATE(phieau_s2w(limin:limax,ljmin:ljmax))
   phieau_s2w(limin:limax,ljmin:ljmax)=0.0_rlg
   ALLOCATE(phieau_s2w_drycell(limin:limax,ljmin:ljmax))
   phieau_s2w_drycell(limin:limax,ljmin:ljmax)=0.0_rlg
   ALLOCATE(phieau_s2w_consol(limin:limax,ljmin:ljmax))
   phieau_s2w_consol(limin:limax,ljmin:ljmax)=0.0_rsh
#endif   
#ifdef key_flocmod
   ALLOCATE(f_ws(1:nv_mud))
   f_ws(1:nv_mud)=0.0_rsh
#endif    
   
   IF ((.NOT.l_testcase) .OR. (l_testcase .AND. l_filesubs)) THEN
      DO iv=1,nvp
!        xws(:,iv)=xws_r(:,irk_fil(iv))  ! tjs dans traceur hors key_sedim
!        tocd(iv)=tocd_r(irk_fil(iv))    ! tjs dans traceur hors key_sedim
        ros(iv)=ros_r(irk_fil(iv))
        diam_sed(iv)=diam_r(irk_fil(iv))
      ENDDO
      ! particulate variable MUDB 
      ! conversion of initial value in sediment expressed in mmole/kg (as NoCP variable)
      ! in kg/kg of sediment
      DO iv=1,nv_state
        cini_sed(iv)=cini_sed_r(irk_fil(iv))*unit_modif_mudbio_N2dw(irk_fil(iv))
      ENDDO
   ENDIF

   ALLOCATE( raphbx(liminm1:limax,ljmin:ljmax),raphby(limin:limax,ljminm1:ljmax) )
   ALLOCATE( frofonx(liminm1:limax,ljmin:ljmax),frofony(limin:limax,ljminm1:ljmax) )
   ALLOCATE( dry_cell(limin:limax,ljmin:ljmax))
   dry_cell(limin:limax,ljmin:ljmax)=0

   PRINT_DBG*, 'FIN SED_ALLOC'

   END SUBROUTINE sed_alloc
 
   !!===========================================================================
 
   SUBROUTINE sed_param(rw)
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_param  ***
   !&E
   !&E ** Purpose : reads parameterization of sediment dynamics
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by : ??? init ou main, after initialisation of physical variabless
   !&E                  and before sed_init and sed_alloc
   !&E
   !&E ** External calls : tool_datosec(), tool_sectodat()
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca)
   !&E       !  2009-02  (P. Le Hir)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comvars2d,    ONLY : iscreenlog,dt
   USE comsubstance, ONLY : nvp,nv_ncp,nvpc,name_var,irk_fil,irkm_var_assoc,  &
                            tdebsubs,date_startsub,ws_free_opt,ws_free_min,ws_free_max,ws_free_para,ws_hind_opt,ws_hind_para
   USE parameters,   ONLY : grav
   USE_MPI toolmpi, ONLY : MASTER

   !! * Arguments
   CHARACTER(LEN=1), INTENT( in ) :: rw


   !! * Local declarations
   LOGICAL               :: l_varassoc
   CHARACTER(len=lchain) :: filepc
   CHARACTER(len=19)     :: tool_sectodat
   INTEGER               :: iv,ivpc,isubs,IERR_MPI
   REAL(KIND=rlg)        :: tool_datosec

#ifdef key_sedim_mixsed
   NAMELIST/namsedim_mixsed/ l_fricwave,l_morphocoupl,fricwav,l_repsed, &
                       filrepsed,l_consolid,l_diffused,l_dzsmaxuni,     &
                       dt_sed,date_start_sed,dtcal_sed,                 &
                       choice_flxdiss_diffsed,                          &
                       l_unised,z0seduni,hseduni,cseduni,aref_sand,     &
                       ksmiuni,ksmauni,sini_sed,tini_sed,l_init_hsed,   &
                       cvolmaxsort,cvolmaxmel,activlayer,frmudcr2,      &
                       coef_frmudcr1,x1toce_mud,x2toce_mud,l_bioturb,   &
                       E0_sand_para,n_eros_sand,E0_mud,n_eros_mud,           &
                       ero_option,xexp_ero,E0_sand_option,              &
                       corfluer1,corfluer2,cfreshmud,csed_mud_ini,      &
                       dzsmin,dzsmaxuni,csedmin ,cmudcr,fexcs,          &
                       xperm1,xperm2,xsigma1,xsigma2,fimpls,            &
                       xdifs1,xdifs2,xdifsi1,xdifsi2,epdifi,MF,         &
                       htncrit_eros,slopefac,coef_erolat,coef_tenfon_lat,&
                       l_erolat_wet_cell,l_bathy_smoothing,             &
                       csegreg,csandseg,l_initsed_vardiss,xbioturbmax,  &
                       xbioturbk,dbiotu0,dbiotum,frmud_db_min,frmud_db_max
                       
#else
   NAMELIST/namsedim_mudsand/ l_fricwave,l_morphocoupl,fricwav,         &
                       filrepsed,l_consolid,l_diffused,l_repsed,        &
                       dt_sed,date_start_sed,l_dzsmaxuni,           &
                       l_unised,z0seduni,hseduni,cseduni,aref_sand,     &
                       ksmiuni,ksmauni,sini_sed,tini_sed,               &
                       fimpls,xcvgce,frmudcr1,frmudcr2,E0sable,         &
                       alphavase,alphasable,xeros,x1toce,x2toce,        &
                       cfreshmud,csmaxmel,dzsmin,dzsmaxuni,             &
                       poro1,xtas11,xtas12,poro2,                       &
                       xtas21,xtas22,poro3,xtas31,xtas32,fexcs,         &
                       xdifs1,xdifs2,xdifsi1,xdifsi2,epdifi,l_initsed_vardiss
#endif

   NAMELIST/namsedoutput/ name_out_eptot,name_out_nbniv,name_out_dzs,name_out_tenfon,     &
                          name_out_tenfonc,name_out_tenfonw,choice_nivsed_out,            &   
                          riog_valid_min_eptot,riog_valid_max_eptot,                      &
                          riog_valid_min_nbniv,riog_valid_max_nbniv,riog_valid_min_dzs,   &
                          riog_valid_max_dzs,riog_valid_min_tenfon,riog_valid_max_tenfon, &
                          nk_nivsed_out,ep_nivsed_out,epmax_nivsed_out,l_outsed_saltemp
!cval variable restee locale                          riog_valid_min_cvsed,riog_valid_max_cvsed


   !!--------------------------------------------------------------------------
   !! * Executable part

IF(rw == 'r')THEN
! Lecture des namelists
!==========================

    filepc='./parasedim.txt'
    OPEN(50,file=filepc,status='old',form='formatted',access='sequential')
#ifdef key_sedim_mixsed
    READ(50,namsedim_mixsed)
    xsigma1sg=xsigma1/grav
    IF(csed_mud_ini==0.0_rsh)csed_mud_ini=cfreshmud
    tstart_sed=tool_datosec(date_start_sed)
    IF(.NOT.l_morphocoupl) MF=1.0_rsh
    cimpls=1.0_rsh-fimpls
    cexcs=1.0_rsh-fexcs
    l_dyn_insed=.FALSE.
    IF(l_consolid .OR. l_bioturb .OR. l_diffused)l_dyn_insed=.TRUE.
#else
    READ(50,namsedim_mudsand)
    cimpls=1.0_rsh-fimpls
    cexcs=1.0_rsh-fexcs
    tstart_sed=tool_datosec(date_start_sed)
#endif
    fws2=fricwav*0.5_rsh
    READ(50,namsedoutput)
    IF(choice_nivsed_out==1) nk_nivsed_out=ksdmax
    CLOSE(50) 

    ! conversion mm lus in m for computation
    epmax_nivsed_out=epmax_nivsed_out/1000.0_rsh
    ep_nivsed_out(:)= ep_nivsed_out(:)/1000.0_rsh

    ! fin de lecture de la namelist

ELSE
! ecriture des namelists
!==========================
     IF_MPI (MASTER) THEN
    
#ifdef key_sedim_mixsed
        WRITE(iscreenlog,namsedim_mixsed)
#else
        WRITE(iscreenlog,namsedim_mudsand)
#endif

    ENDIF_MPI
    
ENDIF
     PRINT_DBG*, 'FIN SED_PARAM'   
   
  END SUBROUTINE sed_param

  !!===========================================================================
 
   SUBROUTINE sed_compatibility
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_compatibility  ***
   !&E
   !&E ** Purpose : verifies compatibility between the various parameters (sedim)
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by : cas1DV apres cas_init_sedim
   !&E                init_param
   !&E
   !&E ** External calls : tool_datosec(), tool_sectodat()
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca)
   !&E       !  2009-02  (P. Le Hir)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comvars2d,    ONLY : iscreenlog,ierrorlog,iwarnlog
   USE comsubstance
   USE_MPI toolmpi, ONLY : MASTER

   !! * Arguments

   !! * Local declarations
   INTEGER               :: iv,ivpc,isubs,IERR_MPI,iv2
   REAL(rsh)             :: rohomog
 
    ! test compatibilite tocd /consolidation
    IF_MPI (MASTER) THEN
    IF (l_consolid) THEN
       WRITE(iwarnlog,*)
       WRITE(iwarnlog,*)'****************************'
       WRITE(iwarnlog,*)' You are taking into account CONSOLIDATION PROCESS'
       WRITE(iwarnlog,*)' and fresh deposit concentration (cfreshmud) = ',cfreshmud
       WRITE(iwarnlog,*)' and critical stress of deposition (tocd) of each sand and mud variable are equal to :'
       DO isubs=imud1,imud2
         WRITE(iwarnlog,*)' variable',name_var(irk_fil(isubs)),'  tocd=',tocd(isubs)
       ENDDO
       WRITE(iwarnlog,*)' If cfreshmud is big (> 100), you have to choose a tocd between 1 and 10'
       WRITE(iwarnlog,*)' otherwise you have to choose a tocd > 10 or 20'
       
    ELSE
       DO isubs=isand2+1,nvp
         IF (tocd(isubs) > 1.5 ) THEN
           WRITE(iwarnlog,*)'****************************'
           WRITE(iwarnlog,*)'  WARNING    '
           WRITE(iwarnlog,*)' You are not taking into account CONSOLIDATION PROCESS'
           WRITE(iwarnlog,*)' fresh deposit concentration (cfreshmud) = ',cfreshmud
           WRITE(iwarnlog,*)' and critical stress of deposition (tocd) of isusb=',isubs,' exceed 1 Pa :',tocd(isubs)
           WRITE(iwarnlog,*)' it should be smaller (0.5 to 1 ?) '
         !  CALL_MPI MPI_FINALIZE(IERR_MPI)
         !  STOP
         ENDIF
       ENDDO
    ENDIF
    ! test ros homogene pour les sables dans tous les cas
    ! test ros homogene pour toutes les particules si consolidation

    IF (l_consolid) THEN
       rohomog=ros_r(irk_fil(1))
       DO iv=2,nvpc
        IF(ros_r(irk_fil(iv)) .NE. rohomog) THEN
            WRITE(ierrorlog,*)
            WRITE(ierrorlog,*)'****************************'
            WRITE(ierrorlog,*)' You are taking into account CONSOLIDATION PROCESS'     
            WRITE(ierrorlog,*)' and you must have same density for all constitutive particles'     
            WRITE(ierrorlog,*)' It is not the case : (see in variable.dat) '
            WRITE(ierrorlog,*)' ros(1)= ',ros_r(irk_fil(1))
            WRITE(ierrorlog,*)' ros(',irk_fil(iv),')= ',ros_r(irk_fil(iv))
            
            CALL_MPI MPI_FINALIZE(IERR_MPI)
            STOP
         ENDIF
       ENDDO
     ELSE
       IF(isand2 > isand1) THEN
        rohomog=ros_r(irk_fil(isand1))
        DO iv=isand1+1,isand2
         IF(ros_r(irk_fil(iv)) .NE. rohomog) THEN
            WRITE(ierrorlog,*)
            WRITE(ierrorlog,*)'****************************'
            WRITE(ierrorlog,*)' you must have same density for all sand particles'     
            WRITE(ierrorlog,*)' It is not the case : (see in variable.dat) '
            WRITE(ierrorlog,*)' ros(1)= ',ros_r(irk_fil(isand1))
            WRITE(ierrorlog,*)' ros(',irk_fil(iv),')= ',ros_r(irk_fil(iv))
            
            CALL_MPI MPI_FINALIZE(IERR_MPI)
            STOP
          ENDIF
          DO iv2=isand1,iv
           IF(diam_r(irk_fil(iv)) > diam_r(irk_fil(iv2))) THEN
             WRITE(ierrorlog,*)
             WRITE(ierrorlog,*)'****************************'
             WRITE(ierrorlog,*)' The "SAND" variables should be stored in variable.dat '
             WRITE(ierrorlog,*)'in order of decreasing diameters (the coarsest sand to the finest sand)'     
             WRITE(ierrorlog,*)' It is not the case : (see in variable.dat) '
             WRITE(ierrorlog,*)' diam_r(',irk_fil(iv),')=',diam_r(irk_fil(iv)),' > diam_r(',irk_fil(iv2),')=',diam_r(irk_fil(iv2))
            
             CALL_MPI MPI_FINALIZE(IERR_MPI)
             STOP
           ENDIF
          ENDDO
        ENDDO
       ENDIF
     ENDIF

    ENDIF_MPI


    ! test compatibilite keys sedimento+biolo
#if defined key_sedim_mixsed
#if defined key_biolo && defined key_benthos && ! defined key_sedim_partial
    IF_MPI (MASTER) THEN
       WRITE(ierrorlog,*)
       WRITE(ierrorlog,*)'****************************'
       WRITE(ierrorlog,*)' You are using key_sedim + key_biolo + key_benthos'
       WRITE(ierrorlog,*)' It is not compatible'
       WRITE(ierrorlog,*)' You must add the key key_sedim_partial and biological variables '
       WRITE(ierrorlog,*)' will not be included in sedim module but in benthos module -in biolo)'
       WRITE(ierrorlog,*)
       WRITE(ierrorlog,*)' OR you want simulate biological variables in sediment module'
       WRITE(ierrorlog,*)' and you have to use : key_sedim + key_biolo without key_benthos'
        CALL_MPI MPI_FINALIZE(IERR_MPI)
        STOP
    ENDIF_MPI
#endif
#else
#if defined key_biolo 
    IF_MPI (MASTER) THEN
       WRITE(iscreenlog,*)
       WRITE(iscreenlog,*)'****************************'
       WRITE(iscreenlog,*)' You are using key_sedim + key_biolo + key_sedim_mudsand'
       WRITE(iscreenlog,*)' ATTENTION : biological variable will be simulate in sediment'
#ifdef key_benthos
       WRITE(ierrorlog,*)' '
       WRITE(ierrorlog,*)' You are using key_sedim + key_biolo + key_benthos'
       WRITE(ierrorlog,*)' It is not compatible'
       WRITE(ierrorlog,*)' you have to use : key_sedim + key_biolo without key_benthos'
        CALL_MPI MPI_FINALIZE(IERR_MPI)
#endif
    ENDIF_MPI
#endif
#endif
     PRINT_DBG*, 'FIN SED_compatibility'   
   
  END SUBROUTINE sed_compatibility

  !!===========================================================================
 
   !!===========================================================================
 
  SUBROUTINE sed_init_ws_sand
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_init_ws_sand  ***
   !&E
   !&E ** Purpose : initialize sand settlings velocities and number of sub time step
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  sed_init, sed_init_fromfile and cas_init_sedim (if testcase)
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2015-04  (B. Thouvenin) extracted from sed_init et sed_initfromfile in sedim.F90
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : isand1,isand2,nb_ws_max,imud1,imud2,       &
                            iv_ws_max,ndt_part,dhmin,l_subs2D
   USE comvars2d,    ONLY : iscreenlog,dt
   USE comvars3d,    ONLY : rhoref
   USE parameters,   ONLY : grav
   USE_MPI toolmpi, ONLY : MASTER

   !! * Local declarations
   INTEGER        :: iv,ivg                

   !!--------------------------------------------------------------------------
   !! * Executable part

! valable aussi pour les graviers ???
    DO iv=1,isand2
#ifdef key_sedim_mixsed

      ! here, for simplification, water density = 1000. kg/m3 
      rosmrowsros(iv)=(ros(iv)-rhoref)/ros(iv)
      diamstar(iv)=diam_sed(iv)*10000.0_rsh*(grav*(ros(iv)/rhoref-1.0_rsh))**0.33_rsh
      ! according to Soulsby, 1997, and if viscosity = 10-6 m/s :
      ws_sand(iv)=.000001_rsh*((107.33_rsh+1.049_rsh*diamstar(iv)**3)**0.5_rsh-10.36_rsh)/diam_sed(iv)
      tetacri0(iv)=0.3_rsh/(1.0_rsh+1.2_rsh*diamstar(iv))+0.055_rsh*(1.0_rsh-EXP(-0.02_rsh*diamstar(iv)))
      stresscri0(iv)=tetacri0(iv)*grav*(ros(iv)-rhoref)*diam_sed(iv)
      xnielsen(iv)=12.0_rsh*1000.0_rsh/grav/(1.0_rsh-rhoref/ros(iv))
#else
      diamstar(iv)=diam_sed(iv)*10000.0_rsh*(grav*(ros(iv)/rhoref-1.0_rsh))**0.33_rsh
      ws_sand(iv)=.000001_rsh*((107.33_rsh+1.049_rsh*diamstar(iv)**3)**0.5_rsh-10.36_rsh)/diam_sed(iv)
#endif
    ENDDO
#ifdef key_sedim_mixsed
    DO iv=imud1,imud2
      rosmrowsros(iv)=(ros(iv)-rhoref)/ros(iv)
    ENDDO
    ! homogeneous sand density
    IF (isand1 > 0) THEN
       iv=isand1
       ros_sand_homogen=ros(iv)
    ENDIF
#endif


! reinitialization of ndt_part for sand variables
   DO ivg=1,nb_ws_max 
     iv=iv_ws_max(ivg,1)
     IF ( iv<=isand2) THEN
         IF(l_subs2D(iv)) THEN
           ndt_part(ivg)=1
         ELSE
           IF(ws_sand(iv) .GT. 0.0_rsh)THEN
             ndt_part(ivg)=NINT(dt/MIN(dhmin/ws_sand(iv),dt))
           ELSE
             ndt_part(ivg)=1
             IF_MPI (MASTER) THEN
                write(iscreenlog,*)'VARIABLE SAND :',iv,'  : settling velocity =0 ==> It is not normal'
             ENDIF_MPI
           ENDIF
         ENDIF
         IF_MPI (MASTER) THEN
           write(iscreenlog,*)'VARIABLE : ',iv,'  : number of sub-time step  =',ndt_part(ivg)
         ENDIF_MPI

     ENDIF
   ENDDO

    PRINT_DBG*, 'FIN SED_INIT_WS_SAND'

  END SUBROUTINE sed_init_ws_sand

   !!===========================================================================
 
  SUBROUTINE sed_init
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_init  ***
   !&E
   !&E ** Purpose : initialize the sediment geometry & content
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  main, after reading sed_param
   !&E                 only if not.l_repsed
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from subsedim.F90 (from F. Dufois)
   !&E       !  2009-02  (P. Le Hir, F. Cayocca) modified for new sand/mud sediment 
   !&E       !  2015-04  (F. Grasso) modified initialization at -valmanq instead of valmanq
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nvp,nvpc,nv_state,nv_adv,irk_mod,nv_tot,irkm_var_assoc,  &
                            isand1,isand2,igrav1,igrav2,imud1,imud2,nb_ws_max,       &
                            iv_ws_max,ndt_part,dhmin,unit_modif_mudbio_N2dw,irk_fil, &
                            cv_wat
   USE comvars2d,    ONLY : ig,id,h0,iscreenlog,dt,ierrorlog,iscreenlog
   USE comvarp2d,    ONLY : temp,sal
   USE parameters,   ONLY : valmanq
   USE parameters,   ONLY : grav
   USE_MPI toolmpi, ONLY : MASTER

   !! * Local declarations
   CHARACTER*50   :: filesand,filemud
   INTEGER        :: i,j,k,iv,ivg,imud_nobio,IERR_MPI
   REAL(KIND=rsh) :: somalp,dzsf,dzsgrv,dzssan,dzsmud,voldepgrv,voldepsan,masdepmud,h0max_def,     &
                     dvolsan,dmasmud,dmasmudgrav,dmasmudsand,cini_modif,tot_csed_init,dzsmaxmin


   !!--------------------------------------------------------------------------
   !! * Executable part

    CALL sed_init_ws_sand

    dzsmax(limin:limax,ljmin:ljmax)=dzsmaxuni
    z0sed(limin:limax,ljmin:ljmax)=z0seduni
    ksmi(limin:limax,ljmin:ljmax)=ksmiuni
    ksma(limin:limax,ljmin:ljmax)=0
    hsed(limin:limaxp1,ljmin:ljmaxp1)=-valmanq
    dzs(ksdmin:ksdmax,limin:limax,ljmin:ljmax)=-valmanq
    cv_sed(-1:nv_tot,ksdmin:ksdmax,limin:limax,ljmin:ljmax)=-valmanq
    c_sedtot(ksdmin:ksdmax,limin:limax,ljmin:ljmax)=-valmanq

    IF (l_unised)THEN
   
      ! uniform bed :
      WHERE (h0(limin:limax,ljmin:ljmax) /= -valmanq) ksmi(limin:limax,ljmin:ljmax)=ksmiuni
      WHERE (h0(limin:limax,ljmin:ljmax) /= -valmanq) ksma(limin:limax,ljmin:ljmax)=ksmauni
      DO k=ksdmin,ksdmax
        WHERE (h0(limin:limax,ljmin:ljmax) /= -valmanq) dzs(k,limin:limax,ljmin:ljmax)=0.0_rsh
        WHERE (h0(limin:limax,ljmin:ljmax) /= -valmanq) c_sedtot(k,limin:limax,ljmin:ljmax)=0.0_rsh
        DO iv=-1,nv_tot
          WHERE (h0(limin:limax,ljmin:ljmax) /= -valmanq) cv_sed(iv,k,limin:limax,ljmin:ljmax)=0.0_rsh
        ENDDO
      ENDDO
 
 ! if biological variable (detrital organic matter) are constitutive particulaite variable
 !     readjustment of cini_sed (fraction of csedtot : somme=1)
      cini_modif=0.0_rsh
      imud_nobio=1
      DO iv=1,isand2
        cini_modif=cini_modif+cini_sed(iv)
      ENDDO
      DO iv=imud1,imud2
        IF(unit_modif_mudbio_N2dw(irk_fil(iv)) .NE. 1.0_rsh) THEN
            ! variable bio (Ndet) mis en constitutive mais exprime dans la donnee initiale en mmole/kg de sediment total
            !cini_sed(iv)=cini_sed(iv)/cseduni
            cini_modif=cini_modif+cini_sed(iv)
        ELSE 
            ! vase non detritique
            IF(cini_sed(iv) > (1.0_rsh-cini_modif)) imud_nobio=iv
            cini_modif=cini_modif+cini_sed(iv)
        ENDIF    
      ENDDO
      IF(cini_modif > 1.0_rsh) cini_sed(imud_nobio)=cini_sed(imud_nobio)-cini_modif+1.0_rsh
   
      tot_csed_init=0.0_rsh
      DO iv=1,nvpc
        ! constitutive variables : cini_sed in fraction of cseduni
        tot_csed_init=tot_csed_init+cini_sed(iv)              
      ENDDO
      IF(tot_csed_init .NE. 1.0_rsh) THEN
        WRITE(ierrorlog,*)' '
        WRITE(ierrorlog,*)' inital concentrations of constitutive particulate matter'
        WRITE(ierrorlog,*)' have not been well defined'
        WRITE(ierrorlog,*)' See variable.dat to give fraction of total concentration '
        WRITE(ierrorlog,*)' for each constitutive variable (GRAV, SAND, MUD) (but not MUDB) '
        WRITE(ierrorlog,*)' : the sum of all must be =1 '
        CALL_MPI MPI_FINALIZE(IERR_MPI)
        STOP         
      ENDIF
      
      ! ajustement du hsed et cv_sed
      ! ==============================
#if defined key_sedim_mixsed
      IF(l_init_hsed .AND. hseduni > 0.0_rsh) THEN
         ALLOCATE(cv_sedini(1:nvpc))
         !!! Concentration massique
         DO iv=1,nvpc
            ! constitutive variables : cini_sed in % of cseduni
            cv_sedini(iv)=cseduni*cini_sed(iv)
         ENDDO

         CALL sed_init_hsed(cv_sedini)
         IF_MPI (MASTER) THEN
           WRITE(iscreenlog,*)'NEW TOTAL SEDIMENT THICKNESS AFTER ADJUSTEMENT = ',hsed_new
         ENDIF_MPI
         cseduni=cseduni*hseduni/hsed_new         
         hseduni=hsed_new
         WHERE (h0(limin:limax,ljmin:ljmax) /= -valmanq) hsed(limin:limaxp1,ljmin:ljmaxp1)=hseduni
         DEALLOCATE(cv_sedini)
      ENDIF
#endif

      DO j=ljmin,ljmax
        DO i=MAX0(limin,ig(j)),MIN0(limax,id(j))
          IF(h0(i,j) /= -valmanq) THEN
            DO k=ksmi(i,j),ksma(i,j)
              somalp=0.
              c_sedtot(k,i,j)=0.0_rsh
              DO iv=1,nvpc
                ! constitutive variables : cini_sed in % of cseduni
                cv_sed(iv,k,i,j)=cseduni*cini_sed(iv)        
                c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
                somalp=somalp+cv_sed(iv,k,i,j)/ros(iv)
              ENDDO
              poro(k,i,j)=1.0_rsh-somalp
#ifdef key_sedim_partial
              cv_sed(nvpc+1:nv_state,k,i,j)=0.0_rsh 
#else
              DO iv=nvpc+1,nvp
                ! non constitutive variables : cini_sed in conc/kg of sediment
                IF (irkm_var_assoc(iv) >0) THEN
                  cv_sed(iv,k,i,j)=cini_sed(iv)*cv_sed(irkm_var_assoc(iv),k,i,j)
                ELSE
                  cv_sed(iv,k,i,j)=cini_sed(iv)*c_sedtot(k,i,j)
                END IF
              ENDDO
              IF(l_initsed_vardiss) THEN
              ! initalisation avec cv_wat du fond
                DO iv=nvp+1,nv_adv
                  ! dissolved variables : cini_sed in conc/m3 of pore water
                  cv_sed(iv,k,i,j)=cv_wat(iv,1,i,j)
                ENDDO
              ELSE
                ! initalisation avec cini (variable.dat)
                DO iv=nvp+1,nv_adv
                  ! dissolved variables : cini_sed in conc/m3 of pore water
                  cv_sed(iv,k,i,j)=cini_sed(iv)
                ENDDO
              ENDIF
              DO iv=nv_adv+1,nv_state
                ! + fixed variables : cini_sed in conc/m3 of sediment
                cv_sed(iv,k,i,j)=cini_sed(iv)
              ENDDO
#endif
              IF(l_initsed_vardiss) THEN
              ! initalisation avec valeurs du fond
                cv_sed(-1,k,i,j)=temp(1,i,j)
                cv_sed( 0,k,i,j)=sal(1,i,j)
              ELSE
                cv_sed(-1,k,i,j)=tini_sed
                cv_sed( 0,k,i,j)=sini_sed
              ENDIF
            ENDDO
          ENDIF
        ENDDO
      ENDDO

    ELSE

      ! non uniform bed :
      ! -----------------------

      PRINT*, 'NON UNIFORM BED COVERAGE'
      PRINT*, 'you have to read a netcdf file describing for each grid cell'
      PRINT*, 'the values for hsed(i,j),z0sed(i,j),ksmi(i,j),ksma(i,j)'
      PRINT*, 'c_sedtot(i,j),cini_sed(iv,iv=1:nvstate)'
      STOP
      
!#if defined key_sedim_mixsed
!      ALLOCATE(cv_sedini(1:nvpc))
!#endif
! variables a declarer
! nom du fichier des numeros de facies a mettre dans le parasedim
! lire dans ce fichier i,j,hsed(i,j),z0sed(i,j),ksmi_file(i,j),ksma_file(i,j)
!                      c_sedtot_file(i,j),cini_sed(iv,iv=1:nvstate)
!
!      ksmi(limin:limax,ljmin:ljmax)=ksmi_file(limin:limax,ljmin:ljmax)
!      DO j=ljmin,ljmax
!        DO i=MAX0(limin,ig(j)),MIN0(limax,id(j))
!          DO k=ksmi(i,j),ksma(i,j)
!            c_sedtot(k,i,j)=c_sedtot_file(i,j)
!            somalp=0.
!            DO iv=1,nvpc
!            ! - constitutive variables : cini_sed as percentage of sediment mass
!              cv_sed(iv,k,i,j)=cini_sed(iv)*c_sedtot(k,i,j)
!              somalp=somalp+cv_sed(iv,k,i,j)/ros(iv)
!            ENDDO
!            poro(k,i,j)=1.-somalp
!            DO iv=nvpc+1,nvp
!            ! - non constitutive variables : cini_sed in conc/kg of sediment
!              cv_sed(iv,k,i,j)=cini_sed(iv)*c_sedtot(k,i,j)
!            ENDDO
!            DO iv=nvp+1,nv_adv
!            ! - dissolved variables : cini_sed in conc/m3 of pore water
!             cv_sed(iv,k,i,j)=cini_sed(iv)
!            ENDDO
!            cv_sed(-1,k,i,j)=tini_sed
!            cv_sed( 0,k,i,j)=sini_sed
!          ENDDO
!
!  reinitializes sediment thickness
!#if defined key_sedim_mixsed
!    !!! Concentration massique
!       IF(l_init_hsed) THEN
!          DO iv=1,nvpc
!         ! constitutive variables : cini_sed in % of cseduni
!           cv_sedini(iv)=0.0_rsh
!           DO k=ksmi(i,j),ksma(i,j)
!              cv_sedini(iv)=cv_sedini(iv)+cv_sed(iv,k,i,j)
!           ENDDO
!          ENDDO
!          CALL sed_init_hsed(cv_sedini)
!          hsed(i,j)=hsed_new
!          IF (hsed(i,j) == 0.0_rsh) ksma(i,j)=0
!        ENDIF
!#endif

!        ENDDO
!      ENDDO

!#if defined key_sedim_mixsed
!      DEALLOCATE(cv_sedini)
!#endif
    ENDIF
!
!   FIN COUVERTURE SEDIMENTAIRE NON UNIFORME L_UNISED
!   -------------------------------------------------
!   regular vertical mesh
!   ---------------------

    DO j=ljmin,ljmax
      DO i=limin,limax
        IF(ksma(i,j).NE.0)THEN
          dzsf=hsed(i,j)/float(ksma(i,j)-ksmi(i,j)+1)
          DO k=ksmi(i,j),ksma(i,j)
            dzs(k,i,j)=dzsf
          ENDDO
        ELSE
          dzs(:,i,j)=0.0_rsh
        ENDIF
      ENDDO
    ENDDO

! DZSmax non uniform
    IF(.NOT. l_dzsmaxuni) THEN
       IF_MPI (MASTER) THEN
            IF(dzsmaxuni == 0.0_rsh) THEN
               write(ierrorlog,*)' ERROR in parasedim : dzsmaxuni =0. and l_repsed=.FALSE.'
               write(ierrorlog,*)' if dzsmaxuni =0. dzsmax must be read in an initial file (l_repsed=T)'
               write(ierrorlog,*)' if l_repsed=.FALSE. dzsmax must be evaluated from dzsmaxuni not null'

               CALL_MPI MPI_FINALIZE(IERR_MPI)
               STOP
            ENDIF
       ENDIF_MPI
       ! definition des dzsmax
       ! estime en fonction de la profondeur et de dzsmaxuni considere comme la valeur max de dzsmax
       ! ici valeur minimum de dzsmax en profondeur=dzsmaxuni/100
       ! profondeur max donnant la plus faible valeur de dzsma a informer, mise par defaut=50m
       dzsmaxmin=dzsmaxuni/100._rsh
       h0max_def=50.0_rsh
       write(iscreenlog,*)
       write(iscreenlog,*)'DZSMAX NON UNIFORM'
       write(iscreenlog,*)'by default linearly computed in sed_init (sedim.F90)'
       write(iscreenlog,*)'from dzsmaxuni (',dzsmaxuni,'m) to dzsmaxuni/100 (',dzsmaxmin,'m) depending on water depth'
       write(iscreenlog,*)'dzsmax minimum for depth > ',h0max_def
       write(iscreenlog,*)'PROGRAM your own initialization of dzsmax (or READ a file) in sed_init'
       dzsmax(limin:limax,ljmin:ljmax)=(h0max_def-h0(limin:limax,ljmin:ljmax))/h0max_def*dzsmaxuni+dzsmaxmin
       WHERE (dzsmax(limin:limax,ljmin:ljmax) > dzsmaxuni ) dzsmax(limin:limax,ljmin:ljmax)=dzsmaxuni
       WHERE (dzsmax(limin:limax,ljmin:ljmax) < dzsmaxmin ) dzsmax(limin:limax,ljmin:ljmax)=dzsmaxmin

       ! ou lus dans un fichier (a programmer)
        
    ENDIF
    
    
    PRINT_DBG*, 'FIN SED_INIT'

  END SUBROUTINE sed_init

   !!===========================================================================
 
  SUBROUTINE sed_init_fromfile
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_init_fromfile  ***
   !&E
   !&E ** Purpose : manages the fields to be re-initialized in case of the 
   !&E              continuation of a previous run
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  main 
   !&E
   !&E ** External calls : ionc4_openr, ionc4_read_time,
   !&E                     ionc4_read_subxyt, ionc4_read_subzxyt
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from init.F90
   !&E       !  oct.2008 inserted into module_sedimento.F90 by F. Cayocca
   !&E       !  2009-02  modified for new sand/mud sediment (P. Le Hir & F. Cayocca)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nv_adv,nvp,nvpc,flx_w2s,nv_tot,irkm_var_assoc,nv_state,  &
                            nb_ws_max,iv_ws_max,ndt_part,dhmin,isand2,init_cv_name,  &
                            unit_modif_mudbio_N2dw,irk_fil,name_var,cv_wat
   USE comvars2d,    ONLY : tsauv,t,saverestart_step,ig,id,h0,dt,iscreenlog,l_restart_subs,iscreenlog
   USE comvarp2d,    ONLY : temp,sal
   USE parameters,   ONLY : riosh,grav,valmanq
   USE_MPI toolmpi, ONLY : MASTER

   !! * Local declarations
   CHARACTER*50     :: filesand,filemud
   CHARACTER*8      :: nomcv,nomcs
   INTEGER          :: i,j,k,iv,ivg  
   LOGICAL          :: l_readiv             
   REAL(KIND=rsh)                                             ::  somalp,dzsf,eptot,dzsmaxmin,h0max_def
   REAL(KIND=riosh),DIMENSION(ksdmax,limin:limax,ljmin:ljmax) ::  tzecrits
   REAL(KIND=riosh),DIMENSION(limin:limax,ljmin:ljmax)        ::  xind

   !!--------------------------------------------------------------------------   
   !! * Executable part

     CALL sed_init_ws_sand

     CALL ionc4_openr(filrepsed,l_out_nc4par=.true.)

     CALL ionc4_read_subxyt(filrepsed,'ksmi',xind,limin,limax,ljmin,ljmax,1,0,0)
     DO j=ljmin,ljmax
        DO i=limin,limax
          ksmi(i,j)=INT(xind(i,j))
        END DO
     END DO

     CALL ionc4_read_subxyt(filrepsed,'ksma',xind,limin,limax,ljmin,ljmax,1,0,0)
     DO j=ljmin,ljmax 
        DO i=limin,limax 
          ksma(i,j)=INT(xind(i,j)) 
        END DO 
     END DO
     WHERE (h0(limin:limax,ljmin:ljmax) == -valmanq) ksmi(limin:limax,ljmin:ljmax)=1
     WHERE (h0(limin:limax,ljmin:ljmax) == -valmanq) ksma(limin:limax,ljmin:ljmax)=0

     IF(.NOT. l_dzsmaxuni) THEN 
       IF( dzsmaxuni==0.0_rsh) THEN ! dzsmax directement lu dans le fihcier initial
         CALL ionc4_read_subxyt(filrepsed,'dzsmax',xind,limin,limax,ljmin,ljmax,1,0,0)
         DO j=ljmin,ljmax 
           DO i=limin,limax 
             dzsmax(i,j)=INT(xind(i,j)) 
           END DO 
         END DO
       ELSE
         ! definition des dzsmax
         ! estime en fonction de la profondeur et de dzsmaxuni considere comme la valeur max de dzsmax
         ! ici valeur minimum de dzsmax en profondeur=dzsmaxuni/100
         ! profondeur max donnant la plus faible valeur de dzsma a informer, mise par defaut=50m
          dzsmaxmin=dzsmaxuni/100._rsh
          h0max_def=50.0_rsh
          write(iscreenlog,*)
          write(iscreenlog,*)'DZSMAX NON UNIFORM and not known (dzsmaxuni/=0) in file :',filrepsed
          write(iscreenlog,*)'by default linearly computed in sed_initfromfile (sedim.F90)'
          write(iscreenlog,*)'from dzsmaxuni (',dzsmaxuni,'m) to dzsmaxuni/100 (',dzsmaxmin,'m) depending on water depth'
          write(iscreenlog,*)'dzsmax minimum for depth > ',h0max_def
          write(iscreenlog,*)'PROGRAM your own initialization of dzsmax (or READ a file) in sed_initfromfile'
          dzsmax(limin:limax,ljmin:ljmax)=(h0max_def-h0(limin:limax,ljmin:ljmax))/h0max_def*dzsmaxuni+dzsmaxmin
          WHERE (dzsmax(limin:limax,ljmin:ljmax) > dzsmaxuni ) dzsmax(limin:limax,ljmin:ljmax)=dzsmaxuni
          WHERE (dzsmax(limin:limax,ljmin:ljmax) < dzsmaxmin ) dzsmax(limin:limax,ljmin:ljmax)=dzsmaxmin

         ! ou lus dans un fichier (a programmer)
       
       ENDIF
     ELSE
         dzsmax(limin:limax,ljmin:ljmax)=dzsmaxuni
     ENDIF
       

     CALL ionc4_read_subzxyt(filrepsed,'dzs',tzecrits,limin,limax,ljmin,ljmax,1,ksdmax,1,0,0,1)
     DO j=ljmin,ljmax 
      DO i=limin,limax 
        DO k = 1,ksdmax 
           dzs(k,i,j)=tzecrits(k,i,j)
        END DO 
      END DO 
     END DO

     DO iv =-1,nv_adv
       l_readiv=.false.
       IF (iv==-1) THEN
          nomcv='concTEM'
          nomcs='fxw2sTEM'
          l_readiv=.true.
       ELSE IF (iv==0) THEN
          nomcv='concSAL'
          nomcs='fxw2sSAL'
          l_readiv=.true.
       ELSE 
          WRITE(nomcv,10) iv
          WRITE(nomcs,20) iv
          IF (l_restart_subs .OR. iv <= nvpc .OR. (.NOT. l_restart_subs .AND. TRIM(init_cv_name(iv))/='none')) l_readiv=.true.
       ENDIF

       IF (l_readiv) THEN
         CALL ionc4_read_subzxyt(filrepsed,nomcv,tzecrits,                         &
                           limin,limax,ljmin,ljmax,1,ksdmax,1,0,0,1)
         DO j =ljmin,ljmax
           DO i =limin,limax
             DO k =1,ksdmax
               cv_sed(iv,k,i,j)=tzecrits(k,i,j)
             ENDDO
           ENDDO
         ENDDO

         CALL ionc4_read_subxyt(filrepsed,nomcs,xind,limin,limax,ljmin,ljmax,1,0,0)
         DO j = ljmin,ljmax
           DO i = limin,limax
             flx_w2s(iv,i,j) = xind(i,j)
           ENDDO
         ENDDO
      ELSE
         IF(l_initsed_vardiss) THEN
         !initialisation des variables dissoutes + salinite et temperature avec cv_wat du fond
           IF(iv==-1)THEN
             DO k=ksmi(i,j),ksma(i,j)
               cv_sed(iv,k,:,:)=temp(1,:,:)
             ENDDO
           ELSE IF(iv==0) THEN
             DO k=ksmi(i,j),ksma(i,j)
               cv_sed(iv,k,:,:)=sal(1,:,:)
             ENDDO
           ELSE IF(iv>nvp) THEN
             DO k=ksmi(i,j),ksma(i,j)
               cv_sed(iv,k,:,:)=cv_wat(iv,1,:,:)
             ENDDO
           ELSE
             cv_sed(iv,:,:,:)=cini_sed(iv)
           ENDIF
         ELSE
           cv_sed(iv,:,:,:)=cini_sed(iv)
         ENDIF
      ENDIF

      ENDDO
      CALL ionc4_close(filrepsed)


     DO j=ljmin,ljmax
       DO i=MAX0(limin,ig(j)),MIN0(limax,id(j))
         z0sed(i,j)=z0seduni
         IF (h0(i,j) /= -valmanq) THEN
         DO k=ksmi(i,j),ksma(i,j)
           somalp=0.0_rsh
           c_sedtot(k,i,j)=0.0_rsh
           DO iv=1,nvpc
             c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
             somalp=somalp+cv_sed(iv,k,i,j)/ros(iv)
           END DO
           poro(k,i,j)=1.0_rsh-somalp
         END DO
        END IF
       END DO
     END DO
      
   10 FORMAT('concen',i2.2)
   20 FORMAT('flxw2s',i2.2)
      
  END SUBROUTINE sed_init_fromfile

   !!===========================================================================
 
  SUBROUTINE sed_morphoinit
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_morphoinit  ***
   !&E
   !&E ** Purpose : 
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  main 
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  march 2009 (P. Le Hir) enables morphodynamics computation
   !&E       !  2011-11  (V. Garnier) Spatial extension of ssh(liminm2:limaxp2,ljminm2:ljmaxp2)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comvars2d,    ONLY : ig,id,jb,jh,hx,hy,h0,h0fond,l_obc_cycl_x,l_obc_cycl_y
   USE comvarp2d,    ONLY : ssh
   USE parameters,   ONLY : valmanq
#ifdef key_castest
   USE parameters,   ONLY : num_testcase
#endif

   USE_MPI toolmpi,  ONLY : ex_i_rsh,ex_j_rsh

   !! * Local declarations
   INTEGER                  :: i,j,k          
   REAL(KIND=rsh)           :: hultra

   !!--------------------------------------------------------------------------  
   !! * Executable part

      PRINT_DBG*, 'DANS SED_MORPHO_INIT'

#ifdef key_toseelater
      ! mask_wallx(i,j) & mask_wally(i,j) indicate whether morphodynamic coupling  
      ! is effective for hx(i,j) or hy(i,j) - coupling only if mask i set to .TRUE.
      mask_wallx(:,:)=.FALSE.
      mask_wally(:,:)=.FALSE.
      DO j=ljmin,ljmax
      DO i=limin,limax            ! modification des boucles MPI
         IF(hx(i,j)/=-valmanq-h0fond) mask_wallx(i,j)=.TRUE.
         IF(hy(i,j)/=-valmanq-h0fond) mask_wally(i,j)=.TRUE.
      ENDDO
      ENDDO
#endif

      morphox(liminm1:limax,ljmin  :ljmax)=1.0_rsh
      morphoy(limin  :limax,ljminm1:ljmax)=1.0_rsh

      DO j=ljminp1,ljmaxm1
      DO i=MAX0(liminp1,ig(j)+1),MIN0(limaxm1,id(j)-1)
        hsed(i,j)=0.0_rsh
        IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
          DO k=ksmi(i,j),ksma(i,j)
            hsed(i,j)=hsed(i,j)+dzs(k,i,j)
          ENDDO
        ENDIF
      ENDDO
      ENDDO

      ! hypothese gradient nul aux frontieres
      IF_MPI (ljmax==jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
            hsed(i,jmax)=hsed(i,jmax-1)
        ENDDO
      ENDIF_MPI
      IF_MPI (ljmin==jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
            hsed(i,jmin+1)=hsed(i,jmin+2)
        ENDDO
      ENDIF_MPI
      IF_MPI (limax == imax) THEN
#ifdef key_castest
      IF (num_testcase==41) THEN   ! testcase estuar
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
           hsed(imax,j)=0.0_rsh
        ENDDO
      ELSE
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
           hsed(imax,j)=hsed(imax-1,j)
        ENDDO
      ENDIF
#else
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
           hsed(imax,j)=hsed(imax-1,j)
        ENDDO
#endif
      ENDIF_MPI

      IF_MPI(limin==imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
           hsed(imin+1,j)=hsed(imin+2,j)
        ENDDO
      ENDIF_MPI

      ! les quatre coins 
      IF_MPI (limax == imax .AND. ljmax == jmax) THEN
         hsed(limax,ljmax)=hsed(limax-1,ljmax-1)
      ENDIF_MPI

     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        hsed(limax,ljmin+1)=hsed(limax-1,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        hsed(limin+1,ljmin+1)=hsed(limin+2,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        hsed(limin+1,ljmax)=hsed(limin+2,ljmax-1)
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : hsed n est pas alloue de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite sur hsed
     IF(l_obc_cycl_x) THEN
       DO j=ljminp1,ljmax
          hsed(imin+1,j)=hsed(imax-1,j)
          hsed(imax,j)=hsed(imin+2,j)
       ENDDO
     ENDIF
     ! condition de periodicite sur hsed
     IF(l_obc_cycl_y) THEN
       DO i=liminp1,limax
          hsed(i,jmin+1)=hsed(i,jmax-1)
          hsed(i,jmax)=hsed(i,jmin+2)
       ENDDO
     ENDIF
#endif

   CALL_MPI ex_i_rsh(0,1,1,limin,limaxp1,ljmin,ljmaxp1,hsed(limin:limaxp1,ljmin:ljmaxp1))
   CALL_MPI ex_j_rsh(0,1,1,limin,limaxp1,ljmin,ljmaxp1,hsed(limin:limaxp1,ljmin:ljmaxp1))

#ifdef key_toseelater
      DO j=ljminp1,ljmaxm1
      DO i=MAX0(liminp1,ig(j)+1),MIN0(limaxm1,id(j)-1)
        IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
          IF(mask_wallx(i,j)) THEN
             hxi(i,j)=hx(i,j)+0.5_rsh*(hsed(i,j)+hsed(i+1,j))*morphox(i,j)
          ELSE
             hxi(i,j)=hx(i,j)
          ENDIF
          IF(mask_wally(i,j)) THEN
             hyi(i,j)=hy(i,j)+0.5_rsh*(hsed(i,j)+hsed(i,j+1))*morphoy(i,j)
          ELSE
             hyi(i,j)=hy(i,j)
          ENDIF
        ENDIF
      ENDDO
      ENDDO
#endif

      DO j=ljmin,ljmax
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
        IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
             hxi(i,j)=hx(i,j)+0.5_rsh*(hsed(i,j)+hsed(i+1,j))*morphox(i,j)
             hyi(i,j)=hy(i,j)+0.5_rsh*(hsed(i,j)+hsed(i,j+1))*morphoy(i,j)
        ENDIF
      ENDDO
      ENDDO

     ! limites
      IF_MPI (ljmax==jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          hxi(i,ljmax)=hxi(i,ljmax-1)
          hyi(i,ljmax)=hyi(i,ljmax-1)
        ENDDO
      ENDIF_MPI
      IF_MPI (ljmin==jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
         hxi(i,ljmin+1)=hxi(i,ljmin+2)
         hyi(i,ljmin+1)=hyi(i,ljmin+2)
        ENDDO
      ENDIF_MPI
      IF_MPI (limax == imax) THEN
#ifdef key_castest
      IF (num_testcase==41) THEN
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
         hxi(limax,j)=hx(limax,j)
         hyi(limax,j)=hy(limax,j)
        ENDDO
      ELSE
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
         hxi(limax,j)=hxi(limax-1,j)
         hyi(limax,j)=hyi(limax-1,j)
        ENDDO
      ENDIF
#else
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
         hxi(limax,j)=hxi(limax-1,j)
         hyi(limax,j)=hyi(limax-1,j)
        ENDDO
#endif
      ENDIF_MPI
      IF_MPI(limin==imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
          hxi(limin+1,j)=hxi(limin+2,j)
          hyi(limin+1,j)=hyi(limin+2,j)
        ENDDO
      ENDIF_MPI

      ! les quatre coins
      IF_MPI (limax == imax .AND. ljmax == jmax) THEN
        hxi(limax,ljmax)=hxi(limax-1,ljmax-1)
        hyi(limax,ljmax)=hyi(limax-1,ljmax-1)
      ENDIF_MPI
      IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        hxi(limax,jmin+1)=hxi(limax-1,ljmin+2)
        hyi(limax,jmin+1)=hxi(limax-1,ljmin+2)
      ENDIF_MPI
      IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        hxi(limin+1,jmin+1)=hxi(limin+2,jmin+2)
        hyi(limin+1,jmin+1)=hyi(limin+2,jmin+2)
      ENDIF_MPI
      IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        hxi(limin+1,jmax)=hxi(limin+2,jmax-1)
        hyi(limin+1,jmax)=hyi(limin+2,jmax-1)
      ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : hxi,hyi ne sont pas alloues de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple

      ! condition de periodicite dans la direction x 
      IF(l_obc_cycl_x) THEN
        DO j=ljminp1,ljmax 
          IF_MPI (limin==imin) THEN 
          hxi(imin+1,j)=hxi(imax-1,j)
          hxi(imax,j)=hxi(imin+2,j)
          hyi(imin+1,j)=hyi(imax-1,j)
          hyi(imax,j)=hyi(imin+2,j)
        ENDDO
      ENDIF

      ! condition de periodicite dans la direction y
      IF(l_obc_cycl_y) THEN
        DO i=liminp1,limax
          hxi(i,jmin+1)=hxi(i,jmax-1)
          hxi(i,jmax)=hxi(i,jmin+2)
          hyi(i,jmin+1)=hyi(i,jmax-1)
          hyi(i,jmax)=hyi(i,jmin+2)
        ENDDO
      ENDIF
#endif

      ! evaluation de la cote des mailles
      ! ---------------------------------
      
      DO j=ljmin,ljmax
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
        IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
          h0(i,j)=MAX(hx(i,j),hy(i,j),hx(i-1,j),hy(i,j-1))+h0fond
#ifdef key_castest
          IF (.NOT. num_testcase==41) ssh(i,j)=MAX(ssh(i,j),-h0(i,j))
#else
          ssh(i,j)=0.0_rsh
#endif
        ENDIF      
      ENDDO
      ENDDO

     ! modification des conditions aux frontieres
     ! hypothese gradient nul aux frontieres
#ifdef key_castest
     IF_MPI (ljmax == jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          IF (.NOT. num_testcase==41) h0(i,jmax)=h0(i,jmax-1)
          ssh(i,jmax)=ssh(i,jmax-1)
        ENDDO
     ENDIF_MPI
     IF_MPI (ljmin == jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
          IF (.NOT. num_testcase==41) THEN
           h0(i,jmin+1)=h0(i,jmin+2)
           ssh(i,jmin+1)=ssh(i,jmin+2)
          ENDIF
        ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax) THEN
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
           IF (.NOT. num_testcase==41) h0(imax,j)=h0(imax-1,j)
           ssh(imax,j)=ssh(imax-1,j)
        ENDDO
     ENDIF_MPI
     IF_MPI (limin == imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
          IF (.NOT. num_testcase==41) THEN
           h0(imin+1,j)=h0(imin+2,j)
           ssh(imin+1,j)=ssh(imin+2,j)
          ENDIF
        ENDDO
     ENDIF_MPI
#else
     IF_MPI (ljmax == jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          h0(i,jmax)=h0(i,jmax-1)
          ssh(i,jmax)=ssh(i,jmax-1)
        ENDDO
     ENDIF_MPI
     IF_MPI (ljmin == jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
          h0(i,jmin+1)=h0(i,jmin+2)
          ssh(i,jmin+1)=ssh(i,jmin+2)
        ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax) THEN
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
           h0(imax,j)=h0(imax-1,j)
           ssh(imax,j)=ssh(imax-1,j)
        ENDDO
     ENDIF_MPI
     IF_MPI (limin == imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
          h0(imin+1,j)=h0(imin+2,j)
          ssh(imin+1,j)=ssh(imin+2,j)
        ENDDO
     ENDIF_MPI
#endif

     ! les quatre coins 
     IF_MPI (limax == imax .AND. ljmax == jmax) THEN
        h0(imax,jmax)=h0(imax-1,jmax-1)
        ssh(imax,jmax)=ssh(imax-1,jmax-1)
     ENDIF_MPI
     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        h0(imax,jmin+1)=h0(imax-1,jmin+2)
        ssh(imax,jmin+1)=ssh(imax-1,jmin+2)
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        IF (.NOT. num_testcase==41) THEN
              h0(imin+1,jmin+1)=h0(imin+2,jmin+2)
              ssh(imin+1,jmin+1)=ssh(imin+2,jmin+2)
        ENDIF
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        h0(imin+1,jmax)=h0(imin+2,jmax-1)
        ssh(imin+1,jmax)=ssh(imin+2,jmax-1)
     ENDIF_MPI
!
!  initial updating of  hx and hy:
     CALL_MPI ex_i_rsh(0,1,1,limin,limaxp1,ljmin,ljmaxp1,h0(limin:limaxp1,ljmin:ljmaxp1))
     CALL_MPI ex_j_rsh(0,1,1,limin,limaxp1,ljmin,ljmaxp1,h0(limin:limaxp1,ljmin:ljmaxp1))
      DO j=ljmin,MIN0(ljmax,jmax-1)   !(avant : jusqu a ljmax)
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-2)
            hx(i,j)=MIN(h0(i,j),h0(i+1,j))-h0fond
            hy(i,j)=MIN(h0(i,j),h0(i,j+1))-h0fond
     enddo
     enddo
    
#ifdef key_toseelater
!  PROBLEME : h0 , ssh ne sont pas alloues de imin a imac et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite dans la direction x
     IF(l_obc_cycl_x) THEN
        DO j=ljminp1,ljmax
          h0(imin+1,j)=h0(imax-1,j)
          h0(imax,j)=h0(imin+2,j)
          ssh(imin+1,j)=ssh(imax-1,j)
          ssh(imax,j)=ssh(imin+2,j)
        ENDDO
     ENDIF

     ! condition de periodicite dans la direction y
     IF(l_obc_cycl_y) THEN
        DO i=liminp1,limax
          h0(i,jmin+1)=h0(i,jmax-1)
          h0(i,jmax)=h0(i,jmin+2)
          ssh(i,jmin+1)=ssh(i,jmax-1)
          ssh(i,jmax)=ssh(i,jmin+2)
        ENDDO
     ENDIF
#endif

#ifdef key_toseelater
!ATTENTION : hupper et dhcell non utilises, a integrer a l avenir pour bien gerer 
!            le decouvrement (coherence avec fwet de SIAM) - voir PLH
      hultra=10000.0_rsh
      DO j=ljmin,ljmax
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
        IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN

          hupper(i,j)=MIN(hx(i,j)*morphox(i,j)+(1.0_rsh-morphox(i,j))*hultra,         &
                          hx(i-1,j)*morphox(i-1,j)+(1.0_rsh-morphox(i-1,j))*hultra,   &
                          hy(i,j)*morphoy(i,j)+(1.0_rsh-morphoy(i,j))*hultra,         &
                          hy(i,j-1)*morphoy(i,j-1)+(1.0_rsh-morphoy(i,j-1))*hultra)
          IF(hupper(i,j).GE.hultra)hupper(i,j)=-99.99_rsh
          dhcell(i,j)=h0(i,j)-hupper(i,j)
        ENDIF
      ENDDO  
      ENDDO        
#endif

! h0i : total depth invariable (while h0 and hsed may vary)
      do j=ljmin,ljmax
      do i=limin,limax
        h0i(i,j)=h0(i,j)+hsed(i,j)
      enddo
      enddo

    CALL_MPI ex_i_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,ssh(liminm2:limaxp2,ljminm2:ljmaxp2))
    CALL_MPI ex_j_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,ssh(liminm2:limaxp2,ljminm2:ljmaxp2))
    CALL_MPI ex_i_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,h0(liminm2:limaxp2,ljminm2:ljmaxp2))
    CALL_MPI ex_j_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,h0(liminm2:limaxp2,ljminm2:ljmaxp2))
   ! exchange hupper and dhcell in the future if required
   ! hxi, hyi are not exchanged because neighboring cells are not used

      PRINT_DBG*, 'FIN SED_MORPHO_INIT'

  END SUBROUTINE sed_morphoinit     

   !!===========================================================================
 
  SUBROUTINE sed_morpho
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_morpho  ***
   !&E
   !&E ** Purpose : 
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  step, at the end
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-03  (P. Le Hir) enables morphodynamics computation
   !&E       !  2011-11  (V. Garnier) Spatial extension of ssh(liminm2:limaxp2,ljminm2:ljmaxp2)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comvars2d,    ONLY : ig,id,jb,jh,hx,hy,h0,h0fond,l_obc_cycl_x,l_obc_cycl_y
   USE comvars2d,    ONLY : htx,hty
   USE comvarp2d,    ONLY : ssh
   USE parameters,   ONLY : valmanq
   USE_MPI toolmpi,  ONLY : ex_i_rsh,ex_j_rsh
#ifdef key_castest
   USE parameters,   ONLY : num_testcase
#endif

   !! * Local declarations
   INTEGER                  :: i,j,k
   REAL(KIND=rsh)           :: hultra                
   
   !!--------------------------------------------------------------------------
   !! * Executable part

      PRINT_DBG*, 'DANS SED_MORPHO'

      DO j=ljmin,ljmax
        DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
         IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN

          hsed(i,j)=0.0_rsh
          DO k=ksmi(i,j),ksma(i,j)
            hsed(i,j)=hsed(i,j)+dzs(k,i,j)
          ENDDO
         ENDIF
        ENDDO
      ENDDO
      ! hypothese gradient nul aux frontieres

      IF_MPI (ljmax==jmax) THEN
        DO i=MAX0(limin,ig(ljmax)+1),MIN0(limax,id(ljmax)-1)
            hsed(i,ljmax)=hsed(i,ljmax-1)
        ENDDO
      ENDIF_MPI
      IF_MPI (ljmin==jmin) THEN
        DO i=MAX0(limin,ig(ljmin)+1),MIN0(limax,id(ljmin)-1)
            hsed(i,ljmin+1)=hsed(i,ljmin+2)
        ENDDO
      ENDIF_MPI
#ifdef key_castest
      IF (num_testcase.NE.41) THEN
#endif
        IF_MPI (limax == imax) THEN
          DO j=MAX0(ljmin,jb(limax)+1),MIN0(ljmax,jh(limax)-1)
             hsed(limax,j)=hsed(limax-1,j)
          ENDDO
        ENDIF_MPI
#ifdef key_castest
      ENDIF
#endif

      IF_MPI(limin==imin) THEN
        DO j=MAX0(ljmin,jb(limin)+1),MIN0(ljmax,jh(limin)-1)
           hsed(limin+1,j)=hsed(limin+2,j)
        ENDDO
      ENDIF_MPI

      ! les quatre coins

      IF_MPI (limax == imax .AND. ljmax == jmax) THEN
         hsed(limax,ljmax)=hsed(limax-1,ljmax-1)
      ENDIF_MPI

     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        hsed(limax,ljmin+1)=hsed(limax-1,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        hsed(limin+1,ljmin+1)=hsed(limin+2,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        hsed(limin+1,ljmax)=hsed(limin+2,ljmax-1)
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : hsed n est pas alloue de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite sur hsed
     IF(l_obc_cycl_x) THEN
       DO j=ljminp1,ljmax
          hsed(imin+1,j)=hsed(imax-1,j)
          hsed(imax,j)=hsed(imin+2,j)
       ENDDO
     ENDIF
     ! condition de periodicite sur hsed
     IF(l_obc_cycl_y) THEN
       DO i=liminp1,limax
         hsed(i,jmin+1)=hsed(i,jmax-1)
         hsed(i,jmax)=hsed(i,jmin+2)
       ENDDO
     ENDIF
#endif

     DO j=ljmin,ljmax
     DO i=limin,limax
       h0(i,j)=h0i(i,j)-hsed(i,j)
     ENDDO
     ENDDO

     CALL_MPI ex_i_rsh(-1,2,1,liminm1,limaxp2,ljminm1,ljmaxp2,hsed(liminm1:limaxp2,ljminm1:ljmaxp2))
     CALL_MPI ex_j_rsh(-1,2,1,liminm1,limaxp2,ljminm1,ljmaxp2,hsed(liminm1:limaxp2,ljminm1:ljmaxp2))
     CALL_MPI ex_i_rsh(0,1,1,limin,limaxp1,ljmin,ljmaxp1,h0(limin:limaxp1,ljmin:ljmaxp1))
     CALL_MPI ex_j_rsh(0,1,1,limin,limaxp1,ljmin,ljmaxp1,h0(limin:limaxp1,ljmin:ljmaxp1))

#ifdef key_toseelater  
     ! probleme sur les masques
      DO j=ljmin,ljmax
        DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
         IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
          ! METHODE M1 : modification des hx/hy par la moyenne des milieux de mailles de part et d autre 
           IF(mask_wallx(i,j)) THEN
             hx(i,j)=hxi(i,j)-0.5_rsh*(hsed(i,j)+hsed(i+1,j))*morphox(i,j)
          ENDIF
          IF(mask_wally(i,j)) THEN
             hy(i,j)=hyi(i,j)-0.5_rsh*(hsed(i,j)+hsed(i,j+1))*morphoy(i,j)
          ENDIF
          ! METHODE M2i : modification des hx/hy par la maille voisine la plus basse
          ! hx(i,j)=hxi(i,j)-MIN(hsed(i,j),hsed(i+1,j))*morphox(i,j)
          ! hy(i,j)=hyi(i,j)-MIN(hsed(i,j),hsed(i,j+1))*morphoy(i,j)
         ENDIF
        ENDDO
      ENDDO
      
     ! modification des conditions aux frontieres 
      IF_MPI (ljmax==jmax) THEN
        DO i=MAX0(limin,ig(ljmax)+1),MIN0(limax,id(ljmax)-1)
           IF(mask_wallx(i,ljmax)) hx(i,ljmax)=hx(i,ljmax-1)
           IF(mask_wally(i,ljmax)) hy(i,ljmax)=hy(i,ljmax-1)
        ENDDO
      ENDIF_MPI
      IF_MPI (ljmin==jmin) THEN
        DO i=MAX0(limin,ig(ljmin)+1),MIN0(limax,id(ljmin)-1)
            IF(mask_wallx(i,ljmin+1)) hx(i,ljmin+1)=hx(i,ljmin+2)
            IF(mask_wally(i,ljmin+1)) hy(i,ljmin+1)=hy(i,ljmin+2)
        ENDDO
      ENDIF_MPI

      IF_MPI (limax == imax) THEN
        DO j=MAX0(ljmin,jb(limax)+1),MIN0(ljmax,jh(limax)-1)
           IF(mask_wallx(limax,j)) hx(limax,j)=hx(limax-1,j)
           IF(mask_wally(limax,j)) hy(limax,j)=hy(limax-1,j)
        ENDDO
      ENDIF_MPI

      IF_MPI(limin==imin) THEN
        DO j=MAX0(ljmin,jb(limin)+1),MIN0(ljmax,jh(limin)-1)
           IF(mask_wallx(limin+1,j)) hx(limin+1,j)=hx(limin+2,j)
           IF(mask_wally(limin+1,j)) hy(limin+1,j)=hy(limin+2,j)
        ENDDO
      ENDIF_MPI

      ! les quatre coins 
      IF_MPI (limax == imax .AND. ljmax == jmax) THEN
         IF(mask_wallx(limax,ljmax)) hx(limax,ljmax)=hx(limax-1,ljmax-1)
         IF(mask_wally(limax,ljmax)) hy(limax,ljmax)=hy(limax-1,ljmax-1)
      ENDIF_MPI

     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        IF(mask_wallx(limax,ljmin+1)) hx(limax,ljmin+1)=hx(limax-1,ljmin+2)
        IF(mask_wally(limax,ljmin+1)) hy(limax,ljmin+1)=hy(limax-1,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        IF(mask_wallx(limin+1,ljmin+1)) hx(limin+1,ljmin+1)=hx(limin+2,ljmin+2)
        IF(mask_wally(limin+1,ljmin+1)) hy(limin+1,ljmin+1)=hy(limin+2,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        IF(mask_wallx(limin+1,ljmax)) hx(limin+1,ljmax)=hx(limin+2,ljmax-1)
        IF(mask_wally(limin+1,ljmax)) hy(limin+1,ljmax)=hy(limin+2,ljmax-1)
     ENDIF_MPI

     ! actualisation des masques
     mask_wallx(:,:)=.FALSE.
     mask_wally(:,:)=.FALSE.
     DO j=ljmin,ljmax
     DO i=limin,limax
       IF(hx(i,j)/=-valmanq-h0fond) mask_wallx(i,j)=.TRUE.
       IF(hy(i,j)/=-valmanq-h0fond) mask_wally(i,j)=.TRUE.
     ENDDO
     ENDDO
#endif 

      IF (l_bathy_smoothing) THEN
        DO j=ljmin,ljmax
        DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-2)
          IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-2) THEN
            hx(i,j)=hxi(i,j)-0.3_rsh*(hsed(i,j)+hsed(i+1,j))                                  &
                          -0.1_rsh*(hsed(i-1,j)+hsed(i+2,j))                                &
                          -0.05_rsh*(hsed(i,j+1)+hsed(i,j-1)+hsed(i+1,j+1)+hsed(i+1,j-1))
            hy(i,j)=hyi(i,j)-0.3_rsh*(hsed(i,j)+hsed(i,j+1))                                  &
                          -0.1_rsh*(hsed(i,j-1)+hsed(i,j+2))                                &
                          -0.05_rsh*(hsed(i-1,j)+hsed(i+1,j)+hsed(i-1,j+1)+hsed(i+1,j+1))       
          ENDIF
        ENDDO
        ENDDO
      ELSE
        DO j=ljmin,ljmaxm1
        DO i=limin,limaxm1
          IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
            hx(i,j)=MIN(h0(i,j),h0(i+1,j))-h0fond
            hy(i,j)=MIN(h0(i,j),h0(i,j+1))-h0fond
          ENDIF
        ENDDO
        ENDDO
      ENDIF

      ! modification des conditions aux frontieres 
      IF_MPI (ljmax==jmax) THEN
        DO i=MAX0(limin,ig(ljmax)+1),MIN0(limax,id(ljmax)-1)
#ifdef key_castest_estuary
          hx(i,ljmax)=-7.0_rsh
          hy(i,ljmax)=-7.0_rsh
          hx(i,ljmax-1)=-7.0_rsh
          hy(i,ljmax-1)=-7.0_rsh
          hy(i,ljmax-2)=-7.0_rsh
#else
          hx(i,ljmax)=hx(i,ljmax-1)
          hy(i,ljmax)=hy(i,ljmax-1)
#endif
        ENDDO
      ENDIF_MPI
      IF_MPI (ljmin==jmin) THEN
        DO i=MAX0(limin,ig(ljmin)+1),MIN0(limax,id(ljmin)-1)
#ifdef key_castest_estuary
          hx(i,ljmin)=-7.0_rsh
          hy(i,ljmin)=-7.0_rsh
          hx(i,ljmin+1)=-7.0_rsh
          hy(i,ljmin+1)=-7.0_rsh
#else
          hx(i,ljmin+1)=hx(i,ljmin+2)
          hy(i,ljmin+1)=hy(i,ljmin+2)
#endif
        ENDDO
      ENDIF_MPI
      IF_MPI (limax == imax) THEN
        DO j=MAX0(ljmin,jb(limax)+1),MIN0(ljmax,jh(limax)-1)
#ifdef key_castest_estuary
          hx(limax,j)=-7.0_rsh
          hy(limax,j)=-7.0_rsh
          hx(limax-1,j)=-7.0_rsh
#else
          hx(limax,j)=hx(limax-1,j)
          hy(limax,j)=hy(limax-1,j)
#endif
        ENDDO
      ENDIF_MPI
      IF_MPI(limin==imin) THEN
        DO j=MAX0(ljmin,jb(limin)+1),MIN0(ljmax,jh(limin)-1)
          hx(limin+1,j)=hx(limin+2,j)
          hy(limin+1,j)=hy(limin+2,j)
        ENDDO
      ENDIF_MPI

      ! les quatre coins 
      IF_MPI (limax == imax .AND. ljmax == jmax) THEN
        hx(limax,ljmax)=hx(limax-1,ljmax-1)
        hy(limax,ljmax)=hy(limax-1,ljmax-1)
      ENDIF_MPI
      IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        hx(limax,ljmin+1)=hx(limax-1,ljmin+2)
        hy(limax,ljmin+1)=hy(limax-1,ljmin+2)
      ENDIF_MPI
      IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        hx(limin+1,ljmin+1)=hx(limin+2,ljmin+2)
        hy(limin+1,ljmin+1)=hy(limin+2,ljmin+2)
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        hx(limin+1,ljmax)=hx(limin+2,ljmax-1)
        hy(limin+1,ljmax)=hy(limin+2,ljmax-1)
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : hx et hy ne sont pas alloues de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite dans la direction x
     IF(l_obc_cycl_x) THEN
       DO j=ljminp1,ljmax
          hx(imin+1,j)=hx(imax-1,j)
          hx(imax,j)=hx(imin+2,j)
          hy(imin+1,j)=hy(imax-1,j)
          hy(imax,j)=hy(imin+2,j)
       ENDDO
     ENDIF
     
     ! condition de periodicite dans la direction y
     IF(l_obc_cycl_y) THEN
       DO i=liminp1,limax
          hx(i,jmin+1)=hx(i,jmax-1)
          hx(i,jmax)=hx(i,jmin+2)
          hy(i,jmin+1)=hy(i,jmax-1)
          hy(i,jmax)=hy(i,jmin+2)
       ENDDO
     ENDIF
#endif

      ! evaluation de la cote des mailles
      !---------------------------------

      DO j=ljmin,ljmax
        DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
         IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
            ssh(i,j)=MAX(ssh(i,j),-h0(i,j))
         ENDIF
        ENDDO
      ENDDO

     ! hypothese gradient nul aux frontieres 
     IF_MPI (ljmax == jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          h0(i,ljmax)=h0(i,ljmax-1)
          ssh(i,ljmax)=ssh(i,ljmax-1)
        ENDDO
     ENDIF_MPI

     IF_MPI (ljmin == jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
          h0(i,ljmin+1)=h0(i,ljmin+2)
          ssh(i,ljmin+1)=ssh(i,ljmin+2)
        ENDDO
     ENDIF_MPI

     IF_MPI (limax==imax) THEN

        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
#ifdef key_castest_estuary
          h0(limax,j)=-5.00_rsh
#else
          h0(limax,j)=h0(limax-1,j)
          ssh(limax,j)=ssh(limax-1,j)
#endif
        ENDDO
     ENDIF_MPI

     IF_MPI (limin == imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
          h0(limin+1,j)=h0(limin+2,j)
          ssh(limin+1,j)=ssh(limin+2,j)
        ENDDO
     ENDIF_MPI

     ! les quatre coins 
     IF_MPI (limax == imax .AND. ljmax == jmax) THEN
        h0(limax,ljmax)=h0(limax-1,ljmax-1)
        ssh(limax,ljmax)=ssh(limax-1,ljmax-1)
     ENDIF_MPI

     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        h0(limax,ljmin+1)=h0(limax-1,ljmin+2)
        ssh(limax,ljmin+1)=ssh(limax-1,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        h0(limin+1,ljmin+1)=h0(limin+2,ljmin+2)
        ssh(limin+1,ljmin+1)=ssh(limin+2,ljmin+2)
     ENDIF_MPI

     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        h0(limin+1,ljmax)=h0(limin+2,ljmax-1)
        ssh(limin+1,ljmax)=ssh(limin+2,ljmax-1)
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : h0 , ssh ne sont pas alloues de imin a imxc et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite dans la direction x
     IF(l_obc_cycl_x) THEN
        DO j=ljminp1,ljmax
          h0(imin+1,j)=h0(imax-1,j)
          h0(imax,j)=h0(imin+2,j)
          ssh(imin+1,j)=ssh(imax-1,j)
          ssh(imax,j)=ssh(imin+2,j)
        ENDDO
     ENDIF
     ! condition de periodicite dans la direction y
     IF(l_obc_cycl_y) THEN
        DO i=liminp1,limax
          h0(i,jmin+1)=h0(i,jmax-1)
          h0(i,jmax)=h0(i,jmin+2)
          ssh(i,jmin+1)=ssh(i,jmax-1)
          ssh(i,jmax)=ssh(i,jmin+2)
        ENDDO
     ENDIF
#endif

!ATTENTION : hupper et dhcell non utilises, a integrer a l avenir pour bien gerer 
!            le decouvrement (coherence avec fwet de SIAM) - voir PLH

#ifdef key_toseelater
      hultra=10000.0_rsh
      DO j=ljmin,ljmax
        DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
         IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN

          hupper(i,j)=MIN(hx(i,j)*morphox(i,j)+(1.0_rsh-morphox(i,j))*hultra,         &
                          hx(i-1,j)*morphox(i-1,j)+(1.0_rsh-morphox(i-1,j))*hultra,   &
                          hy(i,j)*morphoy(i,j)+(1.0_rsh-morphoy(i,j))*hultra,         &
                          hy(i,j-1)*morphoy(i,j-1)+(1.0_rsh-morphoy(i,j-1))*hultra)
          IF(hupper(i,j).GE.hultra)hupper(i,j)=-99.99_rsh
          dhcell(i,j)=h0(i,j)-hupper(i,j)
         ENDIF
        ENDDO
      ENDDO
#endif

   CALL_MPI ex_i_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,h0(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_j_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,h0(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_i_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,hx(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_j_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,hx(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_i_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,hy(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_j_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,hy(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_i_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,ssh(liminm2:limaxp2,ljminm2:ljmaxp2))
   CALL_MPI ex_j_rsh(-2,2,1,liminm2,limaxp2,ljminm2,ljmaxp2,ssh(liminm2:limaxp2,ljminm2:ljmaxp2))

  END SUBROUTINE sed_morpho      

   !!==============================================================================

  SUBROUTINE sed_skinstress
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_skinstress  ***
   !&E
   !&E ** Purpose : computes current related bottom shear stress
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  stepu, stepv
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       ! 2011-11 (J. Vareilles) Change in the expression of the bottom stress to be compatible with the 2D/3D
   !&E                              distinctions as is done in the hydrodynamic part
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE parameters,     ONLY : kmax,epsilon,grav,pi,valmanq,exp1
   USE comvarp2d,      ONLY : ssh,u,v
   USE comvars2d,      ONLY : hx,hy,l_obc_cycl_x,l_obc_cycl_y
   USE comvarp3d,      ONLY : uz,vz,boz
   USE comvars2d,      ONLY : ig,id,jb,jh,h0,hex,hey,htx,hty,hm,hminfrot,hmaxfrot,nbouc,h0fond
   USE comsubstance,   ONLY : tdebsubs
   USE comvars3d,      ONLY : sig,rhoref,dsigu,roswat_bot
#ifdef key_wave
   USE wave,           ONLY : wave_ubot, wave_tp,l_wave_rdir
#endif
#if defined key_siggen || defined key_gencoord
   USE toolgeom,       ONLY : f_hzu_x,f_hzu_y
   USE comsiggen,      ONLY : hzutx,hzuty
#endif
#if defined key_1DV_force_towfile
   USE readforcingk1DV, ONLY : mytauw_out      
#endif

   USE_MPI toolmpi,    ONLY : ex_i_rsh,ex_j_rsh

   !! * Local declarations
   INTEGER i,j,k
   REAL(KIND=rsh)                                   :: sigfrot,vit,z,thoule,hhoule,fws2ij
   REAL(KIND=rsh)                                   :: alofwscd,tentot,xwa,coef_a,coef_b,       &
                                                       coef_m,coef_n,coef_p,coef_q,htn
      
   REAL(KIND=rsh),PARAMETER                         :: zfrot=0.010_rsh
   
   REAL(KIND=rsh),PARAMETER                         :: a1=-0.07_rsh, a2=1.87_rsh, a3=-0.34_rsh, a4=-0.12_rsh,   &
                                                       b1=0.27_rsh, b2=0.51_rsh, b3=-0.1_rsh, b4=-0.24_rsh,     &
                                                       cm1=0.72_rsh, cm2=-0.33_rsh, cm3=0.08_rsh, cm4=0.34_rsh, &
                                                       cn1=0.78_rsh, cn2=-0.23_rsh, cn3=0.12_rsh, cn4=-0.12_rsh,&
                                                       p1=-0.75_rsh, p2=0.13_rsh, p3=0.12_rsh, p4=0.02_rsh,     &
                                                       q1=0.89_rsh, q2=0.4_rsh, q3=0.5_rsh, q4=-0.28_rsh,       &     
                                                       hminwave=0.05_rsh

   REAL(KIND=rsh),PARAMETER                         :: a1pa2=a1+a2,a3pa4=a3+a4,                 &
                                                       b1pb2=b1+b2,b3pb4=b3+b4,                 &
                                                       cm1pm2=cm1+cm2,cm3pm4=cm3+cm4,           &
                                                       cn1pn2=cn1+cn2,cn3pn4=cn3+cn4,           &
                                                       p1pp2=p1+p2,p3pp4=p3+p4,                 &
                                                       q1pq2=q1+q2,q3pq4=q3+q4                 
#ifdef key_wave
   REAL(KIND=rsh)                                   :: courant
#endif
   !!--------------------------------------------------------------------------
   !! * Executable part


!   cdcurrent=0.16_rsh/(LOG(1.0_rsh/z0seduni))**2
   raphbx(limin:limax,ljmin:ljmax)=0.0_rsh
   raphby(limin:limax,ljmin:ljmax)=0.0_rsh
   frofonx(limin:limax,ljmin:ljmax)=0.0_rsh
   frofony(limin:limax,ljmin:ljmax)=0.0_rsh


!$OMP PARALLEL DEFAULT(NONE) SHARED(ljmin,ljmax,limin,limax,ig,id,jb,jh     &
!$OMP& ,htx,hty,hm,raphbx,u,uz,raphby,v,vz,ljminp1,ljminp2,ljmaxm1,frofonx  &
!$OMP& ,frofony,hmaxfrot,hminfrot,z0sed,ssh,h0,dry_cell,rhoref,boz,h0fond   &
!$OMP& ,limaxm1,hx,hy,l_morphocoupl                          &
#if defined key_siggen || defined key_gencoord
!$OMP& ,dsigu,hzutx,hzuty                                    &
#else
!$OMP& ,sig                                                  &
#endif
#ifdef key_sedim_mixsed
!$OMP& ,htncrit_eros                                         &
#endif
#ifdef key_MPI_2D
!$OMP& ,liminm1,ljminm1                                      &
#endif
#ifdef key_wave
!$OMP& ,l_fricwave,wave_ubot,wave_tp,fws2,l_wave_rdir        &
#endif
!$OMP& ,tenfonc,tenfon,tenfonw,roswat_bot)                   &
!$OMP& PRIVATE(i,j,k,vit,z                                   & 
#ifdef key_wave
!$OMP& ,fws2ij ,courant, alpha,beta,cosamb,sinamb            &
#endif
!$OMP& ,htn)

! ATTENTION / A REVOIR avec Franck
! correction janvier 2015
!htx,hty n ont pas ete reactualises apres le calcul de ssh au temps n+1
! on les reactualise ici
#ifdef key_MPI_2D
!$OMP DO schedule(runtime)
#else
!$OMP DO schedule(static)
#endif
   DO j=ljmin,ljmaxm1
     DO i=limin,limaxm1
       htx(i,j)=hx(i,j)+0.5_rsh*(ssh(i,j)+ssh(i+1,j))
       hty(i,j)=hy(i,j)+0.5_rsh*(ssh(i,j)+ssh(i,j+1))
#if defined key_siggen || defined key_gencoord
       hzutx(1,i,j)=f_hzu_x(hx(i,j),0.5_rsh*(ssh(i,j)+ssh(i+1,j)),1,i,j)
       hzuty(1,i,j)=f_hzu_y(hy(i,j),0.5_rsh*(ssh(i,j)+ssh(i,j+1)),1,i,j)
#endif
       IF ( htx(i,j)<=0.0_rsh .AND. ( hx(i,j)+ssh(i,j) > 0.0_rsh .OR. hx(i,j)+ssh(i+1,j) > 0.0_rsh) ) THEN
         htx(i,j)=hx(i,j)+MAX(ssh(i,j),ssh(i+1,j))
#if defined key_siggen || defined key_gencoord
         hzutx(1,i,j)=f_hzu_x(hx(i,j),MAX(ssh(i,j),ssh(i+1,j)),1,i,j)
#endif
       END IF
       IF ( hty(i,j)<=0.0_rsh .AND. ( hy(i,j)+ssh(i,j) > 0.0_rsh .OR. hy(i,j)+ssh(i,j+1) > 0.0_rsh )) THEN
         hty(i,j)=hy(i,j)+MAX(ssh(i,j),ssh(i,j+1))
#if defined key_siggen || defined key_gencoord
         hzuty(1,i,j)=f_hzu_y(hy(i,j),MAX(ssh(i,j),ssh(i,j+1)),1,i,j)
#endif
       ENDIF
     END DO

     IF_MPI (limax==imax) THEN
     IF (hy(imax,j) /= -valmanq-h0fond) THEN
       hty(imax,j)=hy(imax,j)+0.5_rsh*(ssh(imax,j)+ssh(imax,j+1))
#if defined key_siggen || defined key_gencoord
       hzuty(1,imax,j)=f_hzu_y(hy(imax,j),0.5_rsh*(ssh(imax,j)+ssh(imax,j+1)),1,imax,j)
#endif
       IF ( hty(imax,j)<=0.0_rsh .AND. ( hy(imax,j)+ssh(imax,j) > 0.0_rsh .OR. hy(imax,j)+ssh(imax,j+1) > 0.0_rsh )) THEN
           hty(imax,j)=hy(imax,j)+MAX(ssh(imax,j),ssh(imax,j+1))
#if defined key_siggen || defined key_gencoord
           hzuty(1,imax,j)=f_hzu_y(hy(imax,j),MAX(ssh(imax,j),ssh(imax,j+1)),1,imax,j)
#endif
       ENDIF
     END IF
     ENDIF_MPI
   END DO ! end do for j loop
!$OMP END DO
!$OMP SINGLE
   IF_MPI (ljmax==jmax) THEN
     DO i=limin,limaxm1
       IF (hx(i,jmax) /= -valmanq-h0fond) THEN
         htx(i,jmax)=hx(i,jmax)+0.5_rsh*(ssh(i,jmax)+ssh(i+1,jmax))
#if defined key_siggen || defined key_gencoord
         hzutx(1,i,jmax)=f_hzu_x(hx(i,jmax),0.5_rsh*(ssh(i,jmax)+ssh(i+1,jmax)),1,i,jmax)
#endif
         IF ( htx(i,jmax)<=0.0_rsh .AND. ( hx(i,jmax)+ssh(i,jmax) > 0.0_rsh .OR. hx(i,jmax)+ssh(i+1,jmax) > 0.0_rsh) ) THEN
             htx(i,jmax)=hx(i,jmax)+MAX(ssh(i,jmax),ssh(i+1,jmax))
#if defined key_siggen || defined key_gencoord
             hzutx(1,i,jmax)=f_hzu_x(hx(i,jmax),MAX(ssh(i,jmax),ssh(i+1,jmax)),1,i,jmax)
#endif
         END IF
       END IF
     ENDDO
   ENDIF_MPI
!$OMP END SINGLE

!#ifdef key_sedim_mixsed
! modification de PLH pour le cas estuar, mais pourquoi ?
!IF(l_morphocoupl) THEN
!!$OMP DO SCHEDULE(RUNTIME)
!   DO j=ljmin,ljmax
!   DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
!      IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
!       IF (htx(i,j).GE.htncrit_eros)raphbx(i,j)=1.0_rsh
!       IF (hty(i,j).GE.htncrit_eros)raphby(i,j)=1.0_rsh
!      ENDIF
!     ENDDO
!   ENDDO
!!$OMP END DO

!ELSE
!#endif

!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljmin,ljmax
   DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
     IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
        IF (htx(i,j).LE.hm) THEN 
           raphbx(i,j)=ABS(u(i,j))/(ABS(u(i,j))+epsilon)
        ELSE 
           raphbx(i,j)=ABS(uz(1,i,j))/(ABS(uz(1,i,j))+epsilon)
        ENDIF 

        IF(hty(i,j).LE.hm) THEN 
           raphby(i,j)=ABS(v(i,j))/(ABS(v(i,j))+epsilon)
        ELSE
           raphby(i,j)=ABS(vz(1,i,j))/(ABS(vz(1,i,j))+epsilon)
        ENDIF 
      ENDIF
     ENDDO
   ENDDO
!$OMP END DO
!#ifdef key_sedim_mixsed
!ENDIF
!#endif

   ! the bottom stress needs to be computed at a fairly "uniform" distance from the bed
   ! throughout the domain. This distance is called zfrot (=0.5), and transcribed into the
   ! corresponding sigma layer
   ! Otherwise, the bottom stress is simply computed in the first layer 

!FLO : rajouter un booleen dans parasedim pour choisir l option
   
!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljminp2,ljmaxm1
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
       !sigfrot=zfrot/(htx(i,j)+epsilon)-1
       !k=1
       !DO WHILE (sig(k).le.sigfrot)
       !k=k+1
       !ENDDO
       !k=MIN(k,kmax)
       !IF (i.eq.160 .AND. j.eq.2) PRINT*, k,sig(k),sigfrot,htx(i,j)

       IF(htx(i,j).LE.hm) THEN            !under hm, hydrodynamic 2D calculation
          vit=SQRT(u(i,j)**2+0.0625_rsh*(v(i,j)+v(i+1,j)            &
              +v(i,j-1)+v(i+1,j-1))**2)*u(i,j)
          frofonx(i,j)=0.16_rsh*(LOG(MAX(MIN(htx(i,j),hmaxfrot),hminfrot)/(z0sed(i,j)*exp1)))**(-2)*vit
       ELSE                               !above hm, hydrodynamic 3D calculation
          k=1
#if defined key_siggen || defined key_gencoord
          z=0.5_rsh*hzutx(k,i,j)*dsigu(k)
#else
          z=(1.0_rsh+sig(k))*htx(i,j)
#endif
          vit=SQRT(uz(k,i,j)**2+0.0625_rsh*(vz(k,i,j)+vz(k,i+1,j)            &
               +vz(k,i,j-1)+vz(k,i+1,j-1))**2)*uz(k,i,j)
          frofonx(i,j)=0.16_rsh*(LOG(z/z0sed(i,j)+1.0_rsh))**(-2)*vit
       ENDIF   
       
       !sigfrot=zfrot/(hty(i,j)+epsilon)-1
       !k=1
       !DO WHILE (sig(k).le.sigfrot)
       !k=k+1
       !ENDDO
       !k=MIN(k,kmax)
      ! IF (i.eq.160 .AND. j.eq.2) PRINT*, 'k',k,sig(k),sigfrot,htx(i,j)
       
       IF(hty(i,j).LE.hm) THEN            !under hm, hydrodynamic 2D calculation
          vit=SQRT(0.0625_rsh*(u(i,j)+u(i,j+1)+u(i-1,j+1)         &
                  +u(i-1,j))**2+v(i,j)**2)*v(i,j)
          frofony(i,j)=0.16_rsh*(LOG(MAX(MIN(hty(i,j),hmaxfrot),hminfrot)/(z0sed(i,j)*exp1)))**(-2)*vit
       ELSE                               !above hm, hydrodynamic 3D calculation
          k=1
#if defined key_siggen || defined key_gencoord
          z=0.5_rsh*hzuty(k,i,j)*dsigu(k)
#else
          z=(1.0_rsh+sig(k))*hty(i,j)
#endif
          vit=SQRT(0.0625_rsh*(uz(k,i,j)+uz(k,i,j+1)+uz(k,i-1,j+1)         &
                           +uz(k,i-1,j))**2+vz(k,i,j)**2)*vz(k,i,j)
          frofony(i,j)=0.16_rsh*(LOG(z/z0sed(i,j)+1.0_rsh))**(-2)*vit
       ENDIF
     ENDDO
   ENDDO
!$OMP END DO

OMPMPI barrier
OMPMPI master
   CALL_MPI ex_i_rsh(-1,0,1,liminm1,limax,ljmin  ,ljmax,raphbx (liminm1:limax,ljmin  :ljmax))
   CALL_MPI ex_i_rsh(-1,0,1,liminm1,limax,ljmin  ,ljmax,frofonx(liminm1:limax,ljmin  :ljmax))
   CALL_MPI ex_j_rsh(-1,0,1,limin  ,limax,ljminm1,ljmax,raphby (limin  :limax,ljminm1:ljmax))
   CALL_MPI ex_j_rsh(-1,0,1,limin  ,limax,ljminm1,ljmax,frofony(limin  :limax,ljminm1:ljmax))
OMPMPI end master
OMPMPI barrier
OMPMPI flush(raphbx,frofonx,raphby,frofony)

    ! calcul de la tension (en N/m2)
    ! ------------------------------
!$OMP SINGLE
   tenfonc(limin:limax,ljmin:ljmax)=0.0_rsh
   tenfonw(limin:limax,ljmin:ljmax)=0.0_rsh
   tenfon(limin:limax,ljmin:ljmax)=0.0_rsh
!$OMP END SINGLE

!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljminp2,ljmax
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j))
       IF (h0(i,j) /= -valmanq) THEN
         htn=h0(i,j)+ssh(i,j)
#ifdef key_sedim_mixsed
         IF(htn .LT.htncrit_eros+h0fond .AND. dry_cell(i,j)==0) THEN
           dry_cell(i,j)=1
         ENDIF
         IF(htn .GT.2.0_rsh*htncrit_eros+h0fond .AND. dry_cell(i,j)==1) THEN
           dry_cell(i,j)=0
         ENDIF
#endif
         IF(dry_cell(i,j)==0) THEN
           tenfonc(i,j)=SQRT(((frofonx(i,j)*raphbx(i,j)+frofonx(i-1,j)        &
                     *raphbx(i-1,j))/(raphbx(i,j)                             &
                     +raphbx(i-1,j)+epsilon))**2+((frofony(i,j)*raphby(i,j)   &
                     +frofony(i,j-1)*raphby(i,j-1))/(raphby(i,j)              &
                     +raphby(i,j-1)+epsilon))**2)*roswat_bot(i,j)

#ifdef key_wave
            fws2ij=fws2
            IF (l_fricwave .AND. wave_ubot(i,j)*wave_tp(i,j) > 0.0_rsh .AND.  &
                     wave_tp(i,j) > 0.001_rsh.AND.wave_ubot(i,j)>0.001_rsh) THEN
              fws2ij=0.5_rsh*1.39_rsh*(wave_ubot(i,j)*wave_tp(i,j)/REAL(2.0_rlg*pi*z0sed(i,j),rsh))**(-0.52_rsh)
            ENDIF

            ! calcul de tenfonw (vagues)
            ! --------------------------
!FLO 11jan2011           tenfonw(i,j)=(rho_bott(i,j)*fws2*wave_ubot(i,j)**2)
            tenfonw(i,j)=(1025._rsh*fws2ij*wave_ubot(i,j)**2)
            !tenfon(i,j)=SQRT(tenfonw(i,j)**2+tenfonc(i,j)**2)
            tenfonw(i,j)=min(15.0_rsh,tenfonw(i,j))  !limitation sur tenfonw, FG(21/07/2015)

            IF (l_wave_rdir ) THEN
               courant=SQRT(u(i,j)**2+v(i,j)**2)
               IF(tenfonc(i,j) > 0.0_rsh .AND. tenfonw(i,j) > 0.0_rsh .AND. courant> 0.0_rsh) THEN

                ! calcul de tenfon avec la formulation de Soulsby (1995)
                ! ======================================================
                ! calcul de tenfonc (courant) influence par les vagues
                ! ----------------------------------------------------
                  tenfonc(i,j)=tenfonc(i,j)*(1+(1.2*(tenfonw(i,j)/(tenfonw(i,j)+tenfonc(i,j)))**3.2))
                  tenfonc(i,j)=min(10.0_rsh,tenfonc(i,j))  !limitation sur tenfonc, FG(21/07/2015)

                ! calcul de la difference d angle entre la direction des vagues et du courant
                ! ---------------------------------------------------------------------------
                ! calcul de l orientation du courant par rapport au nord
                  alpha=ACOS(v(i,j)/courant)   ! en radians
                ! calcul de l orientation des vagues par rapport au nord
                  beta=wave_dir(i,j)*pi/180   ! en radians
                ! calcul de cos(alpha-beta) et sin(alpha-beta)
                  cosamb=ABS(COS(alpha-beta))
                  sinamb=ABS(SIN(alpha-beta))

                ! calcul de tenfon (vagues + courant)
                ! -----------------------------------
                  tenfon(i,j)=SQRT((tenfonc(i,j)+tenfonw(i,j)*cosamb)**2 +(tenfonw(i,j)*sinamb)**2)

              ELSE
                 tenfon(i,j)=tenfonw(i,j)+tenfonc(i,j)
              ENDIF
            ELSE

            ! calcul de tenfon avec la moyenne arithmetique de tw,tc (maximise tenfon, max=25N/m2)
            ! =======================================================================
               tenfon(i,j)=tenfonw(i,j)+tenfonc(i,j)

            ! calcul de tenfon avec la moyenne quadratique de tw,tc (minimise tenfon, max=18N/m2)
            ! =======================================================================
            !   tenfon(i,j)=SQRT(tenfonw(i,j)**2+tenfonc(i,j)**2)
            ENDIF
#elif key_1DV_force_towfile
            tenfon(i,j)=mytauw_out
#else
            tenfon(i,j)=tenfonc(i,j)
#endif
         ENDIF
       ELSE
         tenfonc(i,j)=-valmanq
         tenfonw(i,j)=-valmanq
         tenfon(i,j)=-valmanq
       ENDIF
     ENDDO
   ENDDO
!$OMP END DO
!$OMP END PARALLEL

  ! modification des conditions aux frontieres (28 fevrier 2012)
     ! hypothese gradient nul aux frontieres 
     IF_MPI (ljmax == jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          tenfon(i,jmax)=tenfon(i,jmax-1)
        ENDDO
     ENDIF_MPI
     IF_MPI (ljmin == jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
          tenfon(i,jmin+1)=tenfon(i,jmin+2)
        ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax) THEN
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
           tenfon(imax,j)=tenfon(imax-1,j)
        ENDDO
     ENDIF_MPI
     IF_MPI (limin == imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
          tenfon(imin+1,j)=tenfon(imin+2,j)
        ENDDO
     ENDIF_MPI

     ! les quatre coins (28 fevrier 2012)
     IF_MPI (limax == imax .AND. ljmax == jmax) THEN
        tenfon(imax,jmax)=tenfon(imax-1,jmax-1)
     ENDIF_MPI
     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
        tenfon(imax,jmin+1)=tenfon(imax-1,jmin+2)
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
        tenfon(imin+1,jmin+1)=tenfon(imin+2,jmin+2)
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
        tenfon(imin+1,jmax)=tenfon(imin+2,jmax-1)
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : tenfon n est pas alloue de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple

     ! condition de periodicite dans la direction x (28 fevrier 2012)
     IF(l_obc_cycl_x) THEN
        DO j=ljminp1,ljmax
          tenfon(imin+1,j)=tenfon(imax-1,j)
          tenfon(imax,j)=tenfon(imin+2,j)
        ENDDO
     ENDIF
     ! condition de periodicite dans la direction y (9 mai 2012)
     IF(l_obc_cycl_y) THEN
        DO i=liminp1,limax
          tenfon(i,jmin+1)=tenfon(i,jmax-1)
          tenfon(i,jmax)=tenfon(i,jmin+2)
        ENDDO
     ENDIF
#endif

   PRINT_DBG*,'controle tenfon max: ',MAXVAL(tenfonc),MAXVAL(tenfonw),MAXVAL((tenfon))
   PRINT_DBG*,'controle tenfon max: ',MAXVAL(tenfonc),MAXVAL(roswat_bot)
   PRINT_DBG*,'controle tenfon max: ',MAXLOC(tenfonc),MAXLOC(roswat_bot)

   PRINT_DBG*,'controle tenfon max: ',MAXVAL(tenfon)


   PRINT_DBG*, 'FIN SED_SKINSTRESS'  


  END SUBROUTINE sed_skinstress

   !!==============================================================================

!  SUBROUTINE sed_settlveloc_ini

   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_settlveloc_ini  ***
   !&E
   !&E ** Purpose :     initializes settling velocity parameters
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :    main
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference : parametric formulation of settling velocity, with hindering effects
   !&E                 from communications INTERCOH 98 et 2000
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from DUFOIS
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       !  2009-02  (P. Le Hir)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
!   USE comsubstance, ONLY : nvp

   !! * Local declarations
!   INTEGER iv
!   REAL(KIND=rsh)                        :: voleau6,w6
!   REAL(KIND=rsh),PARAMETER              :: cend=500.0_rsh,wsend=0.0000001_rsh                   
   
   !!---------------------------------------------------------------------------
   !! * Executable part

      !we assume a variation of Ws according to mes up to cend 
      !for which the (extremely) hindered settling velocity is wsend
      
      !hindered formulation is applied up to cmes=xws(6,iv)
      !the volumic concentration is computed as voleau6:
      !voleau6=1.-xws(4,iv)*xws(6,iv)**xws(5,iv)
      !above xws(6,iv), a sedimentation power law is applied,
      !reaching wsfin when cmes=cfend

      !xws(1,iv) is min value of settling velocity
      !xws(2,iv) is max value of settling velocity
      !xws(3,iv) is concentration for which Ws is max
      !xws(4,iv) is param. beta1 de passage de cmes a la concent.volum.
      !xws(5,iv) is param. beta2 de passage de cmes a la concent.volum.
      !xws(6,iv) is max concentration for which hindering is applied
      !xws(7,iv) is for dependence on salinity (sal.max)
      !xws(8,iv) is for dependence on turbulence (vitmax**2)
      !xws(9,iv) is a new parameter available (e.g. for differentiating vertical advection) 

!      DO iv=1,nvp
!        IF(xws(1,iv).EQ.0.0_rsh .OR. xws(2,iv).EQ.0.0_rsh) THEN
!          alp1(iv)=0.0_rsh
!          alp2(iv)=0.0_rsh
!          alp3(iv)=0.0_rsh
!          alp4(iv)=0.0_rsh
!          alp5(iv)=1.0_rsh
!          xws(10,iv)=0.0_rsh
!          xws(11,iv)=0.0_rsh
!          xws(12,iv)=0.0_rsh
!          xws(13,iv)=0.0_rsh
!        ELSE
!          alp1(iv)=2.0_rsh*(xws(2,iv)/(xws(1,iv))-1.0_rsh)/xws(3,iv)
!          alp2(iv)=(1.0_rsh-xws(2,iv)/(xws(1,iv)))/xws(3,iv)**2.0_rsh
!          alp3(iv)=1.0_rsh/(1.0_rsh-xws(4,iv)*xws(3,iv)**xws(5,iv))
!          voleau6=1.0_rsh-xws(4,iv)*xws(6,iv)**xws(5,iv)
!          w6=xws(2,iv)*(voleau6/(1.0_rsh-xws(4,iv)*xws(3,iv)**xws(5,iv)))**4.65_rsh
!          alp5(iv)=(LOG10(wsend)-LOG10(w6))/(LOG10(cend)-LOG10(xws(6,iv)))
!          alp4(iv)=10**(LOG10(w6)-alp5(iv)*LOG10(xws(6,iv)))
!          xws(10,iv)=0.0_rsh
!          IF(xws(7,iv).GT.0.0_rsh)THEN
!            xws(10,iv)=1.0_rsh
!            xws(12,iv)=1.0_rsh/xws(7,iv)
!          ENDIF

          ! presently, the effect of turbulence follows Van Leussen straightforwardly 
          !xws(11,iv)=0.0_rsh
          !if(xws(8,iv).gt.0.0_rsh)then
          !  xws(11,iv)=1.0_rsh
          !   xws(13,iv)=1.0_rsh/xws(8,iv)
          !endif
!        ENDIF
!      ENDDO

!  END SUBROUTINE sed_settlveloc_ini
      
   !!==============================================================================

  SUBROUTINE sed_settlveloc

   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_settlveloc  ***
   !&E
   !&E ** Purpose : settling velocity computation
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  stepu and stepv
   !&E
   !&E ** Reference : Settling velocity computed after Van Leussen (1994)
   !&E                Ws=Ws*(1+aG)/(a+bG**2) with a=0.3 and b=0.09 (Ems estuary)
   !&E                G=sqrt(eps(k,i,j)/nz(k,i,j))
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       !  2014-05  (R. Verney) modifying available settling velocity formulations
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : ws3,nvp,nvpc,nv_adv,imud1,isand1,isand2,cv_wat, &
                            ws_free_opt,ws_free_para,ws_free_min,ws_free_max,ws_hind_opt,ws_hind_para
   USE comvars2d,    ONLY : h0fond,h0,ig,id,jb,jh
   USE comvarp2d,    ONLY : ssh,sal
   USE comvars3d,    ONLY : sig,rhoref,nz,turb_nbeq, turb_2eq_option
   USE parameters,   ONLY : kmax,nb_var,grav
#ifdef key_flocmod
   USE parameters,   ONLY : l_testcase
#endif
#ifdef key_parsub_newdt
   USE comsubstance, ONLY : ws3max
#endif
   USE comturb,      ONLY : eps 

   !! * Local declarations
   INTEGER i,j,iv,k,ivpc
   REAL(KIND=rsh)                     :: gradvit,cmes,htn,phi,phiv,De
   REAL(KIND=rsh),PARAMETER           :: nuw=0.00000102_rsh

   !!---------------------------------------------------------------------------
   !! * Executable part

#ifdef key_parsub_newdt   
   ! rajoute pour calcul de ndt_part en fonction du temps
      ws3max(:)=0.0_rsh
#endif

!$OMP PARALLEL DEFAULT(NONE) SHARED(ljminp1,ljmaxm1,limin,limax,ig,id,jb,jh         &
!$OMP& ,h0,ssh,h0fond,ustarbot,tenfon,rhoref,turb_nbeq,turb_2eq_option,eps          &
!$OMP& ,nz,sig,cv_wat,ivpc,imud1,nvpc,isand1,isand2,ws3,ws_sand,nvp,ws_free_opt     &
!$OMP& ,ws_free_min,ws_free_para,ros,ws_hind_opt,ws_hind_para,dry_cell              &
#ifdef key_parsub_newdt
!$OMP& ,ws3max                        &
#endif
#ifdef key_flocmod
!$OMP& ,f_ws,l_testcase               &
#endif
!$OMP& ,ws_free_max,nv_adv)                       &
!$OMP& PRIVATE(i,j,k,htn,gradvit,cmes,iv,De,phi,phiv)                                   


!$OMP DO SCHEDULE(RUNTIME)
      DO j=ljminp1,ljmaxm1
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
        IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN

          htn=h0(i,j)+ssh(i,j)
          IF(htn.GT.h0fond)  THEN
            IF(tenfon(i,j).LT.0.) THEN
              PRINT*,'i,j,tenf,h0,ssh,dry_cell= ',i,j,tenfon(i,j),h0(i,j),ssh(i,j),dry_cell(i,j)
              ustarbot(i,j)=0.0_rsh
            ELSE
              ustarbot(i,j)=(tenfon(i,j)/rhoref)**0.5_rsh
            ENDIF
            DO k=1,kmax
              IF (turb_nbeq.EQ.2 .AND. turb_2eq_option.EQ.2) THEN ! using k-epsilon closure scheme
                gradvit=sqrt(eps(k,i,j)/nz(k,i,j))
              ELSE ! using nezu and nakagawa
                gradvit=sqrt(ustarbot(i,j)**3._rsh/(0.4_rsh)*(-sig(k)/(1._rsh+sig(k))))
              ENDIF

              cmes=0.0_rsh
              DO ivpc=imud1,nvpc
                cmes=cmes+cv_wat(ivpc,k,i,j)
              ENDDO
              cmes=MAX(0.0_rsh,cmes)

! first calculating sand settling velocity
              DO iv=isand1,isand2
                ws3(k,iv,i,j)=ws_sand(iv)
#ifdef key_parsub_newdt
                IF (ws3(k,iv,i,j)>ws3max(iv))ws3max(iv)=ws3(k,iv,i,j)
#endif
              ENDDO
              
! next mud settling velocity 
#ifdef key_flocmod
              DO iv=imud1,nvp     
                 
                 ws3(k,iv,i,j)=f_ws(iv)
                 if (l_testcase) ws3(k,iv,i,j)=0.0_rsh      
              ENDDO
      
#else
      
              DO iv=imud1,nvp
! free settling velocity - flocculation
    
                IF(ws_free_opt(iv) == 0) THEN ! constant settling velocity
                  ws3(k,iv,i,j)=ws_free_min(iv)
                ELSEIF (ws_free_opt(iv) == 1) THEN ! Van Leussen 1994
                  ws3(k,iv,i,j)=ws_free_para(1,iv)*cmes**ws_free_para(2,iv) &
                              *(1._rsh+ws_free_para(3,iv)*gradvit)/(1._rsh+ws_free_para(4,iv)*gradvit**2._rsh)
                ELSEIF (ws_free_opt(iv) == 2) THEN ! Winterwerp 1999
                  De=ws_free_para(1,iv)+ws_free_para(2,iv)*cmes/(ws_free_para(3,iv)*sqrt(gradvit))
                  IF (De.GT.sqrt(nuw/gradvit)) THEN 
                    De=sqrt(nuw/gradvit) ! in case of large C/low G limit floc size to kolmogorov microscale
                  ENDIF
                  ws3(k,iv,i,j)=(ros(iv)-rhoref)*grav/(18._rsh*rhoref*nuw)*ws_free_para(1,iv)**(3._rsh-ws_free_para(4,iv))  &
                                *De**(ws_free_para(4,iv)-1._rsh)
                
                ELSEIF (ws_free_opt(iv).EQ.3) THEN ! Wolanski et al., 1989
                  ws3(k,iv,i,j)=ws_free_para(1,iv)*cmes**ws_free_para(2,iv)

                ENDIF


! Hindered settling
! if ws_hind_opt.EQ.0 : no hindered settling...ws3 unchanged
                IF (ws_hind_opt(iv).EQ.1) THEN ! Scott, 1984
                  phi=MIN(1.0_rsh,cmes/ws_hind_para(1,iv))
                  ws3(k,iv,i,j)=ws3(k,iv,i,j)*(1._rsh-phi)**ws_hind_para(2,iv)
                ELSEIF (ws_hind_opt(iv).EQ.2) THEN ! Winterwerp, 2002 - ATTENTION : ros(iv) must be the same for all MUDS variables
                  phi=cmes/ros(iv)
                  IF (ws_free_opt(iv).EQ.2) THEN
                    phi=cmes/ros(iv)
                    phiv=phi*(De/ws_free_para(1,iv))**(3._rsh-ws_free_para(4,iv))
                  ELSE
                    phiv=cmes/ws_hind_para(1,iv)
                  ENDIF

                  ws3(k,iv,i,j)=ws3(k,iv,i,j)*(1._rsh-phiv)**ws_hind_para(2,iv)*(1._rsh-phi)  &
                                /(1._rsh+2.5_rsh*phiv)
                ELSEIF (ws_hind_opt(iv).EQ.3) THEN ! wolanski et al., 1989
                  IF (ws_free_opt(iv).EQ.3) THEN
                    ws3(k,iv,i,j)=ws3(k,iv,i,j)/(cmes**2._rsh+ws_hind_para(1,iv)**2._rsh)**ws_hind_para(2,iv)
                  ELSE
                    
                  ENDIF
                ENDIF

! limiting ws with min/max values...
! necessary if ndt_part not updated during the simulation, ndt_part calculated in subreaddat from a maximum settling velocity
              ws3(k,iv,i,j)=max(ws_free_min(iv),min(ws_free_max(iv),ws3(k,iv,i,j)))

              ENDDO
              

            ! rverney : attention update parsub_newdt with flocculation! 
#ifdef key_parsub_newdt   
              DO iv=imud1,nvp
                if (ws3(k,iv,i,j)>ws3max(iv)) ws3max(iv)=ws3(k,iv,i,j)
              ENDDO
#endif	      
#endif
              DO iv=nvp+1,nv_adv
                ws3(k,iv,i,j)=0.0_rsh
              ENDDO
            ENDDO
          ELSE
            ustarbot(i,j)=0.0_rsh
            ws3(:,:,i,j)=0.0_rsh
          ENDIF
        ENDIF
        ENDDO
      ENDDO
!$OMP END DO
!$OMP END PARALLEL

  END SUBROUTINE sed_settlveloc      

   !!==============================================================================
 
#ifdef key_sedim_mudsand

  SUBROUTINE sed_erosion_mudsand
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_erosion  ***
   !&E
   !&E ** Purpose : computes erosion fluxes
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  stepu, stepv
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from subsedim.F90 (from F. Dufois)
   !&E       !  2008-10  (F. Cayocca) included into module_sedimento
   !&E       !  2008-02  (P. Le Hir) replaced by new "Marennes-Oleron" sand/mud sediment model
   !&E       !  2011-04  (F. Cayocca) introduction of the fraction of wet cell (fwetp)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used  
   USE comsubstance, ONLY : nvpc,nv_adv,nvp,flx_s2w,typart,imud1,imud2

   USE comvars2d,    ONLY : h0,h0fond,dt,ig,id,fwetp,jb,jh
   USE comvarp2d,    ONLY : ssh
   USE parameters,   ONLY : epsilon
   
   !! * Local declarations
   INTEGER i,j,iv,ksmax,ksmaxa,k
   REAL(KIND=rsh) :: dt1,toce,erodab,ero,erosi,dzsa,dtinv
   REAL(KIND=rsh) :: ddzs,dzsam1,poroa,poroam1,dzsisu,somalp,dzpoi
   REAL(kind=rsh) :: cmud,fcr,E0,alpha,E0vase

   !!---------------------------------------------------------------------------
   !! * Executable part

    dtinv=2.0_rsh/REAL(dt,rsh)
    fcr=0.0_rsh
    E0=0.0_rsh
    alpha=0.0_rsh
    E0vase=xeros
    
    DO j=ljminp1,ljmaxm1
    DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
     IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
        flx_s2w(-1,i,j)=0.0_rsh
        flx_s2w( 0,i,j)=0.0_rsh
        DO iv=1,nv_adv
          flx_s2w(iv,i,j)=0.0_rsh
        ENDDO
       IF (h0(i,j)+ssh(i,j).GT.h0fond) THEN

        ksmax=ksma(i,j)


        IF(ksmax.GE.ksmi(i,j))THEN

          dt1=REAL(dt,rsh)*0.5_rsh
          ! epeaui represente l epaisseur d eau interstitielle init_fromfileeree 
          ! par le sediment lors du depot (calcule par depeff precedent) 
          ! ici, epeaui va representer la variation d epaisseur d eau a
          ! prendre en compte dans la maille inferieure de la colonne d eau
          ! epeaui(i,j)=-epeaui(i,j)

          2 CONTINUE

          CALL sed_comp_tocr_mudsand(c_sedtot(ksmax,i,j))
          toce=sed_tocr_mudsand
          IF(tenfon(i,j).GT.toce)THEN

            erodab=c_sedtot(ksmax,i,j)*dzs(ksmax,i,j)
            ! relation de Partheniades:
!fdufois
            cmud=0.0_rsh
            DO iv=imud1,imud2
              cmud=cmud+cv_sed(iv,ksmax,i,j)
            ENDDO
            fcr=(cmud/cfreshmud)
            IF (fcr.GT.frmudcr2) THEN
              E0=E0vase
              alpha=alphavase
            ELSEIF (fcr.LT.frmudcr1) THEN
              E0=E0sable
              alpha=alphasable
            ELSE
              E0=(E0vase-E0sable)/(frmudcr2-frmudcr1)*(fcr-frmudcr1)+E0sable
              alpha=(alphavase-alphasable)/(frmudcr2-frmudcr1)*(fcr-frmudcr1)+alphasable
            ENDIF

            ero=E0*(tenfon(i,j)/toce-1.)**alpha
            !  ero=xeros*(tenfon(i,j)/toce-1.0_rsh)
!fdufois
            erosi=ero*dt1*fwetp(i,j)

          IF(erosi.LT.erodab)THEN
            ddzs=erosi/c_sedtot(ksmax,i,j)
            dzs(ksmax,i,j)=dzs(ksmax,i,j)-ddzs
            !epeaui(i,j)=epeaui(i,j)+ddzs*poro(ksmax,i,j)
            DO iv=1,nvp
              flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+ddzs*cv_sed(iv,ksmax,i,j)
            ENDDO
            flx_s2w(-1,i,j)=flx_s2w(-1,i,j)+ddzs*poro(ksmax,i,j)*cv_sed(-1,ksmax,i,j)
            flx_s2w( 0,i,j)=flx_s2w( 0,i,j)+ddzs*poro(ksmax,i,j)*cv_sed( 0,ksmax,i,j)
            DO iv=nvp+1,nv_adv
              flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+ddzs*poro(ksmax,i,j)*cv_sed(iv,ksmax,i,j)
            ENDDO
          ELSE
            ddzs=erodab*fwetp(i,j)/c_sedtot(ksmax,i,j)
            !epeaui(i,j)=epeaui(i,j)+ddzs*poro(ksmax,i,j)
            DO iv=1,nvp
              flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+ddzs*cv_sed(iv,ksmax,i,j)
            ENDDO
            flx_s2w(-1,i,j)=flx_s2w(-1,i,j)+ddzs*poro(ksmax,i,j)*cv_sed(-1,ksmax,i,j)
            flx_s2w( 0,i,j)=flx_s2w( 0,i,j)+ddzs*poro(ksmax,i,j)*cv_sed( 0,ksmax,i,j)
            DO iv=nvp+1,nv_adv
              flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+ddzs*poro(ksmax,i,j)*cv_sed(iv,ksmax,i,j)
            ENDDO
            dt1=dt1-erodab/ero
            ksmax=ksmax-1
            IF(ksmax.GE.ksmi(i,j))THEN
              GOTO 2
            ELSE
              !write(*,*)'a t=',t,i,j,', il n"y a plus de sediment'
              GOTO 120
            ENDIF
          ENDIF
        ENDIF

      ENDIF

      !fusion des 2 couches superf., si dzs(ksmax) < dzsmin
      !---------------------------------------------------
      ! if(ksmax.ne.0)then

      1000 IF(ksmax.GE.2)THEN
      IF(dzs(ksmax,i,j).LE.dzsmin)THEN
        ksmaxa=ksmax
        dzsa=dzs(ksmax,i,j)
        dzsam1=dzs(ksmax-1,i,j)
        poroa=poro(ksmax,i,j)
        poroam1=poro(ksmax-1,i,j)
        ksmax=ksmax-1
        dzs(ksmax,i,j)=dzsa+dzs(ksmax,i,j)
        dzsisu=1.0_rsh/dzs(ksmax,i,j)
        c_sedtot(ksmax,i,j)=0.0_rsh
        somalp=0.0_rsh

        DO iv=1,nvp
          cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmaxa,i,j)*dzsa+cv_sed(iv,ksmax,i,j)*dzsam1)*dzsisu
          c_sedtot(ksmax,i,j)=c_sedtot(ksmax,i,j)+cv_sed(iv,ksmax,i,j)*typart(iv)
            somalp=somalp+cv_sed(iv,ksmax,i,j)*typart(iv)/(ros(iv)+epsilon)
        ENDDO
        poro(ksmax,i,j)=1.0_rsh-somalp
        dzpoi=dzsisu/poro(ksmax,i,j)            
        cv_sed(-1,ksmax,i,j)=(cv_sed(-1,ksmaxa,i,j)*poroa*dzsa+cv_sed(-1,ksmax,i,j)*poroam1*dzsam1)*dzpoi
        cv_sed( 0,ksmax,i,j)=(cv_sed( 0,ksmaxa,i,j)*poroa*dzsa+cv_sed( 0,ksmax,i,j)*poroam1*dzsam1)*dzpoi
        DO iv=nvp+1,nv_adv
          ! les cs dissous sont en .../m3 d eau interst.
          cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmaxa,i,j)*poroa*dzsa+cv_sed(iv,ksmax,i,j)*poroam1*dzsam1)*dzpoi
        ENDDO
        ! et les variables benthiques ???
 

        GOTO 1000
       ENDIF
      ENDIF

     120 CONTINUE

      DO iv=-1,nv_adv
        ! pour retrouver un flux d erosion en .../m2/s :
        flx_s2w(iv,i,j)=flx_s2w(iv,i,j)*dtinv
      ENDDO
      flx_s2w(-1,i,j)=flx_s2w(-1,i,j)+fwetp(i,j)*(-fludif(-1,i,j)+fluconsol(-1,i,j))
      flx_s2w( 0,i,j)=flx_s2w( 0,i,j)+fwetp(i,j)*(-fludif( 0,i,j)+fluconsol( 0,i,j))
      DO iv=nvp+1,nv_adv
        ! pour les dissoutes, on ajoute le flux diffusif a l interface
        ! et celui qui resulte de l expulsion d eau interst. par tasst:
        flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+fwetp(i,j)*(-fludif(iv,i,j)+fluconsol(iv,i,j))
      ENDDO

      ! reactualisation de ksma 
      ksma(i,j)=ksmax

      ENDIF
    ENDIF
   END DO
   END DO

  END SUBROUTINE sed_erosion_mudsand

#endif
   !!==============================================================================

#ifdef key_sedim_mixsed 
 
  SUBROUTINE sed_erosion_mixsed
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_erosion  ***
   !&E
   !&E ** Purpose : computes erosion fluxes
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  stepu, stepv
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (P. Le Hir) extracted from subsedim.F90 (from F. Dufois)
   !&E       !  2008-10  (F. Cayocca) included into module_sedimento
   !&E       !  2008-02  (P. Le Hir) replaced by new "Marennes-Oleron" sand/mud sediment model
   !&E       !  2011-04  (F. Cayocca) introduction of the fraction of wet cell (fwetp)
   !&E       !  2015-07  (B.Thouvenin  P. Le Hir) : correction lateral erosion of dry cell  
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nvpc,nv_adv,nvp,flx_s2w,flx_w2s,igrav1,igrav2,typart
   USE comvars2d,    ONLY : h0,h0fond,ig,id,fwet,jb,jh,surf,halfdt
   USE comvarp2d,    ONLY : ssh,u,v
   USE parameters,   ONLY : epsilon
   USE_MPI toolmpi,  ONLY : ex_i_rsh,ex_j_rsh

   !! * Local declarations
   INTEGER        ::  i,j,k,iv,ksmax,ksup,ksmaxa,nv_use
   REAL(KIND=rsh) ::  dt1,toce,cvolgrv,csanmud,dtinv,                          &
                      erodab,ero,erosi,ddzs,dzsa,dzsisu,dzsam1,dflx_s2w,       &
                      cvolp,volerod,profsed,poroa,poroam1,dflusve,      &
                      xeros,sed_tocr_mixsed,sed_eros_flx,excespowr,dzpoi,      &
                      heauw,heaue,heaun,heaus,heau_milieu,eroe,erow,eros,eron
   REAL(KIND=rsh),DIMENSION(-1:nv_adv,limin  :limaxp1,ljmin  :ljmax  ) :: flx_s2w_corim1
   REAL(KIND=rsh),DIMENSION(-1:nv_adv,liminm1:limax  ,ljmin  :ljmax  ) :: flx_s2w_corip1
   REAL(KIND=rsh),DIMENSION(-1:nv_adv,limin  :limax  ,ljmin  :ljmaxp1) :: flx_s2w_corjm1
   REAL(KIND=rsh),DIMENSION(-1:nv_adv,limin  :limax  ,ljminm1:ljmax  ) :: flx_s2w_corjp1


   !!---------------------------------------------------------------------------
   !! * Executable part

!$OMP PARALLEL DEFAULT(NONE) SHARED(ljminp1,ljmaxm1,limin,limax,limaxp1,ljmin     &
!$OMP&  ,ljmax,liminm1,ljmaxp1,ljminm1,ig,id,jb,jh,l_consolid                     &
!$OMP&  ,flx_s2w,flx_w2s,nv_adv,h0,ssh,h0fond,ksma,ksmi,halfdt,tenfon,igrav1,fludif   &
!$OMP&  ,igrav2,cv_sed,ros,nvpc,dzs,c_sedtot,fwet,l_morphocoupl,MF,dzsmax         &
!$OMP&  ,surf,phieau_s2w,nvp,poro,typart,dzsmin,nv_use,fluconsol                  &
!$OMP&  ,l_erolat_wet_cell,coef_erolat,htncrit_eros,u,v,coef_tenfon_lat,activlayer &
!$OMP&  ,flx_s2w_corip1,flx_s2w_corim1,flx_s2w_corjp1,flx_s2w_corjm1,cvolmaxsort)  &
!$OMP& PRIVATE(i,j,k,iv,ksmax,dt1,toce,cvolgrv,csanmud,erodab,ero,dzsam1,dzpoi    &
!$OMP&  ,erosi,ddzs,dzsa,sed_tocr_mixsed,excespowr,dzsisu,dflx_s2w,xeros,dflusve  &
!$OMP&  ,heaue,heauw,heaus,heaun,heau_milieu,eroe,erow,eros,eron             &
!$OMP&  ,cvolp,volerod,profsed,ksup,ksmaxa,poroa,poroam1,dtinv,sed_eros_flx)  

#ifdef key_sedim_partial 
   nv_use=nvpc
#else
   nv_use=nvp
#endif
   dtinv=1.0_rsh/REAL(halfdt,rsh)
!$OMP SINGLE
   flx_s2w_corip1(:,:,:)=0.0_rsh
   flx_s2w_corim1(:,:,:)=0.0_rsh
   flx_s2w_corjp1(:,:,:)=0.0_rsh
   flx_s2w_corjm1(:,:,:)=0.0_rsh
!$OMP END SINGLE
   
!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljminp1,ljmaxm1
    DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
      IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
        DO iv=-1,nv_adv
          flx_s2w(iv,i,j)=0.0_rsh
        ENDDO
        
        ksmax=ksma(i,j)
        ero=0.0_rsh

        IF(ksmax.GE.ksmi(i,j))THEN

          dt1=REAL(halfdt,rsh)
        ! epeaui represente l epaisseur d eau interstitielle recuperee 
        ! par le sediment lors du depot (calcule par depeff precedent) 
        ! ici, epeaui va representer la variation d epaisseur d eau a
        ! prendre en compte dans la maille inferieure de la colonne d eau
        ! epeaui(i,j)=-epeaui(i,j)

          k=ksmax
                       
        2 CONTINUE

          CALL sed_comp_tocr_mixsed(k,i,j,xeros,excespowr,sed_tocr_mixsed)
          toce=MAX(0.00005_rsh,sed_tocr_mixsed)
          cvolgrv=0.0_rsh
          DO iv=igrav1,igrav2
            cvolgrv=cvolgrv+cv_sed(iv,k,i,j)/ros(iv)
          ENDDO
          csanmud=0.0_rsh
          DO iv=igrav2+1,nvpc
            csanmud=csanmud+cv_sed(iv,k,i,j)
          ENDDO
          erodab=csanmud*dzs(k,i,j)
          ero=0.0_rsh

          IF((h0(i,j)+ssh(i,j)).GT.h0fond) THEN
            IF(tenfon(i,j).GT.toce)THEN
              CALL sed_comp_eros_flx(tenfon(i,j),toce,c_sedtot(ksmax,i,j),excespowr,xeros,sed_eros_flx)
              ero=sed_eros_flx*fwet(i,j)    

              ! lateral erosion :  wet cell (cellule mouillee)
              IF (l_erolat_wet_cell) THEN
#ifdef key_castest_estuary
                !PLH : precaution for test case ESTUAR (secteur amont ou le courant fluvial peut etre fort)
               IF(i.le.id(j)-4) THEN
#endif                                                                         
                 heaue=h0(i+1,j)+ssh(i+1,j)-htncrit_eros
                 heauw=h0(i-1,j)+ssh(i-1,j)-htncrit_eros
                 heaus=h0(i,j-1)+ssh(i,j-1)-htncrit_eros
                 heaun=h0(i,j+1)+ssh(i,j+1)-htncrit_eros
                 heau_milieu=h0(i,j)+ssh(i,j)-h0fond
                 eroe=max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(v(i+1,j-1)+v(i+1,j))**2-toce)*max(0.,heaue-heau_milieu)
                 erow=max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(v(i-1,j-1)+v(i-1,j))**2-toce)*max(0.,heauw-heau_milieu)
                 eros=max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(u(i-1,j-1)+u(i,j-1))**2-toce)*max(0.,heaus-heau_milieu)
                 eron=max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(u(i-1,j+1)+u(i,j+1))**2-toce)*max(0.,heaun-heau_milieu)
                 ero=ero+coef_erolat*(eroe+erow+eros+eron)
#ifdef key_castest_estuary
               ENDIF
#endif                                                                         
              ENDIF
            ENDIF
          ELSE
          ! lateral erosion :  dry cell 
#ifdef key_castest_estuary
            !PLH : precaution for test case ESTUAR (secteur amont ou le courant fluvial peut etre fort)
            IF(i.le.id(j)-2) THEN                                                                         
#endif
              heaue=max(0.,h0(i+1,j)+ssh(i+1,j)-htncrit_eros)
              heauw=max(0.,h0(i-1,j)+ssh(i-1,j)-htncrit_eros)
              heaus=max(0.,h0(i,j-1)+ssh(i,j-1)-htncrit_eros)
              heaun=max(0.,h0(i,j+1)+ssh(i,j+1)-htncrit_eros)
              eroe=coef_erolat*max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(v(i+1,j-1)+v(i+1,j))**2-toce)*heaue
              erow=coef_erolat*max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(v(i-1,j-1)+v(i-1,j))**2-toce)*heauw
              eros=coef_erolat*max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(u(i-1,j-1)+u(i,j-1))**2-toce)*heaus
              eron=coef_erolat*max(0.0_rsh,coef_tenfon_lat/4.0_rsh*(u(i-1,j+1)+u(i,j+1))**2-toce)*heaun
              ero=eroe+erow+eros+eron
#ifdef key_castest_estuary
            ENDIF
#endif
          ENDIF

          erosi=MF*dt1*ero

          IF(erosi >  0.0_rsh)THEN
           IF(erosi.LE.erodab)THEN
                ddzs=erosi/csanmud
                dzsa=dzs(k,i,j)
                dzs(k,i,j)=MAX(dzsa-ddzs,dzsa*cvolgrv/cvolmaxsort)
                IF(dzs(k,i,j).LE.0.0_rsh)THEN
                  !WRITE(*,*)'en kij:',k,i,j,dzs(k,i,j),dzsa,ddzs,csanmud,cvolgrv
                  dzs(k,i,j)=epsilon
                ENDIF
                dzsisu=1.0_rsh/dzs(k,i,j)
                DO iv=igrav1,igrav2
                  cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*dzsa*dzsisu
                ENDDO
                DO iv=igrav2+1,nv_use ! nv_use=nvp (or nvpc if key_sedim_partial)
                  dflx_s2w=ddzs*cv_sed(iv,k,i,j)
                  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+dflx_s2w/MF 
                  cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)*dzsa-dflx_s2w)*dzsisu
                ENDDO
                c_sedtot(k,i,j)=0.0_rsh
                cvolp=0.0_rsh
                DO iv=1,nvpc
                  c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
                  cvolp=cvolp+cv_sed(iv,k,i,j)/ros(iv)
                ENDDO
                poroa=poro(k,i,j)
                poro(k,i,j)=1.0_rsh-cvolp

#if ! defined key_nodiss_insed
                ! dissolved variable in pore waters
#if ! defined key_sedim_partial
                DO iv=nvp+1,nv_adv
                  dflusve=ddzs*poroa*cv_sed(iv,k,i,j)
                  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+dflusve
                  ! Fev2017 BT : qd il y a erosion, pourquoi conc dissouste changerait elle dans les eaux intertertitielles ?
                  !cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)*dzsa*poroa-dflusve)*dzsisu/poro(k,i,j) 
                ENDDO
#endif

                ! Temperature and salinity
                DO iv=-1,0
                  dflusve=ddzs*poroa*cv_sed(iv,k,i,j)
                  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+dflusve
                ! Fev2017 BT : qd il y a erosion, pourquoi conc dissouste changerait elle dans les eaux intertertitielles ?
                !  cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)*dzsa*poroa-dflusve)*dzsisu/poro(k,i,j)
                ENDDO
#endif
                ! flux d eau du a l erosion
                phieau_s2w(i,j)=phieau_s2w(i,j)+REAL(ddzs*poroa*surf(i,j),rlg)

          ELSE IF(csanmud /= 0.0_rsh) THEN  !erosi/erodab
                ! correction PLH Juillet 2015
                !volerod=erodab*fwet(i,j)/csanmud
                volerod=erodab/csanmud
                DO iv=igrav2+1,nv_use ! nv_use=nvp (or nvpc if key_sedim_partial)
                  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+volerod*cv_sed(iv,k,i,j)/MF
                  cv_sed(iv,k,i,j)=0.0_rsh
                ENDDO
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                ! dissolved variable in pore waters
                DO iv=nvp+1,nv_adv
                  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+volerod*poro(k,i,j)*cv_sed(iv,k,i,j)
                  cv_sed(iv,k,i,j)=0.0_rsh
                ENDDO
#endif
                ! Temperature and salinity
                DO iv=-1,0
                  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+volerod*poro(k,i,j)*cv_sed(iv,k,i,j)
                  cv_sed(iv,k,i,j)=0.0_rsh
                ENDDO
#endif
               ! flux d eau du a l erosion
                phieau_s2w(i,j)=phieau_s2w(i,j)+ REAL(volerod*poro(k,i,j)*surf(i,j),rlg)

                IF(cvolgrv.LE.0.0_rsh)THEN
                  ! mise a zero des dzs et des poro
                  dzs(ksmax,i,j)=0.0_rsh
                  poro(ksmax,i,j)=0.0_rsh
                  ksmax=ksmax-1
                ELSE
                  dzsa=dzs(k,i,j)
                  dzs(k,i,j)=dzsa*cvolgrv/cvolmaxsort
                  !??? dzs(k,i,j)=dzsa*cvolgrv/cvolmaxmel
                  c_sedtot(k,i,j)=0.0_rsh
                  DO iv=igrav1,igrav2
                      cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*dzsa/dzs(k,i,j)
                      c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
                  ENDDO
                  poroa=poro(k,i,j)
                  poro(k,i,j)=1.0_rsh-cvolmaxsort
                  !??? poro(k,i,j)=1.0_rsh-cvolmaxmel
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                  ! dissolved variable in pore waters
                  DO iv=nvp+1,nv_adv
                    flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+cv_sed(iv,k,i,j)*(dzsa*poroa   &
                                   -dzs(k,i,j)*poro(k,i,j))
                  ENDDO
#endif
                  ! Temperature and salinity
                  DO iv=-1,0
                    flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+cv_sed(iv,k,i,j)*(dzsa*poroa   &
                                   -dzs(k,i,j)*poro(k,i,j))
                  ENDDO
#endif
                  ! flux d eau du a l erosion
                  phieau_s2w(i,j)=phieau_s2w(i,j)+                         &
                                 REAL((dzsa*poroa-dzs(k,i,j)*poro(k,i,j))*surf(i,j),rlg)
                ENDIF  ! fin boucle sur cvolgrv
              
                ! memorisation of lateral erosion for dry cell
                IF((h0(i,j)+ssh(i,j)).LE.h0fond .AND. coef_erolat .NE. 0.0_rsh) THEN
                   DO iv=-1,nv_adv
                     flx_s2w_corip1(iv,i,j)=flx_s2w_corip1(iv,i,j)+flx_s2w(iv,i,j)*eroe/ero*surf(i,j)/surf(i+1,j)
                     flx_s2w_corim1(iv,i,j)=flx_s2w_corim1(iv,i,j)+flx_s2w(iv,i,j)*erow/ero*surf(i,j)/surf(i-1,j)
                     flx_s2w_corjm1(iv,i,j)=flx_s2w_corjm1(iv,i,j)+flx_s2w(iv,i,j)*eros/ero*surf(i,j)/surf(i,j-1)
                     flx_s2w_corjp1(iv,i,j)=flx_s2w_corjp1(iv,i,j)+flx_s2w(iv,i,j)*eron/ero*surf(i,j)/surf(i,j+1)
                   ENDDO
                ENDIF
                ! test on active layer...
                profsed=0.0_rsh
                DO ksup=k,ksmax
                  profsed=profsed+dzs(ksup,i,j)
                ENDDO
                k=k-1
                IF(profsed.LE.activlayer.AND.k.GE.ksmi(i,j))THEN
                  dt1=dt1-erodab/ero
                  GOTO 2
                ENDIF ! fin test activlayer

           ENDIF   ! fin test erosi > erodab
          ENDIF    ! fin test erosi=0
        ENDIF       ! fin test ksmax > ksmi(i,j) 
 
        ! fusion des 2 couches superf., tant que dzs(ksmax) < dzsmin
        !     et si l_consolid=TRUE et couche diminuee par erosion
        !     dans ce cas, il faudrait rajouter un test 
        !    sur la difference entre les concentrations des 2 couches superficielles
        ! pas encore fait
        ! ----------------------------------------------------------
        IF(ero > 0.0_rsh) THEN
 1000     IF(ksmax.GT.ksmi(i,j))THEN
            IF(dzs(ksmax,i,j).LE.dzsmin .AND. (dzs(ksmax-1,i,j)< dzsmax(i,j)  .OR. l_consolid))THEN
              ksmaxa=ksmax
              dzsa=dzs(ksmax,i,j)
              dzsam1=dzs(ksmax-1,i,j)
              poroa=poro(ksmax,i,j)
              poroam1=poro(ksmax-1,i,j)
              ksmax=ksmax-1
              dzs(ksmax,i,j)=dzsa+dzsam1
              dzsisu=1.0_rsh/dzs(ksmax,i,j)
              c_sedtot(ksmax,i,j)=0.0_rsh
              cvolp=0.0_rsh
              DO iv=1,nv_use ! nv_use=nvp (or nvpc if key_sedim_partial)
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmaxa,i,j)*dzsa             &
                                     +cv_sed(iv,ksmax,i,j)*dzsam1)*dzsisu
                c_sedtot(ksmax,i,j)=c_sedtot(ksmax,i,j)                      &
                                    +cv_sed(iv,ksmax,i,j)*typart(iv)
                cvolp=cvolp+cv_sed(iv,ksmax,i,j)*typart(iv)/ros(iv)
              ENDDO
              poro(ksmax,i,j)=1.0_rsh-cvolp
              dzpoi=dzsisu/poro(ksmax,i,j)
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
              ! dissolved variable in pore waters
              DO iv=nvp+1,nv_adv
              ! in .../m3 of interstial waters
                 cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmaxa,i,j)*poroa*dzsa+        &
                                    cv_sed(iv,ksmax,i,j)*poroam1*dzsam1)*dzpoi
              ENDDO
#endif
              ! Temperature and salinity
              DO iv=-1,0
                 cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmaxa,i,j)*poroa*dzsa+        &
                                    cv_sed(iv,ksmax,i,j)*poroam1*dzsam1)*dzpoi
              ENDDO
#endif
               
              GOTO 1000
            ENDIF
          ENDIF
        ENDIF

          ! pour retrouver un flux d erosion en .../m2/s (pour les particulaires seulement) :
          DO iv=1,nv_use ! nv_use=nvp (or nvpc if key_sedim_partial)
            flx_s2w(iv,i,j)=flx_s2w(iv,i,j)*dtinv
          ENDDO
          !==============================================
#if ! defined key_nodiss_insed
          ! for dissolved variable in pore waters
          ! add water-to-sediment flux explicitly treated with the sediment-to-water flux also explicitly treated
#if ! defined key_sedim_partial
          DO iv=nvp+1,nv_adv
          !  flx_s2w(iv,i,j)=flx_s2w(iv,i,j)-flx_w2s(iv,i,j)*dtinv
          !    pour les dissoutes, on ajoute le flux diffusif a l interface
          !    et celui qui resulte de l expulsion d eau interst. par tasst:
            !flx_s2w(iv,i,j)=(flx_s2w(iv,i,j)-flx_w2s(iv,i,j))*dtinv+fluconsol(iv,i,j)-fludif(iv,i,j)
            flx_s2w(iv,i,j)=(flx_s2w(iv,i,j)-flx_w2s(iv,i,j)+fluconsol(iv,i,j)-fludif(iv,i,j))*dtinv
          ENDDO
#endif
          DO iv=-1,0
            ! flx_s2w(iv,i,j)=flx_s2w(iv,i,j)-flx_w2s(iv,i,j)*dtinv
            !flx_s2w(iv,i,j)=(flx_s2w(iv,i,j)-flx_w2s(iv,i,j))*dtinv+fluconsol(iv,i,j)-fludif(iv,i,j)
            flx_s2w(iv,i,j)=(flx_s2w(iv,i,j)-flx_w2s(iv,i,j)+fluconsol(iv,i,j)-fludif(iv,i,j))*dtinv
          ENDDO
#endif
          ! updating ksma (as ksmax can be modified in the routine)
          ksma(i,j)=ksmax

          ! no correction of water column height (could be !)

        ENDIF  ! fin boucle sur jb,jh 

      END DO
    END DO
!$OMP END DO

IF(coef_erolat .NE. 0.0_rsh) THEN
! lateral erosion of dry cell
! echange MPI
OMPMPI barrier
OMPMPI master
CALL_MPI ex_i_rsh(0,1,nv_adv+2 ,limin  ,limaxp1  ,ljmin  ,ljmax   ,flx_s2w_corim1(:,limin  :limaxp1,ljmin  :ljmax  ))
CALL_MPI ex_i_rsh(-1,0,nv_adv+2,liminm1,limax    ,ljmin  ,ljmax   ,flx_s2w_corip1(:,liminm1:limax  ,ljmin  :ljmax  ))
CALL_MPI ex_j_rsh(0,1,nv_adv+2 ,limin  ,limax    ,ljmin  ,ljmaxp1 ,flx_s2w_corjm1(:,limin  :limax  ,ljmin  :ljmaxp1))
CALL_MPI ex_j_rsh(-1,0,nv_adv+2,limin  ,limax    ,ljminm1,ljmax   ,flx_s2w_corjp1(:,limin  :limax  ,ljminm1:ljmax  ))
OMPMPI end master
OMPMPI barrier
OMPMPI flush(flx_s2w_corim1,flx_s2w_corip1,flx_s2w_corjm1,flx_s2w_corjp1)

! correction : neighboring cells of eroded laterally  dry cell receive one fraction of eroded sediment 
!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljminp1,ljmaxm1
    DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
      IF(j.GE.jb(i)+1 .AND. j .LE. jh(i)-1) THEN
        DO iv=-1,nv_adv
           flx_s2w(iv,i,j)=flx_s2w(iv,i,j)+ dtinv*(                            &
                       +flx_s2w_corip1(iv,i-1,j)+flx_s2w_corim1(iv,i+1,j)   &
                       +flx_s2w_corjp1(iv,i,j-1)+flx_s2w_corjm1(iv,i,j+1))
       ENDDO
      ENDIF  ! fin boucle sur jb,jh 
    END DO
   END DO
!$OMP END DO                          
ENDIF  ! fin if coef_erolat
!$OMP END PARALLEL

   PRINT_DBG*, 'FIN SED_EROSION'



  END SUBROUTINE sed_erosion_mixsed

   !!==============================================================================

  SUBROUTINE sed_comp_tocr_mixsed(k,i,j,xeros,excespowr,sed_tocr_mixsed)
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  SUBROUTINE sed_comp_tocr_mixsed  ***
   !&E
   !&E ** Purpose : the critical shear stress for erosion in sediment layer k
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  sed_erosion
   !&E 
   !&E ** External calls : none
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-02  (P. Le Hir) extracted from (SiAM) new "Marennes-Oleron"
   !&E                               sand/mud sediment model
   !&E       !  2016-02  (B. Mengual, B. Thouvenin) : modification of erosion formulations - several choices
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : igrav1,igrav2,isand1,isand2,imud1,imud2
   USE parameters,   ONLY : epsilon
   !! * Arguments
   INTEGER,INTENT(in) :: k,i,j
   REAL(KIND=rsh),INTENT(out) :: xeros,excespowr,sed_tocr_mixsed

   !! * Local declarations
   INTEGER            :: iv
   REAL(KIND=rsh)     :: sommud,somsan,diamsan,critstressan,frvolsan,frvolgrv,somgrav,   &
                         somsedsusp,frvolsangrv,frmudsup,frmudcr1,pinterp,cmudr,frgrav
   ! utilisation de la relation de van Rijn pour flux d erosion (valable seulement si sable seul)
   REAL(KIND=rsh)     :: rossan,xeromud,coef_tmp,E0_sand
   !!---------------------------------------------------------------------------
   !! * Executable part

   sommud=0.0_rsh     
   DO iv=imud1,imud2
     sommud=sommud+cv_sed(iv,k,i,j)
   ENDDO
   somsan=0.0_rsh
   somgrav=0.0_rsh
   diamsan=0.0_rsh
   critstressan=0.0_rsh
   frvolsan=0.0_rsh   
   frvolgrv=0.0_rsh         
   !rossan=0.0_rsh
   !!!!!!!!!!!!!!!!!
!!! ATTENTION : MEME SI PLUSIEURS SABLES, ON SUPPOSE QU ILS ONT TOUS LA MEME DENSITE
   rossan=ros_sand_homogen
!!!!!!!!!!!!!!!!!
   DO iv=isand1,isand2
     somsan=somsan+cv_sed(iv,k,i,j)
     diamsan=diamsan+diam_sed(iv)*cv_sed(iv,k,i,j)
     critstressan=critstressan+stresscri0(iv)*cv_sed(iv,k,i,j)
     frvolsan=frvolsan+cv_sed(iv,k,i,j)/ros(iv)
     !rossan=rossan+ros(iv)*cv_sed(iv,k,i,j)
   ENDDO
   somsedsusp=sommud+somsan
   IF(somsedsusp.LE.0.0_rsh)THEN
     ! surficial sediment non transportable in suspension
     sed_tocr_mixsed=1000.0_rsh
   ELSE
     IF (isand2>0 .AND. somsan>0.0_rsh) THEN
       diamsan=MAX(diamsan/(somsan+epsilon),diam_sed(isand2))
       critstressan=MAX(critstressan/(somsan+epsilon),stresscri0(isand2))
     ENDIF
    
     DO iv=igrav1,igrav2
       somgrav=somgrav+cv_sed(iv,k,i,j)
       frvolgrv=frvolgrv+cv_sed(iv,k,i,j)/ros(iv)
     ENDDO
     frvolsangrv=frvolgrv+frvolsan
     frgrav=somgrav/(somgrav+sommud+somsan)
     IF(frgrav == 1._rsh) THEN
!****************************************!
! Il n y a que du gravier ! 
!****************************************!
       xeros=0.0_rsh
       excespowr=n_eros_sand
       sed_tocr_mixsed=critstressan
     ELSE      
!**************************************************************!
! Il y a  potentiellement du sable et/ou de la vase            !
!                                                              ! 
!   ATTENTION : les formules proposees pour l erosion          !
!               des melanges sablo-vaseux sont discutables     !
!               et doivent etre testees, ameliorees, changees  !
!               chaque utilisateur peut ecrire sa loi          !  
!**************************************************************!
       frmudsup=sommud/(sommud+somsan)
       frmudcr1=MIN(coef_frmudcr1*diamsan,frmudcr2)
       
       IF(frmudsup.LE.frmudcr1)THEN
       !************************************!
       !************************************!
       ! I) Comportement sableux du melange !
       !************************************!
       !************************************!
       !  Si E0_sand_option==0 :  utilisation de E0_sand lu dans parasedim
          IF (E0_sand_option == 2) THEN
            ! E0_sand calcule par formulation erodimetrie en fonction du diametre moyen des sables
              E0_sand = E0_sand_para * critstressan**n_eros_sand * MIN(0.27,1000*diamsan-0.01)
          ELSE IF(E0_sand_option == 0) THEN    !utilisation de E0_sand_para lu dans parasedim
              E0_sand = E0_sand_para
          ELSE IF(E0_sand_option == 1 .AND. rossan.GT.1000_rsh) THEN
            ! E0_sand calcule a partir de la fomrule de Van Rijn (1984)
              E0_sand=0.000005_rsh*rossan*((rossan/1000.0_rsh-1.0_rsh)*9.81*diamsan)**0.5_rsh &
                     *(diamsan*((rossan/1000.0_rsh-1)*9.81_rsh/(0.000001_rsh)**2)**(1.0_rsh/3.0_rsh))**(0.3_rsh)
          ENDIF
          IF (ero_option == 0) THEN
              cmudr=sommud/(1.0_rsh-frvolsangrv)
              xeros=E0_mud
              sed_tocr_mixsed=x1toce_mud*cmudr**x2toce_mud
              excespowr=n_eros_mud
          ELSE
              xeros=E0_sand
              sed_tocr_mixsed=critstressan
              excespowr=n_eros_sand
          ENDIF
          

       ELSE IF(frmudsup.LE.frmudcr2)THEN
       !****************************************!
       !****************************************!
       ! II) Intermediaire sable / vase         !
       !****************************************!
       !****************************************!
          cmudr=sommud/(1.0_rsh-frvolsangrv)
       !  Si E0_sand_option==0 :  utilisation de E0_sand lu dans parasedim
          IF (E0_sand_option == 2) THEN
            ! E0_sand calcule par formulation erodimetrie en fonction du diametre moyen des sables
              E0_sand = E0_sand_para * critstressan**n_eros_sand * MIN(0.27,1000*diamsan-0.01)
          ELSE IF(E0_sand_option == 0) THEN    !utilisation de E0_sand_para lu dans parasedim
              E0_sand = E0_sand_para
          ELSE IF(E0_sand_option == 1 .AND. rossan.GT.1000_rsh) THEN
            ! E0_sand calcule a partir de la fomrule de Van Rijn (1984)
              E0_sand=0.000005_rsh*rossan*((rossan/1000.0_rsh-1.0_rsh)*9.81*diamsan)**0.5_rsh &
                     *(diamsan*((rossan/1000.0_rsh-1)*9.81_rsh/(0.000001_rsh)**2)**(1.0_rsh/3.0_rsh))**(0.3_rsh)
          ENDIF
          pinterp=(frmudcr2-frmudsup)/(frmudcr2-frmudcr1)

          IF (ero_option == 0) THEN

            !!! On garde des parametres constants (par defaut ceux definis pour la vase)
            xeros=E0_mud
            sed_tocr_mixsed=x1toce_mud*cmudr**x2toce_mud
            excespowr=n_eros_mud

          ELSE IF (ero_option == 1) THEN

            !!! Formulation initiale avec transition lineaire dans le cas dun melange intermediaire
            !!! Le Hir et al (2011)
            
            xeros=pinterp*E0_sand+(1.0_rsh-pinterp)*E0_mud
            excespowr=pinterp*n_eros_sand+(1.0_rsh-pinterp)*n_eros_mud
            sed_tocr_mixsed=critstressan*pinterp+(1.0_rsh-pinterp)*x1toce_mud*cmudr**x2toce_mud

          ELSE IF (ero_option .EQ. 2) THEN

            !!! Formulation de Julie Vareilles (2013) 
            !!! En accord avec Van Ledden (2001) et Carniello et al (2012)
            xeromud=x1toce_mud*cmudr**x2toce_mud
            xeros = ( (E0_sand/E0_mud)**pinterp )*E0_mud
            sed_tocr_mixsed = ( (critstressan/xeromud)**pinterp )*xeromud
            excespowr = ( (n_eros_sand/n_eros_mud)**pinterp )*n_eros_mud

          ELSE IF (ero_option .EQ. 3) THEN

            !!! Formulation de Baptiste Mengual (2015)
            !!! Formulations exponentielles des parametres pour un melange sablovaseux            
            !xeromud=x1toce_mud*cmudr**x2toce_mud
            !coef_tmp=((-5.0_rsh*frmudsup+(frmudcr1/0.2_rsh)) / (frmudcr2-0.1_rsh))*xexp_ero 
            !!! Parametre d erodabilite
            !xeros = (E0_sand-E0_mud)*EXP(coef_tmp) + E0_mud       
            !!! Contrainte critique pour l erosion
            !sed_tocr_mixsed = ABS((-critstressan +xeromud) * EXP( coef_tmp ) - xeromud)
            !!! Puissance
            !excespowr = (n_eros_sand-n_eros_mud)*EXP( coef_tmp )+ n_eros_mud

            !!! Formulation de Baptiste Mengual 
            !!!Mengual, B.; Le Hir, P.; Cayocca, F.; Garlan, T. Modelling Fine Sediment Dynamics: Towards a Common Erosion Law for Fine Sand, Mud and Mixtures. Water 2017, 9, 564.

            !!! Formulations exponentielles des parametres pour un melange sablovaseux            
            xeromud=x1toce_mud*cmudr**x2toce_mud
            coef_tmp=(frmudcr1-frmudsup)/(frmudcr2-frmudcr1) 
            !!! Parametre d erodabilite
            xeros = (E0_sand-E0_mud)*EXP(coef_tmp*xexp_ero) + E0_mud       
            !!! Contrainte critique pour l erosion
            sed_tocr_mixsed = (critstressan -xeromud) * EXP( coef_tmp*xexp_ero ) + xeromud
            !!! Puissance
            excespowr = (n_eros_sand-n_eros_mud)*EXP( coef_tmp*xexp_ero)+ n_eros_mud

          END IF

       ELSE
       !****************************************!
       !****************************************!
       ! III) Comportement vaseux               !
       !****************************************!
       !****************************************!

          cmudr=sommud/(1.0_rsh-frvolsangrv)
          sed_tocr_mixsed=x1toce_mud*cmudr**x2toce_mud
          excespowr=n_eros_mud
          xeros=E0_mud

       ENDIF

     ENDIF
   ENDIF
   END SUBROUTINE sed_comp_tocr_mixsed
#endif   

!!==============================================================================

#ifdef key_sedim_mudsand

  SUBROUTINE sed_comp_tocr_mudsand(csedim)

   !&E--------------------------------------------------------------------------
   !&E                 ***  SUBROUTINE sed_comp_tocr_mudsand  ***
   !&E
   !&E ** Purpose : compute the critical shear stress of sediment
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by : 
   !&E 
   !&E ** External calls : none
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used

   !! * Arguments
   REAL(KIND=rsh),INTENT(in)  :: csedim

   !! * Local declarations

   !!---------------------------------------------------------------------------
   !! * Executable part

   sed_tocr_mudsand=x1toce*MAX(csedim,cfreshmud)**x2toce
   IF(csedim.GE.1200.0_rsh) sed_tocr_mudsand=20.0_rsh

  END SUBROUTINE sed_comp_tocr_mudsand

#endif   
   
   !!==============================================================================

#ifdef key_sedim_mixsed

  SUBROUTINE sed_comp_eros_flx(tenfo,toce,csurface,excespowr,xeros,sed_eros_flx)
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  SUBROUTINE sed_erosion_flux  ***
   !&E
   !&E ** Purpose : computes erosion flux for given stress, critical stress and
   !&E              surficial sediment concentration
   !&E              uses toce, excespowr and xeros computed by sed_tocr
   !&E
   !&E ** Description : Partheniades or adapted Partheniades
   !&E
   !&E ** Called by :  sed_erosion
   !&E 
   !&E ** External calls : nonee
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-02  (P. Le Hir) extracted from (SiAM) new "Marennes-Oleron"
   !&E                               sand/mud sediment model
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   !! * Arguments
   REAL(KIND=rsh),INTENT(in) :: csurface,tenfo,toce
   REAL(KIND=rsh),INTENT(in) :: excespowr,xeros
   REAL(KIND=rsh),INTENT(out) :: sed_eros_flx

   !! * Local declarations   
   REAL(KIND=rsh) ::  corfluero

   !!---------------------------------------------------------------------------
   !! * Executable part
   
   corfluero=1.0_rsh+corfluer1*MAX(0.0_rsh,corfluer2-csurface)     
   ! Partheniades :
   sed_eros_flx=xeros*corfluero*(tenfo/toce-1.0_rsh)**excespowr
!choisir une des formules
!  sed_eros_flx=xeros*corfluero*(tenfo-toce)**excespowr
    
  END SUBROUTINE sed_comp_eros_flx

#endif

   !!==============================================================================

  SUBROUTINE sed_sandconcextrap

   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_sandconcextrap  ***
   !&E
   !&E ** Purpose : interpolates sand concentration in the first layer
   !&E              assuming a Rouse profile 
   !&E
   !&E ** Description : tenfon has to be known
   !&E
   !&E ** Called by :  main ou step
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (P. Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       !  2009-02 (P. Le Hir)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance,   ONLY : ws3,flx_w2s,isand1,isand2,nv_adv,l_subs2D
   USE comvarp2d,      ONLY : ssh
   USE comvars2d,      ONLY : h0,hm,ig,id,h0fond,l_obc_cycl_x,l_obc_cycl_y,nbouc,t,jb,jh
   USE comvars3d,      ONLY : sig,sigw
   USE_MPI toolmpi,    ONLY : ex_i_rsh,ex_j_rsh
#if defined key_siggen || defined key_gencoord
   USE toolgeom,       ONLY : f_hzu
   USE comvars3d,      ONLY : dsigu
#endif


   !! * Local declarations
   REAL(KIND=rsh)                       :: altc1,ep,htot,extrap,rouse,som,dzcche,hzed,           &
                                           einstein,alogaltc1sz0,ashmapwrouse
   INTEGER                              :: izz,i,j,ivp
   INTEGER,PARAMETER                    :: nbcche=20
   REAL(KIND=rsh),DIMENSION(1:nbcche+1) :: hzi

   REAL(KIND=rsh)                        :: rouse1
#ifdef key_sand2D
   REAL(KIND=rsh),DIMENSION(1:nbcche+1) :: hzisdbot
#endif
   !!---------------------------------------------------------------------------
   !! * Executable part

   corflux(:,limin:limaxp1,ljmin:ljmax  )=1.0_rsh
   corfluy(:,limin:limax  ,ljmin:ljmaxp1)=1.0_rsh

   
!$OMP PARALLEL DEFAULT(NONE) SHARED(ljminp1,ljminp2,ljmaxm1,limin,limax,limaxp1   &
!$OMP&  ,ig,id,h0,ssh,sig,h0fond,isand1,isand2,corflux,corfluy,z0sed,ws3,ustarbot  &
!$OMP&  ,aref_sand,l_subs2D                     &
#if defined key_siggen || defined key_gencoord
!$OMP&  ,dsigu                                   &
#else
!$OMP&  ,sigw                                    &
#endif
#ifdef key_sand2D
!$OMP&  ,rouse2d,sum_tmp                         &
#endif
#ifdef key_MPI_2D
!$OMP&  ,nv_adv                                  &
#endif
!$OMP&  ,flx_w2s,ljmin,ljmax,ljmaxp1,hm,jb,jh)   &
!$OMP& PRIVATE(i,j,htot,extrap,ivp,alogaltc1sz0,altc1,hzi,izz,rouse,rouse1,som   &
#ifdef key_sand2D
!$OMP&  ,hzisdbot    &
#endif
!$OMP& ,einstein,hzed,dzcche,ashmapwrouse)  

!$OMP DO SCHEDULE(RUNTIME)
!cvalerie a verifier avec florence bug corriges mais...
!   DO j=ljminp1,ljmaxm1
!     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
   DO j=ljminp2,ljmaxm1
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)

          htot=h0(i,j)+ssh(i,j)  
          altc1=(1.0_rsh+sig(1))*htot
          IF(altc1.LE.aref_sand .OR. htot.LE.h0fond)THEN
            extrap=1.0_rsh
            ! in this case, flx_w2s(ivp,i,j) is not changed
            DO ivp=isand1,isand2
              corflux(ivp,i,j)=1.0_rsh
              corfluy(ivp,i,j)=1.0_rsh
            ENDDO
          ELSE
            alogaltc1sz0=LOG(altc1/z0sed(i,j))
#if defined key_siggen || defined key_gencoord
            hzi(1)=dsigu(1)*f_hzu(h0(i,j),ssh(i,j),1,i,j)
#else
            hzi(1)=(1.0_rsh+sigw(1))*htot
#endif
!            PRINT*, 'i,j,hzi(1),ustarbot',i,j,hzi(1),ustarbot(i,j)
            DO izz=1,nbcche
              hzi(izz+1)=hzi(izz)-(hzi(1)-aref_sand)/2.0_rsh**izz
            ENDDO     
            hzi(nbcche+1)=aref_sand
#ifdef key_sand2D
            hzisdbot(1)=htot
            DO izz=1,nbcche
              hzisdbot(izz+1)=hzisdbot(izz)-(hzisdbot(1)-aref_sand)/2.0_rsh**izz
            ENDDO     
            hzisdbot(nbcche+1)=aref_sand
#endif
            DO ivp=isand1,isand2
            ! Rouse number depends on settling velocity, then on the sand variable
            ! modif Julie 2012 to taking inti account flat bottom
              IF(ws3(1,ivp,i,j)>1.34_rsh*ustarbot(i,j)) THEN
                 rouse=1.2_rsh
              ELSE
                rouse1=ws3(1,ivp,i,j)/ustarbot(i,j)
                IF(rouse1>=0.75_rsh) THEN
                   rouse=0.353_rsh*rouse1+0.727
                ELSEIF(rouse1>0.1_rsh .AND. rouse1<0.75_rsh) THEN
                   rouse=rouse1/(0.4_rsh+0.8_rsh*rouse1*rouse1)   ! rouse=rouse1/(0.4*beta) avec beta=1+2*rouse1*rouse1
                ELSE
                  rouse=rouse1/0.4_rsh
                ENDIF
              ENDIF
            ! integrale concentration et concentration*vitesse log
            ! dans premiere couche
              som=0.0_rsh
              einstein=0.0_rsh
              DO izz=1,nbcche
#ifdef key_sand2D
               IF(l_subs2D(ivp)) THEN
                hzed=0.5_rsh*(hzisdbot(izz)+hzisdbot(izz+1))
                dzcche=hzisdbot(izz)-hzisdbot(izz+1) 
               ELSE
#endif
                hzed=0.5_rsh*(hzi(izz)+hzi(izz+1))
                dzcche=hzi(izz)-hzi(izz+1) 
#ifdef key_sand2D
               ENDIF
#endif
                som=som+dzcche*((htot-hzed)/hzed)**rouse
                einstein=einstein+dzcche*((htot-hzed)/hzed)**rouse      &  
                                  *LOG(hzed/z0sed(i,j))
              ENDDO
#ifdef key_sand2D
              IF(l_subs2D(ivp)) THEN
                rouse2D(ivp,i,j)=rouse
                sum_tmp(ivp,i,j)=som
              ENDIF
#endif 
!!
              ashmapwrouse=(aref_sand/(htot-aref_sand))**rouse
              som=som*ashmapwrouse
              !IF (som==0) PRINT*, 'i,j,hzi(1),ashmapwrouse rouse',i,j,hzi(1),ashmapwrouse,rouse

              einstein=einstein*ashmapwrouse/som
              ! the computation of einstein and USE of corflux should be checked
              !??? modif P.LeHir              if(hex(i,j).le.hm)then
              !??? modif P.LeHir              if(hey(i,j).le.hm)then

#ifdef key_sand2D
              IF(l_subs2D(ivp)) THEN
                extrap=(hzisdbot(1)-aref_sand)/som 
                corflux(ivp,i,j)=einstein/LOG(htot/(2.718_rsh*z0sed(i,j)))
                corfluy(ivp,i,j)=einstein/LOG(htot/(2.718_rsh*z0sed(i,j)))
              ELSE
#endif
                extrap=(hzi(1)-aref_sand)/som
                IF(htot.LE.hm)THEN
                  corflux(ivp,i,j)=einstein/LOG(htot/(2.718_rsh*z0sed(i,j)))
                  corfluy(ivp,i,j)=einstein/LOG(htot/(2.718_rsh*z0sed(i,j)))
                ELSE
                  corflux(ivp,i,j)=einstein/alogaltc1sz0
                  corfluy(ivp,i,j)=einstein/alogaltc1sz0
                ENDIF
#ifdef key_sand2D
              ENDIF
#endif 
              flx_w2s(ivp,i,j)=flx_w2s(ivp,i,j)*extrap              
            ENDDO              
          ENDIF
          
        ENDDO
      ENDDO
!$OMP END DO

!$OMP SINGLE
     ! hypothese gradient nul aux frontieres 
     IF_MPI (ljmax == jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          DO ivp=isand1,isand2
             corflux(ivp,i,jmax)=corflux(ivp,i,jmax-1)
             corfluy(ivp,i,jmax)=corfluy(ivp,i,jmax-1)
          ENDDO
        ENDDO
     ENDIF_MPI
     IF_MPI (ljmin == jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
          DO ivp=isand1,isand2
             corflux(ivp,i,jmin+1)=corflux(ivp,i,jmin+2)
             corfluy(ivp,i,jmin+1)=corfluy(ivp,i,jmin+2)
          ENDDO
        ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax) THEN
        DO j=MAX0(ljmin,jb(imax)+1),MIN0(ljmax,jh(imax)-1)
          DO ivp=isand1,isand2
             corflux(ivp,imax,j)=corflux(ivp,imax-1,j)
             corfluy(ivp,imax,j)=corfluy(ivp,imax-1,j)
          ENDDO
        ENDDO
     ENDIF_MPI
     IF_MPI (limin == imin) THEN
        DO j=MAX0(ljmin,jb(imin)+1),MIN0(ljmax,jh(imin)-1)
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,j)=corflux(ivp,imin+2,j)
             corfluy(ivp,imin+1,j)=corfluy(ivp,imin+2,j)
          ENDDO
        ENDDO
     ENDIF_MPI

     ! les quatre coins
     IF_MPI (limax == imax .AND. ljmax == jmax) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imax,jmax)=corflux(ivp,imax-1,jmax-1)
             corfluy(ivp,imax,jmax)=corfluy(ivp,imax-1,jmax-1)
          ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imax,jmin+1)=corflux(ivp,imax-1,jmin+2)
             corfluy(ivp,imax,jmin+1)=corfluy(ivp,imax-1,jmin+2)
          ENDDO
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,jmin+1)=corflux(ivp,imin+2,jmin+2)
             corfluy(ivp,imin+1,jmin+1)=corfluy(ivp,imin+2,jmin+2)
          ENDDO
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,jmax)=corflux(ivp,imin+2,jmax-1)
             corfluy(ivp,imin+1,jmax)=corfluy(ivp,imin+2,jmax-1)
          ENDDO
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : corflux, corfluy se sont pas alloues de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite dans la direction x 
     IF(l_obc_cycl_x) THEN
        DO j=ljminp1,ljmax
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,j)=corflux(ivp,imax-1,j)
             corfluy(ivp,imin+1,j)=corfluy(ivp,imax-1,j)
             corflux(ivp,imax,j)=corflux(ivp,imin+2,j)
             corfluy(ivp,imax,j)=corfluy(ivp,imin+2,j)
          ENDDO
        ENDDO
     ENDIF
     ! condition de periodicite dans la direction y
     IF(l_obc_cycl_y) THEN
        DO i=liminp1,limax
          DO ivp=isand1,isand2
             corflux(ivp,i,jmin+1)=corflux(ivp,i,jmax-1)
             corfluy(ivp,i,jmin+1)=corfluy(ivp,i,jmax-1)
             corflux(ivp,i,jmax)=corflux(ivp,i,jmin+2)
             corfluy(ivp,i,jmax)=corfluy(ivp,i,jmin+2)
          ENDDO
        ENDDO
     ENDIF
#endif
!$OMP END SINGLE

OMPMPI barrier
OMPMPI master
   CALL_MPI ex_i_rsh(0,1,nv_adv,limin,limaxp1,ljmin,ljmax  ,corflux(:,limin:limaxp1,ljmin:ljmax  ))
   CALL_MPI ex_j_rsh(0,1,nv_adv,limin,limax  ,ljmin,ljmaxp1,corfluy(:,limin:limax  ,ljmin:ljmaxp1))
OMPMPI end master
OMPMPI barrier
OMPMPI flush(corflux,corfluy)

!$OMP END PARALLEL

      ! corflux are interpolated on mesh edges (in u & v)
      ! -------------------------------------------------
   DO j=ljminp1,ljmaxm1
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
          DO ivp=isand1,isand2
            corflux(ivp,i,j)=0.5_rsh*(corflux(ivp,i,j)+corflux(ivp,i+1,j))
            corfluy(ivp,i,j)=0.5_rsh*(corfluy(ivp,i,j)+corfluy(ivp,i,j+1))
           ENDDO
     ENDDO
   ENDDO

     ! hypothese gradient nul aux frontieres 
     ! corflux et corfluy sont ainsi calcules pour liminp1 -> limax et ljminp1 ->ljmax 
    IF_MPI (ljmax == jmax) THEN
        DO i=MAX0(limin,ig(jmax)+1),MIN0(limax,id(jmax)-1)
          DO ivp=isand1,isand2
             corflux(ivp,i,jmax)=corflux(ivp,i,jmax-1)
             corfluy(ivp,i,jmax)=corfluy(ivp,i,jmax-1)
          ENDDO
        ENDDO
     ENDIF_MPI
     IF_MPI (ljmin == jmin) THEN
        DO i=MAX0(limin,ig(jmin)+1),MIN0(limax,id(jmin)-1)
          DO ivp=isand1,isand2
             corflux(ivp,i,jmin+1)=corflux(ivp,i,jmin+2)
             corfluy(ivp,i,jmin+1)=corfluy(ivp,i,jmin+2)
          ENDDO
        ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax) THEN
        DO j=ljminp1,ljmaxm1
          DO ivp=isand1,isand2
             corflux(ivp,imax,j)=corflux(ivp,imax-1,j)
             corfluy(ivp,imax,j)=corfluy(ivp,imax-1,j)
          ENDDO
        ENDDO
     ENDIF_MPI
     IF_MPI (limin == imin) THEN
        DO j=ljminp1,ljmaxm1
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,j)=corflux(ivp,imin+2,j)
             corfluy(ivp,imin+1,j)=corfluy(ivp,imin+2,j)
          ENDDO
        ENDDO
     ENDIF_MPI

     ! les quatre coins 
     IF_MPI (limax == imax .AND. ljmax == jmax) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imax,jmax)=corflux(ivp,imax-1,jmax-1)
             corfluy(ivp,imax,jmax)=corfluy(ivp,imax-1,jmax-1)
          ENDDO
     ENDIF_MPI
     IF_MPI (limax==imax .AND. ljmin==jmin) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imax,jmin+1)=corflux(ivp,imax-1,jmin+2)
             corfluy(ivp,imax,jmin+1)=corfluy(ivp,imax-1,jmin+2)
          ENDDO
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmin==jmin) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,jmin+1)=corflux(ivp,imin+2,jmin+2)
             corfluy(ivp,imin+1,jmin+1)=corfluy(ivp,imin+2,jmin+2)
          ENDDO
     ENDIF_MPI
     IF_MPI (limin==imin .AND. ljmax==jmax) THEN
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,jmax)=corflux(ivp,imin+2,jmax-1)
             corfluy(ivp,imin+1,jmax)=corfluy(ivp,imin+2,jmax-1)
          ENDDO
     ENDIF_MPI

#ifdef key_toseelater
!  PROBLEME : corflux et corfluy ne sont pas alloues de imin a imax et de jmin a jmax
!             il faut les echanger avec les processeurs extremes et les ranger dans m2 ou p2
!             voir comme dans tsobc3dapply par exemple
     ! condition de periodicite dans la direction x 
     IF(l_obc_cycl_x) THEN
        DO j=ljminp1,ljmax
          DO ivp=isand1,isand2
             corflux(ivp,imin+1,j)=corflux(ivp,imax-1,j)
             corfluy(ivp,imin+1,j)=corfluy(ivp,imax-1,j)
             corflux(ivp,imax,j)=corflux(ivp,imin+2,j)
             corfluy(ivp,imax,j)=corfluy(ivp,imin+2,j)
          ENDDO
        ENDDO
     ENDIF
     ! condition de periodicite dans la direction y 
     IF(l_obc_cycl_y) THEN
        DO i=liminp1,limax
          DO ivp=isand1,isand2
             corflux(ivp,i,jmin+1)=corflux(ivp,i,jmax-1)
             corfluy(ivp,i,jmin+1)=corfluy(ivp,i,jmax-1)
             corflux(ivp,i,jmax)=corflux(ivp,i,jmin+2)
             corfluy(ivp,i,jmax)=corfluy(ivp,i,jmin+2)
          ENDDO
        ENDDO
     ENDIF
#endif

   PRINT_DBG*, 'FIN SED_SANDCONCEXTRAP'

  END SUBROUTINE sed_sandconcextrap

   !!==============================================================================
 
  SUBROUTINE sed_depflx
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_depflx  ***
   !&E
   !&E ** Purpose : computes deposition flux trends after sed_erosion and 
   !&E              and sand_concextrap, before advection computations
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  stepu, stepv
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-03  (F. Cayocca) extracted from marsedim.F90 (from F. Dufois)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nvp,nvpc,tocd,flx_w2s,ws3,cv_wat,irkm_var_assoc,isand2,igrav2
   USE comvars2d,    ONLY : ig,id,fwet

   !! * Local declarations
   INTEGER                          :: i,j,ivp
   REAL(KIND=rlg)                   :: tocdpe,depo
   REAL(KIND=rlg),PARAMETER         :: epsdepot=1.e-14

   !!---------------------------------------------------------------------------
   !! * Executable part
!$OMP PARALLEL DEFAULT(NONE) SHARED(ljminp2,ljmaxm1,limin,limax,ig,id,igrav2      &
!$OMP&  ,nvp,nvpc,isand2,flx_w2s,ws3,tocd,tenfon,cv_wat,irkm_var_assoc,ljmax,fwet)&
!$OMP& PRIVATE(i,j,ivp,tocdpe,depo)  

!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljminp2,ljmax
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j))
       ! Benedicte : separation des boucles car pas forcement la meme unite pour les non constitutives
       ! pas de calcul pour les graviers 
       DO ivp=igrav2+1,nvpc
         IF(ivp.LE.isand2) THEN 
            ! Sanford et Halka (1993), Winterwerp (2004), Dufois (2008)
            flx_w2s(ivp,i,j)=ws3(1,ivp,i,j)*fwet(i,j)
         ELSE
            tocdpe=tocd(ivp)+0.00001_rsh
            flx_w2s(ivp,i,j)=ws3(1,ivp,i,j)*fwet(i,j)                &
                          *MAX(0.0_rsh,1.0_rsh-(tenfon(i,j)/tocdpe)) &  
                          *tocd(ivp)/tocdpe
         ENDIF
         depo=flx_w2s(ivp,i,j)*cv_wat(ivp,1,i,j)
         IF(depo.LE.epsdepot)flx_w2s(ivp,i,j)=0.0_rsh
       ENDDO
#ifdef key_sedim_partial
       DO ivp=nvpc+1,nvp
          flx_w2s(ivp,i,j)=0.0_rsh
       ENDDO
#else
       DO ivp=nvpc+1,nvp
         tocdpe=tocd(ivp)+0.00001_rsh
         flx_w2s(ivp,i,j)=ws3(1,ivp,i,j)*fwet(i,j)                   &
                          *MAX(0.0_rsh,1.0_rsh-(tenfon(i,j)/tocdpe)) &  
                          *tocd(ivp)/tocdpe
         depo=flx_w2s(ivp,i,j)*cv_wat(ivp,1,i,j)
         IF(irkm_var_assoc(ivp) > 0 ) THEN
          IF (flx_w2s(irkm_var_assoc(ivp),i,j)==0.0_rsh) flx_w2s(ivp,i,j)=0.0_rsh
         ELSE
          IF(depo.LE.epsdepot)flx_w2s(ivp,i,j)=0.0_rsh
         END IF
       ENDDO
#endif
     END DO
   END DO
!$OMP END DO
!$OMP END PARALLEL
         
  END SUBROUTINE sed_depflx

   !!==============================================================================
 
#ifdef key_sedim_mixsed

  SUBROUTINE sed_effdep_mixsed(xeloc)
    
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_effdep_mixsed  ***
   !&E
   !&E ** Purpose : computes effective deposition
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  step3dxy, step3dyx
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (P. Le Hir) extracted from subsedim.F90 (from F. Dufois)
   !&E       !  2008-10  (F. Cayocca) included into module_sedimento
   !&E       !  2008-02  (P. Le Hir)replaced by new "Marennes-Oleron" sand/mud sediment model
   !&E       !  2010-07  (B. Thouvenin) taking into account of non constitutive particulate variables
   !&E       !  2011-11  (V. Garnier) Spatial extension of ssh(liminm2:limaxp2,ljminm2:ljmaxp2)
   !&E       !  2015-10  (F. Grasso) Modification from B. Mengual on mud deposition
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : typart,nv_adv,nvp,nvpc,flx_w2s,flx_w2s_sum,cv_wat, &
                            igrav1,igrav2,isand1,isand2,imud1,imud2,irkm_var_assoc
   USE comvars2d,    ONLY : ig,id,dt,t,h0,h0fond,surf,dx,dy
   USE parameters,   ONLY : epsilon
   USE comvars3d,    ONLY : dsigu
   USE comvarp2d,     ONLY : sal,temp
   USE_MPI toolmpi,  ONLY : ex_i_rsh,ex_j_rsh
#if defined key_siggen || defined key_gencoord
  USE toolgeom,     ONLY : f_hzu
#endif

   !! * Arguments
   REAL(KIND=rsh),DIMENSION(liminm2:limaxp2,ljminm2:ljmaxp2),INTENT(IN) :: xeloc

   !! * Local declarations
   REAL(KIND=rsh),DIMENSION(nvp)  :: flx_w2s_loc
   REAL(KIND=rsh),DIMENSION(nvpc) :: frdep          
   INTEGER                        :: i,j,k,iv,ksmin,ksmax,kl,ivp_assoc,nv_use
   REAL(KIND=rsh) :: fludep,qdep,vitdepo,ddzs,ddzs1,ddzs2,dzsa,dzsisu,dzsi,dzsaici,      &
                     dzsgrv,dzssan,dzsmud,dzsnew,dzsa2,dzsa3,ddzs3,ddzs4,ddzs5,ddzs6,    &
                     poroa,somalp,somala,cdepiv,porosi,dzpoi,porodep,fluxdissous,        &
                     ddzsici,voldepgrv,voldepsan,masdepmud,dzskmanew,porewatera,         &
                     sommud,cvolinigrv,cvolinisan,cvolp,cmudr,porewater,                 &
                     dvolgrv,dvolsan,dmasmud,dmasmudgrav,dmasmudsand,cordepflu,          &
                     cordepfluw,cordepflue,cordepflus,cordepflun,                        &
                     dmasmud1,dmasmud2,dmasmud3,dmasmud4
   REAL(KIND=rlg),PARAMETER       :: epsdepef=1.e-14,epsd=1.e-16
#ifdef key_sedim_mixsed
   REAL(KIND=rsh),DIMENSION(nvp,limin:limax,ljmin:ljmax) :: flx_w2s_corin
   REAL(KIND=rsh),DIMENSION(nvp,limin  :limaxp1,ljmin  :ljmax  ) :: flx_w2s_corim1
   REAL(KIND=rsh),DIMENSION(nvp,liminm1:limax  ,ljmin  :ljmax  ) :: flx_w2s_corip1
   REAL(KIND=rsh),DIMENSION(nvp,limin  :limax  ,ljmin  :ljmaxp1) :: flx_w2s_corjm1
   REAL(KIND=rsh),DIMENSION(nvp,limin  :limax  ,ljminm1:ljmax  ) :: flx_w2s_corjp1
#endif

   !!----------------------------------------------------------------------
   !! * Executable part

   !deposit if strong bottom slope 
#ifdef key_sedim_mixsed
   flx_w2s_corim1(:,:,:)=0.0_rsh   
   flx_w2s_corip1(:,:,:)=0.0_rsh
   flx_w2s_corjm1(:,:,:)=0.0_rsh
   flx_w2s_corjp1(:,:,:)=0.0_rsh
   flx_w2s_corin(:,:,:)=0.0_rsh 
#endif

!$OMP PARALLEL DEFAULT(NONE) SHARED(ljmin,ljmax,limin,limax,ig,id,h0,xeloc              &
!$OMP&  ,h0fond,ksma,igrav1,igrav2,nvp,nvpc,cv_wat,flx_w2s_sum,l_morphocoupl,MF    &
!$OMP&  ,ros,isand1,isand2,imud1,imud2,cv_sed,cmudcr,dzs,cvolmaxmel,ksmi,cvolmaxsort    &
!$OMP&  ,surf,phieau_s2w,temp,sal                                              &
!$OMP&  ,dzsmax,cfreshmud,irkm_var_assoc,c_sedtot,poro,dzsmin,nv_adv,flx_w2s,dsigu      &
#ifdef key_MPI_2D
!$OMP&  ,liminm1,ljminm1,limaxp1,ljmaxp1                                                &
#endif
!$OMP&  ,slopefac,flx_w2s_corim1,flx_w2s_corip1,flx_w2s_corjm1,flx_w2s_corin,flx_w2s_corjp1   &
!$OMP&  ,l_consolid,dx,dy,ljminp1,ljmaxm1)                                                    &
!$OMP& PRIVATE(i,j,iv,ksmax,flx_w2s_loc,fludep,voldepgrv,voldepsan,masdepmud,frdep,ivp_assoc  &
!$OMP&  ,sommud,cvolinigrv,cvolinisan,cmudr,dzsa,dvolgrv,ddzs,ddzs1,ddzs2,ddzsici,dzsi,cvolp  &
!$OMP&  ,ddzs3,ddzs4,ddzs5,ddzs6,dzsaici,dzsa2,dzsa3,dvolsan,dmasmud,dmasmudgrav,dmasmudsand  &
!$OMP&  ,nv_use,dzsgrv,dzssan,dzsmud,dzsnew,dzskmanew,dzpoi,poroa,porewatera,porewater,fluxdissous  &
!$OMP&  ,cordepfluw,cordepflue,cordepflus,cordepflun,cordepflu                                &
!$OMP&  ,dmasmud1,dmasmud2,dmasmud3,dmasmud4)
#ifdef key_sedim_partial
   nv_use=nvpc
#else
   nv_use=nvp
#endif

   ddzsici=-1000.0_rsh
   flx_w2s_loc(:)=0.0_rsh
#if ! defined key_nodiss_insed
!$OMP SINGLE
   flx_w2s(nvp+1:nv_adv,:,:)=0.0_rsh
   flx_w2s(-1:0,:,:)=0.0_rsh
!$OMP END SINGLE
#endif

IF(slopefac .NE. 0.0_rsh) THEN
!$OMP DO SCHEDULE(RUNTIME)   
   DO j=ljminp1,ljmaxm1
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
       IF(h0(i,j)+xeloc(i,j).GT.h0fond) THEN
         cordepfluw=max(0.0_rsh,slopefac*(h0(i-1,j)-h0(i,j))/dx(i,j))
         cordepflue=max(0.0_rsh,slopefac*(h0(i+1,j)-h0(i,j))/dx(i,j))
         cordepflus=max(0.0_rsh,slopefac*(h0(i,j-1)-h0(i,j))/dy(i,j))
         cordepflun=max(0.0_rsh,slopefac*(h0(i,j+1)-h0(i,j))/dy(i,j))
         cordepflu=cordepfluw+cordepflue+cordepflus+cordepflun
         IF (cordepflu.gt.1.0_rsh)THEN
           cordepfluw=cordepfluw/cordepflu
           cordepflue=cordepflue/cordepflu
           cordepflus=cordepflus/cordepflu
           cordepflun=cordepflun/cordepflu
           cordepflu=1.0_rsh
         ENDIF
         DO iv=isand2+1,nvp
           flx_w2s_corim1(iv,i,j)=cordepfluw*flx_w2s_sum(iv,i,j)*surf(i,j)/surf(i-1,j)
           flx_w2s_corip1(iv,i,j)=cordepflue*flx_w2s_sum(iv,i,j)*surf(i,j)/surf(i+1,j)
           flx_w2s_corjm1(iv,i,j)=cordepflus*flx_w2s_sum(iv,i,j)*surf(i,j)/surf(i,j-1)
           flx_w2s_corjp1(iv,i,j)=cordepflun*flx_w2s_sum(iv,i,j)*surf(i,j)/surf(i,j+1)
           flx_w2s_corin(iv,i,j)=-cordepflu*flx_w2s_sum(iv,i,j)
         ENDDO
       ENDIF
     ENDDO
   ENDDO
!$OMP END DO

OMPMPI barrier
OMPMPI master
CALL_MPI ex_i_rsh(0,1,nvp,limin  ,limaxp1  ,ljmin  ,ljmax  ,flx_w2s_corim1(:,limin:limaxp1  ,ljmin:ljmax  ))
CALL_MPI ex_i_rsh(-1,0,nvp,liminm1,limax    ,ljmin  ,ljmax  ,flx_w2s_corip1(:,liminm1:limax  ,ljmin:ljmax  ))
CALL_MPI ex_j_rsh(0,1,nvp,limin  ,limax    ,ljmin  ,ljmaxp1,flx_w2s_corjm1(:,limin:limax  ,ljmin:ljmaxp1  ))
CALL_MPI ex_j_rsh(-1,0,nvp,limin  ,limax    ,ljminm1,ljmax  ,flx_w2s_corjp1(:,limin:limax  ,ljminm1:ljmax  ))
OMPMPI end master
OMPMPI barrier
OMPMPI flush(flx_w2s_corim1,flx_w2s_corip1,flx_w2s_corjm1,flx_w2s_corjp1)
   
ENDIF

!$OMP DO SCHEDULE(RUNTIME)   
   DO j=ljminp1,ljmaxm1
     DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)
      IF(h0(i,j)+xeloc(i,j).GT.h0fond) THEN

        ksmax=ksma(i,j)

        ! updating effective deposition :  (flx_w2s) is implicit in the vertical advection scheme
        ! hence multiplied here by the newly computed concentration
        DO iv=igrav2+1,nv_use   ! nv_use=nvp (or nvpc if key_sedim_partial)
! Benedicte: enleve ce test car il y a un test MAX apres qui remplace
!          IF(cv_wat(iv,1,i,j) >= 0.0_rsh) THEN
!          flx_w2s_loc(iv)=flx_w2s(iv,i,j)*cv_wat(iv,1,i,j)*fwet(i,j)*REAL(dt,rsh)*0.5_rsh
!       modif bene pour prendre le depot integre sur les ndt_part pas de temps
!       deja calcule a chaque sous pas de temps en fonction des cv_wat intermediaire
!       et exprime en Masse/m2 integre sur le demi pas de temps
           flx_w2s_loc(iv)=MAX(0.0_rsh,flx_w2s_sum(iv,i,j)+flx_w2s_corin(iv,i,j)      &
#if defined key_sedim_mixsed
                           +flx_w2s_corip1(iv,i-1,j)+flx_w2s_corim1(iv,i+1,j)         &
                           +flx_w2s_corjp1(iv,i,j-1)+flx_w2s_corjm1(iv,i,j+1))
#else
                           ) 
#endif
           flx_w2s_sum(iv,i,j)=0.0_rsh
! BT         ELSE
! BT          flx_w2s_loc(iv)=0.0_rsh
! BT         ENDIF
         ! MF /= 1 only if l_morphocoupl
         flx_w2s_loc(iv)=MF*flx_w2s_loc(iv)
        ENDDO

        fludep=0.0_rsh
        DO iv=1,nvpc
          fludep=fludep+flx_w2s_loc(iv)
        ENDDO

        voldepgrv=0.0_rsh
        voldepsan=0.0_rsh
        masdepmud=0.0_rsh
        dmasmud1 = 0.0_rsh
        dmasmud2 = 0.0_rsh
        dmasmud3 = 0.0_rsh
        dmasmud4 = 0.0_rsh
              
        IF(fludep.GT.0.0_rsh)THEN

          ! case 1:  there is deposition
          ! ****************************

          ! characterising deposition:
          DO iv=igrav1,igrav2
            voldepgrv=voldepgrv+flx_w2s_loc(iv)/ros(iv)
          ENDDO
          DO iv=igrav1,igrav2
            frdep(iv)=flx_w2s_loc(iv)/(voldepgrv+epsd)
          ENDDO
          DO iv=isand1,isand2
            voldepsan=voldepsan+flx_w2s_loc(iv)/ros(iv)
          ENDDO
          DO iv=isand1,isand2
            frdep(iv)=flx_w2s_loc(iv)/(voldepsan+epsd)
          ENDDO
          DO iv=imud1,imud2
            masdepmud=masdepmud+flx_w2s_loc(iv)
          ENDDO
          DO iv=imud1,imud2
            frdep(iv)=flx_w2s_loc(iv)/(masdepmud+epsd)
          ENDDO

          IF(ksmax.GE.ksmi(i,j))THEN
          
            ! case 1.1: sediment already exists
            ! ---------------------------------
            ! characterising previous surficial sediment:

            sommud=0.0_rsh      
            DO iv=imud1,imud2
              sommud=sommud+cv_sed(iv,ksmax,i,j)
            ENDDO
            cvolinigrv=0.0_rsh      
            DO iv=igrav1,igrav2
              cvolinigrv=cvolinigrv+cv_sed(iv,ksmax,i,j)/ros(iv)
            ENDDO
            cvolinisan=0.0_rsh
            DO iv=isand1,isand2
              cvolinisan=cvolinisan+cv_sed(iv,ksmax,i,j)/ros(iv)
            ENDDO
            cmudr=sommud/(1.0_rsh-cvolinisan-cvolinigrv)
            
            IF(cmudr.LE.cmudcr)THEN
            
              ! case 1.1.1: surficial sediment is not consolidated
              ! --------------------------------------------------
              ! mixing deposits with upper layer, until completion:

              dzsa=dzs(ksmax,i,j)

              ! first, gravels deposition :
              ! ---------------------------
              ! dvolgrv represente le volume de graviers qui s insere dans
              ! le sediment existant, en le densifiant
              ! il restera ddzs a deposer a la concentration volumique
              ! cvolmaxsort, dont ddzs2 dans la maille existante, ddzs1 en
              ! une nouvelle couche
              ! attention: a confirmer:
              dvolgrv=MIN(voldepgrv,dzsa*(cvolmaxsort-cvolinigrv),dzsa*(cvolmaxmel-cvolinigrv-cvolinisan))
              dvolgrv=MAX(dvolgrv,0.0_rsh)
              ddzs=(voldepgrv-dvolgrv)/cvolmaxsort
              ddzsici=ddzs
              dzsaici=dzsa
              IF((dzsa+ddzs).LE.dzsmax(i,j))THEN
                ddzs1=0.0_rsh
              ELSEIF(dzsa.GE.dzsmax(i,j))THEN
                ddzs1=ddzs
              ELSE
                ddzs1=dzsa+ddzs-dzsmax(i,j)
              ENDIF              
              !ddzs1=max(0.0_rsh,dzsa+ddzs-dzsmax(i,j))t
              ddzs2=ddzs-ddzs1
              dzsa2=dzsa+ddzs2
              voldepgrv=ddzs1*cvolmaxsort

              ! sand deposition :
              ! -----------------
              ! attention: a confirmer:
              ! modification du calcul de dvolsan (9 janvier 2012)
              !dvolsan=MIN(voldepsan,dzsa2*cvolmaxsort-dzsa*cvolinisan, &
              !                      dzsa2*cvolmaxmel-dzsa*(cvolinigrv+cvolinisan)-ddzs2*cvolmaxsort)
              ! ajout dvolgrv
              dvolsan=MIN(voldepsan,dzsa2*cvolmaxsort-dzsa*cvolinisan, &
                                    dzsa2*cvolmaxmel-dzsa*(cvolinigrv+cvolinisan)-ddzs2*cvolmaxsort)
              dvolsan=MAX(dvolsan,0.0_rsh)
              ! une partie des sandes dvolsab (avec repartition frdep) 
              ! vient densifier l epaisseur dzsa2,l autre partie vient creer 
              ! une surepaisseur ddzs4 (repartition frdep) et
              ! contribuer a une nouvelle couche pour ddzs3 (repartition frdep)
              ddzs=(voldepsan-dvolsan)/cvolmaxsort
              ! suppression de la ligne suivante (9 janvier 2012)
              !voldepsan=0.0_rsh
              IF((dzsa2+ddzs).LE.dzsmax(i,j))THEN
                ddzs3=0.0_rsh
              ELSEIF(dzsa2.GE.dzsmax(i,j))THEN
                ddzs3=ddzs
              ELSE
                ddzs3=dzsa2+ddzs-dzsmax(i,j)
              ENDIF              
              !ddzs3=max(0.0_rsh,dzsa2+ddzs-dzsmax(i,j))
              ddzs4=ddzs-ddzs3
              dzsa3=dzsa2+ddzs4
              voldepsan=ddzs3*cvolmaxsort

              ! mud deposition :
              ! ----------------
              ! une partie des vases dmasmud (avec repartition frdep) 
              ! vient densifier l epaisseur dzsa3, l autre partie vient creer 
              ! une surepaisseur ddzs6 (repartition frdep) et
              ! contribuer a une nouvelle couche pour ddzs5 (repartition frdep)

!!! B.Mengual (17/09/2015): 
!!! Le depot de la vase se fait en commencant a melanger depuis la surface
!!! dans le cas ou un excedant de sables ou de graviers conduira forcement
!!! a la creation dune nouvelle couche
!!! BUT : ne pas pieger de la vase par melange dans la couche ksmax-1 suite
!!!       a la creation dune nouvelle couche


              IF ((voldepgrv+voldepsan) .GT. 0.0_rsh) THEN

                !!! Part de vase qui va etre melangee avec la future couche
                ! On enleve les cas a cvolmaxmel pour etre coherent avec les ddzs1 et ddzs3
                ! calcules avec cvolmaxsort
                  dmasmud1 = MIN(masdepmud,(ddzs1+ddzs3)*cfreshmud*(1-cvolmaxsort))
                !!! Part de vase melangee avec les depots en sables / graviers effectues 
                !!! au cours du pas de temps dans la couche ksmax
                ! Meme commentaire
                  dmasmud2 = MIN(masdepmud-dmasmud1,(dzsa3-dzsa)*cfreshmud*(1-cvolmaxsort))
                !!! Part de vase melangee avec le sediment present initialement dans la couche ksmax
                IF((cvolinigrv+cvolinisan) .GT. 0.0_rsh) THEN
                  dmasmud3 = MIN(masdepmud-dmasmud1-dmasmud2,dzsa*(cfreshmud-cmudr)*(1-cvolinigrv-cvolinisan))
                END IF
                dmasmud3 = MAX(0.0_rsh,dmasmud3)
                dmasmud = dmasmud2 + dmasmud3
                !!! Calcul de l excedant de vase a ajouter dans la futur couche une fois que tout a ete melange
                dmasmud4 = masdepmud - dmasmud1 - dmasmud
                !!! Calcul de l epaisseur totale de vase qui sera attribuee a la future couche
                !!! Attention a ne pas confondre ddzs5 et dzsmud car une partie de ddzs5 sera melangee a lexcedant 
                !!! de sable gravier avant daccroitre lepaisseur de la couche
                ddzs5 = (dmasmud4/cfreshmud) + (dmasmud1/cfreshmud)
                ddzs6 = 0.0_rsh

                !IF (dmasmud1+dmasmud2+dmasmud3+dmasmud4 .LT. masdepmud) THEN
                !  print*,'*** BUG ***'
                !  print*,'La somme des dmasmud est inferieure a masdepmud au point (i,j) : ',i,' ',j
                !  print*,'dmasmud1,dmasmud2,dmasmud3,dmasmud4,masdepmud : ',dmasmud1,dmasmud2,dmasmud3,dmasmud4,masdepmud
                !END IF

                !IF (dmasmud1+dmasmud2+dmasmud3+dmasmud4 .GT. masdepmud) THEN
                !  print*,'*** BUG ***'
                !  print*,'La somme des dmasmud est superieure a masdepmud au point (i,j) : ',i,' ',j
                !  print*,'dmasmud1,dmasmud2,dmasmud3,dmasmud4,masdepmud : ',dmasmud1,dmasmud2,dmasmud3,dmasmud4,masdepmud
                !END IF


              ELSE
!!!BM
                dmasmud2 = MIN(masdepmud,(dzsa3-dzsa)*cfreshmud*(1-cvolmaxsort))
                IF((cvolinigrv+cvolinisan) .GT. 0.0_rsh) THEN
                  dmasmud3 = MIN(masdepmud-dmasmud2,dzsa*(cfreshmud-cmudr)*(1-cvolinigrv-cvolinisan))
                END IF
                dmasmud3 = MAX(0.0_rsh,dmasmud3)
                dmasmud = dmasmud2 + dmasmud3

!                ! une partie des vases dmasmud (avec repartition frdep) 
!                ! vient densifier l epaisseur dzsa3, l autre partie vient creer 
!                ! une surepaisseur ddzs6 (repartition frdep) et
!                ! contribuer a une nouvelle couche pour ddzs5 (repartition frdep)
!                IF(cvolinigrv >0.0_rsh .and. cvolinisan > 0.0_rsh) THEN
!                  ! melange sable+gravier  
!                  dmasmud=MIN(masdepmud,(dzsa3-dzsa)*cfreshmud*(1.0_rsh-cvolmaxmel))  ! masse de vase qui s insere dans un melange
!                ELSE IF ((cvolinisan > 0.0_rsh .AND. isand2>isand1) .OR. (cvolinigrv > 0.0_rsh .AND. igrav2>igrav1) ) THEN
!                  ! melange sables  ou graviers
!                  dmasmud=MIN(masdepmud,(dzsa3-dzsa)*cfreshmud*(1.0_rsh-cvolmaxmel))  ! masse de vase qui s insere dans un melange
!                ELSE
!                  ! un seul type de sediment 
!                  dmasmud=MIN(masdepmud,(dzsa3-dzsa)*cfreshmud*(1.0_rsh-cvolmaxsort))  ! masse de vase qui s insere dans le gravier ou sable (1-cvolmaxsort)
!                ENDIF

                ddzs=(masdepmud-dmasmud)/cfreshmud
                ! suppression ligne suivante (9 janvier 2012)
                !masdepmud=0.0_rsh
                IF((dzsa3+ddzs).LE.dzsmax(i,j))THEN
                  ddzs5=0.0_rsh
                ELSEIF(dzsa3.GE.dzsmax(i,j))THEN
                  ddzs5=ddzs
                ELSE
                  ddzs5=dzsa3+ddzs-dzsmax(i,j)
                ENDIF
                !ddzs5=max(0.0_rsh,dzsa3+ddzs-dzsmax(i,j))
                ddzs6=ddzs-ddzs5

              END IF


              masdepmud=ddzs5*cfreshmud

              dzs(ksmax,i,j)=dzsa3+ddzs6
              dzsi=1.0_rsh/dzs(ksmax,i,j)
              DO iv=igrav1,igrav2
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+(dvolgrv    &
                                     +ddzs2*cvolmaxsort)*frdep(iv))*dzsi
              ENDDO
              DO iv=isand1,isand2
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+(dvolsan    &
                                     +ddzs4*cvolmaxsort)*frdep(iv))*dzsi
              ENDDO
              DO iv=imud1,imud2
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+(dmasmud    &
                                     +ddzs6*cfreshmud)*frdep(iv))*dzsi
              ENDDO

              DO iv=nvpc+1,nvp
#ifdef key_sedim_partial
               cv_sed(iv,ksmax,i,j)=0.0_rsh
#else
                ivp_assoc=irkm_var_assoc(iv)
                IF (ivp_assoc == 0) THEN
                   ! its own settling velocity , totaly integrated in this layer
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+flx_w2s_loc(iv))*dzsi
                ELSE IF (ivp_assoc < isand1) THEN
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+        &
                                     flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*    &
                                     (dvolgrv+ddzs2*cvolmaxsort)*frdep(ivp_assoc))*dzsi
                ELSE IF (ivp_assoc < imud1) THEN
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+         &
                                      flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*   &
                                    (dvolsan+ddzs4*cvolmaxsort)*frdep(ivp_assoc))*dzsi
                ELSE 
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa             &
                                     +flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*    &
                                     (dmasmud+ddzs6*cfreshmud)*frdep(ivp_assoc))*dzsi
                END IF
#endif
              ENDDO
              k=ksmax
              c_sedtot(k,i,j)=0.0_rsh
              cvolp=0.0_rsh
              DO iv=1,nvpc
                c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
                cvolp=cvolp+cv_sed(iv,k,i,j)/ros(iv)
              ENDDO    
              poroa=poro(k,i,j)
              poro(k,i,j)=1.0_rsh-cvolp

              !  water fluxes and dissolved variable in pore waters
              !------------------------------------------
                porewatera=poroa*dzsa
                porewater=poro(k,i,j)*dzs(ksmax,i,j)
                IF(porewater > porewatera) THEN
                  !input of pore water from water column
                  dzpoi=dzsi/poro(ksmax,i,j)
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                  DO iv=nvp+1,nv_adv
                    fluxdissous=(porewater-porewatera)*cv_wat(iv,1,i,j)  
                    ! flux dissous ou flx_w2s  sera divise par dt qd pris en compte dans erosion, pour etre en quantite/m2/s
                    cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*porewatera +fluxdissous)*dzpoi
                    flx_w2s(iv,i,j)=flx_w2s(iv,i,j)+fluxdissous
                  ENDDO
#endif
                  ! temperature et salinite
                  fluxdissous=(porewater-porewatera)*temp(1,i,j)  
                  cv_sed(-1,ksmax,i,j)=(cv_sed(-1,ksmax,i,j)*porewatera +fluxdissous)*dzpoi
                  flx_w2s(-1,i,j)=flx_w2s(-1,i,j)+fluxdissous
                  fluxdissous=(porewater-porewatera)*sal(1,i,j)  
                  cv_sed(0,ksmax,i,j)=(cv_sed(0,ksmax,i,j)*porewatera +fluxdissous)*dzpoi
                  flx_w2s(0,i,j)=flx_w2s(0,i,j)+fluxdissous
#endif
                  ! flux d eau 
                  phieau_s2w(i,j)=phieau_s2w(i,j)+REAL((porewatera-porewater)*surf(i,j),rlg)
                ELSE
                !output of pore-water to water column ; cvsed are inchanged
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                  DO iv=nvp+1,nv_adv
                    flx_w2s(iv,i,j)=flx_w2s(iv,i,j)+(porewater-porewatera)*cv_sed(iv,k,i,j)  
                    !flx_w2s sera divise par dt qd pris en compte dans erosion, pour etre en quantite/m2/s
                  ENDDO
#endif
                  ! temperature et salinite
                  flx_w2s(-1,i,j)=flx_w2s(-1,i,j)+(porewater-porewatera)*cv_sed(-1,k,i,j)  
                  flx_w2s(0,i,j)=flx_w2s(0,i,j)+(porewater-porewatera)*cv_sed(0,k,i,j)
#endif
                  ! flux d eau 
                  phieau_s2w(i,j)=phieau_s2w(i,j)+REAL((porewatera-porewater)*surf(i,j),rlg)
                ENDIF              
            ENDIF
          ENDIF
  
          ! case 1.2 or following 1.1: computation of remaining deposits
          ! -----------------------------------------------------------

          dzsgrv=0.0_rsh
          dzssan=0.0_rsh
          dzsmud=0.0_rsh
          ! gravel deposition:
          ! ------------------
          IF(voldepgrv.GE.0.0_rsh)THEN
            dzsgrv=voldepgrv/cvolmaxsort
          ENDIF

          ! sand deposition:
          ! ----------------
          IF(voldepsan.GE.0.0_rsh)THEN
            dvolsan=MIN(voldepsan,dzsgrv*(cvolmaxmel-cvolmaxsort))
            dzssan=(voldepsan-dvolsan)/cvolmaxsort
          ENDIF

          ! mud deposition:
          ! ---------------
          IF(masdepmud.GE.0.0_rsh)THEN
            ! depot de la vase
            dmasmud=MIN(masdepmud,(dzsgrv+dzssan)*cfreshmud*(1.0_rsh-cvolmaxmel))
            dzsmud=(masdepmud-dmasmud)/cfreshmud
          ENDIF
          
          dzsnew=dzsgrv+dzssan+dzsmud

          IF(dzsnew.GT.0.0_rsh)THEN
          
            ! case 1.2 or following 1.1: possible creation of a new layer
            ! ----------------------------------------------------------

            !we choose to do the same test with or whithout consolidation. 
            !We will manage very small dzs in consolidation module
            IF(ksmax == 0 .OR. l_consolid) THEN
              dzskmanew=0.0_rsh
            ELSE
              dzskmanew=dzs(ksmax,i,j)+dzsnew
            ENDIF
            ! creation only if dzsnew>dzsmin or if overtake dzsmax 
            IF(((dzsnew >= dzsmin .OR. dzskmanew > dzsmax(i,j)) .AND. ksdmax > 1) .OR. ksmax == 0)THEN

              ! actual constitution of the new layer:
              ! -------------------------------------
              IF(ksmax.EQ.ksdmax)CALL sed_fusion(i,j,ksmax)
              dzsa=0.0_rsh
              ksmax=ksmax+1
              dzs(ksmax,i,j)=dzsnew
              dzsi=1.0_rsh/dzs(ksmax,i,j)
              DO iv=igrav1,igrav2
                cv_sed(iv,ksmax,i,j)=voldepgrv*frdep(iv)*dzsi
              ENDDO
              DO iv=isand1,isand2
                cv_sed(iv,ksmax,i,j)=voldepsan*frdep(iv)*dzsi
              ENDDO
              DO iv=imud1,imud2
                cv_sed(iv,ksmax,i,j)=masdepmud*frdep(iv)*dzsi
              ENDDO

#if ! defined key_sedim_partial
              DO iv=nvpc+1,nvp
                ivp_assoc=irkm_var_assoc(iv)
                IF (ivp_assoc .NE. 0) THEN
                !   ! pas de depot si pas associe car tout depose dans la couche juste avant
                   cv_sed(iv,ksmax,i,j)= flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*    &
                                        cv_sed(ivp_assoc,ksmax,i,j)
                ELSE
                   cv_sed(iv,ksmax,i,j)=0.0_rsh
                END IF 
              ENDDO
#endif
              ! computing total concentration and porosity of the surf.layer:
              ! -------------------------------------------------------------
              k=ksmax
              c_sedtot(k,i,j)=0.0_rsh
              cvolp=0.0_rsh
              DO iv=1,nvpc
                c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
                cvolp=cvolp+cv_sed(iv,k,i,j)/ros(iv)
              ENDDO

              poro(k,i,j)=1.0_rsh-cvolp
              
              !  dissolved variable in pore waters
              !------------------------------------------
                porewater=poro(k,i,j)*dzs(ksmax,i,j)
                !input of pore water from water column
                dzpoi=dzsi/poro(ksmax,i,j)
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                DO iv=nvp+1,nv_adv
                  cv_sed(iv,ksmax,i,j)=cv_wat(iv,1,i,j)
                  flx_w2s(iv,i,j)=flx_w2s(iv,i,j)+porewater*cv_wat(iv,1,i,j)   
                  !sera divise par dt qd pris en compte dans erosion, pour etre en quantite/m2/s
                ENDDO
#endif
                cv_sed(-1,ksmax,i,j)=temp(1,i,j)
                flx_w2s(-1,i,j)=flx_w2s(-1,i,j)+porewater*temp(1,i,j) 
                cv_sed(0,ksmax,i,j)=sal(1,i,j)
                flx_w2s(0,i,j)=flx_w2s(0,i,j)+porewater*sal(1,i,j) 
#endif
                ! flux d eau 
                phieau_s2w(i,j)=phieau_s2w(i,j)-REAL(porewater*surf(i,j),rlg)
            ELSE
            
              ! as the new layer is too small, back to an increase of the surf. layer:
              ! ----------------------------------------------------------------------
              dzsa=dzs(ksmax,i,j)
              dzs(ksmax,i,j)=dzs(ksmax,i,j)+dzsnew
              dzsi=1.0_rsh/dzs(ksmax,i,j)
              DO iv=igrav1,igrav2
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa                 &
                                  +voldepgrv*frdep(iv))*dzsi
              ENDDO
              DO iv=isand1,isand2
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa                 &
                                 +voldepsan*frdep(iv))*dzsi
              ENDDO
              DO iv=imud1,imud2
                cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa                 &
                                  +masdepmud*frdep(iv))*dzsi
              ENDDO

#if ! defined key_sedim_partial
              DO iv=nvpc+1,nvp
                ivp_assoc=irkm_var_assoc(iv)
                IF (ivp_assoc == 0) THEN
                   ! its own settling velocity 

                ELSE IF (ivp_assoc < isand1) THEN
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+                    &
                                       flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*  &
                                       voldepgrv*frdep(ivp_assoc))*dzsi
               ELSE IF (ivp_assoc < imud1) THEN
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+                    &
                                     flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*   &
                                     voldepsan*frdep(ivp_assoc))*dzsi
                ELSE 
                   cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+                    &
                                      flx_w2s_loc(iv)/(flx_w2s_loc(ivp_assoc)+epsd)*   &
                                      masdepmud*frdep(ivp_assoc))*dzsi
                END IF 
              ENDDO
#endif
            
              ! computing total concentration and porosity of the surf.layer:
              ! -------------------------------------------------------------
              k=ksmax
              c_sedtot(k,i,j)=0.0_rsh
              cvolp=0.0_rsh
              DO iv=1,nvpc
                c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
                cvolp=cvolp+cv_sed(iv,k,i,j)/ros(iv)
              ENDDO
              poroa=poro(k,i,j)
              poro(k,i,j)=1.0_rsh-cvolp
 
              !  dissolved variable in pore waters
              !------------------------------------------
                porewatera=poroa*dzsa
                porewater=poro(k,i,j)*dzs(ksmax,i,j)
                IF(porewater > porewatera) THEN
                  !input of pore water from water column
                  dzpoi=dzsi/poro(ksmax,i,j)
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                  DO iv=nvp+1,nv_adv
                    fluxdissous=(porewater-porewatera)*cv_wat(iv,1,i,j)  
                    !sera divise par dt qd pris en compte dans erosion, pour etre en quantite/m2/s
                    cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*porewatera +fluxdissous)*dzpoi
                    flx_w2s(iv,i,j)=flx_w2s(iv,i,j)+fluxdissous
                  ENDDO
#endif
                  ! salinite et temperature
                  fluxdissous=(porewater-porewatera)*temp(1,i,j)  
                  cv_sed(-1,ksmax,i,j)=(cv_sed(-1,ksmax,i,j)*porewatera +fluxdissous)*dzpoi
                  flx_w2s(-1,i,j)=flx_w2s(-1,i,j)+fluxdissous
                  fluxdissous=(porewater-porewatera)*sal(1,i,j)  
                  cv_sed(0,ksmax,i,j)=(cv_sed(0,ksmax,i,j)*porewatera +fluxdissous)*dzpoi
                  flx_w2s(0,i,j)=flx_w2s(0,i,j)+fluxdissous                          
#endif
                  ! flux d eau 
                  phieau_s2w(i,j)=phieau_s2w(i,j)+REAL((porewatera-porewater)*surf(i,j),rlg)
                ELSE
                !output of pore-water to water column ; cvsed are inchanged
#if ! defined key_nodiss_insed
#if ! defined key_sedim_partial
                  DO iv=nvp+1,nv_adv
                    flx_w2s(iv,i,j)=flx_w2s(iv,i,j)+(porewater-porewatera)*cv_sed(iv,k,i,j)  
                    !sera divise par dt qd pris en compte dans erosion, pour etre en quantite/m2/s
                  ENDDO
#endif
                ! salinite et temperature
                  DO iv=-1,0
                    flx_w2s(iv,i,j)=flx_w2s(iv,i,j)+(porewater-porewatera)*cv_sed(iv,k,i,j)  
                  ENDDO
#endif
                ! flux d eau 
                  phieau_s2w(i,j)=phieau_s2w(i,j)+REAL((porewatera-porewater)*surf(i,j),rlg)
              ENDIF
            ENDIF       
 
            ! control writing :            
            !if(poro(k,i,j).ge.0.9999_rsh)then
            !  write(*,*)'dans depeff, a',t,'  en kij:',k,i,j
            !  write(*,555)k,dzs(k,i,j),c_sedtot(k,i,j),poro(k,i,j)
            !  write(*,*)dzsa,dzsgrv,dzssan,dzsmud,voldepgrv,voldepsan, &
            !            masdepmud,frdep,(cv_sed(iv,k,i,j),iv=1,4)
            !  write(*,*)igrav1,igrav2,isand1,isand2,imud1,imud2
            !  write(*,*)(fluevs(iv,i,j),iv=1,5)
            !  write(*,*)cvasr,cvascr,ddzs,ddzs1,ddzs2,ddzs3,ddzs4,ddzs5
            !  write(*,*)ddzsici,dvolgrv,dvolsan,cvolinigrv,cvolinisan,dzsaici
            !endif

          ENDIF
        ELSE

          ! case 2. : no deposition
          ! ***********************  
!         IF(fludep > 0.0_rsh) THEN
!    !      write(*,*)'no deposition ',i,j,fludep
!          ! reintegration dans la colonne d eau
!          DO iv=1,nvpc
!#if defined key_siggen || defined key_gencoord
!              cv_wat(iv,1,i,j)=cv_wat(iv,1,i,j)                                        &
!                               +flx_w2s_loc(iv)/(dsigu(1)*f_hzu(h0(i,j),xeloc(i,j),1,i,j))
!#else
!              cv_wat(iv,1,i,j)=cv_wat(iv,1,i,j)                                        &
!                               +flx_w2s_loc(iv)/(dsigu(1)*(xeloc(i,j)+h0(i,j)))
!#endif
!             
!          ENDDO
!         ENDIF
          ! computing flx_w2s for dissolved var., to be used in the next time step:
          ! -----------------------------------------------------------------------
#if ! defined key_nodiss_insed
          DO iv=nvp+1,nv_adv
            flx_w2s(iv,i,j)=0.0_rsh
          ENDDO
          flx_w2s(-1:0,i,j)=0.0_rsh
#endif
          ! accounting for possible deposition of non constitutive particulate variable:
          ! ----------------------------------------------------------------------------
          ! prise en compte des depots eventuels 
          ! de variables particulaires non constitutives:
          IF(ksmax.GE.ksmi(i,j))THEN
            DO iv=nvpc+1,nvp
              cv_sed(iv,ksmax,i,j)=cv_sed(iv,ksmax,i,j)+flx_w2s_loc(iv)/dzs(ksmax,i,j)
            ENDDO
          ELSE
            DO iv=nvpc+1,nvp
#if defined key_siggen || defined key_gencoord
              cv_wat(iv,1,i,j)=cv_wat(iv,1,i,j)                                        &
                               +flx_w2s_loc(iv)/(dsigu(1)*f_hzu(h0(i,j),xeloc(i,j),1,i,j))
#else
              cv_wat(iv,1,i,j)=cv_wat(iv,1,i,j)                                        &
                               +flx_w2s_loc(iv)/(dsigu(1)*(xeloc(i,j)+h0(i,j)))
#endif
            ENDDO
          ENDIF

! Benedicte :   il manque ici echange des cv_wat pour MPI ???????

        ENDIF

        !GOTO 51
        ! control writing :            
        DO k=ksmi(i,j),ksmax
          IF(poro(k,i,j).GE.0.9999_rsh)THEN
            !WRITE(*,*)'a la fin de depeff, a',t,'  en kij:',k,i,j
            !DO kl=ksmax,ksmi(i,j),-1
              !WRITE(*,555)kl,dzs(kl,i,j),c_sedtot(kl,i,j),poro(kl,i,j)
              !555 FORMAT('k=',i3,'  dzs ',g8.2,'  csed ',g8.2,'  poro ',g8.2)
            !ENDDO
            GOTO 51
          ENDIF
        ENDDO
        51 CONTINUE

        ! updating ksma ( ksmax can be modified in the routine)
        ksma(i,j)=ksmax
        
       END IF ! test on h0+xe
      END DO  ! loop on i
    END DO    ! loop on j
!$OMP END DO
!$OMP END PARALLEL

   PRINT_DBG*, 'FIN SED_EFFDEP'   

  END SUBROUTINE sed_effdep_mixsed

#endif

   !!==============================================================================
 
#ifdef key_sedim_mudsand

  SUBROUTINE sed_effdep_mudsand(xeloc)
    
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_effdep  ***
   !&E
   !&E ** Purpose : computes effective deposition
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  step3dxy, step3dyx
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (Pierre Le Hir) extracted from subsedim.F90 (from F. Dufois)
   !&E       !  2008-10  (F. Cayocca) included into module_sedimento by F. Cayocca
   !&E       !  2008-02  (P. Le Hir) replaced by new "Marennes-Oleron" sand/mud sediment model
   !&E       !  2011-11  (V. Garnier) Spatial extension of ssh(liminm2:limaxp2,ljminm2:ljmaxp2)
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used   
#if defined key_contaminant
   USE contareaddat , ONLY : cin_max_re,cf_stochio_re,    &
                             irkm_var_re,nreacmax,nb_var_re,ityp_reac
#endif 
   USE comsubstance,  ONLY : typart,nv_adv,nvp,nvpc,flx_w2s,cv_wat,flx_w2s_sum
   USE comvars2d,     ONLY : h0fond,t,ig,id,h0,dt
   USE comvars3d,     ONLY : dsigu
   USE comvarp2d,     ONLY : sal,temp
   USE parameters,    ONLY : epsilon,valmanq
#if defined key_siggen || defined key_gencoord
  USE toolgeom,     ONLY : f_hzu
#endif

   !! * Arguments
   REAL(KIND=rsh),DIMENSION(liminm2:limaxp2,ljminm2:ljmaxp2),INTENT(IN) :: xeloc

   !! * Local declarations
   REAL(KIND=rsh),DIMENSION(nvp) :: flx_w2s_loc
   INTEGER        :: i,j,k,iv,ksmin,ksmax,kl,niter
   REAL(KIND=rsh) :: fludep,qdep,vitdepo,ddzs,ddzs1,ddzs2,dzsa,dzsisu,      &
                     poroa,somalp,somala,cdepiv,porosi,dzpoi,porodep,dts2
#if defined key_contaminant 
   INTEGER        :: ivr,ire,itypr
#endif
   !!
   !!----------------------------------------------------------------------
   !! * Executable part

    ddzs=0.0_rsh
    dts2=0.5_rsh*REAL(dt,rsh)

    DO j=ljmin,ljmax
    DO i=MAX0(limin,ig(j)),MIN0(limax,id(j))

      IF(h0(i,j)+xeloc(i,j).GT.h0fond) THEN

        ksmax=ksma(i,j)

        ! reactualisation du depot effectif (flx_w2s) car implicite

        DO iv=1,nvp
!FLOoct2009          flx_w2s(iv,i,j)=flx_w2s(iv,i,j)*cv_wat(iv,1,i,j)
!        flx_w2s_loc(iv)=flx_w2s(iv,i,j)*cv_wat(iv,1,i,j)
!      flx_w2s_loc(iv)=MAX(flx_w2s_loc(iv),0.0_rsh)
! modif bene pour prendre le depot integre sur les ndt_part pas de temps
!      deja calcule a chaque sous pas de temps en fonction des cv_wat intermediaire
!       et exprime en Masse/m2 integre sur le demi pas de temps
         flx_w2s_loc(iv)=MAX(flx_w2s_sum(iv,i,j),0.0_rsh)/dts2
         flx_w2s_sum(iv,i,j)=0.0_rsh
        ENDDO

        fludep=0.0_rsh
        DO iv=1,nvpc
!FLOoct2009          fludep=fludep+flx_w2s(iv,i,j)
          fludep=fludep+flx_w2s_loc(iv)
        ENDDO

      IF(fludep.GT.0.0_rsh)THEN
         ! cas ou il y a depot
         ! *******************
          qdep=fludep*dts2
          vitdepo=fludep/cfreshmud
          ddzs=dts2*vitdepo
          somalp=0.0_rsh
          DO iv=1,nvpc
!FLOoct2009            somalp=somalp+flx_w2s(iv,i,j)/(ros(iv)+epsilon)
            somalp=somalp+flx_w2s_loc(iv)/(ros(iv)+epsilon)
          ENDDO
          porodep=1.0_rsh-somalp/vitdepo
          epeaui(i,j)=ddzs*porodep
          !i.e. ddzs=qdep/cfreshmud
          IF(ksmax.LT.ksmi(i,j))THEN
            ddzs2=ddzs

          ELSE
            ! il existe deja une couche
            ! -------------------------
            ddzs1=MIN(dzsmax(i,j)-dzs(ksmax,i,j),ddzs)
            ddzs1=0.5_rsh*(ddzs1+ABS(ddzs1))
            IF(ksdmax.GT.1 .AND. c_sedtot(ksmax,i,j).GE.csmaxmel) ddzs1=0.0_rsh 
            ddzs2=ddzs-ddzs1
            IF(ddzs2.LE.dzsmin)THEN
              ddzs1=ddzs
              ddzs2=0.0_rsh
            ENDIF

            ! cas ou il n'y a qu'une couche : on remplit indefiniment
            ! -------------------------------------------------------
            IF(ddzs2>epsilon .AND. ksdmax==1) THEN
              ddzs1=ddzs
              ddzs2=0.0_rsh
            ENDIF
 

            ! melange avec la couche superieure
            ! ---------------------------------
            dzsa=dzs(ksmax,i,j)
            dzs(ksmax,i,j)=dzs(ksmax,i,j)+ddzs1
            dzsisu=1.0_rsh/dzs(ksmax,i,j)
            c_sedtot(ksmax,i,j)=(c_sedtot(ksmax,i,j)*dzsa+cfreshmud*ddzs1)*dzsisu
            poroa=poro(ksmax,i,j)
            somalp=0.0_rsh
            somala=0.0_rsh
            DO iv=1,nvp
              cdepiv=flx_w2s_loc(iv)/vitdepo
              cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*dzsa+cdepiv*ddzs1)*dzsisu
              somala=somala+cdepiv*typart(iv)/(ros(iv)+epsilon)
              somalp=somalp+cv_sed(iv,ksmax,i,j)*typart(iv)/(ros(iv)+epsilon)
            ENDDO
            porosi=1.0_rsh-somala
            poro(ksmax,i,j)=1.0_rsh-somalp
            dzpoi=dzsisu/poro(ksmax,i,j)
            cv_sed(-1,ksmax,i,j)=(cv_sed(-1,ksmax,i,j)*poroa*dzsa+temp(1,i,j)*porosi*ddzs1)*dzpoi
            cv_sed( 0,ksmax,i,j)=(cv_sed( 0,ksmax,i,j)*poroa*dzsa+sal(1,i,j)*porosi*ddzs1)*dzpoi
            DO iv=nvp+1,nv_adv
              cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax,i,j)*poroa*dzsa+cv_wat(iv,1,i,j)*porosi*ddzs1)*dzpoi
              ! attention, le puits dans l eau a pu etre different,   
              ! car flx_w2s calcule dt avant.
              !                 +flx_w2s(iv,i,j)/vitdepo*ddzs1)*dzpoi
              ! a condition que: flx_w2s(iv,i,j) en m/s =cv_wat*vitdepo*porosi
            ENDDO

          ENDIF

          ! poursuite du remplissage
          ! ------------------------ 

          niter=0
777       niter=niter+1
          IF(niter.GE.1000)THEN
            WRITE(*,778)t,i,j,ksmax,ddzs2,(flx_w2s_loc(iv),cv_wat(iv,1,i,j),iv=1,nvp)
778         FORMAT('a',f12.0,'s en i,j=',i3,1x,i3,' ksmax=',i3,' ddzs2=',g10.4,'flu+cv',8g9.3)
            STOP
          ENDIF

          IF(ddzs2.GT.0.0_rsh)THEN
            IF(ksmax.EQ.ksdmax)THEN

              ! cas ou on a atteint le nbre max de couches:
              ! fusion des 2 premieres couches (fond) et decalage des autres
              ! ------------------------------------------------------------
              ksmin=ksmi(i,j)
              dzsa=dzs(ksmin,i,j)
              poroa=poro(ksmin,i,j)
              dzs(ksmin,i,j)=dzs(ksmin,i,j)+dzs(ksmin+1,i,j)
              c_sedtot(ksmin,i,j)=0.0_rsh
              somalp=0.0_rsh
              DO iv=1,nvp
                cv_sed(iv,ksmin,i,j)=(cv_sed(iv,ksmin,i,j)*dzsa+cv_sed(iv,ksmin+1,i,j)*dzs(ksmin+1,i,j))/dzs(ksmin,i,j)
                c_sedtot(ksmin,i,j)=c_sedtot(ksmin,i,j)+cv_sed(iv,ksmin,i,j)*typart(iv)
                somalp=somalp+cv_sed(iv,ksmin,i,j)*typart(iv)/(ros(iv)+epsilon)
              ENDDO
              poro(ksmin,i,j)=1.0_rsh-somalp
              cv_sed(-1,ksmin,i,j)=(cv_sed(-1,ksmin,i,j)*dzsa*poroa                             &
                                   +cv_sed(-1,ksmin+1,i,j)*dzs(ksmin+1,i,j)*poro(ksmin+1,i,j))  &
                                  /(dzs(ksmin,i,j)*poro(ksmin,i,j))
              cv_sed( 0,ksmin,i,j)=(cv_sed( 0,ksmin,i,j)*dzsa*poroa                             &
                                   +cv_sed( 0,ksmin+1,i,j)*dzs(ksmin+1,i,j)*poro(ksmin+1,i,j))  &
                                  /(dzs(ksmin,i,j)*poro(ksmin,i,j))
              DO iv=nvp+1,nv_adv
                cv_sed(iv,ksmin,i,j)=(cv_sed(iv,ksmin,i,j)*dzsa*poroa                             &
                                     +cv_sed(iv,ksmin+1,i,j)*dzs(ksmin+1,i,j)*poro(ksmin+1,i,j))  &
                                    /(dzs(ksmin,i,j)*poro(ksmin,i,j))
              ENDDO

              DO k=ksmin+1,ksmax-1
                dzs(k,i,j)=dzs(k+1,i,j)
                c_sedtot(k,i,j)=c_sedtot(k+1,i,j)
                poro(k,i,j)=poro(k+1,i,j)
                !do iv=1,nvar
                DO iv=-1,nv_adv
                  cv_sed(iv,k,i,j)=cv_sed(iv,k+1,i,j)
                ENDDO
              ENDDO
              dzs(ksmax,i,j)=0.0_rsh
              DO iv=-1,nv_adv
                cv_sed(iv,ksmax,i,j)=-valmanq
              ENDDO

              ksmax=ksmax-1

            ENDIF

            ! creation d une nouvelle couche
            ! ------------------------------
            ksmax=ksmax+1
            dzs(ksmax,i,j)=MIN(dzsmax(i,j),ddzs2)
            ddzs2=ddzs2-dzs(ksmax,i,j)
            IF(ddzs2.LE.dzsmin)THEN
              dzs(ksmax,i,j)=ddzs2+dzs(ksmax,i,j)
              ddzs2=0.0_rsh
            ENDIF
    
            dzsisu=1.0_rsh/dzs(ksmax,i,j)
            c_sedtot(ksmax,i,j)=cfreshmud
            DO iv=1,nvp
              cv_sed(iv,ksmax,i,j)=flx_w2s_loc(iv)/vitdepo
            ENDDO
            poro(ksmax,i,j)=porodep

            cv_sed(-1,ksmax,i,j)=temp(1,i,j)
            cv_sed( 0,ksmax,i,j)=sal(1,i,j)
            DO iv=nvp+1,nv_adv
              cv_sed(iv,ksmax,i,j)=cv_wat(iv,1,i,j)
            ENDDO

            GOTO 777
          ENDIF

          ! calcul du flx_w2s des var. diss. pour le pas de temps suivant:
          flx_w2s(-1,i,j)=porodep*vitdepo
          flx_w2s( 0,i,j)=porodep*vitdepo
          DO iv=nvp+1,nv_adv
            !flx_w2s(iv,i,j)=fludep*porosi/cfreshmud
            !flx_w2s est une vitesse de chute virtuelle
            !commune a toutes les variables dissoutes : 
            flx_w2s(iv,i,j)=porodep*vitdepo
          ENDDO

        ELSE

          ! cas ou pas de depot
          ! *******************  
          ! calcul du flx_w2s des var. diss. pour le pas de temps suivant:
          flx_w2s(-1,i,j)=0.0_rsh
          flx_w2s( 0,i,j)=0.0_rsh
          !do iv=nvp+1,nvar
          DO iv=nvp+1,nv_adv
            flx_w2s(iv,i,j)=0.0_rsh
          ENDDO
          epeaui(i,j)=0.0_rsh

          ! prise en compte des depots eventuels 
          ! de variables particulaires non constitutives:
          !if(ksmax.ge.ksmi(i,j).and.dzs(ksmax,i,j).ge.dzsmin)then
          IF(ksmax.GE.1)THEN
            DO iv=nvpc+1,nvp
              cv_sed(iv,ksmax,i,j)=cv_sed(iv,ksmax,i,j)+flx_w2s_loc(iv)*dts2/dzs(ksmax,i,j)
            ENDDO
          ELSE
            DO iv=nvpc+1,nvp
#if defined key_siggen || defined key_gencoord
              cv_wat(iv,1,i,j)=cv_wat(iv,1,i,j) &
                               +flx_w2s_loc(iv)*dts2/(dsigu(1)*f_hzu(h0(i,j),xeloc(i,j),k,i,j))
#else
              cv_wat(iv,1,i,j)=cv_wat(iv,1,i,j) &
                               +flx_w2s_loc(iv)*dts2/(dsigu(1)*(xeloc(i,j)+h0(i,j)))
#endif
            ENDDO
          ENDIF

        ENDIF ! test on fludep

        ! reactualisation de ksma ( ksmax a pu etre modifie dans la routine)
        ksma(i,j)=ksmax

#ifdef key_contaminant
!      DO ire=1,nreacmax
!        itypr=ityp_reac(ire)
!        IF(itypr.EQ.1) THEN
!          iv=irkm_var_re(ire,1) 
!          IF (SUM(cv_sed(iv,:,i,j)).NE.0.) THEN  
!            DO k=ksdmin,ksma(i,j)
!              cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*(1+cf_stochio_re(ire,1)*cin_max_re(ire)*dts2)
!            ENDDO
!          ENDIF
!        ENDIF  
!      ENDDO
#endif

      ENDIF ! test on h0+xe

      END DO ! loop on i
    END DO ! loop on j

  END SUBROUTINE sed_effdep_mudsand

#endif
   !!==============================================================================
 
#ifdef key_sedim_mixsed

  SUBROUTINE sed_fusion(i,j,ksmaxhere)
 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_fusion  ***
   !&E
   !&E ** Purpose : makes fusion of the 2 first layers of the sediment (at the bottom)
   !&E              when the max. number of layers is reached
   !&E              and updating of the sediment column
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  sed_effdep
   !&E 
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-03 (P. Le Hir) reproduces s_fusion in new "Marennes-Oleron" sand/mud sediment model
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nv_adv,nvp,typart

   !! * Arguments
   INTEGER,INTENT(IN)     ::  i,j
   INTEGER,INTENT(INOUT)  ::  ksmaxhere

   !! * Local declarations
   INTEGER        ::  k,iv,ksmin
   REAL(KIND=rsh) ::  dzsa,poroa,cvolp,dzspwi               
   
   !!----------------------------------------------------------------------
   !! * Executable part
      
   ksmin=ksmi(i,j)
   dzsa=dzs(ksmin,i,j)
   poroa=poro(ksmin,i,j)
   dzs(ksmin,i,j)=dzs(ksmin,i,j)+dzs(ksmin+1,i,j)
   cvolp=0.0_rsh
   c_sedtot(ksmin,i,j)=0.0_rsh
   DO iv=1,nvp
     cv_sed(iv,ksmin,i,j)=(cv_sed(iv,ksmin,i,j)*dzsa+cv_sed(iv,ksmin+1,i,j)*dzs(ksmin+1,i,j))/dzs(ksmin,i,j)
     c_sedtot(ksmin,i,j)=c_sedtot(ksmin,i,j)+cv_sed(iv,ksmin,i,j)*typart(iv)
     cvolp=cvolp+cv_sed(iv,ksmin,i,j)*typart(iv)/ros(iv)
   ENDDO
   poro(ksmin,i,j)=1.0_rsh-cvolp
#if ! defined key_nodiss_insed
   dzspwi=1.0_rsh/(dzs(ksmin,i,j)*poro(ksmin,i,j))
   DO iv=-1,0
      cv_sed(iv,ksmin,i,j)=dzspwi*(cv_sed(iv,ksmin,i,j)*dzsa*poroa &
                                +cv_sed(iv,ksmin+1,i,j)*dzs(ksmin+1,i,j)*poro(ksmin+1,i,j))
   ENDDO
#if ! defined key_sedim_partial
   DO iv=nvp+1,nv_adv
      cv_sed(iv,ksmin,i,j)=dzspwi*(cv_sed(iv,ksmin,i,j)*dzsa*poroa &
                                +cv_sed(iv,ksmin+1,i,j)*dzs(ksmin+1,i,j)*poro(ksmin+1,i,j))
   ENDDO
#endif
#endif
   DO k=ksmin+1,ksmaxhere-1
     dzs(k,i,j)=dzs(k+1,i,j)
     poro(k,i,j)=poro(k+1,i,j)
     c_sedtot(k,i,j)=c_sedtot(k+1,i,j)
     DO iv=-1,nv_adv
       cv_sed(iv,k,i,j)=cv_sed(iv,k+1,i,j)
     ENDDO
   ENDDO
   ksmaxhere=ksmaxhere-1

  END SUBROUTINE sed_fusion
      
#endif
#ifdef key_sedim_mudsand
!!==============================================================================
   SUBROUTINE sed_consol_diffu_mudsand
! 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_consol_diffu (key_mudsand)***
   !&E
   !&E ** Purpose : call subroutines of consolidation and/or diffusion if needed
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  step
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2010-09  (B. Thouvenin) 
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
  
   USE comvars2d,    ONLY : h0,ig,id,h0fond,dt,nbouc,halfdt
   USE comvarp2d,    ONLY : ssh
   USE comvars2d,    ONLY : t
   USE comsubstance, ONLY : nvp,nv_adv

   !! * Local declarations
   LOGICAL                                   :: l_consol_now
   INTEGER                                   :: i,j,k,iv,celldry
   INTEGER                                   :: ksmin,ksmax,ksmaxa,kp,kl
   
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax) :: poroa
   REAL(KIND=rsh),DIMENSION(-1:nv_adv)       :: varpwa 
   REAL(KIND=rsh)                            :: volpwa
   REAL(KIND=rsh),DIMENSION(ksdmin-1:ksdmax) :: winter
   REAL(KIND=rsh),DIMENSION(ksdmin:ksdmax)   :: poroin,dzsiin
   REAL(KIND=rsh)                            :: dtdiffuinv,dt_sedcor,dt_sedeff,dt_sedinv


   !!----------------------------------------------------------------------
   !! * Executable part
   
   poroin(ksdmin:ksdmax)=0.0_rsh
   l_consol_now=.false.
   IF (l_consolid) THEN
     IF(.NOT.l_diffused .AND. .NOT. l_bioturb) THEN
      IF(t.GE.tstart_sed .AND. t.GE.t_sed) then
         ! consolidation only : time step=dt_sed
        dt_sedcor=MAX(dt_sed,halfdt)
        dt_sedeff=dt_sedcor+(t-t_sed)
        t_sed=t+dt_sedcor
        dt_sedinv=1.0_rsh/REAL(dt_sedeff,rsh)
        l_consol_now=.true.
      ENDIF
     ELSE
         ! consolidation and diffusion also : time step=halfdt (because of dissolved fluxes must have same time step as consolidation)
      dtdiffuinv=1.00_rsh/REAL(halfdt,rsh)
      dt_sedeff=halfdt
      dt_sedinv=dtdiffuinv
      l_consol_now=.true.
     ENDIF
   ELSE IF (l_diffused) THEN
   ! diffusion all halfdt
      dtdiffuinv=1.00_rsh/REAL(halfdt,rsh)
   END IF
   PRINT_DBG*, 'DEBUT DE DIF et CONSOL '

!!!!$OMP PARALLEL DEFAULT(NONE) SHARED(ljminp1,ljmax,limin,limax,ig,id,h0,ssh,ksma,ksmi,poro         &
!!!!$OMP&  ,dzs,nvp,nv_adv,cv_sed,l_consol_now,l_diffused,l_consolid,tstart_sed,t,t_sed,dt_sedeff &
!!!!$OMP&  ,dt_sed,dt_sedinv,h0fond,dtdiffuinv,l_bioturb) &
!!!!$OMP& PRIVATE(i,j,k,poroa,volpwa,varpwa,winter,poroin,dzsiin)

   varpwa(-1:nv_adv)=0.0_rsh
   
!!!!$OMP DO SCHEDULE(RUNTIME)
   DO j=ljminp1,ljmaxm1
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)

        IF (ksma(i,j).GE.ksmi(i,j))THEN
           celldry=0
           IF(h0(i,j)+ssh(i,j) .LE. h0fond)celldry=1
           
           ! memorisation des porosites, du volume d eau interstitielle
           ! et de l epaisseur de la couche de surface
           ! ----------------------------------------------------------
           DO k=ksmi(i,j),ksma(i,j)
             poroa(k)=poro(k,i,j)
           END DO
           volpwa=poro(ksma(i,j),i,j)*dzs(ksma(i,j),i,j)
           varpwa(-1)=volpwa*cv_sed(-1,ksma(i,j),i,j)
           varpwa( 0)=volpwa*cv_sed( 0,ksma(i,j),i,j)
           DO iv=nvp+1,nv_adv
             varpwa(iv)=volpwa*cv_sed(iv,ksma(i,j),i,j)
           END DO

           poroin(ksma(i,j))=poro(ksma(i,j),i,j)
           DO k=ksmi(i,j),ksma(i,j)-1
            dzsiin(k)=2.0_rsh/(dzs(k,i,j)+dzs(k+1,i,j))
            poroin(k)=0.5_rsh*(poro(k+1,i,j)+poro(k,i,j))        
           ENDDO

           winter(:)=0.0_rsh          
           
           IF (l_consol_now) THEN  

             CALL sed_consolid_mudsand(i,j,volpwa,varpwa,poroa,poroin,winter,dzsiin,dt_sedeff,dt_sedinv)
             poroin(ksma(i,j))=poro(ksma(i,j),i,j)
             DO k=ksmi(i,j),ksma(i,j)-1
              dzsiin(k)=2.0_rsh/(dzs(k,i,j)+dzs(k+1,i,j))
              poroin(k)=0.5_rsh*(poro(k+1,i,j)+poro(k,i,j))          
             ENDDO
             IF(l_diffused) CALL sed_diffusion_mudsand(i,j,poroa,poroin,dtdiffuinv,dzsiin,winter,varpwa)
           ELSE
             IF(l_diffused) CALL sed_diffusion_mudsand(i,j,poroa,poroin,dtdiffuinv,dzsiin,winter,varpwa)
           ENDIF

        END IF
    
      END DO
     END DO
!!!!!$OMP END DO

!!!!!$OMP END PARALLEL
        
  END SUBROUTINE sed_consol_diffu_mudsand
#endif
   !!==============================================================================


#ifdef key_sedim_mixsed
!!==============================================================================
   SUBROUTINE sed_consol_diff_bioturb
! 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_consol_diff_bioturb ***
   !&E
   !&E ** Purpose : dynamic in sediment : processes of consolidation 
   !&E                   and/or diffusion and/or bioturbation
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  step
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (P. Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       !  2009-02  (P. Le Hir) new version from SiAM "sable-vase"
   !&E       !  2014-05  (F. Grasso) modifications based on "Grasso et al. (Ocean Dynynamics, 2015)"
   !&E       !  2015-07  (F. Grasso, P. Le Hir)  rewriting             
   !&E       !  2017-03  (B.Thouvenin) fusion of consolidation and diffusion for module mixsed and corrections for dissolved subst

   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
  
   USE comvars2d,    ONLY : h0,ig,id,h0fond,dt,nbouc,halfdt,t,surf,hm
   USE comvarp2d,    ONLY : ssh,sal,temp
   USE comsubstance, ONLY : typart,nvpc,nvp,nv_adv,isand1,isand2,imud1,imud2,igrav1,igrav2,cv_wat
   USE parameters,   ONLY : valmanq,epsilon
   USE comvars3d,    ONLY : rhoref,saliref_lin,tetaref_lin,l_stateeq_lin
   USE toolgeom,    ONLY : f_dzu
   USE comvars3d,   ONLY : roswat_bot

   !! * Local declarations
   INTEGER                                   :: i,j,k,iv,celldry,nv_use
   INTEGER                                   :: ksmin,ksmax,ksmaxa,kp,kl
   REAL(KIND=rsh)                            :: volpwa_tot,volpwnv_tot,volpwk,roro,dt_sed_inv,dtsdzs,   &
                                                sigmadjge,somdeltaro,halfmaslayer,somcsan,somcgrav,   &
                                                somcmud,cvolp,rapcsed,csednew,poroam1,poroa,     &
                                                dzsa,dzsam1,dzsisu,rowinv,dtsdzsmin,  &
                                                volak,volakm1,vola,vola_inv
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax) :: volpwak,stateconsol,permeab,sigmapsg,  &
                                                poroin,dzsiin,loadograv,sed_rate,hinder,cseda
   REAL(KIND=rsh),DIMENSION(ksdmin-1:ksdmax) :: winter                                                    
   REAL(KIND=rsh)                            :: dt_sed_cor,dtrest,dtiter,dt_sed_eff   
   REAL(KIND=rsh),DIMENSION(nvp,ksdmin:ksdmax)            :: cvsednew
   REAL(KIND=rsh),DIMENSION(ksdmin:ksdmax,-1:nv_adv)      :: difbio

#if ! defined key_nodiss_insed
   !REAL(KIND=rsh),DIMENSION(-1:nv_adv)                    :: flu_fusion              
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax)              :: disvi,aa,bb,cc,dd
   REAL(KIND=rsh)                                         :: hcrit,dzssdt,epn_bottom
#endif

   !!----------------------------------------------------------------------
   !! * Executable part

#if ! defined key_sedim_partial
   nv_use=nv_adv
#else
   nv_use=0
#endif
   IF(t.GE.tstart_sed .AND. t.GE.t_sed) THEN
      
      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      !!!!! DYNAMIQUE INTERNE DANS LE SEDIMENT    !!!!!!
      !!!!  COSOLIDATION/BIOTURBATION/DIFFUSION   !!!!!!
      !!!!  MISE A JOUR TOUS LES dt_sed     !!!!!!
      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

     dt_sed_cor=MAX(dt_sed,halfdt)
     dt_sed_eff=dt_sed_cor+(t-t_sed)
     dt_sed_inv=1.0_rsh/REAL(dt_sed_eff,rsh)
     phieau_s2w_consol(:,:)=0.0_rsh

     PRINT_DBG*, 'DEBUT DE DIFFUSION et CONSOL et Bioturb '

!$OMP PARALLEL DEFAULT(NONE) SHARED(ljminp1,ljmaxm1,limin,limax,ig,id,h0,ssh,ksma,ksmi         &
!$OMP&  ,poro,dzs,nvp,nvpc,cv_sed,l_diffused,l_consolid,dt_sed_eff,dt_sed_inv,hm    &
!$OMP&  ,h0fond,l_bioturb,nv_use, saliref_lin,tetaref_lin,rhoref,phieau_s2w  &
!$OMP&  ,phieau_s2w_consol,c_sedtot,dtcal_sed,rosmrowsros,igrav1,igrav2   &
!$OMP&  ,isand1,isand2,imud1,imud2,csegreg,csandseg,ws_sand,ros,cvolmaxmel  &
!$OMP&  ,typart,csedmin,dzsmin,surf,choice_flxdiss_diffsed,xdifsi1,xdifs1,epdifi &
!$OMP&  ,cexcs,fludif,temp,sal,cv_wat,flu_dyninsed,phieau_s2w_drycell,halfdt  &
!$OMP&  ,fluconsol,fluconsol_drycell,ustarbot,fexcs,roswat_bot,l_stateeq_lin) &

!$OMP& PRIVATE(i,j,k,kp,volpwak,winter,poroin,dzsiin,difbio,celldry,volpwa_tot  &
!$OMP&  ,ksmax,ksmin,rowinv,sed_rate,hinder,volak,volakm1,dtrest,cseda,csednew   &
#if ! defined key_nodiss_insed
!$OMP&  ,hcrit,dzssdt,epn_bottom,disvi,aa,bb,cc,dd    &
#endif
!$OMP&  ,dtiter,sigmadjge,somdeltaro,halfmaslayer,loadograv,sigmapsg,permeab,stateconsol  &
!$OMP&  ,somcgrav,dtsdzs,cvsednew,cvolp,rapcsed,dzsa,ksmaxa,dzsam1,poroam1,poroa,dzsisu  &
!$OMP&  ,vola,vola_inv,volpwnv_tot,volpwk,somcsan,somcmud,roro )

   
 

!$OMP DO SCHEDULE(RUNTIME)
     DO j=ljminp1,ljmaxm1
      DO i=MAX0(limin,ig(j)+1),MIN0(limax,id(j)-1)

       difbio(ksdmin:ksdmax,:)=0.0_rsh
       poroin(ksdmin:ksdmax)=0.0_rsh
       volpwak(:)=0.0_rsh

       IF (ksma(i,j).GE.ksmi(i,j))THEN
         celldry=0
         IF(h0(i,j)+ssh(i,j) .LE. h0fond)celldry=1
           
         ! memorisation des porosites, du volume d eau interstitielle
         !  des masses de substances dissoutes
         ! et de l epaisseur de la couche de surface
         ! ----------------------------------------------------------
         volpwak(ksma(i,j))=poro(ksma(i,j),i,j)*dzs(ksma(i,j),i,j)
         volpwa_tot=volpwak(ksma(i,j))
         poroin(ksma(i,j))=poro(ksma(i,j),i,j)
         DO k=ksmi(i,j),ksma(i,j)-1
            dzsiin(k)=2.0_rsh/(dzs(k,i,j)+dzs(k+1,i,j))
            poroin(k)=0.5_rsh*(poro(k+1,i,j)+poro(k,i,j))
            volpwak(k)=poro(k,i,j)*dzs(k,i,j)
            volpwa_tot=volpwa_tot+volpwak(k)
         ENDDO

         winter(:)=0.0_rsh
                      
         ksmax=ksma(i,j)
         ksmin=ksmi(i,j)

     !!! calcul de la densite de l eau 
         ! densite de l eau interstitielle
         ! on la suppose egale a la densite de l eau au fond de la colonne d eau
         ! dans MARS celle ci n est calcule que si htot>hm (3D) par tsstateeqblumberg si l_stateeq_lin=F
         !                        tout le temps par tsstateeqlinear si l_stateeq_lin=T
         ! si il n y a pas d eau la salinite et temperature ne sont pas connus
         ! si defined key_nodiss_insed, temp et sal ne sont pas calcules dans le sediment 
         !  et sont faux (=valmanq) dans les nouvelles couches
         IF(celldry ==1) THEN
         ! pas d eau
         !  densite a partir de la maille du fond ou de surface de sediment
#ifdef key_nodiss_insed
           roro=(rhoref*(1.0_rsh+0.0008_rsh*(cv_sed(0,1,i,j)-saliref_lin)  &
                                       -0.00016_rsh*(cv_sed(-1,1,i,j)-tetaref_lin)))
#else
           roro=(rhoref*(1.0_rsh+0.0008_rsh*(cv_sed(0,ksmax,i,j)-saliref_lin)  &
                                       -0.00016_rsh*(cv_sed(-1,ksmax,i,j)-tetaref_lin)))
#endif
         ELSE
           IF(l_stateeq_lin) THEN
               roro=(rhoref*(1.0_rsh+0.0008_rsh*(sal(1,i,j)-saliref_lin)  &
                                       -0.00016_rsh*(temp(1,i,j)-tetaref_lin)))
               !roro=REAL(roswat_bot(i,j),rsh)
           ELSE
              IF(h0(i,j)+ssh(i,j) < hm) THEN
               ! roswat_bot non connu
                roro=(rhoref*(1.0_rsh+0.0008_rsh*(sal(1,i,j)-saliref_lin)  &
                                         -0.00016_rsh*(temp(1,i,j)-tetaref_lin)))
              ELSE
                roro=REAL(roswat_bot(i,j),rsh)
              ENDIF
           ENDIF
         ENDIF
         rowinv=1.0_rsh/roro


         sed_rate(ksdmin:ksdmax)=0.0_rsh
         hinder(ksdmin:ksdmax)=0.0_rsh
         !dvol=0.0_rsh
         !dvol_fusion=0.0_rsh
         volak=0.0_rsh
         volakm1=0.0_rsh
#if ! defined key_nodiss_insed
  !       flu_fusion(:)=0.0_rsh
#endif
         
         dtrest=REAL(dt_sed_eff,rsh)

  100    CONTINUE
              
         cseda(:)=0.0_rsh     
         DO k=ksmin,ksmax
              cseda(k)=c_sedtot(k,i,j)
         ENDDO
           
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         !!!!!!!!!!!  CONSOLIDATION   !!!!!!!!!!!!!!!!!!!!!!!!!!
         !!!!!  seulement si plus d une couche   !!!!!!!!!!!!!!!
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         dtiter=MIN(dtrest,dtcal_sed)

         IF(l_consolid .AND. ksma(i,j) > ksmi(i,j)) THEN
             
          ! computation of permeability, effective stress and hydraulic load
          ! ----------------------------------------------------------------
           CALL sed_constitutivrel(i,j,stateconsol,permeab,sigmapsg)        

           sigmadjge=0.0_rsh
           DO k=ksmax,ksmin,-1
              somdeltaro=0.0_rsh
              DO iv=1,nvpc
              ! rosmrowsros=(ros-row)/ros
                somdeltaro=somdeltaro+cv_sed(iv,k,i,j)*rosmrowsros(iv)
              ENDDO
              halfmaslayer=.5*dzs(k,i,j)*somdeltaro
              sigmadjge=sigmadjge+halfmaslayer
              ! loadograv : exces de pression d eau interstitielle au milieu de la couche
              ! sigmadjge : sigma dejauge (sans la part de l eau)
              ! sigmapsg : contrainte effective (transmise de grains a grains)
              loadograv(k)=MAX(0.0_rsh,sigmadjge-sigmapsg(k))
              ! poids total de toutes les couches au dessus de la couche k
              sigmadjge=sigmadjge+halfmaslayer
           ENDDO
          
           ! computing new concentrations from mass conservation
           !  only particulate variables are modified during consolidation
           ! ---------------------------------------------------       
           k=ksmin
           !sed_rate : vitesse d advection des particules de vase
           ! loi de Darcy
           ! stateconsol : indicateur d etat de la consolidation
           sed_rate(k)=-rowinv*(permeab(k+1)+permeab(k))                                 &
                *MIN(0.0_rsh,loadograv(k+1)-loadograv(k))*stateconsol(k)         &
                /(dzs(k+1,i,j)+dzs(k,i,j))
           somcgrav=0.0_rsh
           DO iv=igrav1,igrav2
              somcgrav=somcgrav+cv_sed(iv,k,i,j)
           ENDDO
           somcsan=0.0_rsh
           DO iv=isand1,isand2
              somcsan=somcsan+cv_sed(iv,k,i,j)
           ENDDO
           somcmud=0.0_rsh
           DO iv=imud1,imud2
             somcmud=somcmud+cv_sed(iv,k,i,j)
           ENDDO
           !hinder : entravement du sable/gravier (sans dimension) entre 0 et 1
           ! ATTENTION : hypothese de ros homogene quelque soit le type de sediment
           ! entrave par le trop de vase qui empeche la segregation sable/vase (1er terme)
           ! entrave par le trop de sablequi ne permet pas le passage entre les grains (2ieme terme)
           hinder(k)=(MAX(0.0_rsh,MIN(1.0_rsh-somcmud/(1-(somcsan+somcgrav)/ros(1))/csegreg,   &
                   1.0_rsh-(somcsan+somcgrav)/csandseg)))**4.65_rsh
                   
           DO k=ksmin+1,ksmax-1

              sed_rate(k)=-rowinv*(permeab(k+1)+permeab(k))                               &
                  *MIN(0.0_rsh,loadograv(k+1)-loadograv(k))*stateconsol(k)       &
                  /(dzs(k+1,i,j)+dzs(k,i,j))
              somcgrav=0.0_rsh
              DO iv=igrav1,igrav2
                somcgrav=somcgrav+cv_sed(iv,k,i,j)
              ENDDO
              somcsan=0.0_rsh
              DO iv=isand1,isand2
                somcsan=somcsan+cv_sed(iv,k,i,j)
              ENDDO
              somcmud=0.0_rsh
              DO iv=imud1,imud2
                somcmud=somcmud+cv_sed(iv,k,i,j)
              ENDDO
              hinder(k)=(MAX(0.0_rsh,MIN(1.0_rsh-somcmud/(1-(somcsan+somcgrav)/ros(1))/csegreg,   &
                   1.0_rsh-(somcsan+somcgrav)/csandseg)))**4.65_rsh
           ENDDO
        
           k=ksmax
           dtsdzs=dtiter/dzs(k,i,j)
           !schema implicite decentre amont -cv_sed(k+1) connu juste avant donc implicite
           DO iv=igrav1,isand2
              cv_sed(iv,ksmax,i,j)=cv_sed(iv,ksmax,i,j)                               &
                                 /(1.0_rsh+dtsdzs*MAX(sed_rate(ksmax-1),hinder(ksmax-1)*ws_sand(iv)))
           ENDDO
           DO iv=imud1,nvp
              cv_sed(iv,ksmax,i,j)=cv_sed(iv,ksmax,i,j)/(1.0_rsh+dtsdzs*sed_rate(ksmax-1))
           ENDDO
           DO k=ksmax-1,ksmin+1,-1
              dtsdzs=dtiter/dzs(k,i,j)
              DO iv=igrav1,isand2
                cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)+dtsdzs*MAX(sed_rate(k),ws_sand(iv)*               &
                               hinder(k))*cv_sed(iv,k+1,i,j))                        &
                               /(1.0_rsh+dtsdzs*MAX(sed_rate(k-1),hinder(k-1)*ws_sand(iv)))
              ENDDO
              DO iv=imud1,nvp
                cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)+dtsdzs*sed_rate(k)*cv_sed(iv,k+1,i,j))/(1.0_rsh+dtsdzs*sed_rate(k-1))
              ENDDO
           ENDDO
           k=ksmin
           dtsdzs=dtiter/dzs(k,i,j)
           DO iv=igrav1,isand2
              cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)+dtsdzs*MAX(sed_rate(k),ws_sand(iv)*hinder(k))*cv_sed(iv,k+1,i,j))
           ENDDO
           DO iv=imud1,nvp
              cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)+dtsdzs*sed_rate(k)*cv_sed(iv,k+1,i,j))
           ENDDO
          
         ELSE
            dtiter=dtrest
         ENDIF 
         ! end of l_consolid

         
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         !!!!!!!!!!!  BIOTURBATION PARTICULAIRE    !!!!!!!!!!!!!
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                                      
!  bioturbation particulaire A REVOIR pas de modification des dzs mais des cv_sed
#ifdef key_toseelater_bioturb
          ! schema explicite par pas fractionnaire pour la diffusion : bioturbation par melange diffusif
         IF(l_bioturb) THEN
         
            ! calcul du coef de biodiffusion a reactualiser si nombre de couches a change pendant diter
            CALL sed_coefbioturb(i,j,difbio) ! A REprogrammer pour differencier particulaires et dissoutes

            k=ksmax
            dtsdzs=dtiter/dzs(k,i,j)
            dtsdzsmin=dtiter/MIN(dzs(k,i,j),dzs(k-1,i,j))
            IF(dtsdzsmin>0.5_rsh*dzs(k,i,j)/(difbio(k-1,imud1)+1.e-10_rsh) .AND. difbio(k-1,imud1) > 1.e-13) THEN
            ! melange instantane
              DO iv=isand1,nvp
                cv_sed(iv,k,i,j)= (cv_sed(iv,k,i,j)*dzs(k,i,j)+cv_sed(iv,k-1,i,j)*dzs(k-1,i,j)) &
                                   /(dzs(k,i,j)+dzs(k-1,i,j))
                cv_sed(iv,k-1,i,j)= cv_sed(iv,k,i,j) 
                cvsednew(iv,k)= cv_sed(iv,k,i,j)                                                     
              ENDDO
            ELSE
              DO iv=isand1,nvp
                cvsednew(iv,k)= cv_sed(iv,k,i,j) + &
                                dtsdzs*difbio(k-1,iv)*dzsiin(k-1)*(cv_sed(iv,k-1,i,j)-cv_sed(iv,k,i,j))                                     
              ENDDO
            ENDIF
            DO k=ksmax-1,ksmin+1,-1
              dtsdzs=dtiter/dzs(k,i,j)
              dtsdzsmin=dtiter/MIN(dzs(k,i,j),dzs(k-1,i,j),dzs(k+1,i,j))
              IF(dtsdzsmin>0.5_rsh*dzs(k,i,j)/(difbio(k,imud1)+1.e-10_rsh).AND. difbio(k,imud1) > 1.e-13) THEN
               ! melange instantane
               DO iv=isand1,nvp
                  cv_sed(iv,k,i,j)= (cv_sed(iv,k,i,j)*dzs(k,i,j)+cv_sed(iv,k-1,i,j)*dzs(k-1,i,j)+ &
                          cv_sed(iv,k+1,i,j)*dzs(k+1,i,j))/(dzs(k,i,j)+dzs(k-1,i,j)+dzs(k+1,i,j))
                  cv_sed(iv,k-1,i,j)= cv_sed(iv,k,i,j) 
                  cv_sed(iv,k+1,i,j)= cv_sed(iv,k,i,j) 
                  cvsednew(iv,k)= cv_sed(iv,k,i,j)                                                     
                ENDDO
              ELSE
                DO iv=isand1,nvp
                  cvsednew(iv,k)= cv_sed(iv,k,i,j) + dtsdzs*(   &
                                difbio(k,iv)*dzsiin(k)*cv_sed(iv,k+1,i,j)  &
                              -(difbio(k,iv)*dzsiin(k)+difbio(k-1,iv)*dzsiin(k-1))*cv_sed(iv,k,i,j) &
                              + difbio(k-1,iv)*dzsiin(k-1)*cv_sed(iv,k-1,i,j))                                     
                ENDDO              
              ENDIF
            ENDDO              
            k=ksmin
            dtsdzs=dtiter/dzs(k,i,j)    
            dtsdzsmin=dtiter/MIN(dzs(k,i,j),dzs(k+1,i,j))
            IF(dtsdzsmin>0.5_rsh*dzs(k,i,j)/(difbio(k,imud1)+1.e-10_rsh).AND. difbio(k,imud1) > 1.e-13) THEN
            ! melange instantane
              DO iv=isand1,nvp
                cv_sed(iv,k,i,j)= (cv_sed(iv,k,i,j)*dzs(k,i,j)+cv_sed(iv,k+1,i,j)*dzs(k+1,i,j))&
                                   /(dzs(k,i,j)+dzs(k+1,i,j))
                cv_sed(iv,k+1,i,j)= cv_sed(iv,k,i,j) 
                cvsednew(iv,k)= cv_sed(iv,k,i,j)                                                     
              ENDDO
            ELSE
              DO iv=isand1,nvp
               cvsednew(iv,k)= cv_sed(iv,k,i,j) + &
                                dtsdzs*difbio(k,iv)*dzsiin(k)*(cv_sed(iv,k+1,i,j)-cv_sed(iv,k,i,j))                                     
              ENDDO              
            ENDIF
            DO k=ksmin,ksmax
              cv_sed(isand1:nvp,k,i,j)=cvsednew(isand1:nvp,k)
            ENDDO              
         ENDIF   
          ! end of l_bioturb
#endif

          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          !!!!!!!!!!!  MISE A JOUR DES CONCENTRATIONS PARTICULAIRES   !!!!!!!!!!!
          !!!!!!!!!!!       APRES CONSOLIDATION ET BIOTURBATION       !!!!!!!!!!!
          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

#ifdef key_toseelater_bioturb
        IF(l_consolid .OR. l_bioturb) THEN
#else
        IF(l_consolid) THEN
#endif
         ! computing new concentrations/porosities :
         DO k=ksmin,ksmax
            c_sedtot(k,i,j)=0.0_rsh
            cvolp=0.0_rsh
            DO iv=1,nvpc
              c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
              cvolp=cvolp+cv_sed(iv,k,i,j)/ros(iv)
            ENDDO
            poro(k,i,j)=1.0_rsh-cvolp
            
            ! if(porosity too small (<32%), it is increased until (1.0_rsh-cvolmaxmel):
            IF(poro(k,i,j).LT.1.0_rsh-cvolmaxmel-0.01_rsh)THEN
              poro(k,i,j)=1.0_rsh-cvolmaxmel
            !!! ATTENTION : on suppose ros identique quelque soit les particules
              csednew=ros(1)*cvolmaxmel
              rapcsed=csednew/c_sedtot(k,i,j)
              DO iv=1,nvp
                cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*rapcsed
              ENDDO
              c_sedtot(k,i,j)=csednew
              dzs(k,i,j)=dzs(k,i,j)/rapcsed
            ENDIF 
            
         ENDDO
        
         ! again calcul pour ksmax car on fait varier dzs dans la couche de surface
         !  on a perdu de la matiere mais c_sedtot reste constant => dzs change
         k=ksmax
         dzsa=dzs(k,i,j)
         dzs(k,i,j)=c_sedtot(k,i,j)*dzsa/cseda(k)
         cvolp=0.0_rsh
         c_sedtot(k,i,j)=0.0_rsh
         DO iv=1,nvp
            cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*dzsa/dzs(k,i,j)
            c_sedtot(k,i,j)=c_sedtot(k,i,j)+typart(iv)*cv_sed(iv,k,i,j)
            cvolp=cvolp+typart(iv)*cv_sed(iv,k,i,j)/ros(iv)
         ENDDO
         ! dans l hypothese ou ros est homogene quelque soit le type de sediment, 
         !  poro devrait rester inchange aussi
         poro(k,i,j)=1.0_rsh-cvolp
          
         ! mis en commentaire car inutile
         ! if(porosity too small (<32%), it is increased until (1.0_rsh-cvolmaxmel):
         !IF(poro(k,i,j) < 1.0_rsh-cvolmaxmel-0.01_rsh)THEN
         !   poro(k,i,j)=1.0_rsh-cvolmaxmel
         !   !!! ATTENTION : on suppose ros identique quelque soit les particules
         !   csednew=ros(1)*cvolmaxmel
         !   rapcsed=csednew/c_sedtot(k,i,j)
         !   DO iv=1,nvp
         !     cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*rapcsed
         !   ENDDO
         !   c_sedtot(k,i,j)=csednew
         !   dzs(k,i,j)=dzs(k,i,j)/rapcsed
         !ENDIF 
 
         ksmaxa=ksmax
         DO k=ksmaxa,ksmin+1,-1
                   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                   !!!  FUSION DE 2 COUCHES SI TROP FINE OU TROP DE PEU DE MATIERE   !!!!!
                   !!! (HYP : csed_tot de la couche de dessous inchange)             !!!!!
                   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            IF(c_sedtot(k,i,j) .LE. csedmin .OR. dzs(k,i,j) .LE. dzsmin)THEN

               ! etat de la couche avant fusion
              dzsa=dzs(k,i,j)
              dzsam1=dzs(k-1,i,j)
              poroam1=poro(k-1,i,j)
              poroa=poro(k,i,j)
              
              ! csed_tot(k-1 Cste : l epaisseur de la couche k-1 n est donc pas la somme des deux epaisseurs.
              !dzs(k-1,i,j)=(dzsam1*c_sedtot(k-1,i,j)+c_sedtot(k,i,j)*dzsa)   &
              !             /c_sedtot(k-1,i,j)
              !dzsisu=1.0_rsh/dzs(k-1,i,j)
              
              ! autre hypothese pour conserver eau
              dzs(k-1,i,j)=dzsam1+dzsa
              dzsisu=1.0_rsh/dzs(k-1,i,j)
              c_sedtot(k-1,i,j)=0.0_rsh
              cvolp=0.0_rsh
              DO iv=1,nvp
                cv_sed(iv,k-1,i,j)=(cv_sed(iv,k,i,j)*dzsa+                           &
                                cv_sed(iv,k-1,i,j)*dzsam1)*dzsisu
                ! calcul a priori inutile car c_sedtot ne doit pas changer
                c_sedtot(k-1,i,j)=c_sedtot(k-1,i,j)+cv_sed(iv,k-1,i,j)*typart(iv)
                cvolp=cvolp+cv_sed(iv,k-1,i,j)*typart(iv)/ros(iv)
              ENDDO
              poro(k-1,i,j)=1.0_rsh-cvolp
              
              ! mis en commentaire car inutile
              ! if(porosity too small (<32%), it is increased until (1.0_rsh-cvolmaxmel):
              !IF(poro(k-1,i,j) < 1.0_rsh-cvolmaxmel-0.01_rsh)THEN
              !  poro(k-1,i,j)=1.0_rsh-cvolmaxmel
            !!!! ATTENTION : on suppose ros identique quelque soit les particules
              !  csednew=ros(1)*cvolmaxmel
              !  rapcsed=csednew/c_sedtot(k-1,i,j)
              !  DO iv=1,nvp
              !    cv_sed(iv,k-1,i,j)=cv_sed(iv,k-1,i,j)*rapcsed
              !  ENDDO
              !  c_sedtot(k-1,i,j)=csednew
              !  dzs(k-1,i,j)=dzs(k-1,i,j)/rapcsed
              !ENDIF   
             
             ! calcul des flux d eau et de matiere dissoute dus a la fusion des deux couches
             ! dvol_fusion  en m3/m2; 
              volak=poroa*dzsa
              volakm1=poroam1*dzsam1
              vola=volak+volakm1
              !dvol=vola-poro(k-1,i,j)*dzs(k-1,i,j)
              !dvol_fusion=dvol +dvol_fusion            

#if ! defined key_nodiss_insed
              ! calcul des nouvelles concentrations de variables dissoutes dans l eau interstitielle
              vola_inv=1._rsh/vola

              DO iv=-1,0
                cv_sed(iv,k-1,i,j)=vola_inv*(cv_sed(iv,k-1,i,j)*volakm1 + &
                                   cv_sed(iv,k,i,j)*volak)
                !flu_fusion(iv)=flu_fusion(iv)+cv_sed(iv,k-1,i,j)*dvol
              ENDDO
#if ! defined key_sedim_partial
              DO iv=nvp+1,nv_use
                cv_sed(iv,k-1,i,j)=vola_inv*(cv_sed(iv,k-1,i,j)*volakm1 + &
                                   cv_sed(iv,k,i,j)*volak)
                !flu_fusion(iv)=flu_fusion(iv)+cv_sed(iv,k-1,i,j)*dvol
              ENDDO
#endif
#endif
              volpwak(k-1)=volpwak(k-1)+volpwak(k)

              DO kp=k,ksmax-1
                dzs(kp,i,j)=dzs(kp+1,i,j)
                volpwak(kp)=volpwak(kp+1)
                DO iv=-1,nv_use
                  cv_sed(iv,kp,i,j)=cv_sed(iv,kp+1,i,j)
                ENDDO
                c_sedtot(kp,i,j)=c_sedtot(kp+1,i,j)
                poro(kp,i,j)=poro(kp+1,i,j)
              ENDDO
              dzs(ksmax:ksdmax,i,j)=0.0_rsh
              c_sedtot(ksmax:ksdmax,i,j)=-valmanq
              cv_sed(-1:nv_use,ksmax:ksdmax,i,j)=-valmanq
              poro(ksmax:ksdmax,i,j)=0.0_rsh
              ksmax=ksmax-1
            ENDIF  
            ! fin fusion

         ENDDO        
             
         ! updating ksma (ksmax can be modified in the routine)
         ksma(i,j)=ksmax
 
         ! plusieurs pas possibles de consolidation 
         dtrest=dtrest-dtiter
         IF(dtrest.GE.1.0_rsh)GOTO 100

         ! Exchange flux at the water/sediment interface
         ! and intertitial water vertical rates
         ! ---------------------------------------------
         !  fluconsol is flux resulting from consolidation, >0 upwards, centree a l interface superieure
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
         !!!! interstitial water vertical rates  : winter (m3/m2/s) k :between k and k+1
         !!!!flux total de substance dissoute due à la fusion : M/m2/s
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
         winter(ksmin-1)=0.0_rsh
         volpwnv_tot=0.0_rsh
          DO k=ksmin,ksmax
           volpwk=poro(k,i,j)*dzs(k,i,j)
           volpwnv_tot=volpwnv_tot+volpwk
           winter(k)=winter(k-1)+(volpwak(k)-volpwk)*dt_sed_inv
          ENDDO
 
         
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
         !!!! water fluxes between water and sediment due to consolidation and fusion (m3/s)
         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
        ! rajout du volume d eau perdu par fusion des couches pendant le tassement
        ! probleme de conservativite de l eau
         !phieau_s2w_consol(i,j)=(winter(ksmax)+dvol_fusion*dt_sed_inv)*surf(i,j)

         !ou mieux 
         phieau_s2w_consol(i,j)=(volpwa_tot-volpwnv_tot)*surf(i,j)
               
          !  flu_dyninsed est le flux par tassement a l interface, >0 vers le haut (M/m2/s)
          ! auquel on rajoute le flux de substance perdu par fusion pendant le tassement            
         flu_dyninsed(-1,i,j)=winter(ksmax)*cv_sed(-1,ksmax,i,j)*REAL(dt_sed_eff,rsh)!  &
         flu_dyninsed(0,i,j)=winter(ksmax)*cv_sed(0,ksmax,i,j)*REAL(dt_sed_eff,rsh) ! &
         flu_dyninsed(nvp+1:nv_use,i,j)= &
                        winter(ksmax)*cv_sed(nvp+1:nv_use,ksmax,i,j)*REAL(dt_sed_eff,rsh) ! &
 
          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                      
          !!!!!!!  FIN consolidation -                               !!!
          !! actualisation epaisseurs et porosites intermediaires    !!!
          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                      
           
         poroin(ksma(i,j))=poro(ksma(i,j),i,j)
         DO k=ksmi(i,j),ksma(i,j)-1
              dzsiin(k)=2.0_rsh/(dzs(k,i,j)+dzs(k+1,i,j))
              poroin(k)=0.5_rsh*(poro(k+1,i,j)+poro(k,i,j))          
         ENDDO
        ENDIF  ! fin test l_consolid or l_bioturb
        
#if ! defined key_nodiss_insed
        
        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        !!!!!!!!!!!  DIFFUSION -BIOTURBATION DES VARIABLES DISSOUTES       !!!!
        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         IF(l_bioturb) THEN
         
            ! calcul du coef de biodiffusion a reactualiser si nombre de couches a change 
            CALL sed_coefbioturb(i,j,difbio) ! A Reprogrammer pour differencier particulaires et dissoutes
         ENDIF

           hcrit=MAX(0.0_rsh,ssh(i,j)+h0(i,j)-h0fond)
           DO iv=-1,nv_use
           !only temperature and Salinity and (-1 and 0) if NOT key_sedim_partial :  dissolved variables also
            IF(iv<1 .OR. iv>nvp) THEN
         
              ! calcul des vitesses de diffusion/biodiffusion dans le sediment
              !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              disvi(:)=0.0_rsh
             IF(l_diffused) THEN 
              k=ksmax
              IF(choice_flxdiss_diffsed == 1) THEN
               epn_bottom=f_dzu(h0(i,j),ssh(i,j),1,i,j)
               disvi(k)=2.0_rsh*xdifsi1/(dzs(k,i,j)+epn_bottom)
              ELSE IF(choice_flxdiss_diffsed == 2) THEN
               disvi(k)=xdifsi1/(dzs(k,i,j)*0.5_rsh+epdifi)
              ELSE
               ! dans la couche limite : formulation de Boudreau (1997)
               ! vitesse de diffusion= D/deltae=beta (page 182) eq 5.55 a 5.56)
               ! et beta =0.0889 u* Sc^(-0.704)
               ! formule de Shaw and Hanratty (1977) eq 5.58 in Boudreau 
               ! Sc nombre de Schmidt = viscosite cinematique/diffusivite massique
               ! de l ordre de 1000 mais peut varier ??   A REVOIR
               disvi(k)=0.0889*ustarbot(i,j)*(1000._rsh)**(-0.704)
              ENDIF
              disvi(k)=disvi(k)*hcrit/(hcrit+epsilon)
              DO k=ksmin,ksmax-1
                ! formulation en fonction de la tortuosite Dsed=Dpure/Tortuosite^2
                ! tortuosite fontion de la porosite (eq 4.120)
                ! in Boudreau 1997 p 132 ! totuosity^2=1-log(poro^2)
                !disvi(k)=xdifs1*dzsiin(k,i,j)/(1-LOG(poro(k,i,j)**2))
                disvi(k)=(xdifs1/(1.0_rsh-2.0_rsh*LOG(poro(k,i,j)))+difbio(k,iv))*dzsiin(k)
              ENDDO
             ENDIF
!
              !resolution equation de diffusion 
!
              IF(ksmax.GT.ksmin)THEN
!
                !cas ou il y a plusieurs couches:
                !--------------------------------
                !coefficients de la matrice
!
                k=ksmin
                dzssdt=dzs(k,i,j)*dt_sed_inv
                aa(k)=0.0_rsh
                bb(k)=poro(k,i,j)*dzssdt+disvi(k)*poroin(k)+winter(k)*fexcs
                cc(k)=-disvi(k)*poroin(k)+winter(k)*cexcs
                dd(k)=cv_sed(iv,k,i,j)*volpwak(k)*dt_sed_inv
                DO k=ksmin+1,ksmax-1
                 dzssdt=dzs(k,i,j)*dt_sed_inv
                 aa(k)=-disvi(k-1)*poroin(k-1)-winter(k-1)*fexcs
                 bb(k)=poro(k,i,j)*dzssdt+disvi(k-1)*poroin(k-1)+disvi(k)*poroin(k) &
                                +winter(k)*fexcs-winter(k-1)*cexcs
                 cc(k)=-disvi(k)*poroin(k)+winter(k)*cexcs
                 dd(k)=cv_sed(iv,k,i,j)*volpwak(k)*dt_sed_inv
                ENDDO
                k=ksmax
                aa(k)=-disvi(k-1)*poroin(k-1)-winter(k-1)*fexcs
                bb(k)=dzs(k,i,j)*poro(k,i,j)*dt_sed_inv+disvi(k-1)*poroin(k-1)+disvi(k)+winter(k)-winter(k-1)*cexcs
                cc(k)=0.0_rsh
                IF (iv==-1) THEN
                 fludif(iv,i,j)=disvi(k)*temp(1,i,j)
                ELSE IF (iv== 0) THEN
                 fludif(iv,i,j)=disvi(k)*sal(1,i,j)
                ELSE
                 fludif(iv,i,j)=disvi(k)*cv_wat(iv,1,i,j)
                ENDIF
                dd(k)=cv_sed(iv,k,i,j)*volpwak(k)*dt_sed_inv+fludif(iv,i,j)
!
               !resolution du systeme tridiagonal
!
                dd(1)=dd(1)/bb(1)
                DO k=ksmin+1,ksmax
                  bb(k)=bb(k)-aa(k)*cc(k-1)/bb(k-1)
                  dd(k)=(dd(k)-aa(k)*dd(k-1))/bb(k)
                ENDDO
                cv_sed(iv,ksmax,i,j)=dd(ksmax)
                DO k=ksmax-1,ksmin,-1
                  cv_sed(iv,k,i,j)=dd(k)-cc(k)*cv_sed(iv,k+1,i,j)/bb(k)
                ENDDO
!
              ELSE
!
               !cas ou il n y a qu une couche (ksmax=ksmin):
               !--------------------------------------------       
                k=ksmax        
                IF (iv==-1) THEN
                  fludif(iv,i,j)=disvi(k)*temp(1,i,j)
                ELSE IF (iv== 0) THEN
                  fludif(iv,i,j)=disvi(k)*sal(1,i,j)
                ELSE
                  fludif(iv,i,j)=disvi(k)*cv_wat(iv,1,i,j)
                ENDIF        
                cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)*volpwak(k)+fludif(iv,i,j)*REAL(dt_sed_eff,rsh))           &
                 /(dzs(k,i,j)*poro(k,i,j)+(disvi(k)+winter(k))*REAL(dt_sed_eff,rsh))
              ENDIF
!
              !  flux d echange a l interface eau/sediment:
              !  ------------------------------------------
              !  fludif est le flux par diffusion a l interface, >0 vers le bas
              fludif(iv,i,j)=(fludif(iv,i,j)-disvi(ksmax)*cv_sed(iv,ksmax,i,j))*REAL(dt_sed_eff,rsh)
  
              !  flu_dyninsed est le flux par tassement a l interface, >0 vers le haut (M/m2/s)
              ! auquel on rajoute le flux de substance perdu par fusion pendant le tassement            
              !flu_dyninsed(iv,i,j)=winter(ksmax)*cv_sed(iv,ksmax,i,j)*REAL(dt_sed_eff,rsh) + flu_fusion(iv) ! m/s*M/m3 ==> M/m2

            ENDIF                     ! test sur iv ( var dissoutes seules)
          ENDDO                         ! fin boucle sur iv
#endif
       ENDIF    ! test si existence sediment

    
       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       !!!!!!!!!!!! FIN DU PROCESSUS DE DYNAMIQUE DANS LE SEDIMENT      !!
       !!!!!!!!!!!!  CALCUL DES FLUX D EAU AVEC TERME CONSTANT          !!
       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       ! si la cellule est mise a sec  ==> on cumule les apports d  eau et les flux de substances
       !  dissoutes pour ne pas perdre de la matiere
       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         

       IF(h0(i,j)+ssh(i,j) .LE. h0fond) THEN  
            ! il n y a pas d eau
            ! phieau_s2w_drycell en m3  
            phieau_s2w_drycell(i,j)=phieau_s2w_drycell(i,j)+REAL(phieau_s2w_consol(i,j),rlg)*halfdt
#if ! defined key_nodiss_insed
            !fluconsol_drycell : cumul => M/m2
            !fluconsol_drycell(-1:0,i,j)=fluconsol_drycell(-1:0,i,j) +flu_dyninsed(-1:0,i,j)*halfdt
            fluconsol_drycell(-1:0,i,j)=fluconsol_drycell(-1:0,i,j) +flu_dyninsed(-1:0,i,j)
            fluconsol_drycell(nvp+1:nv_use,i,j)=fluconsol_drycell(nvp+1:nv_use,i,j)  &
                                               +flu_dyninsed(nvp+1:nv_use,i,j)
            fluconsol(-1:0,i,j)=0.0_rsh
            fluconsol(nvp+1:nv_use,i,j)=0.0_rsh                                    
#endif 
       ELSE
           ! phieau_s2w en m3  
           phieau_s2w(i,j)=phieau_s2w(i,j)+phieau_s2w_drycell(i,j) + &
                                          REAL(phieau_s2w_consol(i,j),rlg)
           phieau_s2w_drycell(i,j)=0.0_rlg
#if ! defined key_nodiss_insed
            ! fluconsol  => M/m2/s sera distribue dans flx_s2w (M/m2/s) (dans 
            fluconsol(-1:0,i,j)=flu_dyninsed(-1:0,i,j) +fluconsol_drycell(-1:0,i,j)
            fluconsol(nvp+1:nv_use,i,j)=flu_dyninsed(nvp+1:nv_use,i,j)  &
                                       +fluconsol_drycell(nvp+1:nv_use,i,j)
            fluconsol_drycell(-1:0,i,j)=0.0_rsh
            fluconsol_drycell(nvp+1:nv_use,i,j)=0.0_rsh
#endif 
       ENDIF
     ENDDO
   ENDDO
!$OMP END DO
!$OMP END PARALLEL
     t_sed=t+dt_sed_cor

    ELSE
            fluconsol(:,:,:)=0.0_rsh
            fludif(:,:,:)=0.0_rsh

    ENDIF


  END SUBROUTINE sed_consol_diff_bioturb
#endif
   !!==============================================================================


#ifdef key_sedim_mudsand

  SUBROUTINE sed_consolid_mudsand(i,j,volpwa,varpwa,poroa,poroin,winter,dzsiin,dt_sedeff,dt_sedinv)

   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_consolid  ***
   !&E
   !&E ** Purpose : computes sediment consolidation and manages sediment layers
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  consol_diffu
   !&E
   !&E ** External calls : sed_constitutivrel
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (P. Le Hir) extracted from init.F90
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       !  2009-02  (P. Le Hir) new version from SiAM "sable-vase"
   !&E
   !&E--------------------------------------------------------------------------

   !! * Modules used
   USE comvars2d,    ONLY : h0
   USE comvarp2d,    ONLY : ssh
   USE comsubstance, ONLY : nvp,nvpc,nv_adv
   USE parameters,   ONLY : epsilon,valmanq

   !! Arguments 
   INTEGER, intent(IN)                       :: i,j
   REAL(KIND=rsh), intent(INOUT)             :: volpwa,dt_sedeff,dt_sedinv
   REAL(KIND=rsh), DIMENSION(-1:nv_adv),intent(INOUT)         :: varpwa
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax), intent(INOUT)   :: poroa,poroin,dzsiin
   REAL(KIND=rsh),DIMENSION(ksdmin-1:ksdmax), intent(INOUT)   :: winter

   !! * Local declarations
   INTEGER                                   :: ksmin,ksmax,iv,k,it
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax) :: ws
   REAL(KIND=rsh) :: dzsa,dtrest,dzsan,dt1,dt1s
   REAL(KIND=rsh) :: dtsdzs,dzsam1,dvol,dzsisu,somalp
   REAL(KIND=rsh),PARAMETER                  :: dtminconsol=10.0_rsh

   !!----------------------------------------------------------------------
   !! * Executable part


        ksmin=ksmi(i,j)
        ksmax=ksma(i,j)

        ! 1- calcul du tassement
        ! **********************

        ! actuellement, la vitesse de sedimentation est supposee 
        ! identique pour toutes les particules

        dtrest=REAL(dt_sedeff,rsh)
        it=0
  1     CONTINUE
        it=it+1
        dzsan=dzs(ksmax,i,j)
        ! modif du 1-2-99:
        dt1=dtrest
        IF(ksmax.GE.2)THEN

          ! cas ou il y a plus d une couche :
          DO k=ksmin,ksmax-1
            CALL sed_comp_sedvel(poroin(k))
            ws(k)=sed_sedimvel
            dt1=MIN(xcvgce*dzs(k,i,j)/(ws(k)+1.e-16),dt1)
          ENDDO
          k=ksmax
          CALL sed_comp_sedvel(poroin(k))
          ws(k)=sed_sedimvel
          dt1s=MIN(xcvgce*dzs(k,i,j),dzsan-dzsmin)/(ws(k)+1.e-16)
          dt1=MIN(dt1,MAX(0.0_rsh,dt1s))
          dzs(ksmax,i,j)=dzsan-dt1*ws(ksmax)

          k=ksmin
          dtsdzs=dt1/dzs(k,i,j)
          DO iv=1,nvp
            !cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)+dtsdzs*(ws(k)*fexcs &
            !                *cv_sed(iv,k+1,i,j)+ws(k)*cexcs*cv_sed(iv,k,i,j))
            ! excentrement total impose pour gagner du temps:
            cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)+dtsdzs*ws(k)*cv_sed(iv,k+1,i,j)
          ENDDO
          DO k=ksmin+1,ksmax-1
            dtsdzs=dt1/dzs(k,i,j)
            DO iv=1,nvp
             !cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)+dtsdzs*(ws(k)*fexcs &    
             !                *cv_sed(iv,k+1,i,j)+(ws(k)*cexcs-ws(k-1)*fexcs) &
             !                *cv_sed(iv,k,i,j))-ws(k-1)*cexcs*cv_sed(iv,k-1,i,j))
              cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)+dtsdzs*(-ws(k-1)*cv_sed(iv,k,i,j)+ws(k)*cv_sed(iv,k+1,i,j))
            ENDDO
          ENDDO
          k=ksmax
          DO iv=1,nvp
            !cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)*dzsan-dt1*ws(k-1)* &
            !                 (fexcs*cv_sed(iv,k,i,j)+cexcs*cv_sed(iv,k-1,i,j)))/dzs(k,i,j)
            cv_sed(iv,k,i,j)=(cv_sed(iv,k,i,j)*dzsan-dt1*ws(k-1)*cv_sed(iv,k,i,j))/dzs(k,i,j)
          ENDDO

          IF(dzs(ksmax,i,j).LE.dzsmin)THEN
            ! fusion des 2 couches de surface           
            dzsan=dzs(ksmax,i,j)
            dzsam1=dzs(ksmax-1,i,j)
            ! reactualisation de dzsa et volpwa:
            dzsa=dzsa+dzsam1
            dvol=poroa(ksmax-1)*dzsam1
            volpwa=volpwa+dvol
            varpwa(-1)=varpwa(-1)+dvol*cv_sed(-1,ksmax-1,i,j)
            varpwa( 0)=varpwa( 0)+dvol*cv_sed(0,ksmax-1,i,j)
            DO iv=nvp+1,nv_adv
                varpwa(iv)=varpwa(iv)+dvol*cv_sed(iv,ksmax-1,i,j)
            ENDDO
            ksmax=ksmax-1
            dzs(ksmax,i,j)=dzs(ksmax,i,j)+dzsan
            dzsisu=1.0_rsh/dzs(ksmax,i,j)
            DO iv=1,nvp
              cv_sed(iv,ksmax,i,j)=(cv_sed(iv,ksmax+1,i,j)*dzsan+cv_sed(iv,ksmax,i,j)*dzsam1)*dzsisu
            ENDDO
            DO iv=1,nvp
              cv_sed(iv,ksmax+1,i,j)=-valmanq
            ENDDO
            dzs(ksmax+1,i,j)=0.0_rsh
 
          ENDIF

        ELSE
          ! cas ou il n y a qu une couche :
          !write(*,*)'attention: le sediment n"a qu"une couche !'
          k=ksmin
          IF(dzs(k,i,j).GT.dzsmin)THEN
            CALL sed_comp_sedvel(poro(k,i,j))
            ws(k)=sed_sedimvel
            dt1=MIN(xcvgce*dzs(k,i,j)/(ws(k)+1.e-16),dt1)
            dzs(k,i,j)=dzsan-dt1*ws(k)
            IF(dzs(k,i,j).LE.dzsmin)THEN
              dzs(k,i,j)=dzsmin
              dt1=dtrest
            ENDIF            
            dzsisu=1.0_rsh/dzs(k,i,j)
            DO iv=1,nvp
              cv_sed(iv,k,i,j)=cv_sed(iv,k,i,j)*dzsan*dzsisu
            ENDDO
          ENDIF
        ENDIF

        ! calcul de la densite (kg/m3) et de la porosite du sediment
        ! ----------------------------------------------------------
        DO k=ksmin,ksmax
          c_sedtot(k,i,j)=0.0_rsh
          somalp=0.0_rsh
          DO iv=1,nvpc
            c_sedtot(k,i,j)=c_sedtot(k,i,j)+cv_sed(iv,k,i,j)
            somalp=somalp+cv_sed(iv,k,i,j)/(ros(iv)+epsilon)
          ENDDO
          poro(k,i,j)=1.0_rsh-somalp
        ENDDO
        poroin(ksmax)=poro(ksmax,i,j)
        IF(ksmax.GE.2)THEN
          DO k=ksmin,ksmax-1
              poroin(k)=0.5_rsh*(poro(k,i,j)+poro(k+1,i,j))
              dzsiin(k)=2.0_rsh/(dzs(k,i,j)+dzs(k+1,i,j))
          ENDDO
        ENDIF

        dtrest=dtrest-dt1
        IF(dtrest.GT.dtminconsol)THEN
          IF(it.LE.200)THEN
            GOTO 1
          !ELSE
           !WRITE(*,555)it,i,j,dt1,ksmax,dzs(ksmax,i,j),poro(ksmax,i,j)
 ! 555       FORMAT('tassdif iter',i3,' en i,j=',2i3,' dt1=',g8.2,' ksmax',i3,' dzs',g8.2,'po',f4.2)
          ENDIF
        ENDIF

        ! 2- calcul des vitesses du fluide interstitiel
        ! *********************************************
        ! considerees >0 vers le haut, centree a l interface superieure

        winter(0)=0.0_rsh
        DO k=ksmin,ksmax-1
            winter(k)=winter(k-1)+(poroa(k)-poro(k,i,j))*dzs(k,i,j)*dt_sedinv
        ENDDO
        k=ksmax
        winter(k)=winter(k-1)+(volpwa-poro(k,i,j)*dzs(k,i,j))*dt_sedinv
        DO iv=nvp+1,nv_adv
          fluconsol(iv,i,j)=winter(ksmax)*cv_sed(iv,ksmax,i,j)
        ENDDO

!
      !  Reactualisation de ksma (ksmax a pu etre modifie)
!
        ksma(i,j)=ksmax
!
!
!

   PRINT_DBG*, 'FIN SED_CONSOLID'   

  END SUBROUTINE sed_consolid_mudsand

#endif

!!==============================================================================

#ifdef key_sedim_mudsand
  SUBROUTINE sed_diffusion_mudsand(i,j,poroa,poroin,dtdiffuinv,dzsiin,winter,varpwa)

   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_diffusion  ***
   !&E
   !&E ** Purpose :  computes diffusion of dissolved substances into the sediment  
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  step (if not l_consolid) or sed_consolid (if l_consolid)
   !&E
   !&E ** External calls : sed_constitutivrel
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2008-09  (P. Le Hir) extracted from init.F90
   !&E       !  2010-09  (B. Thouvenin) extracted from consolid_mudsand
   !&E
   !&E--------------------------------------------------------------------------

   !! * Modules used
   USE comvars2d,    ONLY : h0,h0fond,nbouc,halfdt
   USE comvarp2d,    ONLY : sal,temp,ssh
   USE comsubstance, ONLY : nvp,nv_adv,cv_wat
   USE parameters,   ONLY : epsilon
   
   !! Argument
   INTEGER, intent(IN)                       :: i,j
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax), intent(IN)   :: poroa,poroin,dzsiin
   REAL(KIND=rsh),DIMENSION(ksdmin-1:ksdmax), intent(IN)   :: winter
   REAL(KIND=rsh), DIMENSION(-1:nv_adv),intent(INOUT)      :: varpwa
   REAL(KIND=rsh),intent(IN)   :: dtdiffuinv

   !! * Local declarations
   INTEGER                                   :: ksmin,ksmax,iv,k
   REAL(KIND=rsh),DIMENSION(ksdmin  :ksdmax) :: disvi,aa,bb,cc,dd
   REAL(KIND=rsh)                            :: hcrit,dzssdt

   !!----------------------------------------------------------------------
   !! * Executable part
   
   disvi(:)=0.0_rsh
   ksmax=ksma(i,j)
   ksmin=ksmi(i,j)

   ! calcul des concentrations des var. dissoutes ds sediment
   ! ***********************************************************
#if ! defined key_sedim_partial
   !DO iv=nvp+1,nv_adv
   !    la boucle sur les variables positionnee ici permet de faire
   !    varier les coef. de diffusion en fonction des variables
   ! actuellement ils ne dependent pas des variables dont la boucle est 
   ! positionnee plus loin
!
      k=ksmax
      !CALL sed_difcoef_int(poro(k,i,j))
      ! coef de diffusion a l interface ????
      !sed_difint=xdifsi1/(1-LOG(poro(k,i,j)**2))
      disvi(k)=xdifsi1/(dzs(k,i,j)*0.5_rsh+epdifi)
      hcrit=MAX(0.0_rsh,ssh(i,j)+h0(i,j)-h0fond)
      disvi(k)=disvi(k)*hcrit/(hcrit+epsilon)
!gain            disve(k)=disvi(k)*cimpls
!gain            disvi(k)=disvi(k)*fimpls
!
!c        accroissement de la diffusion a l interface si charriage:
!c        if(iopcoh.ne.1)then
!c          efchar=xdifs3*teta**.5*max(0.0_rsh,teta-tetac)
!c          disve(k)=disve(k)*efchar
!c          disvi(k)=disvi(k)*efchar
!c        endif
!
         !calcul des vitesses de diffusion dans le sediment
         DO k=ksmin,ksmax-1
!gain         CALL sed_difcoef_sed(poro(k,i,j))
!gain         disvi(k)=sed_difsed*dzsiin(k)
!gain         disvi(k)=xdifs1*poroin(k)**xdifs2*dzsiin(k)
              disvi(k)=xdifs1*dzsiin(k)
!gain         disve(k)=disvi(k)*cimpls
!gain         disvi(k)=disvi(k)*fimpls
         ENDDO
!
         !calcul d advection-diffusion 
!
    DO iv=nvp+1,nv_adv

      IF(ksmax.GT.ksmin)THEN
!
         !cas ou il y a plusieurs couches:
         !--------------------------------
!
         !calcul des vitesses de diffusion
!
         !coefficients de la matrice
!
         !calcul implicite pour l advection, partiellement implicite
         !(fimpls) pour la diffusion; 
         !flux advectifs partielt decentres amont (fexcs), totalt en surf
         k=ksmin
         dzssdt=dzs(k,i,j)*dtdiffuinv
         aa(k)=0.0_rsh
         bb(k)=dzssdt*poro(k,i,j)+disvi(k)+winter(k)*fexcs
         cc(k)=-disvi(k)+winter(k)*cexcs
!gain            dd(k)=dzssdt*poroa(k)*cv_sed(iv,k,i,j)+disve(k)*
!gain     $            (cv_sed(iv,k+1,i,j)-cv_sed(iv,k,i,j))
         dd(k)=dzssdt*poroa(k)*cv_sed(iv,k,i,j)
         DO k=ksmin+1,ksmax-1
              dzssdt=dzs(k,i,j)*dtdiffuinv
              aa(k)=-disvi(k-1)-winter(k-1)*fexcs
              bb(k)=dzssdt*poro(k,i,j)-winter(k-1)*cexcs             &
                   +winter(k)*fexcs+disvi(k-1)+disvi(k)
              cc(k)=-disvi(k)+winter(k)*cexcs
              dd(k)=dzssdt*poroa(k)*cv_sed(iv,k,i,j)
!gain     $              +disve(k)*(cv_sed(iv,k+1,i,j)-cv_sed(iv,k,i,j))
!gain     $              -disve(k-1)*(cv_sed(iv,k,i,j)-cv_sed(iv,k-1,i,j))
         ENDDO
         k=ksmax
         aa(k)=-disvi(k-1)-winter(k-1)*fexcs
         bb(k)=dzs(k,i,j)*poro(k,i,j)*dtdiffuinv                     &
                +disvi(k-1)+disvi(k)-winter(k-1)*cexcs+winter(k)
         cc(k)=0.0_rsh
!gain            fludif(iv,i,j)=(disve(k)+disvi(k))*cv_wat(iv,1,i,j)
!gain     $                     -disve(k)*cv_sed(iv,k,i,j)
         fludif(iv,i,j)=disvi(k)*cv_wat(iv,1,i,j)
         dd(k)=varpwa(iv)*dtdiffuinv+fludif(iv,i,j)
!gain     $            -disve(k-1)*(cv_sed(iv,k,i,j)-cv_sed(iv,k-1,i,j))
!
         !resolution du systeme tridiagonal
!
         dd(1)=dd(1)/bb(1)
         DO k=ksmin+1,ksmax
              bb(k)=bb(k)-aa(k)*cc(k-1)/bb(k-1)
              dd(k)=(dd(k)-aa(k)*dd(k-1))/bb(k)
         ENDDO
         cv_sed(iv,ksmax,i,j)=dd(ksmax)
         DO k=ksmax-1,ksmin,-1
              cv_sed(iv,k,i,j)=dd(k)-cc(k)*cv_sed(iv,k+1,i,j)/bb(k)
         ENDDO
!
      ELSE
!
        !cas ou il n y a qu une couche (ksmax=ksmin):
        !--------------------------------------------       
        k=ksmax        
!gain       fludif(iv,i,j)=(disve(k)+disvi(k))*cv_wat(iv,1,i,j)
!gain     $                     -disve(k)*cv_sed(iv,k,i,j)
        fludif(iv,i,j)=disvi(k)*cv_wat(iv,1,i,j)
        cv_sed(iv,k,i,j)=(varpwa(iv)+fludif(iv,i,j)*REAL(halfdt,rsh))           &
              /(dzs(k,i,j)*poro(k,i,j)+(winter(k)+disvi(k))*REAL(halfdt,rsh)+epsilon)
      ENDIF
!
      !  flux d echange a l interface eau/sediment:
      !  ------------------------------------------
      !  fludif est le flux par diffusion a l interface, >0 vers le bas
          fludif(iv,i,j)=fludif(iv,i,j)-disvi(ksmax)*cv_sed(iv,ksmax,i,j)
      !  fluconsol est le flux par tassement a l interface, >0 vers le haut
      !  si pas de consolidation a ce moment winter=0 => pas de flux de consolidation
          fluconsol(iv,i,j)=winter(ksmax)*cv_sed(iv,ksmax,i,j)

   ENDDO                         ! fin boucle sur iv
#endif
      !  3bis- calcul des concentrations de la temperature (-1) et salinite (0) 
      !     ds sediment
      !  ***********************************************************
!
   DO iv=-1,0
      !    la boucle sur les variables positionnee ici permet de faire
      !    varier les coef. de diffusion en fonction des variables
!
      k=ksmax
 !     CALL sed_difcoef_int(poro(k,i,j))
!c          disvi(k)=sed_difcoef_int
!c          disvi(k)=sed_difint
!c          disvi(k)=xdifsi1*poro(k,i,j)**xdifsi2
      disvi(k)=xdifsi1 /(dzs(k,i,j)*0.5_rsh+epdifi)
      hcrit=MAX(0.0_rsh,ssh(i,j)+h0(i,j)-h0fond)
      disvi(k)=disvi(k)*hcrit/(hcrit+epsilon)
!gain            disve(k)=disvi(k)*cimpls
!gain            disvi(k)=disvi(k)*fimpls
!
!c        accroissement de la diffusion a l interface si charriage:
!c        if(iopcoh.ne.1)then
!c          efchar=xdifs3*teta**.5*max(0.0_rsh,teta-tetac)
!c          disve(k)=disve(k)*efchar
!c          disvi(k)=disvi(k)*efchar
!c        endif
!
      IF(ksmax.GT.ksmin)THEN
!
            !cas ou il y a plusieurs couches:
            !--------------------------------
!
            !calcul des vitesses de diffusion
!
        DO k=ksmin,ksmax-1
!gain         disvi(k)=sed_difsed(poroin(k))*dzsiin(k)
!gain         CALL sed_difcoef_sed(poro(k,i,j))
!gain         disvi(k)=sed_difsed*dzsiin(k)
!gain         disvi(k)=xdifs1*poroin(k)**xdifs2*dzsiin(k)
              disvi(k)=xdifs1*dzsiin(k)
!gain         disve(k)=disvi(k)*cimpls
!gain         disvi(k)=disvi(k)*fimpls
        ENDDO
!
        !calcul d advection-diffusion 
!
        !coefficients de la matrice
!
        !calcul implicite pour l advection, partiellement implicite
        !(fimpls) pour la diffusion; 
        !flux advectifs partielt decentres amont (fexcs), totalt en surf
        k=ksmin
        dzssdt=dzs(k,i,j)*dtdiffuinv
        aa(k)=0.0_rsh
        bb(k)=dzssdt*poro(k,i,j)+disvi(k)+winter(k)*fexcs
        cc(k)=-disvi(k)+winter(k)*cexcs
!gain            dd(k)=dzssdt*poroa(k)*cv_sed(iv,k,i,j)+disve(k)*
!gain     $            (cv_sed(iv,k+1,i,j)-cv_sed(iv,k,i,j))
        dd(k)=dzssdt*poroa(k)*cv_sed(iv,k,i,j)
        DO k=ksmin+1,ksmax-1
              dzssdt=dzs(k,i,j)*dtdiffuinv
              aa(k)=-disvi(k-1)-winter(k-1)*fexcs
              bb(k)=dzssdt*poro(k,i,j)-winter(k-1)*cexcs             &
                   +winter(k)*fexcs+disvi(k-1)+disvi(k)
              cc(k)=-disvi(k)+winter(k)*cexcs
              dd(k)=dzssdt*poroa(k)*cv_sed(iv,k,i,j)
!gain     $              +disve(k)*(cv_sed(iv,k+1,i,j)-cv_sed(iv,k,i,j))
!gain     $              -disve(k-1)*(cv_sed(iv,k,i,j)-cv_sed(iv,k-1,i,j))
        ENDDO
        k=ksmax
        aa(k)=-disvi(k-1)-winter(k-1)*fexcs
        bb(k)=dzs(k,i,j)*poro(k,i,j)*dtdiffuinv                      &
                 +disvi(k-1)+disvi(k)-winter(k-1)*cexcs+winter(k)
        cc(k)=0.0_rsh
!gain            fludif(iv,i,j)=(disve(k)+disvi(k))*cv_wat(iv,1,i,j)
!gain     $                     -disve(k)*cv_sed(iv,k,i,j)
        IF (iv==-1) fludif(iv,i,j)=disvi(k)*temp(1,i,j)
        IF (iv== 0) fludif(iv,i,j)=disvi(k)*sal(1,i,j) 
        dd(k)=varpwa(iv)*dtdiffuinv+fludif(iv,i,j)
!gain     $            -disve(k-1)*(cv_sed(iv,k,i,j)-cv_sed(iv,k-1,i,j))
!
        !resolution du systeme tridiagonal
!
        dd(1)=dd(1)/bb(1)
        DO k=ksmin+1,ksmax
              bb(k)=bb(k)-aa(k)*cc(k-1)/bb(k-1)
              dd(k)=(dd(k)-aa(k)*dd(k-1))/bb(k)
        ENDDO
        cv_sed(iv,ksmax,i,j)=dd(ksmax)
        DO k=ksmax-1,ksmin,-1
              cv_sed(iv,k,i,j)=dd(k)-cc(k)*cv_sed(iv,k+1,i,j)/bb(k)
        ENDDO
!
      ELSE
!
        !cas ou il n y a qu une couche (ksmax=ksmin):
        !--------------------------------------------       
        k=ksmax        
!gain       fludif(iv,i,j)=(disve(k)+disvi(k))*cv_wat(iv,1,i,j)
!gain     $                     -disve(k)*cv_sed(iv,k,i,j)
        IF (iv==-1) fludif(iv,i,j)=disvi(k)*temp(1,i,j)
        IF (iv== 0) fludif(iv,i,j)=disvi(k)*sal(1,i,j)
        cv_sed(iv,k,i,j)=(varpwa(iv)+fludif(iv,i,j)*REAL(halfdt,rsh))           &
              /(dzs(k,i,j)*poro(k,i,j)+(winter(k)+disvi(k))*REAL(halfdt,rsh)+epsilon)
      ENDIF
!
      !  flux d echange a l interface eau/sediment:
      !  ------------------------------------------
      !  fludif est le flux par diffusion a l interface, >0 vers le bas
      fludif(iv,i,j)=fludif(iv,i,j)-disvi(ksmax)*cv_sed(iv,ksmax,i,j)
      !  fluconsol est le flux par tassement a l interface, >0 vers le haut
      !  si pas de consolidation a ce moment winter=0 => pas de flux de consolidation
      fluconsol(iv,i,j)=winter(ksmax)*cv_sed(iv,ksmax,i,j)

   ENDDO                         ! fin boucle sur temp et salinite
 999 continue


   PRINT_DBG*, 'FIN SED_DIFFUSION'   

  END SUBROUTINE sed_diffusion_mudsand
#endif
!!==============================================================================
#ifdef key_sedim_mixsed

      SUBROUTINE sed_constitutivrel(i,j,stateconsol,permeab,sigmapsg)
! 
   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_constitutivrel  ***
   !&E
   !&E ** Purpose : applies constitutive relationships for permeability, 
   !&E              effective stess
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  consoldif
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-02  new version from SiAM"sande-vase" by P. Le Hir
   !&E       !  2014-05  (F. Grasso) modifications based on "Grasso et al. (Ocean Dynynamics, 2014)"
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nvpc,igrav1,isand2
   USE parameters,   ONLY : grav
   
   !! * Arguments
   INTEGER,INTENT(IN) :: i,j
   REAL(KIND=rsh),DIMENSION(ksdmin:ksdmax),INTENT(out) :: stateconsol,permeab,sigmapsg

   !! * Local declarations
   INTEGER                        :: k,iv,icond
   REAL(KIND=rsh),DIMENSION(nvpc) :: cvol
   REAL(KIND=rsh)                 :: cvolsed,cvolsangrv,fracvolcum,diarepres,       &
                                     voidratio,diamstarrep,wsoulsby,somcmud,crelmud,cvolrelmud, &
                                     permeab_e


   !! * executable statement
   !!   --------------------
   sigmapsg(:)=0.0_rsh
   stateconsol(:)=0.0_rsh

   DO k=ksmi(i,j),ksma(i,j)

     cvol(:)=0.0_rsh

     cvolsed=0.0_rsh
     DO iv=igrav1,isand2
       cvol(iv)=cv_sed(iv,k,i,j)/ros(iv)
       cvolsed=cvolsed+cvol(iv)
     ENDDO
     cvolsangrv=cvolsed
     somcmud=0.0_rsh
     DO iv=isand2+1,nvpc
       cvol(iv)=cv_sed(iv,k,i,j)/ros(iv)
       cvolsed=cvolsed+cvol(iv)
       somcmud=somcmud+cv_sed(iv,k,i,j)
     ENDDO

     !  permeability with voidratio:
     voidratio=poro(k,i,j)/(1.0000001_rsh-poro(k,i,j))
     voidratio=MAX(voidratio,0.0_rsh)
     permeab_e=2.0e-9_rsh*voidratio**3.7_rsh   ! best param for Co<120 kg/m3 (Grasso et al., Ocean Dynamics 2014)

     !  permeability with cvolrelmud (relative volumic concentration of mud, cvolrelmud=cvolmud/(1-cvolsand), cf. Merckelbach & Kranenburg, 2004)
     crelmud=somcmud/(1.0_rsh-cvolsangrv)
     cvolrelmud=crelmud/ros(1)
     !!!FG(06/03/2015) pour corriger le cas ou cvolrelmud est trop faible (Cvolrelmud = 0.01 -> Crelmud = 26 g/l -> permeab = 4 m/s)
     IF(cvolrelmud .LE. 0.01) THEN
       permeab(k)=permeab_e
     ELSE
       permeab(k)=xperm1*cvolrelmud**xperm2
     ENDIF

!     !  minimalisation of permeability
     permeab(k)=MIN(permeab(k),permeab_e,(1.0_rsh+voidratio)*0.0001_rsh/1.65_rsh)   ! equivalent permeability for ws=0.1 mm/s

     !  effective stress :
     icond=1
     DO iv=igrav1,isand2
       icond=icond*MAX(0.0_rsh,100.0_rsh*(cvolmaxsort-cvol(iv)-.02_rsh))
     ENDDO
     IF(cvolsed.LE.cvolmaxmel.AND.icond.NE.0)THEN
       sigmapsg(k)=xsigma1/grav*cvolrelmud**xsigma2 !FG(04/09/2013) to use Merckelback & Kranenburg s (2004) formulation
       stateconsol(k)=1.0_rsh
     ELSE
       !    in this case, the effective stress is maximum, 
       !    but porewater overpressure is zero :
       stateconsol(k)=0.0_rsh
     ENDIF
   ENDDO

  END SUBROUTINE sed_constitutivrel
#endif

!!==============================================================================

      SUBROUTINE sed_difcoef_int(porosi)

   !&E--------------------------------------------------------------------------
   !&E                 ***  SUBROUTINE sed_difcoef_int  ***
   !&E
   !&E ** Purpose : computes diffusion coefficient at the water/sediment interface
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  normally sed_diffusion
   !&E 
   !&E ** External calls : nonee
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-02  extracted from (SiAM) by F. Cayocca and P. Le Hir
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   !!   ------------

   !! * Local declarations
   !!   ------------------
   
      REAL(KIND=rsh), INTENT(in) ::  porosi
         
   !! * Executable part
   !!   ---------------

      sed_difint=xdifsi1*porosi**xdifsi2

      END SUBROUTINE sed_difcoef_int

!!==============================================================================

      SUBROUTINE sed_difcoef_sed(porosi)

   !&E--------------------------------------------------------------------------
   !&E                 ***  SUBROUTINE sed_difcoef_sed  ***
   !&E
   !&E ** Purpose : computes diffusion coefficient in sediment 
   !&E
   !&E ** Description : 
   !&E
   !&E ** Called by :  normally sed_diffusion
   !&E 
   !&E ** External calls : nonee
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E       !  2009-02  extracted from (SiAM) by F. Cayocca and P. Le Hir
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   !!   ------------

   !! * Local declarations
   !!   ------------------
   
      REAL(KIND=rsh), INTENT(in) ::  porosi
         
   !! * Executable part
   !!   ---------------

     ! sed_difsed=xdifs1*porosi**xdifs2
      sed_difsed=xdifs1/(1-LOG(porosi**2))

  END SUBROUTINE sed_difcoef_sed

!!==============================================================================

  SUBROUTINE sed_outsaverestart

   !&E--------------------------------------------------------------------------
   !&E                 ***  ROUTINE sed_outsaverestart  ***
   !&E
   !&E ** Purpose : saves sediment-related field for future runs
   !&E
   !&E ** Description :
   !&E
   !&E ** Called by :  step 
   !&E
   !&E ** External calls : 
   !&E
   !&E ** Reference :
   !&E
   !&E ** History :
   !&E
   !&E       !  2008-10  (F. Cayocca) inserted into module_sedimento.F90
   !&E       !  2009-02  (P. Le Hir) modified declarations
   !
   !objet    :  gestion de la reprise de calcul a partir d un etat
         !           enregistre dans un fichier (netcdf ou binaire acces direct)
         !           lors d un run anterieur
   !
   !     appelant         : stepu
         !                :
   !     appeles          : ionc4_createfile, ionc4_torigine, 
   !     appeles          : ionc4_createvar, ionc4_createvar
   !     appeles          : ionc4_createvar, ionc4_write_time
   !     appeles          : ionc4_write_xy, ionc4_write_xyt, ionc4_write_zxyt
         !                :
   !     canal d ecriture :
         !                :
   !     canal de lecture : 26, filrep
         !                :
   !     cle cpp          : key_notra
         !                :
   !     variables in     : t, u, uz, xu, v, vz, xv, sal, temp, tz
   !     variables in     : ect, boz, nz, kz, wz, vish_xe, vish_phi
   !     variables in     : filsauvsed, lon2d,lat2d, ntra
   !     variables in     : cdate, h0,sig
         !                :
   !     variables out    : 
         !                :
   !     variables inout  : tsauv
         !                :
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   !!   ------------
   
   USE comsubstance, ONLY :  nv_adv,flx_s2w,flx_w2s
   USE parameters,   ONLY :  riosh,kmax,rg_valmanq_io
   USE comvars2d,    ONLY :  lon2d_g,lat2d_g,lon2d,lat2d,l_saverestart_bydate,date_ref, &
                             t,tsauv,cdate,saverestart_step,name_out_h0,name_out_xe
   USE_MPI toolmpi,  ONLY : ADD_TAG
   USE output,       ONLY : l_out_nc4par

   !! * Local declarations
   !!   ------------------

   CHARACTER(LEN=8)      :: nomc
   CHARACTER(LEN=13)     :: prefsauv
   CHARACTER(LEN=lchain) :: chain
   INTEGER               :: i,j,k,l,iv,ifois
   REAL(KIND=riosh),DIMENSION(limin:limax,ljmin:ljmax)          :: xind
   REAL(KIND=riosh),DIMENSION(ksdmin:ksdmax,limin:limax,ljmin:ljmax)   :: tlits
   REAL(KIND=riosh),DIMENSION(0:ksdmax+1)                       :: sigsed

   DATA ifois /0/
   
   !! * Executable part
   !!   ---------------

   PRINT_DBG*, 'enter sed_outsaverestart'

   ! initialisation of sigsed
   DO k=ksdmin,ksdmax
      sigsed(k)=k
   END DO
   sigsed(0)=0
   sigsed(ksdmax+1)=0
   
   ! creation
   ! ********

   IF (ifois.EQ.0 .AND. .NOT.(l_saverestart_bydate)) THEN
     ifois=1
     filsauvsed='./save_sedim.nc'
     IF_MPI(.NOT. l_out_nc4par) CALL ADD_TAG(filsauvsed,LEN(filsauvsed))
     IF ( l_out_nc4par ) THEN
        CALL ionc4_createfile(filsauvsed,lon2d_g,lat2d_g,imin,imax,1,          &
                              jmin,jmax,1,ksdmin,ksdmax,1,ksdmax,0,l_out_nc4par = .TRUE.)
     ELSE
        CALL ionc4_createfile(filsauvsed,lon2d,lat2d,limin,limax,1,          &
                              ljmin,ljmax,1,ksdmin,ksdmax,1,ksdmax,0)
     ENDIF

   ! save attribute of the spatial extension of the domain
   ! -----------------------------------------------------
     CALL ionc4_gatt(filsauvsed,'global_imin',imin)
     CALL ionc4_gatt(filsauvsed,'global_imax',imax)
     CALL ionc4_gatt(filsauvsed,'global_jmin',jmin)
     CALL ionc4_gatt(filsauvsed,'global_jmax',jmax)

   ! indispensable pour concatenation pas terrible a revoir
     CALL ionc4_createvar(filsauvsed,'SIG',' ','sigma variable',&
#if defined key_siggen || defined key_gencoord
                          standard_name= 'ocean_s_variable',&
#else
                          standard_name= 'ocean_sigma_variable',&
#endif
                          l_auxcoordinate=.false.,&
                          valid_min= -1.0_riosh,valid_max= 0.0_riosh,fill_value= rg_valmanq_io,&
                          dims= 'z', l_out_nc4par = l_out_nc4par)
     CALL ionc4_write_sig(filsauvsed,'SIG',sigsed,ksdmax)

     CALL ionc4_torigine(filsauvsed,date_ref)
     CALL ionc4_createvar(filsauvsed,'ksmi','s.o','ksmi',fill_value=rg_valmanq_io, &
                          dims='xyt',valid_min=0.0_riosh,valid_max=10.0_riosh,l_out_nc4par=l_out_nc4par)
     CALL ionc4_createvar(filsauvsed,'ksma','s.o','ksma',fill_value=rg_valmanq_io, &
                          dims='xyt',valid_min=0.0_riosh,valid_max=1000.0_riosh,l_out_nc4par=l_out_nc4par)
     CALL ionc4_createvar(filsauvsed,'dzsmax','s.o','ksma',fill_value=rg_valmanq_io, &
                          dims='xyt',valid_min=0.0_riosh,valid_max=1.0_riosh,l_out_nc4par=l_out_nc4par)
     CALL ionc4_createvar(filsauvsed,'dzs','m','dzs',fill_value=rg_valmanq_io, &
                          dims='zxyt',valid_min=0.0_riosh,valid_max=100.0_riosh,l_out_nc4par=l_out_nc4par)
     DO iv=-1,nv_adv     ! pour T et S
       IF (IV>0) WRITE(nomc,10) iv
       IF (iv==-1) nomc='concTEM'
       IF (iv==0) nomc='concSAL'
       CALL ionc4_createvar(filsauvsed,nomc,'u.s.i','concentration ',&
                            fill_value=rg_valmanq_io,dims='zxyt',l_out_nc4par=l_out_nc4par)
       IF (IV>0) WRITE(nomc,20) iv
       IF (iv==-1) nomc='fxw2sTEM'
       IF (iv==0) nomc='fxw2sSAL'
       CALL ionc4_createvar(filsauvsed,nomc,'u.s.i','flx_w2s ',&
                            fill_value=rg_valmanq_io,dims='xyt',l_out_nc4par=l_out_nc4par)
     END DO 
   ENDIF

   IF (l_saverestart_bydate.AND.t.GE.tsauv) THEN
     prefsauv='./save_sedim_'
     filsauvsed=prefsauv//cdate(7:10)//cdate(4:5)//  &
                    cdate(1:2)//cdate(12:13)//cdate(15:16)//cdate(18:19)//'.nc'
     IF_MPI(.NOT. l_out_nc4par) CALL ADD_TAG(filsauvsed,LEN(filsauvsed))
     IF ( l_out_nc4par ) THEN
        CALL ionc4_createfile(filsauvsed,lon2d_g,lat2d_g,imin,imax,1,          &
                              jmin,jmax,1,ksdmin,ksdmax,1,ksdmax,0,l_out_nc4par = .TRUE.)
     ELSE
        CALL ionc4_createfile(filsauvsed,lon2d,lat2d,limin,limax,1,          &
                              ljmin,ljmax,1,ksdmin,ksdmax,1,ksdmax,0)
     ENDIF

   ! save attribute of the spatial extension of the domain
   ! -----------------------------------------------------
     CALL ionc4_gatt(filsauvsed,'global_imin',imin)
     CALL ionc4_gatt(filsauvsed,'global_imax',imax)
     CALL ionc4_gatt(filsauvsed,'global_jmin',jmin)
     CALL ionc4_gatt(filsauvsed,'global_jmax',jmax)

   ! indispensable pour concatenation pas terrible a revoir
     CALL ionc4_createvar(filsauvsed,'SIG',' ','sigma variable',&
#if defined key_siggen || defined key_gencoord
                          standard_name= 'ocean_s_variable',&
#else
                          standard_name= 'ocean_sigma_variable',&
#endif
                          l_auxcoordinate=.false.,&
                          valid_min= -1.0_riosh,valid_max= 0.0_riosh,fill_value= rg_valmanq_io,&
                          dims= 'z', l_out_nc4par = l_out_nc4par)
     CALL ionc4_write_sig(filsauvsed,'SIG',sigsed,ksdmax)

     CALL ionc4_torigine(filsauvsed,date_ref)
     CALL ionc4_createvar(filsauvsed,'ksmi','s.o','ksmi',fill_value=rg_valmanq_io, &
                          dims='xyt',valid_min= 0.0_riosh,valid_max= 10.0_riosh,l_out_nc4par=l_out_nc4par)
     CALL ionc4_createvar(filsauvsed,'ksma','s.o','ksma',fill_value=rg_valmanq_io, &
                          dims='xyt',valid_min= 0.0_riosh,valid_max= 1000.0_riosh,l_out_nc4par=l_out_nc4par)
     CALL ionc4_createvar(filsauvsed,'dzsmax','s.o','ksma',fill_value=rg_valmanq_io, &
                          dims='xyt',valid_min=0.0_riosh,valid_max=1.0_riosh,l_out_nc4par=l_out_nc4par)
     CALL ionc4_createvar(filsauvsed,'dzs','m','dzs',fill_value=rg_valmanq_io, &
                          dims='zxyt',valid_min= 0.0_riosh,valid_max= 100.0_riosh,l_out_nc4par=l_out_nc4par)
     DO iv=-1,nv_adv     ! pour T et S
       IF (IV>0) WRITE(nomc,10) iv
       IF (iv==-1) nomc='concTEM'
       IF (iv==0) nomc='concSAL'
       CALL ionc4_createvar(filsauvsed,nomc,'u.s.i','concentration ',&
                            fill_value=rg_valmanq_io,dims='zxyt',l_out_nc4par=l_out_nc4par)
       IF (IV>0) WRITE(nomc,20) iv
       IF (iv==-1) nomc='fxw2sTEM'
       IF (iv==0) nomc='fxw2sSAL'
       CALL ionc4_createvar(filsauvsed,nomc,'u.s.i','flx_w2s ',&
                            fill_value=rg_valmanq_io,dims='xyt',l_out_nc4par=l_out_nc4par)
     END DO 
   ENDIF

   ! ecriture
   ! ********

   IF (t.GE.tsauv) THEN
     CALL ionc4_write_time(filsauvsed,1,t)
     DO j=ljmin,ljmax
       DO i=limin,limax
         xind(i,j)=REAL(ksmi(i,j))
       END DO
     END DO
     CALL ionc4_write_xyt(filsauvsed,'ksmi',xind,limin,limax,ljmin,ljmax,1,l_out_nc4par=l_out_nc4par)

     DO j=ljmin,ljmax
       DO i=limin,limax
         xind(i,j)=REAL(ksma(i,j))
       END DO
     END DO
     CALL ionc4_write_xyt(filsauvsed,'ksma',xind,limin,limax,ljmin,ljmax,1,l_out_nc4par=l_out_nc4par)
 
     DO j=ljmin,ljmax
       DO i=limin,limax
         xind(i,j)=REAL(dzsmax(i,j))
       END DO
     END DO
     CALL ionc4_write_xyt(filsauvsed,'dzsmax',xind,limin,limax,ljmin,ljmax,1,l_out_nc4par=l_out_nc4par)
 
     DO j = ljmin,ljmax
       DO i = limin,limax
         DO k = 1,ksdmax
           tlits(k,i,j) = dzs(k,i,j)
         END DO
       END DO
     END DO
     CALL ionc4_write_zxyt(filsauvsed,'dzs',tlits,limin,limax,ljmin,ljmax,ksdmin,ksdmax,1,l_out_nc4par=l_out_nc4par)

     DO iv=-1,nv_adv     ! pour T et S
       IF (IV>0) WRITE(nomc,10) iv
       IF (iv==-1) nomc='concTEM'
       IF (iv==0) nomc='concSAL'
       DO j = ljmin,ljmax
         DO i = limin,limax
           DO k = 1,ksdmax
             tlits(k,i,j) = cv_sed(iv,k,i,j)
           ENDDO
         ENDDO
       ENDDO
       CALL ionc4_write_zxyt(filsauvsed,nomc,tlits,limin,limax,ljmin,ljmax,ksdmin,ksdmax,1,l_out_nc4par=l_out_nc4par)
       IF (IV>0) WRITE(nomc,20) iv
       IF (iv==-1) nomc='fxw2sTEM'
       IF (iv==0) nomc='fxw2sSAL'
       DO j = ljmin,ljmax
         DO i = limin,limax
           xind(i,j) = flx_w2s(iv,i,j)
         ENDDO
       ENDDO
       CALL ionc4_write_xyt(filsauvsed,nomc,xind,limin,limax,ljmin,ljmax,1,l_out_nc4par=l_out_nc4par)       
     ENDDO
     tsauv=t+saverestart_step

     IF (l_saverestart_bydate) THEN
       CALL ionc4_close(filsauvsed)
     ELSE
       ! To write the data on the disk and not loose data in case of run crash
       CALL ionc4_sync(filsauvsed)
     ENDIF

   ENDIF

   10 FORMAT('concen',i2.2)
   20 FORMAT('flxw2s',i2.2)

   PRINT_DBG*, 'exit sed_outsaverestart'

  END SUBROUTINE sed_outsaverestart

  !!===========================================================================
 

#ifdef key_sedim_mudsand
!
      SUBROUTINE sed_comp_sedvel(porosi)
!
!     appele par consoldiff
!     calcule les vitesses de tassement dans le sediment
! **********************************************************************
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used

   !! * Arguments
   REAL(KIND=rsh), INTENT(IN) :: porosi

   !! * Local declarations

   !!---------------------------------------------------------------------------
   !! * Executable part

   IF (porosi >= poro1) THEN
     sed_sedimvel=xtas11*MIN(porosi,0.98_rsh)**xtas12
   ELSEIF(porosi >= poro2)THEN
     sed_sedimvel=xtas21*porosi**xtas22
   ELSEIF(porosi >= poro3)THEN
     sed_sedimvel=xtas31*porosi**xtas32
   ELSE
     sed_sedimvel=0.0_rsh
   ENDIF

  END SUBROUTINE sed_comp_sedvel

#endif

!!===========================================================================================
#ifdef key_sedim_mixsed
!
      SUBROUTINE sed_init_hsed(cv_sedini)
!
!     rinitialize sediment thickness, in order to be coherent with sediment parameters
!     function of cseduni, cvolmax, csed_ini of each sediment, 
! **********************************************************************
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nvp,nvpc,nv_state,nv_adv,irk_mod,nv_tot,irkm_var_assoc,  &
                            isand1,isand2,igrav1,igrav2,imud1,imud2


   !! * Arguments
   REAL(KIND=rsh), INTENT(IN),DIMENSION(nvpc) :: cv_sedini

   !! * Local declarations
   INTEGER        :: iv                
   REAL(KIND=rsh) :: dzsgrv,dzssan,dzsmud,voldepgrv,voldepsan,masdepmud,     &
                     dvolsan,dmasmud,dmasmudgrav,dmasmudsand

   !!---------------------------------------------------------------------------
   !! * Executable part

    
      !!! Volume a deposer
      voldepgrv=0.0_rsh
      voldepsan=0.0_rsh        
      DO iv=igrav1,igrav2
            voldepgrv=voldepgrv+cv_sedini(iv)/ros(iv)*hseduni  ! kg/m3 * m /(kg/m3)  (vol_g)
      ENDDO
      DO iv=isand1,isand2
            voldepsan=voldepsan+cv_sedini(iv)/ros(iv)*hseduni  ! kg/m3 * m /(kg/m3)  (vol_s)
      ENDDO

       !!! Masse a deposer
       masdepmud=0.0_rsh
       DO iv=imud1,imud2
            masdepmud=masdepmud+cv_sedini(iv)*hseduni  ! kg/m2  (m_v)
       ENDDO

       !!! nouvelle Couche de gravier
       IF(voldepgrv.GE.0.0_rsh)THEN
            dzsgrv=voldepgrv/cvolmaxsort
       ENDIF
    
       !!! Couche de sable
       IF(voldepsan.GE.0.0_rsh)THEN
         dvolsan=MIN(voldepsan,dzsgrv*(cvolmaxmel-cvolmaxsort)) ! volume de sable qui s insere dans le gravier (cvolmaxmel-cvolmaxsort)
         dzssan=MAX(0.,(voldepsan-dvolsan)/cvolmaxsort)
       ENDIF
    
       !!! Couche de vase
       IF(masdepmud.GE.0.0_rsh) THEN
            IF(dzsgrv >0.0_rsh .and. dzssan > 0.0_rsh) THEN
               ! melange sable+gravier  
               dmasmudgrav=dzsgrv*csed_mud_ini*(1.0_rsh-cvolmaxmel)  ! masse de vase qui s insere dans le gravier (1-cvolmaxmel)
               IF (isand2>isand1 ) THEN
                  dmasmudsand=dzssan*csed_mud_ini*(1.0_rsh-cvolmaxmel) ! masse de vase qui s insere dans le sable (1-cvolmaxsort)
               ELSE
                  dmasmudsand=dzssan*csed_mud_ini*(1.0_rsh-cvolmaxsort) ! masse de vase qui s insere dans le sable (1-cvolmaxsort)
               ENDIF
            ELSE IF (dzssan > 0.0_rsh .AND. isand2>isand1 ) THEN
               ! melange sables  
               dmasmudgrav=0.
               dmasmudsand=dzssan*csed_mud_ini*(1.0_rsh-cvolmaxmel) ! masse de vase qui s insere dans le sable (1-cvolmaxsort)
            ELSE IF(dzsgrv >0.0_rsh .AND. igrav2>igrav1 ) THEN
               ! melange graviers  
               dmasmudgrav=dzsgrv*csed_mud_ini*(1.0_rsh-cvolmaxmel)  ! masse de vase qui s insere dans le gravier (1-cvolmaxmel)
               dmasmudsand=0.
            ELSE
               ! un seul type de sediment 
               dmasmudgrav=dzsgrv*csed_mud_ini*(1.0_rsh-cvolmaxsort)  ! masse de vase qui s insere dans le gravier ou sable (1-cvolmaxsort)
               dmasmudsand=dzssan*csed_mud_ini*(1.0_rsh-cvolmaxsort) ! masse de vase qui s insere dans le sable (1-cvolmaxsort)
            ENDIF
         ! nouvelle couche de vase
         dzsmud=(masdepmud-dmasmudgrav-dmasmudsand)/csed_mud_ini
         IF(dzsmud <0.0_rsh) THEN
          dzsmud=0.0_rsh
          IF (masdepmud-dmasmudgrav < 0.0_rsh) THEN
             dmasmudgrav = masdepmud
             dmasmudsand = 0.0_rsh
          ELSE
             dmasmudsand = masdepmud-dmasmudgrav
          ENDIF
        ENDIF     
        dmasmud = dmasmudgrav +dmasmudsand
      ENDIF

      !!! Nouvelle Hauteur totale
      hsed_new = dzsgrv +dzssan +dzsmud

  END SUBROUTINE sed_init_hsed

#endif
!!===========================================================================================
#ifdef key_sedim_mixsed
!
      SUBROUTINE sed_coefbioturb(i,j,difbio)
!
!     Bioturbation in sediment
! **********************************************************************
   !&E
   !&E--------------------------------------------------------------------------
   !! * Modules used
   USE comsubstance, ONLY : nvpc,nvp,nv_adv,isand1,isand2,imud1,imud2,igrav1,igrav2

   !! * Arguments
   INTEGER, INTENT(IN) :: i,j
   REAL(KIND=rsh),DIMENSION(ksdmin:ksdmax,-1:nv_adv), INTENT(OUT)     :: difbio

   !! * Local declarations
   INTEGER        :: iv,k,ksmib                
   REAL(KIND=rsh) :: dsurf,somcgravsand,somcmud,coefdifbio,frmud

   !!---------------------------------------------------------------------------
   !! * Executable part

    hsed(i,j)=0.0_rsh
    DO k=ksmi(i,j),ksma(i,j)
      hsed(i,j)=hsed(i,j)+dzs(k,i,j)
      difbio(k,:)=0.0_rsh
    ENDDO   
    IF(hsed(i,j).lt.dbiotu0) THEN
     ksmib=ksma(i,j)
    ELSE
      dsurf=-dzs(ksma(i,j),i,j) ! evaluation de Db(k) a la limite superieure
      DO k=ksma(i,j),ksmi(i,j),-1
        dsurf=dsurf+dzs(k,i,j)
        IF(dsurf .GE. dbiotu0) THEN
          ksmib=k
          GOTO 11
        ENDIF
        !difbio dependent on mud fraction
        somcgravsand=0.0_rsh
        DO iv=igrav1,isand2
            somcgravsand=somcgravsand+cv_sed(iv,k,i,j)
        ENDDO
        somcmud=0.0_rsh
        DO iv=imud1,imud2
            somcmud=somcmud+cv_sed(iv,k,i,j)
        ENDDO
        frmud=somcmud/(somcgravsand+somcmud)
        IF(frmud < frmud_db_min) THEN
            coefdifbio=0.0_rsh
        ELSE IF(frmud > frmud_db_max) THEN
            coefdifbio=1.0_rsh
        ELSE
            coefdifbio=(frmud-frmud_db_min)/(frmud_db_max-frmud_db_min)
        ENDIF
        IF(dsurf .GE. dbiotum) THEN
          ! difbio=0 for gravels
          ! difbio same for sand, muds and dissolved variables here - to be changed furthermore ?
            coefdifbio=coefdifbio*EXP(-xbioturbk*(dsurf-dbiotum)/(dbiotu0-dbiotum))
        ENDIF
        difbio(k,isand1:nv_adv)=coefdifbio*xbioturbmax
        difbio(k,-1:0)=coefdifbio*xbioturbmax
      ENDDO    
      ksmib=1
    ENDIF
 11 DO k=ksmi(i,j),ksmib
        difbio(k,:)=0.0_rsh
    ENDDO
 
  END SUBROUTINE sed_coefbioturb

#endif

#endif

END MODULE sedimento
