!#######################################################################
!<SUBROUTINE NAME="generate_topog">
!<OVERVIEW>
!  generate topography data.
!</OVERVIEW>
!<DESCRIPTION>
!Call horiz_interp to calculate regridded topography.
!Perform topography checks
!</DESCRIPTION>
!   <TEMPLATE>
!     call generate_topog(Hgrid, Topog, Vgrid)
!   </TEMPLATE>
!<IN NAME="Hgrid" TYPE="type(hgrid_data_type)">
!  A derived-type variable that contains horizontal grid information.
!</IN>
!<IN NAME="Vgrid" TYPE="type(vgrid_data_type), optional">
!  A derived-type variable that contains vertical grid information.
!</IN>
!<INOUT NAME="Topog" TYPE="type(topog_data_type)">
!  A derived-type variable that contains topography data.
!</INOUT>
!</SUBROUTINE>


!#######################################################################
!--- Construct a domain similar to the DOME configuration used in
!    Legg, Hallberg, and Girton (2005) Ocean Modelling.
!
!
!                       |     |
!                       |     |
!                      /|     |
!                     / |     |
!     up             /  |     |
!     ^             /   |     |
!     |            /    |     |
!     |           /     |     |
!                /      |     |
!---------------/-------|-----|
!     --->north
!
!


!#######################################################################
! <SUBROUTINE NAME="vgrid_init" >
!   <OVERVIEW>
!    Initialization routine.
!   </OVERVIEW>
!   <DESCRIPTION>
!    Read namelist, write out version and namelist informaiton and generate depth resolution.
!   </DESCRIPTION>
!   <TEMPLATE>
!     call vgrid_init ( )
!   </TEMPLATE>
! </SUBROUTINE>


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_init
!!
!>\BRIEF         Initialisation of all variables linked to SLOWPROC
!!
!! DESCRIPTION  : (definitions, functional, design, flags): The subroutine manages
!! diverses tasks:
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::lcanop, ::veget_update, ::veget_year,
!! ::lai, ::veget, ::frac_nobio, ::totfrac_nobio, ::veget_max, ::height, ::soiltype
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_clear
!!
!>\BRIEF          Clear all variables related to slowproc and stomate modules
!!
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_derivvar
!!
!>\BRIEF         Initializes variables related to the
!! parameters to be assimilated, the maximum water on vegetation, the vegetation height,
!! and the fraction of soil covered by dead leaves and the vegetation height
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!! (1) Initialization of the variables relevant for the assimilation parameters
!! (2) Intialization of the fraction of soil covered by dead leaves
!! (3) Initialization of the Vegetation height per PFT
!! (3) Initialization the maximum water on vegetation for interception with a particular treatement of the PFT no.1
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::qsintmax, ::deadleaf_cover, ::assim_param, ::height
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_mean
!!
!>\BRIEF          Accumulates field_in over a period of dt_tot.
!! Has to be called at every time step (dt).
!! Mean value is calculated if ldmean=.TRUE.
!! field_mean must be initialized outside of this routine!
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!! (1) AcumAcuumlm
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::field_main
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_long
!!
!>\BRIEF        Calculates a temporally smoothed field (field_long) from
!! instantaneous input fields.Time constant tau determines the strength of the smoothing.
!! For tau -> infinity??, field_long becomes the true mean value of field_inst
!! (but  the spinup becomes infinietly long, too).
!! field_long must be initialized outside of this routine!
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!! (1) Testing the time coherence betwen the time step dt and the time tau over which
!! the rescaled of the mean is performed
!!  (2) Computing the rescaled mean over tau period
!! MAIN OUTPUT VARIABLE(S): field_long
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::field_long
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_veget
!!
!>\BRIEF        Sum up veget_max and frac_nobio and test if sum is equal to 1.
!! In case there is a problem, a correction is performed when possible, otherwise
!! it stops.
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!! (1) Summing up frac_nobio and veget_max. Test if the sum is equal to unity.
!!  If not, when possible a solution is proposed, otherwise the routine stops
!! (2) Setting veget to veget_max
!! (3) Testing the  lai of a vegetation type. If small the soil part of the pixel is increased
!! (4) Summing the surface fractions and test if it is equal to 1. If not, when
!! possible, a solution is given, otherwise the routine stops.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::veget
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_lai
!!
!>\BRIEF        Do the interpolation of lai for the PFTs in case the laimap is not read
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!! (1) Interplation by using the mean value of laimin and laimax for the PFTs
!! (2) Interpolation between laimax and laimin values by using the temporal
!!  variations
!! (3) If problem occurs during the interpolation, the routine stops
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::lai
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


! SHOULD BE DROPED (not commented) ???
!! ================================================================================================================================
!! SUBROUTINE   : slowproc_interlai_OLD
!!
!>\BRIEF         Interpolate the LAI map to the grid of the model
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::laimap
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_interlai_NEW
!!
!>\BRIEF         Interpolate the LAI map to the grid of the model
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::laimap
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


! NOT COMMENTED YET!
!! ================================================================================================================================
!! SUBROUTINE   : slowproc_update
!!
!>\BRIEF          Interpolate a vegetation map (by pft) NEED TO BE DONE!!!!!!!!
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


! NEED TO GET RID OF SLOWPROC_INTERPOL_OLD because it is never called!
!! ================================================================================================================================
!! SUBROUTINE   : slowproc_interpol_OLD
!!
!>\BRIEF         Interpolate the IGBP vegetation map to the grid of the model
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!MM TAG 1.6 model !


! NEED TO GET RID OF SLOWPROC_INTERPOL_NEW because it is never called!
!! ================================================================================================================================
!! SUBROUTINE   : slowproc_interpol_NEW
!!
!>\BRIEF         Interpolate the IGBP vegetation map to the grid of the model
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


! NEED TO GET RID OF SLOWPROC_INTERPOL_OLD_g because it correspond to version 1.6 of the code
! for CMIP3 simulations (too old)
!
!! ================================================================================================================================
!! SUBROUTINE   : slowproc_interpol_OLD_g
!!
!>\BRIEF         Interpolate the IGBP vegetation map to the grid of the model
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!MM TAG 1.6 model !


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_interpol_NEW_g
!!
!>\BRIEF         Interpolate the IGBP vegetation map to the grid of the model
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::veget, ::frac_nobio
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_nearest
!!
!>\BRIEF         looks for nearest grid point on the fine map
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::inear
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_soilt
!!
!>\BRIEF         Interpolate the Zobler soil type map
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::soiltype, ::clayfraction
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_slope
!!
!>\BRIEF         Calculate mean slope coef in each  model grid box from the slope map
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::reinf_slope
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! FUNCTION 	: tempfunc
!!
!>\BRIEF        ! This function interpolates value between ztempmin and ztempmax
!! used for lai detection.
!!
!! DESCRIPTION   : This subroutine calculates a scalar between 0 and 1 with the following equation :\n
!!                 \latexonly
!!                 \input{constantes_veg_tempfunc.tex}
!!                 \endlatexonly
!!
!! RECENT CHANGE(S): None
!!
!! RETURN VALUE : tempfunc_result
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : slowproc_read_veg_restfile
!!
!>\BRIEF         read a vegetation map from a restart file, and interpolate if
!necessary to current model grid
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): :: none
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : slowproc_checkveget
!!
!>\BRIEF         To verify the consistency of the various fractions defined within the grid box after having been
!!               been updated by STOMATE or the standard procedures.
!!
!! DESCRIPTION  : (definitions, functional, design, flags):
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): :: none
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================
!


!! ==============================================================================================================================
!! SUBROUTINE   : condveg_init
!!
!>\BRIEF        Dynamic allocation of the variables, the dimensions of the
!! variables are determined by user-specified settings.
!!
!! DESCRIPTION  : The domain size (:: kjpindex) is used to allocate the correct
!! dimensions to all variables in condveg.
!!
!! 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
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE 	: condveg_clear
!!
!>\BRIEF        Deallocate albedo variables
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCES	: None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : condveg_var_init
!!
!>\BRIEF        Initialisation of local array and calculation of emissivity,
!! albedo and roughness height.
!!
!! DESCRIPTION : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : condveg_var_update
!!
!>\BRIEF        Update emissivity, albedo and roughness height.
!!
!! DESCRIPTION  : None
!!
!! MAIN OUTPUT VARIABLE(S): \n
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================\n
!! SUBROUTINE   : condveg_snow
!!
!>\BRIEF        Calcuating snow albedo and snow cover fraction, which are then used to
!! update the gridbox surface albedo following Chalita and Treut (1994).
!!
!! DESCRIPTION  : The snow albedo scheme presented below belongs to prognostic albedo
!! category, i.e. the snow albedo value at a time step depends on the snow albedo value
!! at the previous time step.
!!
!! First, the following formula (described in Chalita and Treut 1994) is used to describe
!! the change in snow albedo with snow age on each PFT and each non-vegetative surfaces,
!! i.e. continental ice, lakes, etc.: \n
!! \latexonly
!! \input{SnowAlbedo.tex}
!! \endlatexonly
!! \n
!! Where snowAge is snow age, tcstSnowa is a critical aging time (tcstSnowa=5 days)
!! snowaIni and snowaIni+snowaDec corresponds to albedos measured for aged and
!! fresh snow respectively, and their values for each PFT and each non-vegetative surfaces
!! is precribed in in constantes_veg.f90.\n
!! In order to estimate gridbox snow albedo, snow albedo values for each PFT and
!! each  non-vegetative surfaces with a grid box are weightedly summed up by their
!! respective fractions.\n
!! Secondly, the snow cover fraction is computed as:
!! \latexonly
!! \input{SnowFraction.tex}
!! \endlatexonly
!! \n
!! Where fracSnow is the fraction of snow on total vegetative or total non-vegetative
!! surfaces, snow is snow mass (kg/m^2) on total vegetated or total nobio surfaces.\n
!! Finally, the surface albedo is then updated as the weighted sum of fracSnow, total
!! vegetated fraction, total nobio fraction, gridbox snow albedo, and previous
!! time step surface albedo.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): :: albedo; surface albedo. :: albedo_snow; snow
!! albedo
!!
!! REFERENCE(S) :
!! Chalita, S. and H Le Treut (1994), The albedo of temperate and boreal forest and
!!  the Northern Hemisphere climate: a sensitivity experiment using the LMD GCM,
!!  Climate Dynamics, 10 231-240.
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! Arsene 16-07-2016 - Add new Albedo - START
!! ==============================================================================================================================\n
!! SUBROUTINE   : condveg_snow_modis
!!
!>\BRIEF        Calcuating snow albedo and snow cover fraction, which are then used to
!! update the gridbox surface albedo following Chalita and Treut (1994).
!!
!! DESCRIPTION  : The snow albedo scheme presented below belongs to prognostic albedo
!! category, i.e. the snow albedo value at a time step depends on the snow albedo value
!! at the previous time step.
!!
!! First, the following formula (described in Chalita and Treut 1994) is used to describe
!! the change in snow albedo with snow age on each PFT and each non-vegetative surfaces,
!! i.e. continental ice, lakes, etc.: \n
!! \latexonly
!! \input{SnowAlbedo.tex}
!! \endlatexonly
!! \n
!! Where snowAge is snow age, tcstSnowa is a critical aging time (tcstSnowa=5 days)
!! snowaIni and snowaIni+snowaDec corresponds to albedos measured for aged and
!! fresh snow respectively, and their values for each PFT and each non-vegetative surfaces
!! is precribed in in constantes_veg.f90.\n
!! In order to estimate gridbox snow albedo, snow albedo values for each PFT and
!! each  non-vegetative surfaces with a grid box are weightedly summed up by their
!! respective fractions.\n
!! Secondly, the snow cover fraction is computed as:
!! \latexonly
!! \input{SnowFraction.tex}
!! \endlatexonly
!! \n
!! Where fracSnow is the fraction of snow on total vegetative or total non-vegetative
!! surfaces, snow is snow mass (kg/m^2) on total vegetated or total nobio surfaces.\n
!! Finally, the surface albedo is then updated as the weighted sum of fracSnow, total
!! vegetated fraction, total nobio fraction, gridbox snow albedo, and previous
!! time step surface albedo.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): :: albedo; surface albedo. :: albedo_snow; snow
!! albedo
!!
!! REFERENCE(S) :
!! Chalita, S. and H Le Treut (1994), The albedo of temperate and boreal forest and
!!  the Northern Hemisphere climate: a sensitivity experiment using the LMD GCM,
!!  Climate Dynamics, 10 231-240.
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! Arsene 16-07-2016 - Add new Albedo - END
!! ==============================================================================================================================
!! SUBROUTINE   : condveg_soilalb
!!
!>\BRIEF        This subroutine calculates the albedo of soil (without snow).
!!
!! DESCRIPTION  This subroutine reads the soil colour maps in 1 x 1 deg resolution
!! from the Henderson-Sellers & Wilson database. These values are interpolated to
!! the model's resolution and transformed into
!! dry and wet albedos.\n
!!
!! If the soil albedo is calculated without the dependence of soil moisture, the
!! soil colour values are transformed into mean soil albedo values.\n
!!
!! The calculations follow the assumption that the grid of the data is regular and
!! it covers the globe. The calculation for the model grid are based on the borders
!! of the grid of the resolution.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):    soilalb_dry for visible and near-infrared range,
!!                             soilalb_wet for visible and near-infrared range,
!!                             soilalb_moy for visible and near-infrared range
!!
!! REFERENCE(S) :
!! -Wilson, M.F., and A. Henderson-Sellers, 1985: A global archive of land cover and
!!  soils data for use in general circulation climate models. J. Clim., 5, 119-143.
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! Arsene 16-07-2016 - Add new Albedo - START
!! ==============================================================================================================================
!! SUBROUTINE   : condveg_background_soilalb
!!
!>\BRIEF        This subroutine reads the albedo of bare soil
!!
!! DESCRIPTION  This subroutine reads the background albedo map in 0.5 x 0.5 deg resolution
!! derived from JRCTIP product to be used as bare soil albedo. These values are then interpolated
!! to the model's resolution.\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): soilalb_bg for visible and near-infrared range
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! Arsene 16-07-2016 - Add new Albedo - END
!! ==============================================================================================================================
!! SUBROUTINE   : condveg_z0logz
!!
!>\BRIEF        Computation of grid average of roughness height by averaging  the
!! logarithm of the roughness height of each grid box components fracbio and fracnobio.
!!
!! DESCRIPTION  : Calculates mean roughness height
!!  over the grid cell. The mean roughness height is derived from the vegetation
!! height which is scaled by the roughness parameter. The sum of the logarithm of the
!! roughness times the fraction per grid cell gives the average roughness height per
!! grid cell for the vegetative PFTs. The roughness height for the non-vegetative PFTs
!! is calculated in a second step. \n
!!
!! To compute the fluxes,
!! the difference between the height of the vegetation and the zero plane displacement height
!! is needed and called roughheight .\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): roughness height (z0), grid effective roughness height (roughheight)
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : condveg_z0cdrag
!!
!>\BRIEF        Computation of grid average of roughness length by calculating
!! the drag coefficient.
!!
!! DESCRIPTION  : This routine calculates the mean roughness height and mean
!! effective roughness height over the grid cell. The mean roughness height (z0)
!! is computed by averaging the drag coefficients  \n
!!
!! \latexonly
!! \input{z0cdrag1.tex}
!! \endlatexonly
!! \n
!!
!! where C is the drag coefficient at the height of the vegetation, kappa is the
!! von Karman constant, z (Ztmp) is the height at which the fluxes are estimated and z0 the roughness height.
!! The reference level for z needs to be high enough above the canopy to avoid
!! singularities of the LOG. This height is set to  minimum 10m above ground.
!! The drag coefficient increases with roughness height to represent the greater
!! turbulence generated by rougher surfaces.
!! The roughenss height is obtained by the inversion of the drag coefficient equation.\n
!!
!! The roughness height for the non-vegetative surfaces is calculated in a second step.
!! In order to calculate the transfer coefficients the
!! effective roughness height is calculated. This effective value is the difference
!! between the height of the vegetation and the zero plane displacement height.\nn
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):  :: roughness height(z0) and grid effective roughness height(roughheight)
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ==============================================================================================================================
!! SUBROUTINE   : condveg_albcalc
!!
!>\BRIEF        This subroutine calculates the albedo without snow.
!!
!! DESCRIPTION  : The albedo is calculated for both the visible and near-infrared
!! domain. First the mean albedo of the bare soil is calculated. Two options exist:
!! either the soil albedo depends on soil wetness (drysoil_frac variable), or the soil albedo
!! is set to a mean soil albedo value.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): albedo
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : explicitsnow_grain
!!
!>\BRIEF        Compute evolution of snow grain size
!!
!! DESCRIPTION  :
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : R. Jordan (1991)
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : explicitsnow_compactn
!!
!>\BRIEF        Compute Compaction/Settling
!!
!! DESCRIPTION  :
!!     Snow compaction due to overburden and settling.
!!     Mass is unchanged: layer thickness is reduced
!!     in proportion to density increases. Method
!!     of Anderson (1976): see Loth and Graf, 1993,
!!     J. of Geophys. Res., 98, 10,451-10,464.
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : Loth and Graf (1993), Mellor (1964) and Anderson (1976)
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : explicitsnow_transf
!!
!>\BRIEF        Computing snow mass and heat redistribution due to grid thickness configuration resetting
!!
!! DESCRIPTION  : Snow mass and heat redistibution due to grid thickness
!!                configuration resetting. Total mass and heat content
!!                of the overall snowpack unchanged/conserved within this routine.
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : explicitsnow_fall
!!
!>\BRIEF    Computes snowfall
!!
!! DESCRIPTION  :
!routine.
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : explicitsnow_gone
!!
!>\BRIEF        Check whether snow is gone
!!
!! DESCRIPTION  : If so, set thickness (and therefore mass and heat) and liquid
!!                content to zero, and adjust fluxes of water, evaporation and
!!                heat into underlying surface.
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!================================================================================================================================
!! SUBROUTINE   : explicitsnow_melt_refrz
!!
!>\BRIEF        Computes snow melt and refreezing processes within snowpack
!!
!! DESCRIPTION  :
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!================================================================================================================================
!! SUBROUTINE   : explicitsnow_levels
!!
!>\BRIEF        Computes snow discretization based on given total snow depth
!!
!! DESCRIPTION  :
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : explicitsnow_coef
!!
!>\BRIEF        Calculate snow thermal properties, integration coefficients, apparent heat flux,
!! surface heat capacity,
!!
!! DESCRIPTION	: This routine computes : \n
!!		1. the soil thermal properties. \n
!!		2. the integration coefficients of the thermal numerical scheme, cgrnd and dgrnd,
!!              which depend on the vertical grid and on soil properties, and are used at the next
!!              timestep.\n
!!              3. the soil apparent heat flux and surface heat capacity soilflux
!!              and soilcap, used by enerbil to compute the surface temperature at the next
!!              timestep.\n
!!             -  The soil thermal properties depend on water content (wetdiag) and on the presence
!!              of snow : snow is integrated into the soil for the thermal calculations, ie if there
!!              is snow on the ground, the first thermal layer(s) consist in snow, depending on the
!!              snow-depth. If a layer consists out of snow and soil, wheighed soil properties are
!!              calculated\n
!!             - The coefficients cgrnd and dgrnd are the integration
!!              coefficients for the thermal scheme \n
!!                              T(k+1)=cgrnd(k)+dgrnd(k)*T(k) \n
!!                                      -- EQ1 -- \n
!!              They correspond respectively to $\beta$ and $\alpha$ from F. Hourdin\'s thesis and
!!              their expression can be found in this document (eq A19 and A20)
!!             - soilcap and soilflux are the apparent surface heat capacity and flux
!!               used in enerbil at the next timestep to solve the surface
!!               balance for Ts (EQ3); they correspond to $C_s$ and $F_s$ in F.
!!               Hourdin\'s PhD thesis and are expressed in eq. A30 and A31. \n
!!                 soilcap*(Ts(t)-Ts(t-1))/dt=soilflux+otherfluxes(Ts(t)) \n
!!                                      -- EQ3 --\n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): cgrnd, dgrnd, pcapa, pkappa, soilcap, soilflx
!!
!! REFERENCE(S) :
!! - Hourdin, F. (1992). Study and numerical simulation of the general circulation of planetary atmospheres,
!! Ph.D. thesis, Paris VII University. Remark: the part of F. Hourdin's PhD thesis relative to the thermal
!! integration scheme has been scanned and is provided along with the documentation, with name :
!! Hourdin_1992_PhD_thermal_scheme.pdf
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : thermosoil_profile
!!
!>\BRIEF        In this routine solves the numerical soil thermal scheme, ie !calculates the new soil temperature profile;
!! This profile is then exported onto the diagnostic axis (call
!thermosoil_diaglev)
!!
!! DESCRIPTION  : The calculation of the new soil temperature profile is based !on
!! the cgrnd and dgrnd values from the previous timestep and the surface
!! temperature Ts aka temp_sol_new. (see detailed
!! explanation in the header of the thermosoil module or in the reference).\n
!!                              T(k+1)=cgrnd(k)+dgrnd(k)*T(k)\n
!!                                      -- EQ1 --\n
!!                           Ts=(1-lambda)*T(1) -lambda*T(2)\n
!!                                      -- EQ2--\n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): ptn (soil temperature profile on the thermal axis),
!!                          stempdiag (soil temperature profile on the diagnostic axis)
!!
!! REFERENCE(S) :
!! - Hourdin, F. (1992). Study and numerical simulation of the general circulation of planetary atmospheres,
!! Ph.D. thesis, Paris VII University. Remark: the part of F. Hourdin's PhD thesis relative to the thermal
!! integration scheme has been scanned and is provided along with the documentation, with name :
!! Hourdin_1992_PhD_thermal_scheme.pdf
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!! Interface for integer scalar to scalar.


!! Interface for initialising an 1D integer array with a scalar integer.


!! Interface for initialising an 1D array integer with an other 1D array integer.


!! Interface for initialising an 2D array integer with a scalar integer.


!! Interface for initialising an 2D array integer with an 1D array integer.
!! Row or column depending size of 1D array to stored.
!!
!! example: 1D 1,2,3     2D is 1, 2, 3,
!!                             1, 2, 3
!!
!!
!! example: 1D 1,2,3     2D is 1, 1,
!!                             2, 2,
!!                             3, 3
!!


!! Interface for initialising an 2D array integer with an other 2D array integer.


!! Interface for scalar to scalar real


!! Interface for initialising an 1D real array with a scalar real.


!! Interface for initialising an 1D array real with an other 1D array real.


!! Interface for initialising an 2D array real with a scalar real.


!! Interface for initialising an 2D array real with an 1D array real.
!! Row or column depending size of 1D array to stored.
!!
!! example: 1D 1.,2.,3.     2D is 1., 2., 3.,
!!                                1., 2., 3.
!!
!!
!! example: 1D 1.,2.,3.     2D is 1., 1.,
!!                                2., 2.,
!!                                3., 3.
!!


!! Interface for initialising an 2D array real with an other 2D array real.


!! Interface for initialising an 3D array real with a scalar real.


!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_init
!!
!>\BRIEF        Allocates local and global arrays; initializes soil temperatures using either restart files
!! or a fixed value set by the flag THERMOSOIL_TPRO.
!!
!! DESCRIPTION  : flag : THERMOSOIL_TPRO (to be set to the desired initial temperature in K; by default 280K).
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_clear
!!
!>\BRIEF        Sets the flag l_first_thermosoil to true and desallocates the allocated arrays.
!! ??!! the call of thermosoil_clear originates from sechiba_clear but the calling sequence and
!! its purpose require further investigation.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_var_init
!!
!>\BRIEF        Define and initializes the soil thermal parameters
!!
!! DESCRIPTION	: This routine\n
!! 1. Defines the parameters ruling the vertical grid of the thermal scheme (fz1, zalpha).\n
!! 2. Defines the scaling coefficients for adimensional depths (lskin, cstgrnd, see explanation in the
!!    variables description of thermosoil_main). \n
!! 3. Calculates the vertical discretization of the soil (zz, zz_coef, dz2) and the constants used
!!    in the numerical scheme and which depend only on the discretization (dz1, lambda).\n
!! 4. Initializes the soil thermal parameters (capacity, conductivity) based on initial soil moisture content.\n
!! 5. Produces a first temperature diagnostic based on temperature initialization.\n
!!
!! The scheme comprizes ngrnd=7 layers by default.
!! The layer' s boundaries depths (zz_coef) follow a geometric series of ratio zalph=2 and first term fz1.\n
!! zz_coef(jg)=fz1.(1-zalph^jg)/(1-zalph) \n
!! The layers' boudaries depths are first calculated 'adimensionally', ie with a
!! discretization adapted to EQ5. This discretization is chosen for its ability at
!! reproducing a thermal signal with periods ranging from days to centuries. (see
!! Hourdin, 1992). Typically, fz1 is chosen as : fz1=0.3*cstgrnd (with cstgrnd the
!! adimensional attenuation depth). \n
!! The factor lskin/cstgrnd is then used to go from adimensional depths to
!! depths in m.\n
!! zz(real)=lskin/cstgrnd*zz(adimensional)\n
!! Similarly, the depths of the numerical nodes are first calculated
!! adimensionally, then the conversion factor is applied.\n
!! the numerical nodes (zz) are not exactly the layers' centers : their depths are calculated as follows:\n
!! zz(jg)=fz1.(1-zalph^(jg-1/2))/(1-zalph)\n
!! The values of zz and zz_coef used in the default thermal discretization are in the following table.
!! \latexonly
!! \includegraphics{thermosoil_var_init1.jpg}
!! \endlatexonly\n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : None
!!
!! REFERENCE(S)	:
!! - Hourdin, F. (1992). Study and numerical simulation of the general circulation of
!! planetary atmospheres, Ph.D. thesis, Paris VII University.
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_coef
!!
!>\BRIEF        Calculate soil thermal properties, integration coefficients, apparent heat flux,
!! surface heat capacity,
!!
!! DESCRIPTION	: This routine computes : \n
!!		1. the soil thermal properties. \n
!!		2. the integration coefficients of the thermal numerical scheme, cgrnd and dgrnd,
!!              which depend on the vertical grid and on soil properties, and are used at the next
!!              timestep.\n
!!              3. the soil apparent heat flux and surface heat capacity soilflux
!!              and soilcap, used by enerbil to compute the surface temperature at the next
!!              timestep.\n
!!             -  The soil thermal properties depend on water content (wetdiag) and on the presence
!!              of snow : snow is integrated into the soil for the thermal calculations, ie if there
!!              is snow on the ground, the first thermal layer(s) consist in snow, depending on the
!!              snow-depth. If a layer consists out of snow and soil, wheighed soil properties are
!!              calculated\n
!!             - The coefficients cgrnd and dgrnd are the integration
!!              coefficients for the thermal scheme \n
!!                              T(k+1)=cgrnd(k)+dgrnd(k)*T(k) \n
!!                                      -- EQ1 -- \n
!!              They correspond respectively to $\beta$ and $\alpha$ from F. Hourdin\'s thesis and
!!              their expression can be found in this document (eq A19 and A20)
!!             - soilcap and soilflux are the apparent surface heat capacity and flux
!!               used in enerbil at the next timestep to solve the surface
!!               balance for Ts (EQ3); they correspond to $C_s$ and $F_s$ in F.
!!               Hourdin\'s PhD thesis and are expressed in eq. A30 and A31. \n
!!                 soilcap*(Ts(t)-Ts(t-1))/dt=soilflux+otherfluxes(Ts(t)) \n
!!                                      -- EQ3 --\n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): cgrnd, dgrnd, pcapa, pkappa, soilcap, soilflx
!!
!! REFERENCE(S) :
!! - Hourdin, F. (1992). Study and numerical simulation of the general circulation of planetary atmospheres,
!! Ph.D. thesis, Paris VII University. Remark: the part of F. Hourdin's PhD thesis relative to the thermal
!! integration scheme has been scanned and is provided along with the documentation, with name :
!! Hourdin_1992_PhD_thermal_scheme.pdf
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_profile
!!
!>\BRIEF        In this routine solves the numerical soil thermal scheme, ie calculates the new soil temperature profile;
!! This profile is then exported onto the diagnostic axis (call thermosoil_diaglev)
!!
!! DESCRIPTION	: The calculation of the new soil temperature profile is based on
!! the cgrnd and dgrnd values from the previous timestep and the surface temperature Ts aka temp_sol_new. (see detailed
!! explanation in the header of the thermosoil module or in the reference).\n
!!                              T(k+1)=cgrnd(k)+dgrnd(k)*T(k)\n
!!                                      -- EQ1 --\n
!!                           Ts=(1-lambda)*T(1) -lambda*T(2)\n
!!                                      -- EQ2--\n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): ptn (soil temperature profile on the thermal axis),
!!                          stempdiag (soil temperature profile on the diagnostic axis)
!!
!! REFERENCE(S) :
!! - Hourdin, F. (1992). Study and numerical simulation of the general circulation of planetary atmospheres,
!! Ph.D. thesis, Paris VII University. Remark: the part of F. Hourdin's PhD thesis relative to the thermal
!! integration scheme has been scanned and is provided along with the documentation, with name :
!! Hourdin_1992_PhD_thermal_scheme.pdf
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!!
!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_diaglev
!!
!>\BRIEF        Interpolation of the soil in-depth temperatures onto the diagnostic profile.
!!
!! DESCRIPTION  : This is a very easy linear interpolation, with intfact(jd, jg) the fraction
!! the thermal layer jg comprised within the diagnostic layer jd. The depths of
!! the diagnostic levels are diaglev(1:nbdl), computed in slowproc.f90.
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): stempdiag (soil temperature profile on the diagnostic axis)
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : thermosoil_humlev
!!
!>\BRIEF        Interpolates the diagnostic soil humidity profile shumdiag_perma(nbdl, diagnostic axis) onto
!!              the thermal axis, which gives wetdiag(ngrnd, thermal axis).
!!
!! DESCRIPTION  : Same as in thermosoil_diaglev : This is a very easy linear interpolation, with intfactw(jd, jg) the fraction
!! the thermal layer jd comprised within the diagnostic layer jg.
!!?? I would think wise to change the indeces here, to keep jD for Diagnostic
!!?? and jG for Ground thermal levels...
!!
!! The depths of the diagnostic levels are diaglev(1:nbdl), computed in slowproc.f90.
!! Recall that when the 11-layer hydrology is used,
!! wetdiag and shumdiag_perma are with reference to the moisture content (mc)
!! at the wilting point mcw : wetdiag=(mc-mcw)/(mcs-mcw).
!! with mcs the saturated soil moisture content.
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S): wetdiag (soil humidity profile on the thermal axis)
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!!
!================================================================================================================================
!! SUBROUTINE   : thermosoil_energy
!!
!>\BRIEF         Energy check-up.
!!
!! DESCRIPTION  : I didn\'t comment this routine since at do not understand its
!use, please
!! ask initial designers (Jan ? Nathalie ?).
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : ??
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_
!===============================================================================================================


! Isa --
!Isa ajout Bruno
!-------------------------------------------------------------------


!-------------------------------------------------------------------
!Isa ajout from thermosoil_bruno


!
!     SUBROUTINE thermosoil_getdiff_thinsnow (kjpindex, ptn, wetdiaglong, snowdz, pkappa, pcapa, pcapa_en,profil_froz)  !! 20-01-2016 - Arsene - Remove ptn and profil_froz because profil_froz is alway compute in thermosoil_getdiff (but only if ok_freeze_thermix... why here was compute in all case) ?  AND NEVER USE ??????


!!
!================================================================================================================================
!! FUNCTION     : thermosoil_levels
!!
!>\BRIEF          Depth of nodes for the thermal layers in meters.
!!
!! DESCRIPTION  : Calculate and return the depth in meters of the nodes of the
!soil layers. This calculation is the same
!!                as done in thermosoil_var_init for zz. See thermosoil_var_init
!for more details.
!!
!! RECENT CHANGE(S) : None
!!
!! RETURN VALUE : Vector of soil depth for the nodes in meters
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!
!*******************************************
!*           FUNCTION  GAMMA(X)            *
!* --------------------------------------- *
!* Returns the value of Gamma(x) in double *
!* precision as EXP(LN(GAMMA(X))) for X>0. *
!*******************************************
!!!  real*8 Function gamma(xx)


!! ================================================================================================================================
!! SUBROUTINE 	: qsatcalc
!!
!>\BRIEF          This routine calculates the saturated humidity using the pressure
!!                and the temperature for all pixels.
!!
!! DESCRIPTION : This routine interpolates qsat between temperatures by the following formula :
!!               \latexonly
!!               \input{qsatcalc.tex}
!!               \endlatexonly
!!               \n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S) : qsat_out
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART	: None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! FUNCTION 	: [DISPENSABLE] qsat
!!
!>\BRIEF         This function computes deviation the saturated humidity with the pressure
!! and the temperature for a scalar.
!!
!! DESCRIPTION : This routine is obsolete : replaced by the subroutine qsatcalc. \n
!!               qsat is interpolated by : \n
!!               \latexonly
!!               \input{qsat.tex}
!!               \endlatexonly
!!
!! RECENT CHANGE(S): None\n
!!
!! RETURN VALUE : qsat_result
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART	: None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE 	: dev_qsatcalc
!!
!>\BRIEF         This routine calculates the deviation of the saturated humidity qsat.
!!
!! DESCRIPTION : The deviation of qsat is calculated by :
!!               \latexonly
!!               \input{dev_qsatcalc.tex}
!!               \endlatexonly
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S) : dev_qsat_out
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART	: None
!!
!! FLOWCHART    :
!! \latexonly
!! \includegraphics[scale = 1]{pheno_moigdd.png}
!! \endlatexonly
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! FUNCTION 	: [DISPENSABLE] dev_qsat
!!
!>\BRIEF         This function computes deviation of qsat.
!!
!! DESCRIPTION : The deviation of qsat is calculated by :
!!               \latexonly
!!               \input{dev_qsat.tex}
!!               \endlatexonly
!!
!! RECENT CHANGE(S): None
!!
!! RETURN VALUE : dev_qsat_result
!!
!! REFERENCE(S)	: None
!!
!! FLOWCHART	: None
!! \n
!_ ================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lhold_2d
!!
!>\BRIEF         Calculate the maximum liquid water holding capacity of
!!               snow layer(s)
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): :: PWHOLDMAX
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lhold_1d
!!
!>\BRIEF         Calculate the maximum liquid water holding capacity of
!!               snow layer(s)
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lhold_0d
!!
!>\BRIEF         Calculate the maximum liquid water holding capacity of
!!               snow layer(s)
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lheat_2d
!!
!>\BRIEF         Compute snow heat content (J m-2) from snow mass and liquid
!!               water content and temperature.
!!               snow layer(s)
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lheat_1d
!!
!>\BRIEF         Compute snow heat content (J m-2) from snow mass and liquid
!!               water content and temperature.
!!               snow layer(s)
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lscap_2d
!!
!>\BRIEF         Calculate the heat capacity of a snow layer.
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) : The method of Verseghy (1991), Int. J. Climat., 11, 111-133.
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lscap_1d
!!
!>\BRIEF         Calculate the heat capacity of a snow layer.
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) : The method of Verseghy (1991), Int. J. Climat., 11, 111-133.
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3ltemp_2d
!!
!>\BRIEF         Diagnose snow temperature (K) from heat content (J m-2)
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3ltemp_1d
!!
!>\BRIEF         Diagnose snow temperature (K) from heat content (J m-2)
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lgrain_2d
!!
!>\BRIEF         Calculate the grain size (m) for initialization
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) : Loth and Graf 1993
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!!
!================================================================================================================================
!! FUNCTION   : snow3lgrain_1d
!!
!>\BRIEF         Calculate the grain size (m) for initialization
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) : Loth and Graf 1993
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!================================================================================================================================
!! FUNCTION   : snow3lgrain_0d
!!
!>\BRIEF         Calculate the grain size (m) for initialization
!!
!! DESCRIPTION :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) : Loth and Graf 1993
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!================================================================================================================================
!! FUNCTION   : snow3lliq_2d
!!
!>\BRIEF         Diagnose snow liquid water content from temperature (K) and
!!               heat content  (J m-2)
!!
!! DESCRIPTION : Diagnose snow liquid water content from temperature (K)
!!               and heat content (J m-2). Note, need to evaluate SNOWTEMP from
!!               SNOW3LTEMP before calling this function (i.e. using same
!!               heat content, mass and diagnosed temperature).
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!================================================================================================================================
!! FUNCTION   : snow3lliq_1d
!!
!>\BRIEF         Diagnose snow liquid water content from temperature (K) and
!!               heat content  (J m-2)
!!
!! DESCRIPTION : Diagnose snow liquid water content from temperature (K)
!!               and heat content (J m-2). Note, need to evaluate SNOWTEMP from
!!               SNOW3LTEMP before calling this function (i.e. using same
!!               heat content, mass and diagnosed temperature).
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): ::
!!
!! REFERENCE(S) :
!!
!! FLOWCHART    : None
!! \n
!_
!================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_init
!!
!> BRIEF         This subroutine allocates the memory and get the fixed fields from the restart file.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    :None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_clear
!!
!> BRIEF        : This subroutine deallocates the block memory previously allocated.
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_flow
!!
!> BRIEF         This subroutine computes the transport of water in the various reservoirs
!!                (including ponds and floodplains) and the water withdrawals from the reservoirs for irrigation.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! This will first compute the amount of water which flows out of each of the 3 reservoirs using the assumption of an
!! exponential decrease of water in the reservoir (see Hagemann S and Dumenil L. (1998)). Then we compute the fluxes
!! for floodplains and ponds. All this will then be used in order to update each of the basins : taking water out of
!! the up-stream basin and adding it to the down-stream one.
!! As this step happens globaly we have to stop the parallel processing in order to exchange the information. Once
!! all reservoirs are updated we deal with irrigation. The final step is to compute diagnostic fluxes. Among them
!! the hydrographs of the largest rivers we have chosen to monitor.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): lakeinflow, returnflow, reinfiltration, irrigation, riverflow, coastalflow, hydrographs, flood_frac, flood_res
!!
!! REFERENCES   :
!! - Ngo-Duc, T., K. Laval, G. Ramillien, J. Polcher, and A. Cazenave (2007)
!!   Validation of the land water storage simulated by Organising Carbon and Hydrology in Dynamic Ecosystems (ORCHIDEE) with Gravity Recovery and Climate Experiment (GRACE) data.
!!   Water Resour. Res., 43, W04427, doi:10.1029/2006WR004941.
!! * Irrigation:
!! - de Rosnay, P., J. Polcher, K. Laval, and M. Sabre (2003)
!!   Integrated parameterization of irrigation in the land surface model ORCHIDEE. Validation over Indian Peninsula.
!!   Geophys. Res. Lett., 30(19), 1986, doi:10.1029/2003GL018024.
!! - A.C. Vivant (2003)
!!   Les plaines d'inondations et l'irrigation dans ORCHIDEE, impacts de leur prise en compte.
!!   , , 51pp.
!! - N. Culson (2004)
!!   Impact de l'irrigation sur le cycle de l'eau
!!   Master thesis, Paris VI University, 55pp.
!! - X.-T. Nguyen-Vinh (2005)
!!   Analyse de l'impact de l'irrigation en Amerique du Nord - plaine du Mississippi - sur la climatologie regionale
!!   Master thesis, Paris VI University, 33pp.
!! - M. Guimberteau (2006)
!!   Analyse et modifications proposees de la modelisation de l'irrigation dans un modele de surface.
!!   Master thesis, Paris VI University, 46pp.
!! - Guimberteau M. (2010)
!!   Modelisation de l'hydrologie continentale et influences de l'irrigation sur le cycle de l'eau.
!!   Ph.D. thesis, Paris VI University, 195pp.
!! - Guimberteau M., Laval K., Perrier A. and Polcher J. (2011).
!!   Global effect of irrigation and its impact on the onset of the Indian summer monsoon.
!!   In press, Climate Dynamics, doi: 10.1007/s00382-011-1252-5.
!! * Floodplains:
!! - A.C. Vivant (2002)
!!   L'ecoulement lateral de l'eau sur les surfaces continentales. Prise en compte des plaines d'inondations dans ORCHIDEE.
!!   Master thesis, Paris VI University, 46pp.
!! - A.C. Vivant (2003)
!!   Les plaines d'inondations et l'irrigation dans ORCHIDEE, impacts de leur prise en compte.
!!   , , 51pp.
!! - T. d'Orgeval (2006)
!!   Impact du changement climatique sur le cycle de l'eau en Afrique de l'Ouest: modelisation et incertitudes.
!!   Ph.D. thesis, Paris VI University, 188pp.
!! - T. d'Orgeval, J. Polcher, and P. de Rosnay (2008)
!!   Sensitivity of the West African hydrological cycle in ORCHIDEE to infiltration processes.
!!   Hydrol. Earth Syst. Sci., 12, 1387-1401
!! - M. Guimberteau, G. Drapeau, J. Ronchail, B. Sultan, J. Polcher, J.-M. Martinez, C. Prigent, J.-L. Guyot, G. Cochonneau,
!!   J. C. Espinoza, N. Filizola, P. Fraizy, W. Lavado, E. De Oliveira, R. Pombosa, L. Noriega, and P. Vauchel (2011)
!!   Discharge simulation in the sub-basins of the Amazon using ORCHIDEE forced by new datasets.
!!   Hydrol. Earth Syst. Sci. Discuss., 8, 11171-11232, doi:10.5194/hessd-8-11171-2011
!!
!! FLOWCHART    :None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_lake
!!
!> BRIEF        : This subroutine stores water in lakes so that it does not cycle through the runoff.
!!                For the moment it only works for endoheric lakes but I can be extended in the future.
!!
!! DESCRIPTION (definitions, functional, design, flags): The return flow to the soil moisture reservoir
!! is based on a maximum lake evaporation rate (maxevap_lake). \n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    :None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_diagnostic_p
!!
!> BRIEF         This parallelized subroutine gives a diagnostic of the basins used
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE 	: routing_diagnostic
!!
!> BRIEF         This non-parallelized subroutine gives a diagnostic of the basins used. This produces some information
!!               on the rivers which are being diagnosed.
!!
!! DESCRIPTION (definitions, functional, design, flags) : As not all rivers can be monitored in the model, we will only
!! archive num_largest rivers. In this routine we will diagnose the num_largest largest rivers and print to the standard
!! output the names of these basins and their area. The list of names of these largest rivers are taken from a list coded in the
!! routine routing_names. As this standard output is not sufficient, we will also write it to a netCDF file with the routine
!! routing_diagncfile. It is important to keep for diagnostic the fraction of the largest basins in each grid box and keep information
!! how they are linked one to the other.
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): No output variables.
!!
!! REFERENCES   : None
!!
!! FLOWCHART    :None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_diagcode
!!
!> BRIEF       This subroutine determines the code in the Pfafstetter system for all points
!!              within the given catchment.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): streamcode
!!
!! REFERENCES   : None
!!
!! FLOWCHART    :None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_diagncfile
!!
!> BRIEF         This subroutine creates a netCDF file containing all the informations
!!                on the largest rivers which can be used for a refined analysis.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_basins_p
!!
!> BRIEF        This parallelized subroutine computes the routing map if needed.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_basins
!!
!> BRIEF        This non-parallelized subroutine reads in the map of basins and flow direction to construct
!!              the catchments of each grid box.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! The work is done in a number of steps which are performed locally on the
!! GCM grid:
!!  1) First we find the grid-points of the high resolution routing grid which are
!!     within the coarser grid of the GCM.
!!  2) When we have these grid points we decompose them into basins in the routine
!!     routing_findbasins. A number of simplifications are done if needed.
!!  3) In the routine routing_globalize we put the basin information of this grid
!!     into the global fields.
!! Then we work on the global grid to perform the following tasks :
!!  1) We link up the basins of the various grid points and check the global consistency.
!!  2) The area of each outflow point is computed.
!!  3) The final step is to reduce the number of basins in order to fit into the truncation.\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S): None, as the routine puts information into the global variables of the module.
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_getgrid
!!
!> BRIEF         This subroutine extracts from the global high resolution fields
!!               the data for the current grid box we are dealing with.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! Convention for trip on the input :
!! The trip field follows the following convention for the flow of the water :
!! trip = 1 : flow = N
!! trip = 2 : flow = NE
!! trip = 3 : flow = E
!! trip = 4 : flow = SE
!! trip = 5 : flow = S
!! trip = 6 : flow = SW
!! trip = 7 : flow = W
!! trip = 8 : flow = NW
!! trip = 97 : return flow into the ground
!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here
!! trip = 99 : river flow into the oceans
!!
!! On output, the grid boxes of the basin map which flow out of the GCM grid are identified
!! by numbers larger than 100 :
!! trip = 101 : flow = N out of the coarse grid
!! trip = 102 : flow = NE out of the coarse grid
!! trip = 103 : flow = E out of the coarse grid
!! trip = 104 : flow = SE out of the coarse grid
!! trip = 105 : flow = S out of the coarse grid
!! trip = 106 : flow = SW out of the coarse grid
!! trip = 107 : flow = W out of the coarse grid
!! trip = 108 : flow = NW out of the coarse grid
!! Inside the grid the convention remains the same as above (ie between 1 and 99).:\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_sortcoord
!!
!> BRIEF         This subroutines orders the coordinates to go from North to South and West to East.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_findbasins
!!
!> BRIEF         This subroutine finds the basins and does some clean up.
!!               The aim is to return the list off all points which are within the
!!               same basin of the grid box.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!!  We will also collect all points which directly flow into the ocean in one basin
!!  Make sure that we do not have a basin with two outflows and other exceptions.
!!  At this stage no effort is made to come down to the truncation of the model.
!!
!! Convention for trip    \n
!! -------------------    \n
!! Inside of the box :    \n
!! trip = 1 : flow = N    \n
!! trip = 2 : flow = NE    \n
!! trip = 3 : flow = E    \n
!! trip = 4 : flow = SE    \n
!! trip = 5 : flow = S    \n
!! trip = 6 : flow = SW    \n
!! trip = 7 : flow = W    \n
!! trip = 8 : flow = NW    \n
!! trip = 97 : return flow into the ground    \n
!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here    \n
!! trip = 99 : river flow into the oceans    \n
!!
!! Out flow from the grid :    \n
!! trip = 101 : flow = N out of the coarse grid    \n
!! trip = 102 : flow = NE out of the coarse grid    \n
!! trip = 103 : flow = E out of the coarse grid    \n
!! trip = 104 : flow = SE out of the coarse grid    \n
!! trip = 105 : flow = S out of the coarse grid    \n
!! trip = 106 : flow = SW out of the coarse grid    \n
!! trip = 107 : flow = W out of the coarse grid    \n
!! trip = 108 : flow = NW out of the coarse grid!    \n
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_simplify
!!
!> BRIEF         This subroutine symplifies the routing out of each basin by taking
!!               out redundancies at the borders of the GCM box.
!!               The aim is to have only one outflow point per basin and grid box.
!!               But here we will not change the direction of the outflow.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_cutbasin
!!
!> BRIEF        This subroutine cuts the original basin which has more than one outflow
!!              into as many subbasins as outflow directions.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_hierarchy
!!
!> BRIEF        This subroutine finds, for each point, the distance to the outflow
!!               point along the flowlines of the basin.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_findrout
!!
!> BRIEF        This subroutine simply computes the route to each outflow point
!!              and returns the outflow point for each point in the basin.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_globalize
!!
!> BRIEF        This subroutine puts the basins found for grid box in the global map.
!!               Connection can only be made later when all information is together.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!! One of the outputs is basin_flowdir. Its convention is 1-8 for the directions from North to North
!! West going through South. The negative values will be -3 for return flow, -2 for coastal flow
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_linkup
!!
!> BRIEF         This subroutine makes the connections between the basins and ensure global coherence.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! The convention for outflow_grid is :
!! outflow_grid = -1 : River flow
!! outflow_grid = -2 : Coastal flow
!! outflow_grid = -3 : Return flow\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_fetch
!!
!> BRIEF        This subroutine computes the fetch of each basin. This means that for each basin we
!!               will know how much area is upstream. It will help decide how to procede with the
!!               the truncation later and allow to set correctly in outflow_grid the distinction
!!               between coastal and river flow.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_truncate
!!
!> BRIEF         This subroutine reduces the number of basins per grid to the value chosen by the user.
!!               It also computes the final field which will be used to route the water at the
!!               requested truncation.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! Truncate if needed and find the path closest to the high resolution data.
!!
!! The algorithm :
!!
!! We only go through this procedure only as many times as there are basins to take out at most.
!! This is important as it allows the simplifications to spread from one grid to the other.
!! The for each step of the iteration and at each grid point we check the following options for
!! simplifying the pathways of water :
!! 1) If the basin of a grid flows into another basin of the same grid. Kill the one which only
!!    served as a transition
!! 2) If in one grid box we have a number of basins which flow into the ocean as coastal flow.
!!    We kill the smallest one and put into the largest basin. There is no need to manage many
!!    basins going into the ocean as coastal flows.
!! 3) If we have streams run in parallel from one gird box to the others (that is these are
!!    different basins) we will put the smaller one in the larger one. This may hapen at any
!!    level of the flow but in theory it should propagate downstream.
!! 4) If we have two basins with the same ID but flow into different grid boxes we sacrifice
!!    the smallest one and route it through the largest.
!!
!! Obviously if any of the options find something then we skip the rest and take out the basin.:\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_killbas
!!
!> BRIEF        The aim of this subroutine is to kill a basin (that is put into another larger one).
!!              When we do this we need to be careful and change all associated variables.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_names
!!
!> BRIEF         This subroutine lists the name of the largest basins which are explicitly listed in the basin
!!               description file used by ORCHIDEE.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_irrigmap
!!
!> BRIEF         This  subroutine interpolates the 0.5x0.5 degree based map of irrigated areas to the resolution of the model.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!
!! ================================================================================================================================
!! SUBROUTINE 	: routing_waterbal
!!
!> BRIEF         This subroutine checks the water balance in the routing module.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES   : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrolc_init
!!
!>\BRIEF        This routine drives the initialisation of the water budget calculations.
!!
!! DESCRIPTION : The following sequences are performed :
!!  - Updating flag l_first_hydrol
!!  - Setting ok_hdiff (default is false) for horizontal diffusion between soil columns
!!  - Dynamic allocation of arrays that are local to module hydrolc
!!  - Initializing prognostic variables from input restart file
!!  - Default attribution is performed in case the model is started without a restart file
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : humrel, vegstress,snow, snow_age, snow_nobio, snow_nobio_age, qsintveg
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART11    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrolc_clear
!!
!>\BRIEF        Deallocates arrays that were allocated in hydrolc_init and hydrolc_var_init.
!!
!! DESCRIPTION  : None
!!
!! RECENT CHANGES : None
!!
!! MAIN OUTPUT VARIABLE(S) : None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!!\n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrolc_var_init
!!
!>\BRIEF        This routine initializes diagnostic hydrologic variables.
!!
!! DESCRIPTION  : The following variables are assigned :
!!  - Soil characteristics : soil water capacities mx_eau_var and ruu_ch \f$(kg m^{-2})\f$ and \f$(kg m^{-3})\f$
!!  - Initial values for diagnostic variables : mean_bqsb, mean_gqsb, mean_dsg, shumdiag, drysoil_frac, rsol, litterhumdiag
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : rsol, drysoil_frac, mx_eau_var, ruu_ch, shumdiag, litterhumdiag
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrolc_snow
!!
!>\BRIEF        This routine computes accumulation, sublimation, snowmelt and snow ageing
!! over vegetated and nobio (eg land-ice) areas. Snowdepth is then updated.
!!
!! DESCRIPTION  : In this routine the snow-related processes accumulation, sublimation,
!! melting and ageing are computed separately on vegetated and nobio areas. This subroutine
!! is the first one among the ones that compute the physical processes. The water budgets
!! of the interception reservoir and the soil are performed afterwards.\n
!!
!! - Values of the main parameters used in this routine are :\n
!! tp_00=273.15K : freezing point\n
!! snowcri=1.5\f$kg m^{-2}\f$ : critical snowmass for sublimation\n
!! sneige=snowcri/1000._r_std : critical snowmass for snow melt\n
!! maxmass_snow=3000 \f$kg m^{-2}\f$ (~ 10m snow) : critical snowmass for snow stock\n
!! snow_trans=0.3 (\f$kg m^{-2}\f$) : critical constant for snow ageing\n
!! max_snow_age=50 (days) : maximum snow age\n
!! sn_dens=330 (\f$kg m^{-3}\f$) : snow density\n
!! one_day=86400 (s) : one day, expressed in seconds...
!!
!! - Accumulation\n
!! On the vegetated areas, the snow mass increases due to area-weighted snow
!! precipitations precip_snow; on nobio areas, rain additionnaly converts into snow.\n
!!
!! - Sublimation\n
!! Sublimation on vegetated and nobio areas is calculated as the area-weighed fraction
!! of vevapsno (from enerbil). In case snow on vegetated areas is limited (less than snowcri)
!! and a significant nobio area exists, the nobio area accomodates the whole sublimation
!! vevapsno. The nobio area also accomodates the possible excess sublimation from vegetated
!! areas, which otherwise goes into bare soil evaporation. In this case vevapsno is updated.\n
!!
!! - Melting\n
!! Over vegetated and nobio areas, snowmelt occurs if the calculated soil temperature
!! temp_soil_new(ji) exceeds the freezing point tp_00. The energy required to warm up the soil
!! surface above tp_00 is converted into melting, according to the following equation :
!! \latexonly
!! \input{hydrolcsnow1.tex}
!! \endlatexonly
!! \n
!! with soilcap the soil heat capacity @tex ($J K^{-1}$) @endtex and chalfu0 the latent heat of
!! fusion.\n
!! A special case occurs in areas with snowmass exceeding maxmass_snow, where
!! all the snow in excess of maxmass_snow adds to the total melting tot_melt.
!! This excess melting is considered as additionnal snowmelt for vegetated areas
!! and as ice_melt for nobio areas.\n
!!
!! - Ageing\n
!! Over vegetated areas, during the time step dt_radia (usually 1800 s), the snow age is
!! incremented by a d_age calculated as follow:
!! \latexonly
!! \input{hydrolcsnow2.tex}
!! \endlatexonly
!! \n
!! Over nobio areas and at subfreezing temperatures, snow ageing is limited by very
!! slow snow metamorphism, hence d_age is reduced as follow:
!! \latexonly
!! \input{hydrolcsnow3.tex}
!! \endlatexonly
!! \n
!! Scientific reference for this parametrization choice is obviously missing !
!! At the end of the routine the snowheight is diagnosed using the fixed
!! snow density sn_dens.
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLES:
!! for vegetated and nobio areas respectively:\n
!! snow(kjpindex) and snow_nobio(kjpindex)\n
!! snow_age(kjpindex) and snow_nobio_age(kjpindex)\n
!! for the whole grid-cell:\n
!! vevapnu(kjpindex)
!! vevapsno(kjpindex)
!! tot_melt(kjpindex)
!! snowdepth(kjpindex)
!!
!! REFERENCES : None
!!
!! FLOWCHART  : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE      : hydrolc_canop
!!
!>\BRIEF           This routine computes the water budget of the canopy interception reservoir.
!!
!! DESCRIPTION     : The first sequence is to withdraw interception loss from the interception
!! reservoir, with independent values for each PFT. The reservoir loading happens afterwards.
!! Rain falls uniformly over the PFTs. It uniformly loads the canopy interception
!! reservoir of each PFT, up to the interception capacity, but a fraction of rainfall always falls to the ground.
!! Throughfall is thus comprised of the fraction that always falls through, plus the remining fraction of rainfall that
!! exceeds the interception capacity, the interception loss having been removed.
!! \latexonly
!! \input{interception.tex}
!! \endlatexonly
!!
!! IMPORTANT NOTE : Bare soil treatment is complex in hydrolc :
!!  - veget_max(:,1) is the fraction of bare soil from the "annual" vegetation map
!!  - veget(:,1) is not the fraction of vegetation over bare soil but the total fraction of bare soil in the grid-cell
!! (including the bare soil fractions over the vegetation PFTs).
!! *** A diagram should be added in the spatial entry of the "umbrella"
!!  - For interception to be zero on bare soil, we thus need to impose qsintmax(:,1)=0
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : precisol (throughfall), qsintveg (amount of water in the canopy interception reservoir)
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrolc_vegupd
!!
!>\BRIEF        This subroutines works at adapting the distribution of water
!! in the soil and interception reservoirs between the different soil columns when the vegetation
!! fraction of the PFTs (veget) has changed in slowproc.
!!
!! DESCRIPTION  : Different vegetation changes are allowed in ORCHIDEE:\n
!!  - veget_max can be updated annually in slowproc (dynamic vegetation or prescribed vegetation change)\n
!!  - veget can be updated daily in slowproc (because of changes in veget_max or depending on LAI)
!!
!! This subroutine aims at adapting the distribution of water among the different liquid water reservoirs
!! (interception reservoir and soil moisture) after these changes of veget :
!! - the variable veget holds the "new" vegetation map
!! - the variable resdist holds the previous vegetation map
!! *** I see no flag or time step dependance to control the call to vegupd : is it called at each time step ?
!!
!! The principle is that PFTs where "veget" has shrunk keep the same water contents in kg.m^{-2},
!! whereas the water contents are increased in PFTs where "veget" has grown.
!! *** I still have questions about redistribution to interception reservoirs which have shrunk
!! *** and about thresholding to the reservoirs' capacities (is it ensured that the capacities are not exceeded ?)
!! 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.
!!
!! IMPORTANT NOTE : the definition of veget is not simple :
!!  - for the non-bare soil PFTs (iv > 2), veget is the fraction effectively covered by
!! vegetation : veget \f$\le\f$ veget_max\n
!!  - for the bare soil PFT (iv=1), veget holds the fraction of bare soil, from all
!! PFTs : veget(:,1) \f$\ge\f$ veget_max(:,1)\n
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : qsintveg, gqsb, bqsb, dsg, dss, dsp, resdist
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART   : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE            : hydrolc_flood
!!
!>\BRIEF                   this routine computes the evolution of the surface reservoir (floodplain)
!!
!! DESCRIPTION           :
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : floodout
!!
!! REFERENCE(S) : Same as for module hydrolc
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================


!! ================================================================================================================================
!! SUBROUTINE   : hydrolc_waterbal
!!
!>\BRIEF        This subroutine checks the water balance closure in each terrestrial grid-cell
!! over a time step.
!!
!! DESCRIPTION  : The change in total water amount over the time step must equal the algebraic sum of the
!! water fluxes causing the change, integrated over the timestep. The equality is checked to some precision,
!! set for double precision calculations (REAL*8). Note that this precision depends on the time step.
!! This verification does not make much sense in REAL*4 as the precision is the same as some of the fluxes.
!! The computation is only done over the soil area, as over glaciers (and lakes?) we do not have
!! water conservation.
!! *** The above sentence is not consistent with what I understand from the code, since snow_nobio is accounted for.
!! *** what is the value of epsilon(1) ?
!!
!! RECENT CHANGE(S) : None
!!
!! MAIN OUTPUT VARIABLE(S) : None
!!
!! REFERENCE(S) : None
!!
!! FLOWCHART    : None
!! \n
!_ ================================================================================================================================