!OPTIONS XOPT(HSFUN)
#ifdef RS6K
@PROCESS NOSTRICT
#endif
SUBROUTINE VDFMAIN    ( CDCONF, &
 & KIDIA  , KFDIA  , KLON   , KLEV   , KLEVS  , KSTEP  , KTILES , &
 & KTRAC  , KLEVSN , KLEVI  , KDHVTLS, KDHFTLS, KDHVTSS, KDHFTSS, &
 & KDHVTTS, KDHFTTS, KDHVTIS, KDHFTIS, &
 & PTSPHY , KTVL   , KTVH   , KCNT   , PCVL   , PCVH, &
 & PLAIL  , PLAIH  , PSIGFLT, &
 & PUM1   , PVM1   , PTM1   , PQM1   , PLM1   , PIM1   , PAM1   , PCM1   , &
 & PAPHM1 , PAPM1  , PGEOM1 , PGEOH  , PTSKM1M, PTSAM1M, PWSAM1M, &
 & PSSRFL , PSLRFL , PEMIS  , PHRLW  , PHRSW  , &
 & PTSNOW , PTICE  , &
 & PHLICE , PTLICE , PTLWML , &  
 & PSST   , KSOTY  , PLIT, PMELTSUM, PFRTI  , PALBTI , PWLMX  , &
 & PCHAR  , PUCURR , PVCURR ,PUSTOKES,PVSTOKES, PTSKRAD, PCFLX  , &
 & PSOTEU , PSOTEV , PSOBETA, &
 & PTHKICE, PSNTICE, &
 ! OUTPUT
 & PZ0M   , PZ0H   , &
 & PVDIS  , PVDISG , PDISGW3D, PAHFLEV, PAHFLSB, PFWSB  , PBIR   , PVAR   , &
 & PU10M  , PV10M  , PT2M   , PD2M   , PQ2M   , PZINV  , PBLH   , KHPBLN , &
 & P10NU  , P10NV  , PUST, &
 & PSSRFLTI,PEVAPSNW,PGUST  , PWUAVG , LDNODECP,KPBLTYPE,&
 ! OUTPUT TENDENCIES
 & PTE    , PQE    , PLE    , PIE    , PAE    , PVOM   , PVOL   , &
 & PTENC  , PTSKE1 , &
 ! UPDATED FIELDS FOR TILES
 & PUSTRTI, PVSTRTI, PAHFSTI, PEVAPTI, PTSKTI , &
 & PFLTRTI, &
 ! OUTPUT FLUXES
 & PDIFTS , PDIFTQ , PDIFTL , PDIFTI , PSTRTU , PSTRTV , PTOFDU , PTOFDV, &
 & PSTRSOU, PSTRSOV,   PKH  , &
 ! DDH OUTPUTS
 & PDHTLS , PDHTSS , PDHTTS , PDHTIS)

!***

!**   *VDFMAIN* - DOES THE VERTICAL EXCHANGE OF U,V,SLG,QT BY TURBULENCE.

!     J.F.GELEYN       20/04/82   Original  
!     C.A.BLONDIN      18/12/86
!     A.C.M. BELJAARS  20/10/89   IFS-VERSION (TECHNICAL REVISION OF CY34)
!     A.C.M. BELJAARS  26/03/90   OBUKHOV-L UPDATE 
!     A.C.M. BELJAARS  30/09/98   SURFACE TILES 
!     P. Viterbo       17/05/2000 Surface DDH for TILES
!     D. Salmond       15/10/2001 FULLIMP mods
!     S. Abdalla       27/11/2001 Passing Zi/L to waves
!     A. Beljaars       2/05/2003 New tile coupling     
!     P.Viterbo        24/05/2004 Change surface units
!     M. Ko"hler        3/12/2004 Moist Advection-Diffusion
!     A. Beljaars       4/04/2005 Turb. orogr. drag
!     A. Beljaars      30/09/2005 Include Subgr. Oro. in solver
!     A.Beljaars       31/03/2005 Introduction of ocean current b.c.
!     P. Viterbo       17/06/2005 surf external library
!     M. Ko"hler        6/06/2006 Single Column Model option (LSCMEC) 
!     G. Balsamo       15/01/2007 Soil type
!     A. Beljaars      27/02/2009 Delete PZIDLWV
!     G. Balsamo       07/04/2008 Lake model (FLAKE)
!     M. Janiskova/G. Balsamo 21/10/2008 Move VDFDIFH5 in VDFDIFH
!     M. Ko"hler/G. Modzinski     Bug correction in optimised qsat computation
!     P.de Rosnay/G.Balsamo   07/03/2009 Offline Jacobians EKF 
!     H. Hersbach   04-Dec-2009 10-m neutral wind and friction velocity
!     P.de Rosnay/G.Balsamo   October 2009 commented EKF (offline in callpar) 
!     S. Boussetta/G.Balsamo  May 2009 (Add variable LAI)
!     R. Forbes        15/03/2010 Changed fn(T) ice/liq split to prognostic
 
!     PURPOSE.
!     --------

!          THIS ROUTINE COMPUTES THE PHYSICAL TENDENCIES OF THE FOUR
!     PROGNOSTIC VARIABLES U,V,T AND Q DUE TO THE VERTICAL EXCHANGE BY
!     TURBULENT (= NON-MOIST CONVECTIVE) PROCESSES. THESE TENDENCIES ARE
!     OBTAINED AS THE DIFFERENCE BETWEEN THE RESULT OF AN IMPLICIT
!     TIME-STEP STARTING FROM VALUES AT T-1 AND THESE T-1 VALUES. ALL
!     THE DIAGNOSTIC COMPUTATIONS (EXCHANGE COEFFICIENTS, ...) ARE DONE
!      FROM THE T-1 VALUES. AS A BY-PRODUCT THE ROUGHNESS LENGTH OVER SEA
!     IS UPDATED ACCORDINGLY TO THE *CHARNOCK FORMULA. HEAT AND MOISTURE
!     SURFACE FLUXES AND THEIR DERIVATIVES AGAINST TS, WS AND WL
!     (THE LATTER WILL BE LATER WEIGHTED WITH THE SNOW FACTOR IN
!     *VDIFF*), LATER TO BE USED FOR SOIL PROCESSES TREATMENT, ARE ALSO
!     COMPUTED AS WELL AS A STABILITY VALUE TO BE USED AS A DIAGNOSTIC
!     OF THE DEPTH OF THE WELL MIXED LAYER IN CONVECTIVE COMPUTATIONS.

!     INTERFACE.
!     ----------
!          *VDIFF* TAKES THE MODEL VARIABLES AT T-1 AND RETURNS THE VALUES
!     FOR THE PROGNOSTIC TIME T+1 DUE TO VERTICAL DIFFUSION.
!     THE MODEL VARIABLES, THE MODEL DIMENSIONS AND THE DIAGNOSTICS DATA
!     ARE PASSED AS SUBROUTINE ARGUMENTS. CONSTANTS THAT DO NOT CHANGE
!     DURING A MODEL RUN (E.G. PHYSICAL CONSTANTS, SWITCHES ETC.) ARE
!     STORED IN A SINGLE COMMON BLOCK *YOMVDF*, WHICH IS INITIALIZED
!     BY SET-UP ROUTINE *SUVDF*.

!     PARAMETER     DESCRIPTION                                   UNITS
!     ---------     -----------                                   -----
!     INPUT PARAMETERS (INTEGER):

!    *KIDIA*        START POINT
!    *KFDIA*        END POINT
!    *KLEV*         NUMBER OF LEVELS
!    *KLON*         NUMBER OF GRID POINTS PER PACKET
!    *KLEVS*        NUMBER OF SOIL LAYERS
!    *KSTEP*        CURRENT TIME STEP INDEX
!    *KTILES*       NUMBER OF TILES (I.E. SUBGRID AREAS WITH DIFFERENT 
!                   OF SURFACE BOUNDARY CONDITION)
!    *KTRAC*        Number of tracers
!    *KLEVSN*       Number of snow layers (diagnostics) 
!    *KLEVI*        Number of sea ice layers (diagnostics)
!    *KDHVTLS*      Number of variables for individual tiles
!    *KDHFTLS*      Number of fluxes for individual tiles
!    *KDHVTSS*      Number of variables for snow energy budget
!    *KDHFTSS*      Number of fluxes for snow energy budget
!    *KDHVTTS*      Number of variables for soil energy budget
!    *KDHFTTS*      Number of fluxes for soil energy budget
!    *KDHVTIS*      Number of variables for sea ice energy budget
!    *KDHFTIS*      Number of fluxes for sea ice energy budget

!    *KTVL*         VEGETATION TYPE FOR LOW VEGETATION FRACTION
!    *KTVH*         VEGETATION TYPE FOR HIGH VEGETATION FRACTION
!    *KSOTY*        SOIL TYPE                                     (1-7)

!    *KCNT*         Index of vdf sub steps.

!     INPUT PARAMETERS (LOGICAL)

!     INPUT PARAMETERS (REAL)

!    *PTSPHY*       TIME STEP FOR THE PHYSICS

!     INPUT PARAMETERS AT T-1 OR CONSTANT IN TIME (REAL):

!    *PCVL*         LOW VEGETATION COVER                          -  
!    *PCVH*         HIGH VEGETATION COVER                         -  
!    *PLAIL*        LOW VEGETATION LAI                           m2/m2
!    *PLAIH*        HIGH VEGETATION LAI                          m2/m2
!    *PSIGFLT*      STANDARD DEVIATION OF FILTERED OROGRAPHY      M
!    *PUM1*         X-VELOCITY COMPONENT                          M/S
!    *PVM1*         Y-VELOCITY COMPONENT                          M/S
!    *PTM1*         TEMPERATURE                                   K
!    *PQM1*         SPECIFIC HUMIDITY                             KG/KG
!    *PLM1*         SPECIFIC CLOUD LIQUID WATER                   KG/KG
!    *PIM1*         SPECIFIC CLOUD ICE                            KG/KG
!    *PAM1*         CLOUD FRACTION                                1
!    *PCM1*         TRACER CONCENTRATION                          KG/KG
!    *PAPM1*        PRESSURE ON FULL LEVELS                       PA
!    *PAPHM1*       PRESSURE ON HALF LEVELS                       PA
!    *PGEOM1*       GEOPOTENTIAL                                  M2/S2
!    *PGEOH*        GEOPOTENTIAL AT HALF LEVELS                   M2/S2
!    *PTSKM1M*      SKIN TEMPERATURE                              K
!    *PTSAM1M*      SURFACE TEMPERATURE                           K
!    *PWSAM1M*      SOIL MOISTURE ALL LAYERS                      M**3/M**3
!    *PSSRFL*       NET SHORTWAVE RADIATION FLUX AT SURFACE       W/M2
!    *PSLRFL*       NET LONGWAVE RADIATION FLUX AT SURFACE        W/M2
!    *PEMIS*        MODEL SURFACE LONGWAVE EMISSIVITY
!    *PHRLW*        LONGWAVE HEATING RATE                         K/s
!    *PHRSW*        SHORTWAVE HEATING RATE                        K/s
!    *PTSNOW*       SNOW TEMPERATURE                              K
!    *PTICE*        ICE TEMPERATURE (TOP SLAB)                    K
!    *PHLICE*       LAKE ICE THICKNESS                            m
!    *PTLICE*       LAKE ICE TEMPERATURE                          K
!    *PTLWML*       LAKE MEAN WATER TEMPERATURE                   K
!    *PSST*         (OPEN) SEA SURFACE TEMPERATURE                K
!    *PFRTI*        TILE FRACTIONS                                (0-1)
!            1 : WATER                  5 : SNOW ON LOW-VEG+BARE-SOIL
!            2 : ICE                    6 : DRY SNOW-FREE HIGH-VEG
!            3 : WET SKIN               7 : SNOW UNDER HIGH-VEG
!            4 : DRY SNOW-FREE LOW-VEG  8 : BARE SOIL
!    *PALBTI*       BROADBAND ALBEDO FOR TILE FRACTIONS
!    *PWLMX*        MAXIMUM SKIN RESERVOIR CAPACITY               kg/m**2
!    *PCHAR*        "EQUIVALENT" CHARNOCK PARAMETER
!    *PUCURR*       OCEAN CURRENT X_COMPONENT      
!    *PVCURR*       OCEAN CURRENT Y_COMPONENT      
!    *PUSTOKES*     SURFACE STOKES VELOCITY X_COMPONENT
!    *PVSTOKES*     SURFACE STOKES VELOCITY Y_COMPONENT
!    *PTSKRAD*      SKIN TEMPERATURE OF LATEST FULL RADIATION
!                      TIMESTEP                                   K
!    *PCFLX*        TRACER SURFACE FLUX                           kg/(m2 s)
!    *PSOTEU*       Explicit part of U-tendency from subgrid orography scheme    
!    *PSOTEV*       Explicit part of V-tendency from subgrid orography scheme     
!    *PSOBETA*      Implicit part of subgrid orography 
!    *PTHKICE*      Sea ice thickness                             m
!    *PSNTICE*      Thickness of snow layer on sea ice            m

!     INPUT PARAMETERS (LOGICAL):

!     CONTRIBUTIONS TO BUDGETS (OUTPUT,REAL):

!    *PVDIS*        TURBULENT DISSIPATION                         W/M2
!    *PVDISG*        SUBGRID OROGRAPHY DISSIPATION                 W/M2
!    *PAHFLEV*      LATENT HEAT FLUX  (SNOW/ICE FREE PART)        W/M2
!    *PAHFLSB*      LATENT HEAT FLUX  (SNOW/ICE COVERED PART)     W/M2

!     UPDATED PARAMETERS (REAL):

!    *PTE*          TEMPERATURE TENDENCY                          K/S
!    *PQE*          MOISTURE TENDENCY                             KG/(KG S)
!    *PLE*          LIQUID WATER TENDENCY                         KG/(KG S)
!    *PIE*          ICE WATER TENDENCY                            KG/(KG S)
!    *PAE*          CLOUD FRACTION TENDENCY                       1/S)
!    *PVOM*         MERIODINAL VELOCITY TENDENCY (DU/DT)          M/S2
!    *PVOL*         LATITUDE TENDENCY            (DV/DT)          M/S2
!    *PTENC*        TRACER TENDENCY                               KG/(KG S)
!    *PTSKE1*       SKIN TEMPERATURE TENDENCY                     K/S
!    *PZ0M*         AERODYNAMIC ROUGHNESS LENGTH                  M
!    *PZ0H*         ROUGHNESS LENGTH FOR HEAT                     M

!     UPDATED PARAMETERS FOR TILES (REAL): 

!    *PUSTRTI*      SURFACE U-STRESS                              N/M2 
!    *PVSTRTI*      SURFACE V-STRESS                              N/M2
!    *PAHFSTI*      SURFACE SENSIBLE HEAT FLUX                    W/M2
!    *PEVAPTI*      SURFACE MOISTURE FLUX                         KG/M2/S
!    *PTSKTI*       SKIN TEMPERATURE                              K
!    *PFLTRTI*      SURFACE LONGWAVE RADIATION

!     OUTPUT PARAMETERS (REAL):

!    *PFWSB*        EVAPORATION OF SNOW                           KG/(M**2*S)
!    *PU10M*        U-COMPONENT WIND AT 10 M                      M/S
!    *PV10M*        V-COMPONENT WIND AT 10 M                      M/S
!    *P10NU*        U-COMPONENT NEUTRAL WIND AT 10 M              M/S
!    *P10NV*        V-COMPONENT NEUTRAL WIND AT 10 M              M/S
!    *PUST*         FRICTION VELOCITY                             M/S
!    *PT2M*         TEMPERATURE AT 2M                             K
!    *PD2M*         DEW POINT TEMPERATURE AT 2M                   K
!    *PQ2M*         SPECIFIC HUMIDITY AT 2M                       KG/KG
!    *PGUST*        GUST AT 10 M                                  M/S
!    *PBLH*         PBL HEIGHT (dry diagnostic based on Ri#)      M
!    *PZINV*        PBL HEIGHT (moist parcel, not for stable PBL) M
!    *PSSRFLTI*     NET SHORTWAVE RADIATION FLUX AT SURFACE, FOR
!                      EACH TILE                                  W/M2
!    *PEVAPSNW*     EVAPORATION FROM SNOW UNDER FOREST            KG/(M2*S)
!    *PSTRTU*       TURBULENT FLUX OF U-MOMEMTUM            KG*(M/S)/(M2*S)
!    *PSTRTV*       TURBULENT FLUX OF V-MOMEMTUM            KG*(M/S)/(M2*S)
!    *PTOFDU*       TOFD COMP. OF TURBULENT FLUX OF U-MOMEMTUM   KG*(M/S)/(M2*S)
!    *PTOFDV*       TOFD COMP. OF TURBULENT FLUX OF V-MOMEMTUM   KG*(M/S)/(M2*S)
!    *PDIFTS*       TURBULENT FLUX OF HEAT                         J/(M2*S)
!    *PDIFTQ*       TURBULENT FLUX OF SPECIFIC HUMIDITY           KG/(M2*S)
!    *PDIFTL*       TURBULENT FLUX OF LIQUID WATER                KG/(M2*S)
!    *PDIFTI*       TURBULENT FLUX OF ICE WATER                   KG/(M2*S)
!    *PSTRSOU*      SUBGRID OROGRAPHY FLUX OF U-MOMEMTUM    KG*(M/S)/(M2*S)
!    *PSTRSOV*      SUBGRID OROGRAPHY FLUX OF V-MOMEMTUM    KG*(M/S)/(M2*S)

!    *PKH*          TURB. DIFF. COEFF. FOR HEAT ABOVE SURF. LAY.  (M2/S)
!                   IN SURFACE LAYER: CH*U                        (M/S)
!    *PDHTLS*       Diagnostic array for tiles (see module yomcdh)
!                      (Wm-2 for energy fluxes, kg/(m2s) for water fluxes)
!    *PDHTSS*       Diagnostic array for snow T (see module yomcdh)
!                      (Wm-2 for fluxes)
!    *PDHTTS*       Diagnostic array for soil T (see module yomcdh)
!                      (Wm-2 for fluxes)
!    *PDHTIS*       Diagnostic array for ice T (see module yomcdh)
!                      (Wm-2 for fluxes)

!     Additional parameters for flux boundary condition (in SCM model):

!    *LSFCFLX*      If .TRUE. flux boundary condtion is used 
!    *REXTSHF*      Specified sensible heat flux [W/m2]
!    *REXTLHF*      Specified latent heat flux [W/m2]

!     METHOD.
!     -------

!          FIRST AN AUXIALIARY VARIABLE CP(Q)T+GZ IS CREATED ON WHICH
!     THE VERTICAL DIFFUSION PROCESS WILL WORK LIKE ON U,V AND Q. THEN
!     ALONG THE VERTICAL AND AT THE SURFACE, EXCHANGE COEFFICIENTS (WITH
!     THE DIMENSION OF A PRESSURE THICKNESS) ARE COMPUTED FOR MOMENTUM
!     AND FOR HEAT (SENSIBLE PLUS LATENT). THE LETTERS M AND H ARE USED
!     TO DISTINGUISH THEM AND THE COMPUTATION IS THE RESULT OF A
!     CONDITIONAL MERGE BETWEEN THE STABLE AND THE UNSTABLE CASE
!     (DEPENDING ON THE SIGN OF THE *RICHARDSON BULK NUMBER).
!          IN THE SECOND PART OF THE ROUTINE THE IMPLICIT LINEAR
!     SYSTEMS FOR U,V FIRST AND T,Q SECOND ARE SOLVED BY A *GAUSSIAN
!     ELIMINATION BACK-SUBSTITUTION METHOD. FOR T AND Q THE LOWER
!     BOUNDARY CONDITION DEPENDS ON THE SURFACE STATE.
!     OVER LAND, TWO DIFFERENT REGIMES OF EVAPORATION PREVAIL:
!     A STOMATAL RESISTANCE DEPENDENT ONE OVER THE VEGETATED PART
!     AND A SOIL RELATIVE HUMIDITY DEPENDENT ONE OVER THE
!     BARE SOIL PART OF THE GRID MESH.
!     POTENTIAL EVAPORATION TAKES PLACE OVER THE SEA, THE SNOW
!     COVERED PART AND THE LIQUID WATER COVERED PART OF THE
!     GRID MESH AS WELL AS IN CASE OF DEW DEPOSITION.
!          FINALLY ONE RETURNS TO THE VARIABLE TEMPERATURE TO COMPUTE
!     ITS TENDENCY AND THE LATER IS MODIFIED BY THE DISSIPATION'S EFFECT
!     (ONE ASSUMES NO STORAGE IN THE TURBULENT KINETIC ENERGY RANGE) AND
!     THE EFFECT OF MOISTURE DIFFUSION ON CP. Z0 IS UPDATED AND THE
!     SURFACE FLUXES OF T AND Q AND THEIR DERIVATIVES ARE PREPARED AND
!     STORED LIKE THE DIFFERENCE BETWEEN THE IMPLICITELY OBTAINED
!     CP(Q)T+GZ AND CP(Q)T AT THE SURFACE.

!     EXTERNALS.
!     ----------

!     *VDFMAIN* CALLS SUCESSIVELY:
!         *SURFEXCDRIVER*
!         *VDFEXCU*
!         *VDFTOFDC*
!         *VDFDIFM*
!         *VDFDIFH*
!         *VDFDIFC*
!         *VDFINCR*
!         *VDFSDRV*
!         *VDFPPCFL*
!         *VDFUPDZ0*

!     REFERENCE.
!     ----------

!          SEE VERTICAL DIFFUSION'S PART OF THE MODEL'S DOCUMENTATION
!     FOR DETAILS ABOUT THE MATHEMATICS OF THIS ROUTINE.

!     ------------------------------------------------------------------

USE PARKIND1  ,ONLY : JPIM     ,JPRB
USE YOMHOOK   ,ONLY : LHOOK    ,DR_HOOK

USE YOMCT0   , ONLY : LSCMEC   ,LSFCFLX  ,REXTSHF  ,REXTLHF
USE YOEVDF   , ONLY : RVDIFTS
USE YOMCST   , ONLY : RG       ,RD       ,&
                    & RCPD     ,RETV     ,RLVTT    ,RLSTT    ,RTT 
USE YOETHF   , ONLY : R2ES     ,R3LES    ,R3IES    ,R4LES    ,&
                    & R4IES    ,R5LES    ,R5IES    ,RVTMP2   ,R5ALVCP  ,&
                    & R5ALSCP  ,RALVDCP  ,RALSDCP  ,RTWAT    ,RTICE    ,&
                    & RTICECU  ,RTWAT_RTICE_R      ,RTWAT_RTICECU_R  
USE YOMJFH   , ONLY : N_VMASS
USE YOEPHY   , ONLY : LVDFTRAC 
!USE YOMSEKF  , ONLY : N_SEKF_PT, LUSEKF_REF, LUSE_JATM
USE YOECLDP  , ONLY : NCLDTOP, RLMIN

IMPLICIT NONE


!*         0.1    GLOBAL VARIABLES

INTEGER(KIND=JPIM),INTENT(IN)    :: KLON 
INTEGER(KIND=JPIM),INTENT(IN)    :: KLEV 
INTEGER(KIND=JPIM),INTENT(IN)    :: KLEVS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KTILES 
INTEGER(KIND=JPIM),INTENT(IN)    :: KTRAC
INTEGER(KIND=JPIM),INTENT(IN)    :: KLEVSN 
INTEGER(KIND=JPIM),INTENT(IN)    :: KLEVI 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHVTLS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHFTLS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHVTSS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHFTSS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHVTTS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHFTTS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHVTIS 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDHFTIS 
CHARACTER(LEN=1)  ,INTENT(IN)    :: CDCONF 
INTEGER(KIND=JPIM),INTENT(IN)    :: KIDIA
INTEGER(KIND=JPIM),INTENT(IN)    :: KFDIA
INTEGER(KIND=JPIM),INTENT(IN)    :: KSTEP 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTSPHY 
INTEGER(KIND=JPIM),INTENT(IN)    :: KTVL(KLON) 
INTEGER(KIND=JPIM),INTENT(IN)    :: KTVH(KLON) 
INTEGER(KIND=JPIM),INTENT(IN)    :: KSOTY(KLON) 
INTEGER(KIND=JPIM),INTENT(IN)    :: KCNT
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLIT(KLON)
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PMELTSUM(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PCVL(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PCVH(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLAIL(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLAIH(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSIGFLT(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PUM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PVM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PQM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PIM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PAM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PCM1(KLON,KLEV,KTRAC) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PAPHM1(KLON,0:KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PAPM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PGEOM1(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PGEOH(KLON,0:KLEV)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTSKM1M(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTSAM1M(KLON,KLEVS) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PWSAM1M(KLON,KLEVS) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSSRFL(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSLRFL(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PEMIS(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PHRLW(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PHRSW(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTSNOW(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTICE(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PHLICE(KLON)  
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTLICE(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTLWML(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSST(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PFRTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PALBTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PWLMX(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PCHAR(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PUCURR(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PVCURR(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PUSTOKES(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PVSTOKES(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTSKRAD(KLON) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PCFLX(KLON,KTRAC)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSOTEU(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSOTEV(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSOBETA(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PTHKICE(KLON)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PSNTICE(KLON)
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PZ0M(KLON) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PZ0H(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PVDIS(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PVDISG(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDISGW3D(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PAHFLEV(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PAHFLSB(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PFWSB(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PBIR(KLON)
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PVAR(KLON,KLEV)
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PU10M(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PV10M(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: P10NU(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: P10NV(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PUST(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PT2M(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PD2M(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PQ2M(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PZINV(KLON)
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PBLH(KLON) 
INTEGER(KIND=JPIM),INTENT(OUT)   :: KHPBLN(KLON)
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PSSRFLTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PEVAPSNW(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PGUST(KLON) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PWUAVG(KLON)
LOGICAL           ,INTENT(IN)    :: LDNODECP(KLON)
INTEGER(KIND=JPIM),INTENT(OUT)   :: KPBLTYPE(KLON)
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PTE(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PQE(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PLE(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PIE(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PAE(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PVOM(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PVOL(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PTENC(KLON,KLEV,KTRAC)
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PTSKE1(KLON) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PUSTRTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PVSTRTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PAHFSTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PEVAPTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PTSKTI(KLON,KTILES) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PFLTRTI(KLON,KTILES)
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDIFTS(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDIFTQ(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDIFTL(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDIFTI(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PSTRTU(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PSTRTV(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PTOFDU(KLON) 
REAL(KIND=JPRB)   ,INTENT(INOUT) :: PTOFDV(KLON)
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PSTRSOU(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PSTRSOV(KLON,0:KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PKH(KLON,KLEV) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDHTLS(KLON,KTILES,KDHVTLS+KDHFTLS) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDHTSS(KLON,KLEVSN,KDHVTSS+KDHFTSS) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDHTTS(KLON,KLEVS,KDHVTTS+KDHFTTS) 
REAL(KIND=JPRB)   ,INTENT(OUT)   :: PDHTIS(KLON,KLEVI,KDHVTIS+KDHFTIS) 

!*         0.2    LOCAL VARIABLES

INTEGER(KIND=JPIM), PARAMETER :: IDRAFT = 2    ! # of mass-flux up/down drafts

REAL(KIND=JPRB) ::    ZDIFTQT(KLON,0:KLEV), ZDIFTSLG(KLON,0:KLEV) 

REAL(KIND=JPRB) ::    ZCPTGZ(KLON,KLEV) , ZCFM(KLON,KLEV)   , ZCFH(KLON,KLEV)   ,&
                    & ZUDIF(KLON,KLEV)  , ZVDIF(KLON,KLEV)  ,&
                    & ZQTDIF(KLON,KLEV) , ZSLGDIF(KLON,KLEV),&
                    & ZSLGM1(KLON,KLEV) , ZQTM1(KLON,KLEV)  , ZQTE(KLON,KLEV)   ,&
                    & ZSLGE(KLON,KLEV)  , ZTOFDC(KLON,KLEV) , ZSOC(KLON,KLEV)
REAL(KIND=JPRB) ::    ZKHFL(KLON)       , ZKQFL(KLON)       , ZKMFL(KLON)  
REAL(KIND=JPRB) ::    ZQEA(KLON,KLEV)   , ZLEA(KLON,KLEV)   , ZIEA(KLON,KLEV)   ,&
                    & ZQTEA(KLON,KLEV)  , ZSLGEA(KLON,KLEV) ,                    &
                    & ZSLGEWODIS(KLON,KLEV)  
REAL(KIND=JPRB) ::    ZZ0MW(KLON)       , ZZ0HW(KLON)       , ZZ0QW(KLON)       ,&
                    & ZBLEND(KLON)      , ZFBLEND(KLON)
REAL(KIND=JPRB) ::    ZZCPTS(KLON)      , ZZQSA(KLON)       , ZZBUOM(KLON)      ,&
                    & ZZZDL(KLON)
REAL(KIND=JPRB) ::    ZTUPD(KLON,KLEV)  , ZQUPD(KLON,KLEV)  , ZLUPD(KLON,KLEV)  ,&
                    & ZIUPD(KLON,KLEV)  , ZQTUPD(KLON,KLEV) , ZLIUPD(KLON,KLEV) ,&
                    & ZSLGUPD(KLON,KLEV), ZLFRAC(KLON,KLEV)  
REAL(KIND=JPRB) ::    ZTINI(KLON,KLEV)  , ZQINI(KLON,KLEV)  , ZLINI(KLON,KLEV)  ,&
                    & ZIINI(KLON,KLEV)  , ZAINI(KLON,KLEV)  
REAL(KIND=JPRB) ::    ZVARGEN           , ZTAU(KLON)        ,&
                    & ZQSVAR(KLON,KLEV) , ZANEW(KLON,KLEV)  , ZLNEW(KLON,KLEV)  
REAL(KIND=JPRB) ::    ZSVFLUXCLD(KLON,0:KLEV)               , ZSVFLUXSUB(KLON,0:KLEV),&
                    & ZSVFLUX(KLON,0:KLEV),ZBUOYPOS(KLON)   , ZBUOYNEG(KLON)    ,&
                    & ZDZH(KLON,0:KLEV)
REAL(KIND=JPRB) ::    ZALFA1            , ZALFA2            , ZDELQ(KLON,KLEV)  ,&
                    & ZCORQS(KLON,KLEV) , ZDQSDTEMP(KLON,KLEV)
REAL(KIND=JPRB) ::    ZMFLX(KLON,0:KLEV,IDRAFT)             , ZQTUH(KLON,0:KLEV,IDRAFT),&
                    & ZSLGUH(KLON,0:KLEV,IDRAFT)            , ZCLDBASE(KLON)
REAL(KIND=JPRB) ::    ZEXTSHF(KLON)     , ZEXTLHF(KLON)

REAL(KIND=JPRB) ::    ZCPTSTI(KLON,KTILES), ZQSTI(KLON,KTILES)  ,&
                    & ZDQSTI(KLON,KTILES) , ZCSATTI(KLON,KTILES),&
                    & ZCAIRTI(KLON,KTILES), ZCFHTI(KLON,KTILES) ,&
                    & ZCFQTI(KLON,KTILES) , ZAHFLTI(KLON,KTILES),&
                    & ZTSKTIP1(KLON,KTILES)
REAL(KIND=JPRB) ::    ZSTR(KLON,KTILES)   , ZG0(KLON,KTILES)

LOGICAL ::            LLRUNDRY(KLON)

INTEGER(KIND=JPIM) :: ITOP, JD, JK, JL, ILEV

REAL(KIND=JPRB) ::    ZGDPH, ZRHO, ZTMST, ZRG, ZRTMST
LOGICAL ::            LLSFCFLX
REAL(KIND=JPRB) ::    ZHU1
REAL(KIND=JPRB) ::    ZALFAW(KLON,KLEV), ZFACW, ZFACI, ZFAC, ZESDP, ZCOR
REAL(KIND=JPRB) ::    ZZQUPD, ZZLUPD, ZZIUPD, ZZTUPD, ZZAUPD
REAL(KIND=JPRB) ::    ZHOOK_HANDLE

INTERFACE
#include "surfexcdriver.h"
#include "surfpp.h"
END INTERFACE

#include "cloudvar.intfb.h"
#include "cover.intfb.h"
#include "vdfdifh.intfb.h"
#include "vdfdifm.intfb.h"
#include "vdfdifc.intfb.h"
#include "vdfdpbl.intfb.h"
#include "vdfexcu.intfb.h"
#include "vdfhghtn.intfb.h"
#include "vdfincr.intfb.h"
#include "vdffblend.intfb.h"
#include "vdftofdc.intfb.h"

#include "fcttre.h"


!     ------------------------------------------------------------------

!*         1.     INITIALIZE CONSTANTS
!                 --------------------

IF (LHOOK) CALL DR_HOOK('VDFMAIN',0,ZHOOK_HANDLE)

ZTMST       = PTSPHY
ZRTMST      = 1.0_JPRB/PTSPHY    ! optimization
ZRG         = 1.0_JPRB/RG        !     -"-
LLRUNDRY(:) = .FALSE.  ! option to run dry updrafts with no condensation
!DO JL=KIDIA,KFDIA
! IF ( .NOT. LDNODECP(JL) )  LLRUNDRY(JL) = .TRUE. ! run dry for real vdfmain's
! IF ( .NOT. LDNODECP(JL) )  PBIR(JL) = 1.0        ! always decouple for real vdfmain's
!ENDDO

!IF (.NOT.LUSEKF_REF.OR.LUSE_JATM.OR.N_SEKF_PT==0) THEN
!Coupled surface
  ILEV=1 
!ELSEIF (N_SEKF_PT>0) THEN
!! Offline surface for EKF surface analysis
!  ILEV=KLEV !loop calculation only on lowest model level 
!ENDIF


!*         1.0  SCM: Fixed fluxes for flux boundary condition ([W/m^2] downward)

IF (LSCMEC) THEN
  LLSFCFLX   = LSFCFLX   ! scm namelist parameters
  ZEXTSHF(:) = REXTSHF
  ZEXTLHF(:) = REXTLHF
ELSE
  LLSFCFLX   = .FALSE.
  ZEXTSHF(:) = 0.0_JPRB
  ZEXTLHF(:) = 0.0_JPRB
ENDIF


!*         1.1  Store initial tendencies for flux calculation
!*              and initialize variable.

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZQEA(JL,JK)=PQE(JL,JK)
    ZLEA(JL,JK)=PLE(JL,JK)
    ZIEA(JL,JK)=PIE(JL,JK)
  ENDDO
ENDDO

DO JD=1,IDRAFT
  DO JK=ILEV-1,KLEV
    DO JL=KIDIA,KFDIA
      ZMFLX (JL,JK,JD) = 0.0_JPRB
      ZSLGUH(JL,JK,JD) = 0.0_JPRB
      ZQTUH (JL,JK,JD) = 0.0_JPRB
    ENDDO
  ENDDO
ENDDO

!*         1.2  dry static energy cp(q)*T + gz

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZCPTGZ(JL,JK)  =PGEOM1(JL,JK)+PTM1(JL,JK)*RCPD*(1.0_JPRB+RVTMP2*PQM1(JL,JK))
  ENDDO
ENDDO

!*         2.  Compute all surface related quantities
!          ------------------------------------------

CALL SURFEXCDRIVER(CDCONF=CDCONF, &
 & KIDIA=KIDIA, KFDIA=KFDIA, KLON=KLON, KLEVS=KLEVS, KTILES=KTILES, KSTEP=KSTEP, &
 & KLEVSN=KLEVSN, KLEVI=KLEVI, KDHVTLS=KDHVTLS, KDHFTLS=KDHFTLS, &
 & KDHVTSS=KDHVTSS, KDHFTSS=KDHFTSS, KDHVTTS=KDHVTTS, KDHFTTS=KDHFTTS, &
 & KDHVTIS=KDHVTIS, KDHFTIS=KDHFTIS, K_VMASS=N_VMASS, &
 & PTSTEP=PTSPHY, PRVDIFTS=RVDIFTS, &
! input data, non-tiled
 & KTVL=KTVL, KTVH=KTVH, PCVL=PCVL, PCVH=PCVH, &
 & PLAIL=PLAIL, PLAIH=PLAIH, &
 & PUMLEV=PUM1(:,KLEV), PVMLEV=PVM1(:,KLEV), PTMLEV=PTM1(:,KLEV), &
 & PQMLEV=PQM1(:,KLEV), PAPHMS=PAPHM1(:,KLEV), PGEOMLEV=PGEOM1(:,KLEV), &
 & PCPTGZLEV=ZCPTGZ(:,KLEV), PSST=PSST, PTSKM1M=PTSKM1M, PCHAR=PCHAR, &
 & PSSRFL=PSSRFL, PSLRFL=PSLRFL, PEMIS=PEMIS, PTICE=PTICE, PTSNOW=PTSNOW, &
 & PHLICE=PHLICE,PTLICE=PTLICE,PTLWML=PTLWML, & 
 & PTHKICE=PTHKICE,PSNTICE=PSNTICE, &
 & PWLMX=PWLMX, PUCURR=PUCURR, PVCURR=PVCURR, &
! input data, soil
 & PTSAM1M=PTSAM1M, PWSAM1M=PWSAM1M, KSOTY=KSOTY, PLIT=PLIT, PMELTSUM=PMELTSUM, &
! input data, tiled
 & PFRTI=PFRTI, PALBTI=PALBTI, &
! updated data, tiled
 & PUSTRTI=PUSTRTI, PVSTRTI=PVSTRTI, PAHFSTI=PAHFSTI, PEVAPTI=PEVAPTI, &
 & PTSKTI=PTSKTI, &
! updated data, non-tiled
 & PZ0M=PZ0M, PZ0H=PZ0H, &
! output data, tiled
 & PSSRFLTI=PSSRFLTI, PQSTI=ZQSTI, PDQSTI=ZDQSTI, PCPTSTI=ZCPTSTI, &
 & PCFHTI=ZCFHTI, PCFQTI=ZCFQTI, PCSATTI=ZCSATTI, PCAIRTI=ZCAIRTI, &
! output data, non-tiled
 & PKHLEV=PKH(:,KLEV), PCFMLEV=ZCFM(:,KLEV), PKMFL=ZKMFL, PKHFL=ZKHFL, &
 & PKQFL=ZKQFL, PEVAPSNW=PEVAPSNW, PZ0MW=ZZ0MW, PZ0HW=ZZ0HW, PZ0QW=ZZ0QW, &
 & PBLENDPP=ZBLEND, PCPTSPP=ZZCPTS, PQSAPP=ZZQSA, PBUOMPP=ZZBUOM, &
 & PZDLPP=ZZZDL, &
! output data, diagnostics
 & PDHTLS=PDHTLS, PDHTSS=PDHTSS, PDHTTS=PDHTTS, PDHTIS=PDHTIS &
 & )


!     ------------------------------------------------------------------

!*         3.     NEW VARIABLES S, SLG, QT
!*                (at initial time level)
!                 ------------------------

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA

!*             total water and generalized liquid water static energy 
!*              slg = cp*T + gz - Lcond*ql - Ldep*qi

    ZSLGM1(JL,JK) = ZCPTGZ(JL,JK) - RLVTT * PLM1(JL,JK) - RLSTT * PIM1(JL,JK)
    ZSLGE(JL,JK)  = RCPD * ( ( 1.0_JPRB + RVTMP2 * PQM1(JL,JK) ) * PTE(JL,JK) &!dcpT/dt
                & + RVTMP2 * PTM1(JL,JK)   * PQE(JL,JK) ) &                    !  -"-
                & - RLVTT * PLE(JL,JK) - RLSTT * PIE(JL,JK)                    !dLqli/dt  
    ZQTM1(JL,JK ) = PQM1(JL,JK) + PLM1(JL,JK) + PIM1(JL,JK)
    ZQTE(JL,JK)   = PQE(JL,JK)  + PLE(JL,JK)  + PIE(JL,JK)             !dyn. qt tendency
    ZSLGEA(JL,JK) = ZSLGE(JL,JK)
    ZQTEA(JL,JK)  = ZQTE(JL,JK)
  ENDDO
ENDDO


!     ------------------------------------------------------------------
 
!*         4.     CALCULATE QT VARIANCE AFTER DYN+RAD (for var. equ.)
!*                AND CONSISTENT T, QV, QL, QI AND CLOUD FRACTION
!*                (for tendency calculation at end) 
!                 ---------------------------------------------------

!*         4.0  state after dynamics and radiation

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZLUPD(JL,JK)  = PLM1(JL,JK) + PLE(JL,JK) * ZTMST
    ZIUPD(JL,JK)  = PIM1(JL,JK) + PIE(JL,JK) * ZTMST
!          total condensate 
    ZLIUPD(JL,JK) = ZLUPD(JL,JK) + ZIUPD(JL,JK)
  ENDDO
ENDDO
DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZQUPD(JL,JK)  = PQM1(JL,JK) + PQE(JL,JK) * ZTMST
    ZTUPD(JL,JK)  = PTM1(JL,JK) + PTE(JL,JK) * ZTMST
    ! Store fraction of condensate that is liquid
    IF (ZLIUPD(JL,JK) > RLMIN) THEN
      ZLFRAC(JL,JK) = MAX(MIN(ZLUPD(JL,JK)/ZLIUPD(JL,JK),1.0_JPRB),0.0_JPRB)
    ELSE
      ZLFRAC(JL,JK) = 1.0_JPRB
    ENDIF
  ENDDO
ENDDO


!*         4.1  qsat, dqsat/dT and alfa (= liquid fraction)
!*              (after dyn+rad, kept constant through vdfmain)

DO JK=1,KLEV
  DO JL=KIDIA,KFDIA
    ZESDP=FOEEWM(ZTUPD(JL,JK))/PAPM1(JL,JK)
    ZQSVAR(JL,JK) = MIN(0.5_JPRB,ZESDP)
    ZQSVAR(JL,JK) = ZQSVAR(JL,JK)/(1.0_JPRB-RETV*ZQSVAR(JL,JK))
    ZQSVAR(JL,JK) = MAX(ZQSVAR(JL,JK),ZQUPD(JL,JK)) !don't allow input supersat.
!          dqsat/dT correction factor (1+L/cp*dqsat/dT) & alfa
    ZALFAW(JL,JK)=FOEALFA(ZTUPD(JL,JK))
    ZFACW=R5LES/((ZTUPD(JL,JK)-R4LES)**2)
    ZFACI=R5IES/((ZTUPD(JL,JK)-R4IES)**2)
    ZFAC=ZALFAW(JL,JK)*ZFACW+(1.0_JPRB-ZALFAW(JL,JK))*ZFACI
    ZCOR=1.0_JPRB/(1.0_JPRB-RETV*ZESDP)
    ZDQSDTEMP(JL,JK)=ZFAC*ZCOR*ZQSVAR(JL,JK)  !dqsat/dT
    ZCORQS(JL,JK)=1.0_JPRB/MAX(1.0_JPRB,1.0_JPRB+FOELDCPM(ZTUPD(JL,JK))*ZDQSDTEMP(JL,JK))
  ENDDO
ENDDO

!IF (.NOT.LUSEKF_REF.OR.LUSE_JATM.OR.N_SEKF_PT==0) THEN
! Coupled surface

!*         4.2  diagnose total water variance
!*              (qv, ql+qi, qsat -> variance;  cloud fraction ignored)

IF ( KCNT == 1 ) THEN  ! prognostic qt variance within vdf interations
  CALL CLOUDVAR &
!---input
 & ( KIDIA, KFDIA, KLON  , KLEV  , 1    , KLEV, &
 &   ZQUPD, ZQSVAR, ZLIUPD, &
!---output
 &   PVAR , ZANEW, ZLNEW ) !last two are dummy args  
ENDIF


!*         4.3  diagnose cloud fraction and T, qv, ql, qi
!*              (T, qv, ql qi should be approximately unchanged;
!*              zdelq ~ 0)  

!          From total water and its variance calculate 
!          cloud cover (zanew) and conversion of qv to qc (zdelq).

CALL COVER &
!---input
 & ( KIDIA, KFDIA , KLON  , KLEV , NCLDTOP, KLEV, &
 &   ZQUPD, ZQSVAR, ZLIUPD, PVAR   , &
!---output
 &   ZLNEW, ZANEW )

!          Add modifications to estimate of initial state.

DO JK=1,NCLDTOP-1
  DO JL=KIDIA,KFDIA
    ZDELQ(JL,JK)  = 0.00_JPRB
    ZANEW(JL,JK)  = 0.00_JPRB
  ENDDO
ENDDO
DO JK=NCLDTOP,KLEV
  DO JL=KIDIA,KFDIA
    ZDELQ(JL,JK)  = ( ZLNEW(JL,JK) - ZLIUPD(JL,JK) ) * ZCORQS(JL,JK)
  ENDDO
ENDDO

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZQINI(JL,JK) = ZQUPD(JL,JK) -                            ZDELQ(JL,JK)
    ! In new scheme, prognostic fraction of liquid/ice retained
    ! fn(T) form no longer used
    ZLINI(JL,JK) = ZLUPD(JL,JK) +       ZLFRAC(JL,JK)      * ZDELQ(JL,JK)
    ZIINI(JL,JK) = ZIUPD(JL,JK) + ( 1.0_JPRB - ZLFRAC(JL,JK)) * ZDELQ(JL,JK)
    ZTINI(JL,JK) = ZTUPD(JL,JK) + &
      & ( ZLFRAC(JL,JK)*RALVDCP+(1.0_JPRB-ZLFRAC(JL,JK))*RALSDCP ) &
      &                                                       * ZDELQ(JL,JK)
    ZAINI(JL,JK) = ZANEW(JL,JK)
!    ZLINI(JL,JK) = ZLUPD(JL,JK) +       ZALFAW(JL,JK)      * ZDELQ(JL,JK)
!    ZIINI(JL,JK) = ZIUPD(JL,JK) + ( 1.0_JPRB - ZALFAW(JL,JK)) * ZDELQ(JL,JK)
!    ZTINI(JL,JK) = ZTUPD(JL,JK) + &
!      & ( ZALFAW(JL,JK)*RALVDCP+(1.0_JPRB-ZALFAW(JL,JK))*RALSDCP ) &
!      & * ZDELQ(JL,JK)
  ENDDO
ENDDO

!     ------------------------------------------------------------------

!*         5.     EXCHANGE COEFFICIENTS
!                 ---------------------

!*         5.4  COMPUTATION OF THE PBL EXTENSION

!          SET PBL HEIGHT-INDEX TO 1

DO JL=KIDIA,KFDIA
  KHPBLN(JL)=1
ENDDO
ITOP=1

!          FLUX BOUNDARY CONDITION
IF (LLSFCFLX) THEN
  DO JL=KIDIA,KFDIA
    ZRHO = PAPHM1(JL,KLEV)/( RD*PTM1(JL,KLEV)*(1.0_JPRB+RETV*PQM1(JL,KLEV)) )
    ZKHFL(JL) = ZEXTSHF(JL) / ( RCPD*(1.0_JPRB+RVTMP2*PQM1(JL,KLEV)) ) / ZRHO
    ZKQFL(JL) = ZEXTLHF(JL) / RLVTT / ZRHO
  ENDDO
ENDIF


!*         5.5  BOUNDARY LAYER HEIGHT FOR DIANOSTICS ONLY

CALL VDFDPBL(KIDIA,KFDIA,KLON,KLEV,&
 & PUM1,PVM1,PTM1,PQM1,PGEOM1,&
 & ZKMFL,ZKHFL,ZKQFL,PBLH)  


!*         5.6  PARCEL UPDRAFT

!          iterate inversion height (PZINV)
 
CALL VDFHGHTN (KIDIA   , KFDIA   , KLON    , KLEV    , KHPBLN   , ZTMST,&
             & PTM1    , PQM1    , PLM1    , PIM1    , PAM1,&
             & PAPHM1  , PAPM1   , PGEOM1  , PGEOH,&
             & ZKMFL   , ZKHFL   , ZKQFL   , ZMFLX,&
             & ZSLGUH  , ZQTUH   , PZINV   , PWUAVG  , ZCLDBASE,&
             & PBIR    , LDNODECP, LLRUNDRY, KPBLTYPE)  


!*         5.7  EXCHANGE COEFFICIENTS ABOVE THE SURFACE LAYER

CALL VDFEXCU(KIDIA  , KFDIA  , KLON   , KLEV   , ZTMST  , PZ0M   , &
           & PHRLW  , PHRSW  , PUM1   , PVM1   , PTM1   , PQM1   , &
           & PAPHM1 , PGEOM1 , PGEOH  , ZCPTGZ , &
           & ZKMFL  , ZKHFL  , ZKQFL  , ZCFM   , ZCFH   , &
           & PZINV  , PKH    , ZCLDBASE        , KPBLTYPE)  


!*         5.8  MASS FLUX MODIFICATIONS

!          Selective mflux=0 for single mflux layers
DO JD=1,IDRAFT
  DO JL=KIDIA,KFDIA
    IF ( ZMFLX(JL,KLEV-2,JD) < 1.E-40 ) THEN
      ZMFLX(JL,KLEV-1,JD) = 0.0
    ENDIF
  ENDDO
ENDDO
!          Turn off mass-flux below convection
DO JD=1,IDRAFT
  DO JL=KIDIA,KFDIA
    IF ( KPBLTYPE(JL) == 3 ) THEN
      ZMFLX (JL,:,JD) = 0.0_JPRB
      ZSLGUH(JL,:,JD) = 0.0_JPRB
      ZQTUH (JL,:,JD) = 0.0_JPRB
    ENDIF
  ENDDO
ENDDO

!*         5.9     TURBULENT OROGRAPHIC DRAG COEFFICIENTS 

CALL VDFTOFDC(KIDIA,KFDIA,KLON,KLEV,ZTMST,&
 & PUM1,PVM1,PGEOM1,PSIGFLT,&
 & ZTOFDC)  

!ENDIF !Offline Jacobians

!     ------------------------------------------------------------------

!*         6.     SOLVE ADVECTION-DIFFUSION EQUATION
!                 ----------------------------------

!*         6.1  MOMENTUM

ZHU1=RVDIFTS*ZTMST
ZSOC(KIDIA:KFDIA,1:KLEV)=PSOBETA(KIDIA:KFDIA,1:KLEV)*ZHU1

CALL VDFDIFM (KIDIA, KFDIA, KLON , KLEV  , ITOP, &
            & ZTMST, PUM1 , PVM1 , PAPHM1, ZCFM, ZTOFDC, &
            & PSOTEU,PSOTEV,ZSOC ,&
            & PVOM,PVOL,PUCURR,PVCURR,ZUDIF,ZVDIF)


!*         6.2  GENERALIZED LIQUID WATER STATIC ENERGY AND TOTAL WATER

CALL VDFDIFH(KIDIA  , KFDIA  , KLON   , KLEV   , IDRAFT , ITOP   , KTILES, &
            & ZTMST  , ZEXTSHF, ZEXTLHF, LLSFCFLX, PLIT, PMELTSUM, &
            & PFRTI  , PSSRFLTI,PSLRFL , PEMIS  , PEVAPSNW, &
            & PHLICE , PTLICE , PTLWML , &
            & ZSLGM1 , PTM1   , PQM1   , ZQTM1  , PAPHM1 , &
            & ZCFH   , ZCFHTI , ZCFQTI , ZMFLX  , ZSLGUH , ZQTUH  , &
            & ZSLGDIF, ZQTDIF , ZCPTSTI, ZQSTI  , ZCAIRTI, ZCSATTI, &
            & ZDQSTI , PTSKTI , PTSKRAD, PTSAM1M(1,1)    , PTSNOW , PTICE  , PSST, &
            & PTHKICE, PSNTICE, &
            & ZTSKTIP1,ZSLGE  , PTE    , ZQTE, &
            & PEVAPTI, PAHFSTI, ZAHFLTI, PFLTRTI, ZG0)


!*         6.3  INCREMENTATION OF U AND V TENDENCIES, STORAGE OF
!*              THE DISSIPATION, COMPUTATION OF MULTILEVEL FLUXES.

CALL VDFINCR (KIDIA  , KFDIA  , KLON   , KLEV   , ITOP   , ZTMST  , &
            & PUM1   , PVM1   , ZSLGM1 , PTM1   , ZQTM1  , PAPHM1 , PGEOM1 , &
            & ZCFM   , ZTOFDC , PSOTEU , PSOTEV , ZSOC   ,&
            & ZUDIF  , ZVDIF  , PUCURR , PVCURR ,ZSLGDIF, ZQTDIF , &
            & PVOM   , PVOL   , ZSLGE  , ZQTE   , ZSLGEWODIS, &
            & PVDIS  , PVDISG , PSTRTU , PSTRTV , PSTRSOU, PSTRSOV , PTOFDU , PTOFDV, & 
            & PDISGW3D)  


!          6.4  Solve for tracers

IF (LVDFTRAC .AND. KTRAC > 0) THEN 
  CALL VDFDIFC(KIDIA,KFDIA,KLON,KLEV,ITOP,KTRAC,&
             & ZTMST,PCM1,PTENC,PAPHM1,ZCFH,PCFLX)
ENDIF


!     ------------------------------------------------------------------

!*         7.     SURFACE FLUXES - TILES
!                 ----------------------
!*         AND    COMPUTE 2M TEMPERATURE AND HUMIDITY, 10M WIND,
!*                  and gustiness

!  Compute wind speed at blending height

CALL VDFFBLEND(KIDIA,KFDIA,KLON,KLEV, &
 & PUM1, PVM1, PGEOM1, PUCURR, PVCURR, ZBLEND, &
 & ZFBLEND)

! Wrap-up computations for the surface and 2T/2D/10U/10V/gustiness computation

CALL SURFPP( KIDIA=KIDIA,KFDIA=KFDIA,KLON=KLON,KTILES=KTILES, &
 & KDHVTLS=KDHVTLS,KDHFTLS=KDHFTLS, &
 & PTSTEP=PTSPHY, &
! input
 & PFRTI=PFRTI, PAHFLTI=ZAHFLTI, PG0TI=ZG0, &
 & PSTRTULEV=PSTRTU(:,KLEV), PSTRTVLEV=PSTRTV(:,KLEV), PTSKM1M=PTSKM1M, &
 & PUMLEV=PUM1(:,KLEV), PVMLEV=PVM1(:,KLEV), PQMLEV=PQM1(:,KLEV), &
 & PGEOMLEV=PGEOM1(:,KLEV), PCPTSPP=ZZCPTS, PCPTGZLEV=ZCPTGZ(:,KLEV), &
 & PAPHMS=PAPHM1(:,KLEV), PZ0MW=ZZ0MW, PZ0HW=ZZ0HW, PZ0QW=ZZ0QW, &
 & PZDL=ZZZDL, PQSAPP=ZZQSA, PBLEND=ZBLEND, PFBLEND=ZFBLEND, PBUOM=ZZBUOM, &
 & PZ0M=PZ0M, PEVAPSNW=PEVAPSNW,PSSRFLTI=PSSRFLTI, PSLRFL=PSLRFL, PSST=PSST, &
 & PUCURR=PUCURR, PVCURR=PVCURR, PUSTOKES=PUSTOKES, PVSTOKES=PVSTOKES, &
! updated
 & PAHFSTI=PAHFSTI, PEVAPTI=PEVAPTI, PTSKE1=PTSKE1,PTSKTIP1=ZTSKTIP1, &
! output
 & PDIFTSLEV=PDIFTS(:,KLEV), PDIFTQLEV=PDIFTQ(:,KLEV), PUSTRTI=PUSTRTI, &
 & PVSTRTI=PVSTRTI,  PTSKTI=PTSKTI, PAHFLEV=PAHFLEV, PAHFLSB=PAHFLSB, &
 & PFWSB=PFWSB, PU10M=PU10M, PV10M=PV10M, PT2M=PT2M, PD2M=PD2M, PQ2M=PQ2M, &
 & PGUST=PGUST, P10NU=P10NU, P10NV=P10NV, PUST=PUST, &
! output DDH
 & PDHTLS=PDHTLS &
 & )

PDIFTL  (KIDIA:KFDIA,KLEV) = 0.0_JPRB
PDIFTI  (KIDIA:KFDIA,KLEV) = 0.0_JPRB
ZDIFTQT (KIDIA:KFDIA,KLEV) = 0.0_JPRB
ZDIFTSLG(KIDIA:KFDIA,KLEV) = 0.0_JPRB
ZDIFTQT (KIDIA:KFDIA,KLEV) = PDIFTQ(KIDIA:KFDIA,KLEV)
ZDIFTSLG(KIDIA:KFDIA,KLEV) = PDIFTS(KIDIA:KFDIA,KLEV)

!     ------------------------------------------------------------------

!*         9.     SLG, QT, U, V FLUX COMPUTATIONS AND T,SKIN TENDENCY
!                 ---------------------------------------------------

DO JL=KIDIA,KFDIA
  ZDIFTQT (JL,0) = 0.0_JPRB
  PDIFTQ  (JL,0) = 0.0_JPRB
  PDIFTL  (JL,0) = 0.0_JPRB
  PDIFTI  (JL,0) = 0.0_JPRB
  PDIFTS  (JL,0) = 0.0_JPRB
  ZDIFTSLG(JL,0) = 0.0_JPRB
  PSTRTU  (JL,0) = 0.0_JPRB
  PSTRTV  (JL,0) = 0.0_JPRB
ENDDO

DO JK=KLEV-1,1,-1
  DO JL=KIDIA,KFDIA
    ZGDPH = - (PAPHM1(JL,JK)-PAPHM1(JL,JK+1)) * ZRG
!...change in slg,qt,u,v tendencies are converted to fluxes
    ZDIFTSLG(JL,JK) = ( ZSLGEWODIS(JL,JK+1) - ZSLGEA(JL,JK+1) ) * ZGDPH &
                    & + ZDIFTSLG(JL,JK+1)  
    ZDIFTQT(JL,JK)  = (ZQTE (JL,JK+1)-ZQTEA(JL,JK+1))*ZGDPH + ZDIFTQT(JL,JK+1)
  ENDDO
ENDDO


!     ------------------------------------------------------------------

!*         10.    VARIANCE EVOLUTION EQUATION
!                 ---------------------------

!          use vdf updated variables for cloud variance

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZQTUPD(JL,JK)  = ZQTM1(JL,JK)  + ZQTE(JL,JK)  * ZTMST
    ZSLGUPD(JL,JK) = ZSLGM1(JL,JK) + ZSLGE(JL,JK) * ZTMST
  ENDDO
ENDDO

!          turbulence source and sink terms
!          solve d(sigma^2)/dt = - 2 w'q' dq/dz - sigma^2/tau - d(w'sigma^2')/dz
!          (analytically)

DO JL=KIDIA,KFDIA
  ZTAU(JL) = PZINV(JL) / MAX(PWUAVG(JL),0.01_JPRB)
  ZTAU(JL) = MAX(ZTAU(JL), 100.0_JPRB)  ! prevent tau=0 for stable boundary layer (zi=0)
ENDDO

DO JK=1,KLEV
  DO JL=KIDIA,KFDIA
    IF ( JK >= KHPBLN(JL) ) THEN        ! only within PBL - for now
      IF ( JK < KLEV ) THEN             ! var. gener. not for KLEV - upstream impossible
!...upstream differencing:
        ZVARGEN     = ZDIFTQT(JL,JK)                                   &! - rho*w'qt'
                  & / PAPHM1(JL,JK) * RD * (PTM1(JL,JK)+PTM1(JL,JK+1)) &! * 2 / rho
                  & * (ZQTUPD(JL,JK)-ZQTUPD(JL,JK+1))                  &! * dqt/dz
                  & / (PGEOM1(JL,JK)-PGEOM1(JL,JK+1)) * RG  
        ZVARGEN     = MAX(ZVARGEN,0.0_JPRB)            ! exclude countergradient flow
        PVAR(JL,JK) = ZVARGEN * ZTAU(JL) + (PVAR(JL,JK)- ZVARGEN * ZTAU(JL) ) &
                  & * EXP( - ZTMST / ZTAU(JL) )  
      ELSE
        PVAR(JL,JK) = PVAR(JL,JK) * EXP( -ZTMST / ZTAU(JL) )    ! decay only for KLEV
      ENDIF
      PVAR(JL,JK) = MAX(PVAR(JL,JK),0.0_JPRB)
    ENDIF
  ENDDO
ENDDO


!     ------------------------------------------------------------------

!*         11.    CONVERT VARIANCE -> QV, QL, QI AND CLOUD FRACTION
!*                (on final state; only for PBL, above PBL tendencies
!*                will be overwritten)
!                 ---------------------------------------------------

!          Guess an (arbitrary) state consistent with final qt and slg.
!          (choice: Use ql and qi state after dyn+rad.  Total water 
!          conservation then dictates qv and energy conservation 
!          dictates T.  Z*UPD values are then estimates, before cover,
!          of final profiles.)

DO JK=ILEV,KLEV
  DO JL=KIDIA,KFDIA
    ZLUPD(JL,JK)  = PLM1(JL,JK) + PLE(JL,JK) * ZTMST   ! arbitrary
    ZIUPD(JL,JK)  = PIM1(JL,JK) + PIE(JL,JK) * ZTMST   ! choice
    ZQUPD(JL,JK)  = ZQTUPD(JL,JK) - ZLUPD(JL,JK) - ZIUPD(JL,JK)
    ZTUPD(JL,JK)  = ( ZSLGUPD(JL,JK) - PGEOM1(JL,JK) &
                & + RLVTT * ZLUPD(JL,JK) + RLSTT * ZIUPD(JL,JK) &
                & ) / ( RCPD * ( 1.0_JPRB + RVTMP2 * ZQUPD(JL,JK) ) )  
    ZLIUPD(JL,JK) = ZLUPD(JL,JK) + ZIUPD(JL,JK) ! total condensate
  ENDDO
ENDDO

!          From total water and its variance calculate 
!          cloud cover (ZANEW) and conversion of qv to qc (ZDELQ).
!          (This produces modifications to qv, ql, qi and T. Cloud
!          fraction is diagnosed.)

CALL COVER &
!---input
 & ( KIDIA, KFDIA , KLON  , KLEV , NCLDTOP, KLEV, &
 &   ZQUPD, ZQSVAR, ZLIUPD, PVAR , &
!---output
 &   ZLNEW, ZANEW )

DO JK=1,NCLDTOP-1
  DO JL=KIDIA,KFDIA
    ZDELQ(JL,JK)  = 0.00_JPRB
    ZANEW(JL,JK)  = ZAINI(JL,JK)
  ENDDO
ENDDO
DO JK=NCLDTOP,KLEV
  DO JL=KIDIA,KFDIA
    ZDELQ(JL,JK)  = ( ZLNEW(JL,JK) - ZLIUPD(JL,JK) ) * ZCORQS(JL,JK)
  ENDDO
ENDDO

DO JK=1,KLEV
  DO JL=KIDIA,KFDIA
    
    ! Add modifications to estimate of final state
    ZZQUPD = ZQUPD(JL,JK) -                            ZDELQ(JL,JK)
    ! Actual fraction of liquid/ice used (no longer use fn(T) split)
    ZZLUPD = ZLUPD(JL,JK) +          ZLFRAC(JL,JK)      * ZDELQ(JL,JK)
    ZZIUPD = ZIUPD(JL,JK) + ( 1.0_JPRB - ZLFRAC(JL,JK)) * ZDELQ(JL,JK)
    ZZTUPD = ZTUPD(JL,JK) + &
      & ( ZLFRAC(JL,JK)*RALVDCP+(1.0_JPRB-ZLFRAC(JL,JK))*RALSDCP ) &
      & * ZDELQ(JL,JK)
    ZZAUPD = ZANEW(JL,JK)
!    ZZLUPD = ZLUPD(JL,JK) +       ZALFAW(JL,JK)      * ZDELQ(JL,JK)
!    ZZIUPD = ZIUPD(JL,JK) + ( 1.0_JPRB - ZALFAW(JL,JK)) * ZDELQ(JL,JK)
!    ZZTUPD = ZTUPD(JL,JK) + FOELDCPM(ZTUPD(JL,JK))   * ZDELQ(JL,JK)

!          vdf tendencies from final and initial state, where the
!          initial state is taken consistent with the beta distribution

    PTE(JL,JK) = ( ZZTUPD - ZTINI(JL,JK) ) * ZRTMST + PTE(JL,JK)
    PQE(JL,JK) = ( ZZQUPD - ZQINI(JL,JK) ) * ZRTMST + PQE(JL,JK)
    PLE(JL,JK) = ( ZZLUPD - ZLINI(JL,JK) ) * ZRTMST + PLE(JL,JK)
  ! PLE(JL,JK) = MAX(-PLM1(JL,JK)*ZRTMST,PLE(JL,JK))
    PIE(JL,JK) = ( ZZIUPD - ZIINI(JL,JK) ) * ZRTMST + PIE(JL,JK)
  ! PIE(JL,JK) = MAX(-PIM1(JL,JK)*ZRTMST,PIE(JL,JK))
    PAE(JL,JK) = ( ZZAUPD - ZAINI(JL,JK) ) * ZRTMST + PAE(JL,JK)
    PAE(JL,JK) = MIN((1.0_JPRB-PAM1(JL,JK))*ZRTMST,MAX(-PAM1(JL,JK)*ZRTMST,PAE(JL,JK)))

  ENDDO
ENDDO

!     ------------------------------------------------------------------

!*         12.    Q, QL, QI AND S FLUX COMPUTATIONS
!                 ---------------------------------

DO JK=KLEV-1,1,-1
  DO JL=KIDIA,KFDIA
    ZGDPH = - (PAPHM1(JL,JK)-PAPHM1(JL,JK+1)) * ZRG
!...changes in q,l,i tendencies are converted to fluxes
    PDIFTQ(JL,JK) = (PQE (JL,JK+1) - ZQEA(JL,JK+1)) * ZGDPH + PDIFTQ(JL,JK+1)
    PDIFTL(JL,JK) = (PLE (JL,JK+1) - ZLEA(JL,JK+1)) * ZGDPH + PDIFTL(JL,JK+1)
    PDIFTI(JL,JK) = (PIE (JL,JK+1) - ZIEA(JL,JK+1)) * ZGDPH + PDIFTI(JL,JK+1)
!...slg=s-Lc*ql-Ld*qi (same for fluxes)
    PDIFTS(JL,JK) = ZDIFTSLG(JL,JK) &
                & + RLVTT * PDIFTL(JL,JK) + RLSTT * PDIFTI(JL,JK)  
  ENDDO
ENDDO


!IF (.NOT.LUSEKF_REF.OR.LUSE_JATM.OR.N_SEKF_PT==0) THEN
! Coupled surface not execute in the offline EKF surface analysis
!     ------------------------------------------------------------------

!*         13.    TKE buoyancy production/consumption decoupling criteria
!                 -------------------------------------------------------

!          buoyancy flux: rho*w'sv' = alfa1 * rho*w'slg'  + alfa2 * L * rho*w'qt'
!          (Martin Koehler, used here)
!          (half level!; convert downward to upward flux; not ice generalized)
!          attention: Stull 1988, p.551 misreads Moeng & Randall 1984 who
!                     originally use slgv: 
!          buoyancy flux: rho*w'sv' = alfa1 * rho*w'slgv' + alfa2 * rho*w'qt' 

IF ( .FALSE. ) THEN

  ZSVFLUXCLD(:,:) = 0.0_JPRB      !initialize (attention PBL top)
  ZSVFLUXSUB(:,:) = 0.0_JPRB
  ZSVFLUX   (:,:) = 0.0_JPRB
  DO JK=1,KLEV
    DO JL=KIDIA,KFDIA

!          cloud

      ZALFA1 = ( 1.0_JPRB + (1.0_JPRB+RETV) * ZQSVAR(JL,JK) - ZQTM1(JL,JK)   &
       & + (1.0_JPRB+RETV) * PTM1(JL,JK) * ZDQSDTEMP(JL,JK)      ) &
       & / ( 1.0_JPRB + RLVTT/RCPD * ZDQSDTEMP(JL,JK) )  
      ZALFA2 = RLVTT * ZALFA1 - RCPD * PTM1(JL,JK)
      ZSVFLUXCLD(JL,JK) = - ZALFA1 * ZDIFTSLG(JL,JK) - ZALFA2 * ZDIFTQT(JL,JK)

!          sub-cloud

      ZALFA1 = 1.0_JPRB + RETV *  ZQTM1(JL,JK)
      ZALFA2 = RETV * RCPD * PTM1(JL,JK)
      ZSVFLUXSUB(JL,JK) = - ZALFA1 * ZDIFTSLG(JL,JK) - ZALFA2 * ZDIFTQT(JL,JK)

      IF ( PGEOH(JL,JK)*ZRG < PZINV(JL) ) THEN     ! only define sv-flux within PBL
        IF ( PGEOH(JL,JK)*ZRG > ZCLDBASE(JL) .AND. &
           & KPBLTYPE(JL) == 2 ) THEN              ! to prevent cldbase=-100  
          ZSVFLUX(JL,JK) = ZSVFLUXCLD(JL,JK)
        ELSE
          ZSVFLUX(JL,JK) = ZSVFLUXSUB(JL,JK)
        ENDIF
      ENDIF

    ENDDO
  ENDDO

!          buoyancy flux integral (pos/neg): rho * w'sv' * dz integral
!          ... simple constant flux layers between two full levels
!          (future: extend to linear assumption between half levels, 
!                   continuous zi & zcldbase)

  DO JK=1,KLEV-1
    DO JL=KIDIA,KFDIA
      ZDZH(JL,JK) = ( PGEOM1(JL,JK) - PGEOM1(JL,JK+1) ) * ZRG ! layer thickness
    ENDDO
  ENDDO
  DO JL=KIDIA,KFDIA
    ZDZH(JL,KLEV) = PGEOM1(JL,KLEV) * ZRG
    ZDZH(JL,0)    = 0.0_JPRB                                  ! approximation

!          pos & neg flux within PBL and it's ratio (BIR)

    ZBUOYPOS(JL) = SUM( ZSVFLUX(JL,KHPBLN(JL):KLEV)*ZDZH(JL,KHPBLN(JL):KLEV), &
     & MASK = ZSVFLUX(JL,KHPBLN(JL):KLEV) > 0.0_JPRB )  
    ZBUOYNEG(JL) = SUM( ZSVFLUX(JL,KHPBLN(JL):KLEV)*ZDZH(JL,KHPBLN(JL):KLEV), &
     & MASK = ZSVFLUX(JL,KHPBLN(JL):KLEV) < 0.0_JPRB )  
    IF ( LDNODECP(JL) ) THEN          ! test vdfmain to get decoupling criteria
      PBIR(JL)   = - ZBUOYNEG(JL) / MAX(ZBUOYPOS(JL), 1e-10_JPRB)
      PBIR(JL)   = MIN(PBIR(JL), 10.0_JPRB)
    ENDIF
  ENDDO

ENDIF

!ENDIF ! End Jacobian If

IF (LHOOK) CALL DR_HOOK('VDFMAIN',1,ZHOOK_HANDLE)
END SUBROUTINE VDFMAIN
