#Metview Macro

#  **************************** LICENSE START ***********************************
# 
#  Copyright 2019 ECMWF. This software is distributed under the terms
#  of the Apache License version 2.0. In applying this license, ECMWF does not
#  waive the privileges and immunities granted to it by virtue of its status as
#  an Intergovernmental Organization or submit itself to any jurisdiction.
# 
#  ***************************** LICENSE END ************************************
# 

#=============================================================================
# Function      : lifted_condensation_level
#
# Syntax        : definition lifted_condensation_level(t: number, p: number)
#                                          
# Category      : THERMODYNAMICS
#
# OneLineDesc   : Computes the Lifted Condensation Level (LCL)
#
# Description   : Compute the Lifted Condensation Level (LCL)
#
# Parameters    : t - the start temperature of the parcel (K)
#                 td - the start dewpoint temperature of the parcel (K) 
#		 		  p - the start pressure of the parcel (Pa)
#           
# Return Value  : definition (t, p) where t is the temperature (K) and p (Pa) is the
#                 pressure of the LCL. If the LCL cannot be computed or does not exist
#                 nil is returned.
#
# Dependencies  : none
#
#==============================================================================

function lifted_condensation_level(t, td, p)

    fn_name = "lifted_condensation_level:"
    
    # check values/units
    if type(t) = "number" and t < 60 then
    	print(fn_name," invalid temperature=",t," K")
    	return nil
  	end if
  	
  	if type(td) = "number" and td < 60  then  	
    	print(fn_name," invalid dew point=",td," K")
  	end if
    
    if type(p) = "number" and p < 1200 then  	
    	print(fn_name," invalid pressure=",p," Pa")
  	end if
    
    # compute the lcl temperature using Davies-Jones (1983)
    #t0 = 273.16 
    #t_lcl =  td - (0.212 + 1.571 * 1E-3 * (td - t0)- 4.36 * 1E-4 * (t - t0))* (t-td)
    
    # compute the lcl temperature using Bolton (1980)
    t_lcl = 56.0 + 1 / (1 / (td - 56) + log(t / td) / 800)
    
    # compute the lcl pressure using the dry adiabat
    KAPPA=0.285611 #Rd/cp
    p_lcl = p * (t_lcl/t)^(1/KAPPA)
   
    return (t: t_lcl, p: p_lcl)
    
end lifted_condensation_level