#Metview Macro

#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      : t_from_equivalent_potential_temperature
#
# Syntax        : number t_from_equivalent_potential_temperature(eqpt:number,p: number)
#                                          
# Category      : THERMODYNAMICS
#
# OneLineDesc   : Compute the temperature from the equivalent potential temperature
#
# Description   : Compute the temperature from the equivalent potential temperature
#                 on a given pressure.  
#
# Parameters    : eqpt - the equivalent potential temperature (K)
#		 		  p - the pressure (Pa)
#           
# Return Value  : the temperature (K)
#
# Dependencies  : none
#
#==============================================================================

function __temperature_from_equivalent_potential_temperature(eqpt: number,p : number)

  	eqpt = eqpt
  	b=2.674456 
  	  	 	
  	tq=273.16 - 20
	d=120.
  	for i=0 to 12 do
  		
  		d=d/2
  			
		x = eqpt*exp(-b*1000*saturation_mixing_ratio(tq,p)/tq)-potential_temperature(tq,p)
		
		#print(i," ",x)
		
		if abs(x) <= 0.0000001 then
			return tq	
		end if
		if x < 0 then
			tq = tq - abs(d)
		else
			tq = tq + abs(d)	
		end if
		
	end for
	
	return tq

end __temperature_from_equivalent_potential_temperature

