#' Parameters of a humid atmosphere 
#'
#'@author \email{paola.marson@cmcc.it} \email{paola.marson@gmail.com}
#'@description This function computes a set of atmospheric parameters both at the surface and on vertical levels. The function computes:
#' - saturation water vapor density at the ground (Kg/m^3 typical values of the order 0.009 Kg/m^3)
#' - environmental lapse rate
#' - moist laspe rate https://kiwi.atmos.colostate.edu/group/dave/pdf/Moist_adiabatic_lapse_rate.pdf
#'
#'@param TREF a s2dverification object of 2 meter temperature of expected dimensions 'lon' and 'lat'. Temperature values can be supplied both in Celsius and K.
#'
#'@param TT a s2dverification object of temperatures on an arbitrary number of vertical levels of expected dimensions 'lon', 'lat', 'levels'. Temperature values can be supplied in both Celsius and K. Levels should be in icreasing order of altitude.
#'
#'@param ZZ a s2dverification object of geopotential heights (m) on an arbitrary number of vertical levels of expected dimensions 'lon', 'lat', 'levels'. Same number of levels as TT is expected. Levels should be in icreasing order of altitude.
#'
#'@param QQ a s2dverification object of specific humidity (Kg/Kg) on an arbitrary number of vertical levels of expected dimensions 'lon', 'lat', 'levels'. Same number of levels as TT is expected. Levels should be in icreasing order of altitude. 
#'
#'@import s2dverification
#'@examples
#'


HumidAtmosParam <- function(TREF, TT, ZZ, QQ){


if (mean(TREF, na.rm=TRUE) < 100) {TREF <- TREF + 273.15} #TREF in K
e_s<-610.78*exp((TREF - 273.15)*17.27/((TREF - 273.15) + 237.3))   #Tetens equation, Pa
R_v<-461               #J Kg^-1 gas constant for vapor
rho_sref <- e_s/(R_v *TREF)        # Kg/m^3 ca. 0.009 Kg/m^3.
Lv = 2.501*10^6        #J Kg^-1 # latent heat of vaporization
c_pd = 1006            #J Kg^-1 K^-1 # specific heat at constant pressure
R = 287                #J Kg^-1 K^-1
ee = R/R_v

# Moisture Lapse rate:
gamma_mo<-apply((0.009*(1+(Lv*QQ/(R_v*TT)))/(1+(Lv^2*QQ/(c_pd*R_v*TT^2)))),c(1,2),mean) 
# Environmental Lapse Rate
gamma<-(-1)*9.8*(TT[,,2]-TT[,,1])/(ZZ[,,2]-ZZ[,,1])

return(humpars = list(rho_sref=list(rho_sref, lon, lat), gamma=list(gamma,lon,lat,levels), gamma_mo=list(gamma_mo,lon,lat,levels)))

}