!! ================================================================================================================================
!! SUBROUTINE  : hydrolc_alma
!!
!>\BRIEF       This routine computes diagnostic variables required under the ALMA standards:
!! changes in water amounts over the time steps (in the soil, snow and interception reservoirs); total water amount
!! at the end of the time steps; soil relative humidity.
!!
!! DESCRIPTION : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!  - soilwet: mean relative humidity of soil in the grid-cells (0-1, unitless)
!!  - delsoilmoist, delswe, delintercept: changes in water amount during the time step @tex ($kg m^{-2}$) @endtex,
!!    for the three water reservoirs (soil,snow,interception)
!!  - tot_watsoil_end: total water amount at the end of the time steps aincluding the three water resrevoirs
!! @tex ($kg m^{-2}$) @endtex.
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE     : hydrolc_hdiff
!!
!>\BRIEF          This subroutine performs horizontal diffusion of water between each PFT/soil column,
!! if the flag ok_hdiff is true.
!!
!! DESCRIPTION    : The diffusion is realized on the water contents of both the top and bottom
!! soil layers, but the bottom soil layers share the same soil moisture since the end of hydrolc_soil (step 6).
!! This subroutine thus only modifies the moisture of the top soil layer.
!!  \latexonly
!!  \input{hdiff.tex}
!!  \endlatexonly
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : gqsb, bqsb, dsg, dss, dsp
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_init
!!
!>\BRIEF        Initializations and memory allocation
!!
!! DESCRIPTION  :
!! - 1 Some initializations
!! - 2 make dynamic allocation with good dimension
!! - 2.1 array allocation for soil textur
!! - 2.2 Soil texture choice
!! - 3 Other array allocation
!! - 4 Open restart input file and read data for HYDROLOGIC process
!! - 5 get restart values if none were found in the restart file
!! - 6 Vegetation array
!! - 7 set humrelv from us
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!!_ hydrol_init


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_clear
!!
!>\BRIEF        Deallocate arrays
!!
!_ ================================================================================================================================
!_ hydrol_clear


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_tmc_update
!!
!>\BRIEF        This routine updates the soil moisture profiles when the vegetation fraction have changed.
!!
!! DESCRIPTION  :
!!
!!    This routine update tmc and mc with variation of veget_max (LAND_USE or DGVM activated)
!!
!!
!!
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_tmc_update


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_var_init
!!
!>\BRIEF        This routine initializes HYDROLOGIC variables.
!!
!! DESCRIPTION  :
!! - 1 compute the depths
!! - 2 compute the profile for roots
!! - 3 compute the profile for ksat, a and n Van Genuchten parameter
!! - 4 compute the linearized values of k, a, b and d for the resolution of Fokker Planck equation
!! - 5 water reservoirs initialisation
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_var_init


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_snow
!!
!>\BRIEF        This routine computes snow processes.
!!
!! DESCRIPTION  :
!! - 0 initialisation
!! - 1 On vegetation
!! - 1.1 Compute snow masse
!! - 1.2 Sublimation
!! - 1.2.1 Check that sublimation on the vegetated fraction is possible.
!! - 1.3. snow melt only if temperature positive
!! - 1.3.1 enough snow for melting or not
!! - 1.3.2 not enough snow
!! - 1.3.3 negative snow - now snow melt
!! - 1.4 Snow melts only on weight glaciers
!! - 2 On Land ice
!! - 2.1 Compute snow
!! - 2.2 Sublimation
!! - 2.3 Snow melt only for continental ice fraction
!! - 2.3.1 If there is snow on the ice-fraction it can melt
!! - 2.4 Snow melts only on weight glaciers
!! - 3 On other surface types - not done yet
!! - 4 computes total melt (snow and ice)
!! - 5 computes snow age on veg and ice (for albedo)
!! - 5.1 Snow age on vegetation
!! - 5.2 Snow age on ice
!! - 6 Diagnose the depth of the snow layer
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_snow


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_canop
!!
!>\BRIEF        This routine computes canopy processes.
!!
!! DESCRIPTION  :
!! - 1 evaporation off the continents
!! - 1.1 The interception loss is take off the canopy.
!! - 1.2 precip_rain is shared for each vegetation type
!! - 1.3 Limits the effect and sum what receives soil
!! - 1.4 swap qsintveg to the new value
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_canop


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_vegupd
!!
!>\BRIEF        Vegetation update
!!
!! DESCRIPTION  :
!!   The vegetation cover has changed and we need to adapt the reservoir distribution
!!   and the distribution of plants on different soil types.
!!   You may note that this occurs after evaporation and so on have been computed. It is
!!   not a problem as a new vegetation fraction will start with humrel=0 and thus will have no
!!   evaporation. If this is not the case it should have been caught above.
!!
!! - 1 Update of vegetation is it needed?
!! - 2 calculate water mass that we have to redistribute
!! - 3 put it into reservoir of plant whose surface area has grown
!! - 4 Soil tile gestion
!! - 5 update the corresponding masks
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_vegupd


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_flood
!!
!>\BRIEF        This routine computes the evolution of the surface reservoir (floodplain).
!!
!! DESCRIPTION  :
!! - 1 Take out vevapflo from the reservoir and transfer the remaining to subsinksoil
!! - 2 Compute the total flux from floodplain floodout (transfered to routing)
!! - 3 Discriminate between precip over land and over floodplain
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_flood


!! ================================================================================================================================
!! SUBROUTINE 	: hydrol_soil
!!
!>\BRIEF        This routine computes soil processes with CWRR scheme.
!!
!! DESCRIPTION  :
!! - 0 Arrays initialisation
!! -   for each soil type
!! - 1 We compare water2infilt and water2extract to keep only difference
!! - 1.1 add to the first layer
!! - 1.2 filling layers
!! - 2 Before diffusion scheme
!! - 2.1 Some initialisation necessary for the diffusion scheme to work
!! - 2.2 coefficients are computed for the profile of mc before infiltration:
!! - 3 The infiltration is computed
!! - 4 Coefficient are recomputed for the profile of mc after infiltration:
!! - 5 Prepar the diffusion scheme
!! - 5.1 Set the values for diffusion scheme
!! - 5.2 verifications for a good soil humidity
!! - 5.3 compute matrix coefficients
!! - 6 Resolve diffusion scheme
!! - 6.1 solve equations assuming atmosphere limiting
!! - 6.2 check if really atmosphere limiting
!! - 6.3 Reset the coefficient for diffusion (only used if resolv(ji) = .TRUE.)
!! - 6.4 resolve the equations with new boundary conditions if necessary
!! - 7 close the water balance
!! - 7.1 compute dr_ns with the bottom boundary condition
!! - 7.2 compute total soil moisture content
!! - 7.3 deduction of upper flux from soil moisture variation and bottom flux
!! - 7.4 deduction of ae_ns and ru_ns:
!! - 8 Special treatment for the unstable cases
!! - 9 Then compute the temporary surface water and correct the outgoing runoff
!! - 10 smooth again
!! - 11 Optional computation of the fluxes
!! - 12 We make some useful output
!! - 13 before closing the soil water, we check the water balance of soil
!! - 14 sum 3d variables into 2d variables
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_soil


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_infilt
!!
!>\BRIEF        Infiltration
!!
!! DESCRIPTION  :
!! - 1 First layer
!! - 2 Infiltration layer by layer
!! - 2.1 Initialisation
!! - 2.2 Infiltrability of each layer if under a saturated one
!! - 2.3 Compute the mean rate at which water actually infiltrate:
!! - 2.4 From which we deduce the time it takes to fill up the layer or to end the time step...
!! - 2.5 The water enters in the layer
!! - 3 Verification
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_soil_infilt


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_soil_smooth
!!
!>\BRIEF        Smooth soil moisture values: avoid over-saturation or under-residual values.
!!
!! DESCRIPTION  :
!! - 1 Avoid over-saturation values
!! - 1.1 top to bottom
!! - 1.2 bottom to top
!! - 2 Avoid below residual values
!! - 2.1 top to bottom
!! - 2.2 bottom to top
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_soil_smooth


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_soil_flux
!!
!>\BRIEF        This subroutine computes the hydrological fluxes between the different soil layers.
!!
!! DESCRIPTION  :
!! - 1 Initialize qflux from the bottom, with dr_ns
!! - 2 between layer nslm and nslm-1
!! - 3 we go to top and deduct qflux(1:nslm-2)
!! - 4 Water balance verification
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_soil_flux


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_soil_tridiag
!!
!>\BRIEF        This subroutine solves a set of linear equations which has a tridiagonal coefficient matrix.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : mcl (global module variable)
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_soil_tridiag


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_soil_coef
!!
!>\BRIEF        Computes coef for the linearised hydraulic conductivity
!! k_lin=a_lin mc_lin+b_lin and the linearised diffusivity d_lin.
!!
!! DESCRIPTION  :
!! First, we identify the interval i in which the current value of mc is located.
!! Then, we give the values of the linearized parameters to compute
!! conductivity and diffusivity as K=a*mc+b and d.
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_soil_coef


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_soil_setup
!!
!>\BRIEF        This subroutine computes the matrix coef.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : matrix coef
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_split_soil
!!
!>\BRIEF        Splits 2d variables into 3d variables, per soil type.
!!
!! DESCRIPTION  :
!! - 1 split 2d variables into 3d variables, per soil type
!! - 1.1 precipitation
!! - 1.2 evaporation
!! - 1.2.1 vevapnu_old
!! - 1.2.2 ae_ns new
!! - 1.3 transpiration
!! - 1.4 root sink
!! - 2 Verification
!! - 2.1 Check of mc
!! - 2.2 Check if the deconvolution is correct and conserves the fluxes
!! - 2.2.1 the precisol and evapnu
!! - 2.2.2 the transpiration and root sink
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_split_soil


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_diag_soil
!!
!>\BRIEF        ??
!!
!! DESCRIPTION  :
!! - 1 Apply mask_soiltile
!! - 2 sum 3d variables in 2d variables with fraction of vegetation per soil type
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_diag_soil


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_waterbal
!!
!>\BRIEF        Checks the water balance.
!!
!! DESCRIPTION  :
!! This routine checks the water balance. First it gets the total
!! amount of water and then it compares the increments with the fluxes.
!! The computation is only done over the soil area as over glaciers (and lakes?)
!! we do not have water conservation.
!! This verification does not make much sense in REAL*4 as the precision is the same as some
!! of the fluxes
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_waterbal


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_alma
!!
!>\BRIEF        This routine computes the changes in soil moisture and interception storage for the ALMA outputs.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!_ hydrol_alma


!
!! ================================================================================================================================
!! SUBROUTINE   : hydrol_calculate_temp_hydro
!!
!>\BRIEF         Calculate the temperature at hydrological levels
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrol_calculate_frac_hydro_diag
!!
!>\BRIEF         Caluculate frac_hydro_diag for interpolation between hydrological and diagnostic axes
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) :
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! pour declencher les restarts rajoutes avec un parametre externe


!! Interface for initialising a real 2D array with a scalar parameter from run.def or an other 2D array in argument


!! ================================================================================================================================
!! SUBROUTINE		 			: diffuco_init
!!
!>\BRIEF					Dynamic allocation algorithm for local arrays
!!
!! DESCRIPTION				        : Housekeeping module to allocate local arrays
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S)	                : q_cdrag
!!
!! REFERENCE(S)				        : None
!!
!! FLOWCHART                                    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : diffuco_inca_init
!!
!>\BRIEF         This subroutine initializes diffuco_inca-related state variables
!!
!! DESCRIPTION  : Some of the variables and flags used in diffuco_inca are allocated and initialised here.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE		 			: diffuco_clear
!!
!>\BRIEF					Housekeeping module to deallocate the variables
!! leaf_ci, rstruct and raero
!!
!! DESCRIPTION				        : Housekeeping module to deallocate the variables
!! leaf_ci, rstruct and raero
!!
!! RECENT CHANGE(S)                             : None
!!
!! MAIN OUTPUT VARIABLE(S)	                : None
!!
!! REFERENCE(S)				        : None
!!
!! FLOWCHART                                    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE		 			: diffuco_flood
!!
!>\BRIEF				       	This routine computes partial beta coefficient : floodplains
!!
!! DESCRIPTION				        :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S)	                : vbeta5
!!
!! REFERENCE(S)				        : None
!!
!! FLOWCHART                                    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : diffuco_inca_read
!!
!>\BRIEF         This subroutine will read and interpolate the data set of CO2 emissions from biomass burning.\n
!!
!! DESCRIPTION  :  This subroutine will interpolate the 1 x 1 deg based data set of CO2 emissions from biomass burning
!!                 expresssed in kgC/m^2 per year (=> density = TRUE), N fertiliser amount expressed in kgN per year and
!!                 per grid cell (=> density = FALSE) to the resolution of the model.\ n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): :: data_year
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!_ ================================================================================================================================


!!  =============================================================================================================================
!! SUBROUTINE		 		    : enerbil_init
!!
!>\BRIEF			            Performs dynamic allocation for local arrays, and retrieves
!! previous data from restart file (if the switch is set to do so)
!!
!! DESCRIPTION			    : The purpose of this module is, firstly, to allocate space
!! in memory for key variables within the 'enerbil' module. The second task is to retrieve previous data
!! from the restart file, if the 'ldrestart-read' flag is set.
!!
!! RECENT CHANGE(S)			    : None
!!
!! MAIN OUTPUT VARIABLE(S)	            : temp_sol, temp_sol_new, qsurf, tsol_rad, vevapp, fluxsens,
!! fluxlat, evapot, evapot_corr
!!
!! REFERENCE(S)			    : None
!!
!! FLOWCHART                              : None
!! \n
!_ ==============================================================================================================================


!!  =============================================================================================================================
!! SUBROUTINE		 		    : enerbil_clear
!!
!>\BRIEF				    Routine deallocates clear output variables if already allocated.
!!
!! DESCRIPTION			    : This is a 'housekeeping' routine that deallocates the key output
!! variables, if they have already been allocated. The variables that are deallocated are psold,
!! qsol_sat, pdqsold, psnew, qsol_sat_new, netrad, lwabs, lwup, lwnet, fluxsubli, qsat_air, tair
!!
!! RECENT CHANGE(S)			    : None
!!
!! MAIN OUTPUT VARIABLE(S)	            : None
!!
!! REFERENCES				    : None
!!
!! FLOWCHART                              : None
!! \n
!_ ==============================================================================================================================


!!  =============================================================================================================================
!! SUBROUTINE		 			: enerbil_var_init
!!
!>\BRIEF					Housekeeping routine that calls enerbil_t2mdiag.
!!
!! DESCRIPTION				: Housekeeping routine that calls the 2 metre temperature
!! diagnostic subroutine 'enerbil_2tmdiag'.
!!
!! MAIN OUTPUT VARIABLE(S)	                : t2mdiag
!!
!! REFERENCE(S)				: None
!!
!! FLOWCHART                                  : None
!! \n
!_ ==============================================================================================================================


!! =============================================================================================================================
!! SUBROUTINE		 			: enerbil_pottemp
!!
!>\BRIEF		This subroutine computes the surface temperature and humidity should the surface been unstressed
!!
!! DESCRIPTION				:
!!
!! MAIN OUTPUT VARIABLE(S)	:
!!
!! REFERENCE(S)		:
!!
!! FLOWCHART    : None
!!
!_ ==============================================================================================================================


!! ==============================================================================================================================\n
!! SUBROUTINE 	: sechiba_init
!!
!>\BRIEF        Dynamic allocation of the variables, the dimensions of the
!! variables are determined by user-specified settings. If ::ldrestart_read is
!! true, initial varaible values are read from the restart file.
!!
!! DESCRIPTION  : The domain size (:: kjpindex) is used to allocate the correct
!! dimensions to all variables in sechiba. Depending on the variable, its
!! dimensions are also determined by the number of PFT's (::nvm), number of
!! soil types (::nstm), number of non-vegetative surface types (::nnobio),
!! number of soil levels (::ngrnd), number of soil layers in the hydrological
!! model (i.e. cwrr) (::nslm). Values for these variables are set in
!! constantes_soil.f90 and constantes_veg.f90.\n
!!
!! Memory is allocated for all Sechiba variables and new indexing tables
!! are build making use of both (::kjpij) and (::kjpindex). New indexing tables
!! are needed because a single pixel can contain several PFTs, soil types, etc.
!! The new indexing tables have separate indices for the different
!! PFTs, soil types, etc.\n
!!
!! The routine uses the flag ::ldrestart_read to retrieve initial variable
!! settings from the restart file.\n
!!
!! ??Flags are getting swapped by it is not entirly clear why??
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): Strictly speaking the subroutine has no output
!! variables. However, the routine allocates memory and builds new indexing
!! variables for later use.
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================\n
!! SUBROUTINE 	: sechiba_clear
!!
!>\BRIEF        Deallocate memory of sechiba's variables
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================\n
!! SUBROUTINE 	: sechiba_var_init
!!
!>\BRIEF        Calculate air density as a function of air temperature and
!! pressure for each terrestrial pixel.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): air density (::rau, kg m^{-3}).
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================\n
!! SUBROUTINE 	: sechiba_end
!!
!>\BRIEF        Swap old for newly calculated soil temperature.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): soil temperature (::temp_sol; K)
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART    : None
!! \n
!! ================================================================================================================================


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!   Definition de ioconf_setatt_p      !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!   Definition de parallel ipslerr functions    !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!===


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_comm_init
!!
!>\BRIEF         Get the MPI communicator.
!!
!! DESCRIPTION  :\n First call to XIOS to get the MPI communicator.
!!                  Note that it is XIOS that initialize the MPI communicator.
!!                  This subroutine is only called in ORCHIDEE offline mode. When running in coupled mode, the
!!                  atmospheric model must initlialize XIOS at the same time as initializing MPI.
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_init
!!
!>\BRIEF         Initialize variables needed for use of XIOS.
!!
!! DESCRIPTION  :\n Initialization of specific varaiables needed to use XIOS such as model domain and time step.
!!
!!                  In this subroutine also a section containg deactivation of some fields is found. The variables are
!!                  deactivated of not according to the corresponding control flag. For exemple the variables cacluated by the
!!                  routing scheme will be deactivated if the routing is deactivated. This is done to be able to keep the same
!!                  iodef.xml input file for several options without geting empty fields in the output file. Note that a field that
!!                  is activated in the code can always be deactivated from the iodef.xml external file.
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_change_context
!!
!>\BRIEF         Use this subroutine to switch between different context.
!!               This subroutine must be called when running in coupled mode at each time ORCHIDEE is called, in the
!!               begining and end of intersurf_gathered. First call is done after xios_orchidee_init is done.
!!
!! DESCRIPTION  :\n
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_update_calendar
!!
!>\BRIEF          Update the calandar in XIOS.
!!
!! DESCRIPTION  :\n Update the calendar in XIOS : let XIOS know that ORCHIDEE avanced one time-step.
!!                  This subroutine should be called in the beginning of each time-step. The first
!!                  time-step in a new execution should always start at 1. Therefore, first calculate
!!                  an offset that is substracted to the current time step in sechiba.
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_context_finalize
!!
!>\BRIEF         Finalize orchidee context.
!!
!! DESCRIPTION  :\n This subroutine finalizes the orchidee context without finalizing XIOS. In coupled mode, the atmospheric
!!                  modele must finalize XIOS. This subroutine is called in the end of the execution of ORCHIDEE only in
!!                  coupeld mode.
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_finalize
!!
!>\BRIEF         Last call to XIOS for finalization.
!!
!! DESCRIPTION  :\n Last call to XIOS for finalization of the orchidee context and XIOS.
!!                  This subroutine is called only when ORCHIDEE is run in offline mode. In coupled mode it is the atmospheric
!!                  model that finalizes XIOS. In that case, the context orchidee must be finalized using the
!!                  subroutine xios_orchidee_context_finalize
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_send_field_r1d
!!
!>\BRIEF          Subroutine for sending 1D (array) fields to XIOS.
!!
!! DESCRIPTION  :\n Send one field to XIOS. This is the interface for 1D fields (array).
!!                  NB! This subroutine should not be called directly. Use interface xios_orchidee_send_field.
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_send_field_r2d
!!
!>\BRIEF          Subroutine for sending 2D fields to XIOS.
!!
!! DESCRIPTION  :\n Send one field to XIOS. This is the interface for 2D fields.
!!                  NB! This subroutine should not be called directly. Use interface xios_orchidee_send_field.
!!
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : xios_orchidee_send_field_r3d
!!
!>\BRIEF          Subroutine for sending 3D fields to XIOS.
!!
!! DESCRIPTION  :\n Send one field to XIOS. This is the interface for 3D fields.
!!                  NB! This subroutine should not be called directly. Use interface xios_orchidee_send_field.
!!
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : solarang
!!
!>\BRIEF         This subroutine computes the solar angle according to the method used by GSWP and developed by J.C. Morill.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::csang
!!
!! REFERENCE(S) : See for further details :
!! http://www.atmo.arizona.edu/~morrill/swrad.html
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : time_zone
!!
!>\BRIEF
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::zone, ::lhour
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : downward_solar_flux
!!
!>\BRIEF
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::solad, ::solai
!!
!! REFERENCE(S) :See for further details :
!! http://www.atmo.arizona.edu/~morrill/swrad.html
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : gauss-jordan_method
!!
!>\BRIEF          This subroutine resolves a linear system by the Gauss-Jordan method.
!! (inversion of the system - complexity O(n^3)) .
!!
!! DESCRIPTION  :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): vector_b contains the solution of the system.
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : error_L1_passive
!!
!>\BRIEF          This subroutine calculates relative errors of a vector by taking the relative error for the passive pool.
!!
!! DESCRIPTION  :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): flag is to true if the maximum relative error is less than a threshold chosen by the user.
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
! This routing will get for each point of the coarse grid the
! indexes of the finer grid and the area of overlap.
! This routine is designed for a fine grid which is regular in lat/lon.
!


!
! This routing will get for each point of the coarse grid the
! indexes of the finer grid and the area of overlap.
! This routine is designed for a fine grid which is regular in meters along lat lon axes.
!


!! ================================================================================================================================
!! SUBROUTINE   : activate_sub_models
!!
!>\BRIEF         This subroutine reads the flags in the configuration file to
!! activate some sub-models like routing, irrigation, fire, herbivory, ...
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : veget_config
!!
!>\BRIEF         This subroutine reads the flags controlling the configuration for
!! the vegetation : impose_veg, veget_mpa, lai_map, etc...
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : veget_config
!!
!>\BRIEF         This subroutine reads in the configuration file the imposed values of the parameters for all SECHIBA modules.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : config_co2_parameters
!!
!>\BRIEF        This subroutine reads in the configuration file all the parameters
!! needed when OK_CO2 is set to true. (ie : when the photosynthesis is activated)
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : config_stomate_parameters
!!
!>\BRIEF        This subroutine reads in the configuration file all the parameters
!! needed when stomate is activated (ie : when OK_STOMATE is set to true).
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : config_dgvm_parameters
!!
!>\BRIEF        This subroutine reads in the configuration file all the parameters
!! needed when the DGVM model is activated (ie : when ok_dgvm is set to true).
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : pft_parameters_init
!!
!>\BRIEF          This subroutine initializes all the pft parameters by the default values
!! of the corresponding metaclasse.
!!
!! DESCRIPTION  : This subroutine is called after the reading of the number of PFTS and the correspondence
!!                table defined by the user in the configuration files. \n
!!                With the correspondence table, the subroutine can search the default values for the parameter
!!                even if the PFTs are classified in a random order (except bare soil). \n
!!                With the correspondence table, the subroutine can initialize the pft parameters in function
!!                of the flags activated (ok_sechiba, ok_stomate, ok_co2, routing, new_hydrol...).\n
!!
!! RECENT CHANGE(S): Didier Solyga : Simplified PFT loops : use vector notation.
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : pft_parameters_alloc
!!
!>\BRIEF         This subroutine allocates memory needed for the PFT parameters
!! in function  of the flags activated.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : config_pft_parameters
!!
!>\BRIEF          This subroutine will read the imposed values for the global pft
!! parameters (sechiba + stomate). It is not called if IMPOSE_PARAM is set to NO.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : config_sechiba_pft_parameters
!!
!>\BRIEF        This subroutine will read the imposed values for the sechiba pft
!! parameters. It is not called if IMPOSE_PARAM is set to NO.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : config_stomate_pft_parameters
!!
!>\BRIEF         This subroutine will read the imposed values for the stomate pft
!! parameters. It is not called if IMPOSE_PARAM is set to NO.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!=
!
!! ================================================================================================================================
!! SUBROUTINE   : pft_parameters_clear
!!
!>\BRIEF         This subroutine deallocates memory at the end of the simulation.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : config_soil_parameters
!!
!>\BRIEF        This subroutine reads in the configuration file all the parameters related to soil and hydrology.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : phenology_clear
!!
!>\BRIEF          Flags setting
!!
!! DESCRIPTION  : This subroutine sets flags
!!                ::firstcall, ::firstcall_hum, ::firstcall_moi, ::firstcall_humgdd,
!!                ::firstcall_moigdd to .TRUE., and therefore activates section 1.1 of each
!!                subroutine which writes messages to the output. \n
!!                This subroutine is called at the beginning of ::stomateLpj_clear in the
!!                ::stomate_lpj module.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::firstcall, ::firstcall_hum, ::firstcall_moi, ::firstcall_humgdd,
!!                ::firstcall_moigdd
!!
!! REFERENCE(S)  : None
!!
!! FLOWCHART     : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : phenology
!!
!>\BRIEF          This subroutine controls the detection of the beginning of the growing season
!!                (if dormancy has been long enough), leaf onset, given favourable biometeorological
!!                conditions, and leaf growth and biomass allocation when leaf biomass is low (i.e.
!!                at the start of the growing season.
!!
!! DESCRIPTION  : This subroutine is called by the module ::stomate_lpj and deals with the beginning of the
!!                growing season. First it is established whether the beginning of the growing season is
!!                allowed. This occurs if the dormance period has been long enough (i.e. greater
!!                than a minimum PFT-dependent threshold, specified by ::lowgpp_time),
!!                AND if the last beginning of the growing season was a sufficiently long time ago
!!                (i.e. when the growing season length is greater than a minimum threshold, specified
!!                by ::min_growthinit_time, which is defined in this module to be 300 days. \n
!!                The dormancy time-length is represented by the variable
!!                ::time_lowgpp, which is calculated in ::stomate_season. It is increased by
!!                the stomate time step when the weekly GPP is lower than a threshold. Otherwise
!!                it is set to zero. \n
!!                ::lowgpp_time is set for each PFT in ::stomate_data from a table of all
!!                PFT values (::lowgpp_time_tab), which is defined in ::stomate_constants. \n
!!                The growing season length is given by ::when_growthinit, which increases
!!                by the stomate time-step at each call to this phenology module, except for when
!!                leaf onset is detected, when it is set to 0. \n
!!                If these two conditions are met, leaf onset occurs if the biometeorological
!!                conditions are also met. This is determined by the leaf onset models, which are
!!                biome-specific. Each PFT is looped over (ignoring bare soil).
!!                The onset phenology model is selected, (according to the parameter
!!                ::pheno_model, which is initialised in stomate_data), and called. \n
!!                There are six leaf onset phenology models currently being used by ORCHIDEE.
!!                These are: 'hum' and 'moi', which are based exclusively on moisture conditions,
!!                'humgdd' and 'moigdd', which are based on both temperature and moisture conditions,
!!                'ncdgdd', which is based on a "chilling" requirement for leaf onset, and
!!                'ngd', which is based on the number of growing days since the temperature was
!!                above a certain threshold, to account for the end of soil frost.
!!                Those models which are based mostly on temperature conditions are used for
!!                temperate and boreal biomes, and those which include a moisture condition are used
!!                for tropical biomes. More detail on the biometeorological conditions is provided
!!                in the sections on the individual onset models. \n
!!                The moisture conditions are based on the concept of plant "moisture availability".
!!                This is based on the soil humidity (relative soil moisture), but is moderated by
!!                the root density profile, as per the equation:
!!                \latexonly
!!                \input{phenology_moiavail_eqn1.tex}
!!                \endlatexonly
!!                \n
!!                Although some studies have shown that the length of the photoperiod is important
!!                in determining onset (and senescence) dates, this is not considered in the current
!!                versions of the onset models (Krinner et al., 2005). \n
!!                If conditions are favourable, leaf onset occurs (::begin_leaves is set to TRUE),
!!                ::when_growthinit is set to 0.0, and the growing season has begun. \n
!!                Following the detection of leaf onset, biomass is allocated from the carbohydrate
!!                reserves equally to the leaves and roots IF the leaf biomass is lower than a minimum
!!                threshold, which is calculated in this subroutine from the parameter
!!                ::lai_initmin, divided by the specific leaf area (both of which are
!!                PFT-dependent and set in ::stomate_constants). \n
!!                Finally, if biomass is required to be allocated from the carbohydrate reserve
!!                because the leaf biomass is too low, the leaf age and leaf age distribution is
!!                re-set. In this case the youngest age class fraction is set to 1 and all other
!!                leaf age class fractions are set to 0. All leaf ages are set to 0. If there is
!!                no biomass in the carbohydrate reserve, leaf onset will not occur and the PFT
!!                will disappear from the grid cell (Krinner et al., 2005). \n
!!                This subrouting is called in ::stomate_lpj.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::biomass,
!!                        ::when_growthinit,
!!                        ::leaf age distribution
!!                        ::leaf fraction
!!
!! REFERENCE(S) :
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{phenology_flowchart.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : pheno_hum
!!
!>\BRIEF          The 'hum' onset model initiate leaf onset based exclusively on moisture
!!                availability criteria.
!!                Currently no PFTs are assigned to this onset model.
!!
!! DESCRIPTION  : This model is for tropical biomes, where temperatures are high but moisture
!!                might be a limiting factor on growth. It is based on leaf onset model 4a in
!!                Botta et al. (2000), which adopts the approach of Le Roux (1995). \n
!!                Leaf onset occurs if the monthly moisture availability is still quite
!!                low (i.e. lower than the weekly availability), but the weekly availability is
!!                higher than the critical threshold ::availability_crit (as it reacts faster),
!!                which indicates the weekly moisture availability is increasing.
!!                OR if the monthly moisture availability is high enough (i.e. above the
!!                threshold value ::moiavail_always), leaf onset is initiated if this has not
!!                already happened. This allows vegetation in arid areas to respond to rapidly
!!                changing soil moisture conditions (Krinner et al., 2005). \n
!!                The critical weekly moisture availability threshold (::availability_crit), is
!!                calculated in this subroutine, and is a function of last year's maximum and
!!                minimum moisture availability and the PFT-dependent parameter
!!                ::hum_frac, which specifies how much of last year's available
!!                moisture is required for leaf onset, as per the equation:
!!                \latexonly
!!                \input{phenology_moi_availcrit_eqn3.tex}
!!                \endlatexonly
!!                \n
!!                ::hum_frac is set for each PFT in ::stomate_data from a table
!!                which contains all the PFT values (::hum_frac_tab) in ::stomate_constants. \n
!!                Last year's maximum and minimum moisture availability and the monthly and
!!                weekly moisture availability are
!!                The ::pheno_hum subroutine is called in the subroutine ::phenology.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::begin_leaves - specifies whether leaf growth can start.
!!
!! REFERENCE(S) :
!! - Botta, A., N. Viovy, P. Ciais, P. Friedlingstein and P. Monfray (2000),
!! A global prognostic scheme of leaf onset using satellite data,
!! Global Change Biology, 207, 337-347.
!! - Le Roux, X. (1995), Etude et modelisation des echanges d'eau et d'energie
!! sol-vegetation-atmosphere dans une savane humide, PhD Thesis, University
!! Pierre et Marie Curie, Paris, France.
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_hum.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : pheno_moi
!!
!>\BRIEF          The 'moi' onset model (::pheno_moi) initiates leaf onset based exclusively
!!                on moisture availability criteria.
!!                It is very similar to the 'hum' onset model but instead of the weekly moisture
!!                availability being higher than a constant threshold, the condition is that the
!!                moisture minimum happened a sufficiently long time ago.
!!                Currently PFT 3 (Tropical Broad-leaved Raingreen) is assigned to this model.
!!
!! DESCRIPTION  : This model is for tropical biomes, where temperatures are high but moisture
!!                might be a limiting factor on growth. It is based on leaf onset model 4b in
!!                Botta et al. (2000).
!!                Leaf onset begins if the plant moisture availability minimum was a sufficiently
!!                time ago, as specified by the PFT-dependent parameter ::hum_min_time
!!                AND if the "monthly" moisture availability is lower than the "weekly"
!!                availability (indicating that soil moisture is increasing).
!!                OR if the monthly moisture availability is high enough (i.e. above the threshold
!!                value ::moiavail_always), leaf onset is initiated if this has not already
!!                happened. \n
!!                ::hum_min_time is set for each PFT in ::stomate_data, and is
!!                defined in the table ::hum_min_time_tab in ::stomate_constants. \n
!!                ::moiavail_always is defined for both tree and grass in this subroutine
!!                (set to 1. and 0.6 respectively). \n
!!                The ::pheno_moi subroutine is called in the subroutine ::phenology.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::begin_leaves - specifies whether leaf growth can start.
!!
!! REFERENCE(S) :
!! - Botta, A., N. Viovy, P. Ciais, P. Friedlingstein and P. Monfray (2000),
!! A global prognostic scheme of leaf onset using satellite data,
!! Global Change Biology, 207, 337-347.
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_moi.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : pheno_humgdd
!!
!>\BRIEF          The 'humgdd' onset model initiates leaf onset based on mixed conditions of
!!                temperature and moisture availability criteria.
!!                Currently no PFTs are assigned to this onset model.
!!
!! DESCRIPTION  : In this model the Growing Degree Day (GDD) model (Chuine, 2000) is combined
!!                with the 'hum' onset model (::pheno_hum), which has previously been described,
!!                in order to account for dependence on both temperature and moisture conditions
!!                in warmer climates. \n.
!!                The GDD model specifies that daily temperatures above a threshold of -5
!!                degrees C are summed, minus this threshold, giving the GDD, starting from
!!                the beginning of the dormancy period (::time_lowgpp>0), i.e. since the leaves
!!                were lost. \n.
!!                The dormancy time-length is represented by the variable
!!                ::time_lowgpp, which is calculated in ::stomate_season. It is increased by
!!                the stomate time step when the weekly GPP is lower than a threshold. Otherwise
!!                it is set to zero. \n
!!                Leaf onset begins when the a PFT-dependent GDD-threshold is reached.
!!                In addition there are temperature and moisture conditions.
!!                The temperature condition specifies that the monthly temperature has to be
!!                higher than a constant threshold (::t_always) OR
!!                the weekly temperature is higher than the monthly temperature.
!!                There has to be at least some moisture. The moisture condition
!!                is exactly the same as the 'hum' onset model (::pheno_hum), which has already
!!                been described. \n
!!                The GDD (::gdd_m5_dormance) is calculated in ::stomate_season. GDD is set to
!!                undef if beginning of the growing season detected, i.e. when there is GPP
!!                (::time_lowgpp>0).
!!                The parameter ::t_always is defined as 10 degrees C in this subroutine,
!!                as are the parameters ::moisture_avail_tree and ::moisture_avail_grass
!!                (set to 1 and 0.6 respectively), which are used in the moisture condition
!!                (see ::pheno_moi onset model description). \n
!!                The PFT-dependent GDD threshold (::gdd_crit) is calculated as in the onset
!!                model ::pheno_humgdd, using the equation:
!!                \latexonly
!!                \input{phenology_hummoigdd_gddcrit_eqn4.tex}
!!                \endlatexonly
!!                \n
!!                The three GDDcrit parameters (::gdd(j,*)) are set for each PFT in
!!                ::stomate_data, and three tables defining each of the three critical GDD
!!                parameters for each PFT is given in ::gdd_crit1_tab, ::gdd_crit2_tab and
!!                ::gdd_crit3_tab in ::stomate_constants. \n
!!                The ::pheno_humgdd subroutine is called in the subroutine ::phenology.
!!
!! RECENT CHANGES: None
!!
!! MAIN OUTPUT VARIABLES: ::begin_leaves - specifies whether leaf growth can start
!!
!! REFERENCE(S) :
!! - Botta, A., N. Viovy, P. Ciais, P. Friedlingstein and P. Monfray (2000),
!! A global prognostic scheme of leaf onset using satellite data,
!! Global Change Biology, 207, 337-347.
!! - Chuine, I (2000), A unified model for the budburst of trees, Journal of
!! Theoretical Biology, 207, 337-347.
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_humgdd.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : pheno_moigdd
!!
!>\BRIEF          The 'moigdd' onset model initiates leaf onset based on mixed temperature
!!                and moisture availability criteria.
!!                Currently PFTs 10 - 13 (C3 and C4 grass, and C3 and C4 agriculture)
!!                are assigned to this model.
!!
!! DESCRIPTION  : This onset model combines the GDD model (Chuine, 2000), as described for
!!                the 'humgdd' onset model (::pheno_humgdd), and the 'moi' model, in order
!!                to account for dependence on both temperature and moisture conditions in
!!                warmer climates. \n
!!                Leaf onset begins when the a PFT-dependent GDD threshold is reached.
!!                In addition there are temperature and moisture conditions.
!!                The temperature condition specifies that the monthly temperature has to be
!!                higher than a constant threshold (::t_always) OR
!!                the weekly temperature is higher than the monthly temperature.
!!                There has to be at least some moisture. The moisture condition
!!                is exactly the same as the 'moi' onset model (::pheno_moi), which has
!!                already been described. \n
!!                GDD is set to undef if beginning of the growing season detected.
!!                As in the ::pheno_humgdd model, the parameter ::t_always is defined as
!!                10 degrees C in this subroutine, as are the parameters ::moisture_avail_tree
!!                and ::moisture_avail_grass (set to 1 and 0.6 respectively), which are used
!!                in the moisture condition (see ::pheno_moi onset model description). \n
!!                The PFT-dependent GDD threshold (::gdd_crit) is calculated as in the onset
!!                model ::pheno_humgdd, using the equation:
!!                \latexonly
!!                \input{phenology_hummoigdd_gddcrit_eqn4.tex}
!!                \endlatexonly
!!                \n
!!                where i and j are the grid cell and PFT respectively.
!!                The three GDDcrit parameters (::gdd(j,*)) are set for each PFT in
!!                ::stomate_data, and three tables defining each of the three critical GDD
!!                parameters for each PFT is given in ::gdd_crit1_tab, ::gdd_crit2_tab and
!!                ::gdd_crit3_tab in ::stomate_constants. \n
!!                The ::pheno_moigdd subroutine is called in the subroutine ::phenology.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::begin_leaves - specifies whether leaf growth can start
!!
!! REFERENCE(S) :
!! - Botta, A., N. Viovy, P. Ciais, P. Friedlingstein and P. Monfray (2000),
!! A global prognostic scheme of leaf onset using satellite data,
!! Global Change Biology, 207, 337-347.
!! - Chuine, I (2000), A unified model for the budburst of trees, Journal of
!! Theoretical Biology, 207, 337-347.
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_moigdd.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : pheno_ncdgdd
!!
!>\BRIEF          The Number of Chilling Days - Growing Degree Day (NCD-GDD) model initiates
!!                leaf onset if a certain relationship between the number of chilling days (NCD)
!!                since leaves were lost, and the growing degree days (GDD) since midwinter, is
!!                fulfilled.
!!                Currently PFT 6 (Temperate Broad-leaved Summergreen) and PFT 8 (Boreal Broad-
!!                leaved Summergreen) are assigned to this model.
!!
!! DESCRIPTION  : Experiments have shown that some
!!                species have a "chilling" requirement, i.e. their physiology needs cold
!!                temperatures to trigger the mechanism that will allow the following budburst
!!                (e.g. Orlandi et al., 2004).
!!                An increase in chilling days, defined as a day with a daily mean air
!!                temperature below a PFT-dependent threshold, reduces a plant's GDD demand
!!                (Cannell and Smith, 1986; Murray et al., (1989); Botta et al., 2000).
!!                The GDD threshold therefore decreases as NCD
!!                increases, using the following empirical negative explonential law:
!!                \latexonly
!!                \input{phenology_ncdgdd_gddmin_eqn5.tex}
!!                \endlatexonly
!!                \n
!!                The constants used have been calibrated against data CHECK FOR REFERENCE OR PERSON WHO DID UPDATE.
!!                Leaf onset begins if the GDD is higher than the calculated minimum GDD
!!                (dependent upon NCD) AND if the weekly temperature is higher than the monthly
!!                temperature. This is to ensure the temperature is increasing. \n
!!                The dormancy time-length is represented by the variable
!!                ::time_lowgpp, which is calculated in ::stomate_season. It is increased by
!!                the stomate time step when the weekly GPP is lower than a threshold. Otherwise
!!                it is set to zero. \n
!!                The NCD (::ncd_dormance) is calculated in ::stomate_season as
!!                the number of days with a temperature below a PFT-dependent constant threshold
!!                (::ncdgdd_temp), starting from the beginning of the dormancy period
!!                (::time_lowgpp>0), i.e. since the leaves were lost. \n
!!                The growing degree day sum of the temperatures higher than
!!                ::ncdgdd_temp (GDD) since midwinter (::gdd_midwinter)
!!                is also calculated in ::stomate_season.
!!                Midwinter is detected if the monthly temperature is lower than the weekly
!!                temperature AND  the monthly temperature is lower than the long-term
!!                temperature. ::gdd_minter is therefore set to 0 at the beginning of midwinter
!!                and increased with each temperature greater than the PFT-dependent threshold.
!!                When midsummer is detected (the opposite of the above conditions),
!!                ::gdd_midwinter is set to undef.
!!                CHECK! WHEN TO START OF DORMANCY BEEN MODIFIED FROM BOTTA- ADD IN?
!!                The ::pheno_ncdgdd subroutine is called in the subroutine ::phenology.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::begin_leaves - specifies whether leaf growth can start
!!
!! REFERENCE(S) :
!! - Botta, A., N. Viovy, P. Ciais, P. Friedlingstein and P. Monfray (2000),
!! A global prognostic scheme of leaf onset using satellite data,
!! Global Change Biology, 207, 337-347.
!! - Cannell, M.J.R. and R.I. Smith (1986), Climatic warming, spring budburst and
!! frost damage on trees, Journal of Applied Ecology, 23, 177-191.
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!! - Murray, M.B., G.R. Cannell and R.I. Smith (1989), Date of budburst of fifteen
!! tree species in Britain following climatic warming, Journal of Applied Ecology,
!! 26, 693-700.
!! - Orlandi, F., H. Garcia-Mozo, L.V. Ezquerra, B. Romano, E. Dominquez, C. Galan,
!! and M. Fornaciari (2004), Phenological olive chilling requirements in Umbria
!! (Italy) and Andalusia (Spain), Plant Biosystems, 138, 111-116.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_ncdgdd.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : pheno_ngd
!!
!>\BRIEF          The Number of Growing Days (NGD) leaf onset model initiates leaf onset if the NGD,
!!                defined as the number of days with temperature above a constant threshold,
!!                exceeds a critical value.
!!                Currently PFT 9 (Boreal Leedleleaf Summergreen) is assigned to this model.
!!
!! DESCRIPTION    The NGD model is a variant of the GDD model. The model was proposed by Botta et
!!                al. (2000) for boreal and arctic biomes, and is designed to estimate
!!                leaf onset after the end of soil frost.
!!                The NDG (::ngd_minus5) is the number of days with a daily mean air
!!                temperature of greater than -5 degrees C,
!!                starting from the beginning of the dormancy period (i.e. time since the leaves
!!                were lost/GPP below a certain threshold).
!!                Leaf onset begins if the NGD is higher than the PFT-dependent constant threshold,
!!                ::ngd,  AND if the weekly temperature is higher than the monthly
!!                temperature. \n
!!                The dormancy time-length is represented by the variable
!!                ::time_lowgpp, which is calculated in ::stomate_season. It is increased by
!!                the stomate time step when the weekly GPP is lower than a threshold. Otherwise
!!                it is set to zero. \n
!!                ::ngd_minus5 is also calculated in ::stomate_season. It is initialised at the
!!                beginning of the dormancy period (::time_lowgpp>0), and increased by the
!!                stomate time step when the temperature > -5 degrees C. \n
!!                ::ngd is set for each PFT in ::stomate_data, and a
!!                table defining the minimum NGD for each PFT is given in ::ngd_crit_tab
!!                in ::stomate_constants. \n
!!                The ::pheno_ngd subroutine is called in the subroutine ::phenology.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::begin_leaves - specifies whether leaf growth can start
!!
!! REFERENCE(S) :
!! - Botta, A., N. Viovy, P. Ciais, P. Friedlingstein and P. Monfray (2000),
!! A global prognostic scheme of leaf onset using satellite data,
!! Global Change Biology, 207, 337-347.
!! - Krinner, G., N. Viovy, N. de Noblet-Ducoudre, J. Ogee, J. Polcher, P.
!! Friedlingstein, P. Ciais, S. Sitch and I.C. Prentice (2005), A dynamic global
!! vegetation model for studies of the coupled atmosphere-biosphere system, Global
!! Biogeochemical Cycles, 19, doi:10.1029/2003GB002199.
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_ngd.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!
! ==============================================================================
! DZ modified for C4 grass: mean monthly temperature must be greater than 22
! degree for C4 to begin leaves (based on moigdd).
!


!! ================================================================================================================================
!! SUBROUTINE  : kill
!!
!>\BRIEF       Kills natural pfts that have low biomass or low number of individuals,
!! returns biomass to litter pools,  and resets biomass to zero.
!!
!! DESCRIPTION : Kills natural PFTS. The PFT vegetation characteristics are
!! reinitialized. Kill is either done in DGVM mode or in non-DGVM mode
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): senescence, PFTpresent, cn_ind, ind, RIP_time, age, when_growthinit,
!! everywhere,beget, veget_max, npp_longterm, biomass, bm_to_litter, leaf_age, leaf_frac
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE    : vmax
!!
!>\BRIEF         This subroutine computes vcmax photosynthesis parameters
!! given optimal vcmax parameter values and a leaf age-related efficiency.
!!
!! DESCRIPTION (functional, design, flags):
!! Leaf age classes are introduced to take into account the fact that photosynthetic activity depends on leaf age
!! (Ishida et al., 1999). There are \f$nleafages\f$ classes (constant defined in stomate_constants.f90).
!! This subroutine first calculates the new age of each leaf age-class based on fraction of leaf
!! that goes from one to another class.
!! Then calculation of the new fraction of leaf in each class is performed.
!! Last, leaf efficiency is calculated for each PFT and for each leaf age class.
!! vcmax is defined as vcmax25 and vjmax_opt weighted by a mean leaf
!! efficiency. vcmax25 is PFT-dependent constants defined in constants_mtc.f90.
!!
!! This routine is called once at the beginning by stomate_var_init and then at each stomate time step by stomateLpj.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): vcmax
!!
!! REFERENCE(S)	:
!! - Ishida, A., A. Uemura, N. Koike, Y. Matsumoto, and A. Lai Hoe (1999),
!! Interactive effects of leaf age and self-shading on leaf structure, photosynthetic
!! capacity and chlorophyll fluorescence in the rain forest tree,
!! dryobalanops aromatica, Tree Physiol., 19, 741-747
!!
!! FLOWCHART    : None
!!
!! REVISION(S)	: None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE 	: data
!!
!>\BRIEF         This routine defines the values of the PFT parameters. It will print the values of the parameters for STOMATE
!!               in the standard outputs of ORCHIDEE.
!!
!! DESCRIPTION : This routine defines PFT parameters. It initializes the pheno_crit structure by tabulated parameters.\n
!!               Some initializations are done for parameters. The SLA is calculated according *to* Reich et al (1992).\n
!!               Another formulation by Reich et al(1997) could be used for the computation of the SLA.
!!               The geographical coordinates might be used for defining some additional parameters
!!               (e.g. frequency of anthropogenic fires, irrigation of agricultural surfaces, etc.). \n
!!               For the moment, this possibility is not used. \n
!!               The specifc leaf area (SLA) is calculated according Reich et al, 1992 by :
!!               \latexonly
!!               \input{stomate_data_SLA.tex}
!!               \endlatexonly
!!               The sapling (young) biomass for trees and for each compartment of biomass is calculated by :
!!               \latexonly
!!               \input{stomate_data_sapl_tree.tex}
!!               \endlatexonly
!!               The sapling biomass for grasses and for each compartment of biomass is calculated by :
!!               \latexonly
!!               \input{stomate_data_sapl_grass.tex}
!!               \endlatexonly
!!               The critical stem diameter is given by the following formula :
!!               \latexonly
!!               \input{stomate_data_stem_diameter.tex}
!!               \endlatexonly
!!
!! RECENT CHANGE(S): Sonke Zaehle: Reich et al, 1992 find no statistically significant differences
!!                  between broadleaved and coniferous forests, specifically, the assumption that grasses grow
!!                  needles is not justified. Replacing the function with the one based on Reich et al. 1997.
!!                  Given that sla=100cm2/gDW at 9 months, sla is:
!!                  sla=exp(5.615-0.46*ln(leaflon in months))
!!                   \latexonly
!!                   \input{stomate_data_SLA_Reich_97.tex}
!!                   \endlatexonly
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) :
!! - Reich PB, Walters MB, Ellsworth DS, (1992), Leaf life-span in relation to leaf, plant and
!! stand characteristics among diverse ecosystems. Ecological Monographs, Vol 62, pp 365-392.
!! - Reich PB, Walters MB, Ellsworth DS (1997) From tropics to tundra: global convergence in plant
!!  functioning. Proc Natl Acad Sci USA, 94:13730 13734
!!
!! FLOWCHART    :
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE 	: light
!!
!>\BRIEF         Light competition within a PFT
!!
!! DESCRIPTION  : This module kills PFTs based on light competition
!!
!! Here, fpc ("foilage projected cover") takes into account the minimum fraction
!! of space covered by trees through branches etc. This is done to prevent strong relative
!! changes of FPC from one day to another for deciduous trees at the beginning of their
!! growing season, which would yield too strong cutbacks.\n
!!
!! fpc is now always calculated from lm_lastyearmax*sla, since the aim of this DGVM is
!! to represent community ecology effects; seasonal variations in establishment related to phenology
!! may be relevant, but beyond the scope of a 1st generation DGVM.\n
!!
!! If agriculture is present, fpc can never reach 1.0 since natural veget_max < 1.0. To
!! correct for this, ::ind must be recalculated to correspond to the natural density.
!! since ::ind is expressed in m^{-2} grid cell, this can be achieved by dividing individual
!! density by the agricultural fraction.\n
!!
!! The flow in the routine is different for ::control%ok_dgvm. When ::control%ok_dgvm is true
!! the following processes are considered:
!!
!! No competition between woody pfts (height of individuals is not considered).
!! Exception: when one woody pft is overwhelming (i.e. fpc > fpc_crit). In that
!! case, eliminate all other woody pfts and reduce dominant pft to fpc_crit.
!! Age of individuals is not considered. In reality, light competition would more
!! easily kill young individuals, thus increasing the mean age of the stand.
!! Exclude agricultural pfts from competition.\n
!!
!! When ::control%ok_dgvm is false then light competition is calculated for the static case if the mortality is not
!! assumed to be constant. The following processes are considered: XXX
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ind, biomass, veget_lastlight, bm_to_litter, mortality
!!
!! REFERENCES   :
!! - Sitch, S., B. Smith, et al. (2003), Evaluation of ecosystem dynamics,
!! plant geography and terrestrial carbon cycling in the LPJ dynamic
!! global vegetation model, Global Change Biology, 9, 161-185.\n
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : prescribe
!!
!>\BRIEF         Works only with static vegetation and agricultural PFT. Initialize biomass,
!!               density, crown area in the first call and update them in the following.
!!
!! DESCRIPTION (functional, design, flags): \n
!! This module works only with static vegetation and agricultural PFT.
!! In the first call, initialize density of individuals, biomass, crown area,
!! and leaf age distribution to some reasonable value. In the following calls,
!! these variables are updated.
!!
!! To fulfill these purposes, pipe model are used:
!! \latexonly
!!     \input{prescribe1.tex}
!!     \input{prescribe2.tex}
!! \endlatexonly
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLES(S): ::ind, ::cn_ind, ::leaf_frac
!!
!! REFERENCES   :
!! - Krinner, G., N. Viovy, et al. (2005). "A dynamic global vegetation model
!!   for studies of the coupled atmosphere-biosphere system." Global
!!   Biogeochemical Cycles 19: GB1015, doi:1010.1029/2003GB002199.
!! - Sitch, S., B. Smith, et al. (2003), Evaluation of ecosystem dynamics,
!!   plant geography and terrestrial carbon cycling in the LPJ dynamic
!!   global vegetation model, Global Change Biology, 9, 161-185.
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : littercalc
!!
!!\BRIEF        Calculation of the litter decomposition and therefore of the
!! heterotrophic respiration from litter following Parton et al. (1987).
!!
!! DESCRIPTION  : The littercal routine splits the litter in 4 pools:
!! aboveground metaboblic, aboveground structural, belowground metabolic and
!! belowground structural. the fraction (F) of plant material going to metabolic
!! and structural is defined following Parton et al. (1987)
!! \latexonly
!! \input{littercalc1.tex}
!! \endlatexonly
!! \n
!! where L is the lignin content of the plant carbon pools considered and CN
!! its CN ratio. L and CN are fixed parameters for each plant carbon pools,
!! therefore it is the ratio between each plant carbon pool within a PFT, which
!! controlled the part of the total litter, that will be considered as
!! recalcitrant (i.e. structural litter) or labile (i.e. metabolic litter).\n
!!
!! The routine calculates the fraction of aboveground litter which is metabolic
!! or structural (the litterpart variable) which is then used in lpj_fire.f90.\n
!!
!! In the section 2, the routine calculate the new plant material entering the
!! litter pools by phenological death of plants organs (corresponding to the
!! variable turnover) and by fire, herbivory and others non phenological causes
!! (variable bm_to_litter). This calculation is first done for each PFT and then
!! the values calculated for each PFT are added up. Following the same approach
!! the lignin content of the total structural litter is calculated and will be
!! then used as a factor control of the decomposition of the structural litter
!! (lignin_struc) in the section 5.1.2. A test is performed to avoid that we add
!! more lignin than structural litter. Finally, the variable litterpart is
!! updated.\n
!!
!! In the section 3 and 4 the temperature and the moisture controlling the
!! decomposition are calculated for above and belowground. For aboveground
!! litter, air temperature and litter moisture are calculated in sechiba and used
!! directly. For belowground, soil temperature and moisture are also calculated
!! in sechiba but are modulated as a function of the soil depth. The modulation
!! is a multiplying factor exponentially distributed between 0 (in depth) and 1
!! in surface.\n
!!
!! Then, in the section 5, the routine calculates the structural litter decomposition
!! (C) following first order kinetics following Parton et al. (1987).
!! \latexonly
!! \input{littercalc2.tex}
!! \endlatexonly
!! \n
!! with k the decomposition rate of the structural litter.
!! k corresponds to
!! \latexonly
!! \input{littercalc3.tex}
!! \endlatexonly
!! \n
!! with littertau the turnover rate, T a function of the temperature and M a function of
!! the moisture described below.\n
!!
!! Then, the fraction of dead leaves (DL) composed by aboveground structural litter is
!! calculated as following
!! \latexonly
!! \input{littercalc4.tex}
!! \endlatexonly
!! \n
!! with k the decomposition rate of the structural litter previously
!! described.\n
!!
!! In the section 5.1, the fraction of decomposed structural litter
!! incorporated to the soil (Input) and its associated heterotrophic respiration are
!! calculated. For structural litter, the C decomposed could go in the active
!! soil carbon pool or in the slow carbon, as described in
!! stomate_soilcarbon.f90.\n
!! \latexonly
!! \input{littercalc5.tex}
!! \endlatexonly
!! \n
!! with f a parameter describing the fraction of structural litter incorporated
!! into the considered soil carbon pool, C the amount of litter decomposed and L
!! the amount of lignin in the litter. The litter decomposed which is not
!! incorporated into the soil is respired.\n
!!
!! In the section 5.2, the fraction of decomposed metabolic litter
!! incorporated to the soil and its associated heterotrophic respiration are
!! calculated with the same approaches presented for 5.1 but no control factor
!! depending on the lignin content are used.\n
!!
!! In the section 6 the dead leaf cover is calculated through a call to the
!! deadleaf subroutine presented below.\n
!!
!! In the section 7, if the flag SPINUP_ANALYTIC is set to true, we fill MatrixA
!! and VectorB following Lardy(2011).
!!
!! MAIN OUTPUT VARIABLES: ::deadleaf_cover, ::resp_hetero_litter, ::soilcarbon_input,
!! ::control_temp, ::control_moist
!!
!! REFERENCES:
!! - Parton, WJ, Schimel, DS, Cole, CV, and Ojima, DS. 1987. Analysis
!! of factors controlling soil organic matter levels in Great Plains
!! grasslands. Soil Science Society of America journal (USA)
!! (51):1173-1179.
!! - Lardy, R, et al., A new method to determine soil organic carbon equilibrium,
!! Environmental Modelling & Software (2011), doi:10.1016|j.envsoft.2011.05.016
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics(scale=0.5){littercalcflow.jpg}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================\n
!! SUBROUTINE   : deadleaf
!!
!>\BRIEF        This routine calculates the deadleafcover.
!!
!! DESCRIPTION  : It first calculates the lai corresponding to the dead leaves (LAI) using
!! the dead leaves carbon content (DL) the specific leaf area (sla) and the
!! maximal coverage fraction of a PFT (vegetmax) using the following equations:
!! \latexonly
!! \input{deadleaf1.tex}
!! \endlatexonly
!! \n
!! Then, the dead leaf cover (DLC) is calculated as following:\n
!! \latexonly
!! \input{deadleaf2.tex}
!! \endlatexonly
!! \n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE: ::deadleaf_cover
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! FUNCTION     : control_moist_func
!!
!>\BRIEF        Calculate moisture control for litter and soil C decomposition
!!
!! DESCRIPTION  : Calculate moisture control factor applied
!! to litter decomposition and to soil carbon decomposition in
!! stomate_soilcarbon.f90 using the following equation: \n
!! \latexonly
!! \input{control_moist_func1.tex}
!! \endlatexonly
!! \n
!! with M the moisture control factor and soilmoisutre, the soil moisture
!! calculated in sechiba.
!! Then, the function is ranged between Moistcont_min and 1:\n
!! \latexonly
!! \input{control_moist_func2.tex}
!! \endlatexonly
!! \n
!! RECENT CHANGE(S) : None
!!
!! RETURN VALUE : ::moistfunc_result
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! FUNCTION     : control_temp_func
!!
!>\BRIEF        Calculate temperature control for litter and soild C decomposition
!!
!! DESCRIPTION  : Calculate temperature control factor applied
!! to litter decomposition and to soil carbon decomposition in
!! stomate_soilcarbon.f90 using the following equation: \n
!! \latexonly
!! \input{control_temp_func1.tex}
!! \endlatexonly
!! \n
!! with T the temperature control factor, temp the temperature in Kelvin of
!! the air (for aboveground litter) or of the soil (for belowground litter
!! and soil)
!! Then, the function is limited in its maximal range to 1:\n
!! \latexonly
!! \input{control_temp_func2.tex}
!! \endlatexonly
!! \n
!! RECENT CHANGE(S) : None
!!
!! RETURN VALUE: ::tempfunc_result
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!!  SUBROUTINE   : soilcarbon
!!
!>\BRIEF        Computes the soil respiration and carbon stocks, essentially
!! following Parton et al. (1987).
!!
!! DESCRIPTION	: The soil is divided into 3 carbon pools, with different
!! characteristic turnover times : active (1-5 years), slow (20-40 years)
!! and passive (200-1500 years).\n
!! There are three types of carbon transferred in the soil:\n
!! - carbon input in active and slow pools from litter decomposition,\n
!! - carbon fluxes between the three pools,\n
!! - carbon losses from the pools to the atmosphere, i.e., soil respiration.\n
!!
!! The subroutine performs the following tasks:\n
!!
!! Section 1.\n
!! The flux fractions (f) between carbon pools are defined based on Parton et
!! al. (1987). The fractions are constants, except for the flux fraction from
!! the active pool to the slow pool, which depends on the clay content,\n
!! \latexonly
!! \input{soilcarbon_eq1.tex}
!! \endlatexonly\n
!! In addition, to each pool is assigned a constant turnover time.\n
!!
!! Section 2.\n
!! The carbon input, calculated in the stomate_litter module, is added to the
!! carbon stock of the different pools.\n
!!
!! Section 3.\n
!! First, the outgoing carbon flux of each pool is calculated. It is
!! proportional to the product of the carbon stock and the ratio between the
!! iteration time step and the residence time:\n
!! \latexonly
!! \input{soilcarbon_eq2.tex}
!! \endlatexonly
!! ,\n
!! Note that in the case of crops, the additional multiplicative factor
!! integrates the faster decomposition due to tillage (following Gervois et
!! al. (2008)).
!! In addition, the flux from the active pool depends on the clay content:\n
!! \latexonly
!! \input{soilcarbon_eq3.tex}
!! \endlatexonly
!! ,\n
!! Each pool is then cut from the carbon amount corresponding to each outgoing
!! flux:\n
!! \latexonly
!! \input{soilcarbon_eq4.tex}
!! \endlatexonly\n
!! Second, the flux fractions lost to the atmosphere is calculated in each pool
!! by subtracting from 1 the pool-to-pool flux fractions. The soil respiration
!! is then the summed contribution of all the pools,\n
!! \latexonly
!! \input{soilcarbon_eq5.tex}
!! \endlatexonly\n
!! Finally, each carbon pool accumulates the contribution of the other pools:
!! \latexonly
!! \input{soilcarbon_eq6.tex}
!! \endlatexonly
!!
!! Section 4.\n
!! If the flag SPINUP_ANALYTIC is set to true, the matrix A is updated following
!! Lardy (2011).
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUTS VARIABLE(S): carbon, resp_hetero_soil
!!
!! REFERENCE(S)   :
!! - Parton, W.J., D.S. Schimel, C.V. Cole, and D.S. Ojima. 1987. Analysis of
!! factors controlling soil organic matter levels in Great Plains grasslands.
!! Soil Sci. Soc. Am. J., 51, 1173-1179.
!! - Gervois, S., P. Ciais, N. de Noblet-Ducoudre, N. Brisson, N. Vuichard,
!! and N. Viovy (2008), Carbon and water balance of European croplands
!! throughout the 20th century, Global Biogeochem. Cycles, 22, GB2022,
!! doi:10.1029/2007GB003018.
!! - Lardy, R, et al., A new method to determine soil organic carbon equilibrium,
!! Environmental Modelling & Software (2011), doi:10.1016|j.envsoft.2011.05.016
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale=0.5]{soilcarbon_flowchart.jpg}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : gap
!!
!>\BRIEF        Simulate tree and grass mortality, transfer dead biomass to litter and update stand density
!!
!! DESCRIPTION  : Calculate mortality of trees and grasses, transfer the dead biomass to litter pool,
!! and update biomass pool and number of individuals. To get tree mortality, it's possible to choose either a
!! constant mortality rate; or to calculate the tree mortality rate based on it's growth efficiency, which is
!! defined as this year's net biomass increment per leaf area.\n
!!
!! When using growth efficiency mortality, first calculate the net biomass increment for the last year, then
!! calculate the growth efficiency and finally calculate the growth efficiency mortality.\n
!!
!! Eqation to calculate growth efficiency:
!! \latexonly
!!     \input{gap1.tex}
!! \endlatexonly
!! Where $greff$ is growth efficiency, $\Delta$ is net biomass increment,
!! $C_{leaf} is last year's leaf biomass, and $SLA$ the specific leaf area.
!!
!!
!! Eqation to calculate growth efficiency mortality:
!! \latexonly
!!     \input{gap2.tex}
!! \endlatexonly
!! Where $mort_{greff}$ is the growth efficiency mortality, $greff$ is growth
!! efficiency, $k_{mort1}$ is asymptotic maximum mortality rate.
!!
!! The name for variable ::availability is not well chosen. Actually the meaning of the variable is mortailty
!! rate derived from growth efficiency related mortality. ?? Suggestion: change the name "availability" to
!! "mortgref", which means "mortality caused by ".\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::biomass; biomass, ::ind density of individuals, ::bm_to_litter biomass transfer
!! to litter and ::mortality mortality (fraction of trees that is dying per time step)
!!
!! REFERENCE(S)   :
!! - Sitch, S., B. Smith, et al. (2003), Evaluation of ecosystem dynamics,
!!         plant geography and terrestrial carbon cycling in the LPJ dynamic
!!         global vegetation model, Global Change Biology, 9, 161-185.
!! - Waring, R. H. (1983). "Estimating forest growth and efficiency in relation
!!         to canopy leaf area." Advances in Ecological Research 13: 327-354.
!!
!! FLOWCHART    : None
!!\n
!_ ================================================================================================================================