#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      : vapour_pressure
#
# Syntax        : number vapour_pressure(q, p)
#                                          
# Category      : THERMODYNAMICS
#
# OneLineDesc   : Computes the vapour pressure for a given specific humidity and pressure
#
# Description   : Computes the vapour pressure for a given specific humidity and pressure
#
# Parameters    : q - the specific humidity (kg/kg)
#		 		  p - the pressure (Pa)
#           
# Return Value  : the vapour pressure (Pa)
#
# Dependencies  : none
#
#==============================================================================


function vapour_pressure(q)
    fn_name = "vapour_pressure"   
    p = __get_pressure_from_pl_arg(q, "q", fn_name)       
    return vapour_pressure(q, p)  
end vapour_pressure

function vapour_pressure(q, p)
    fn_name = "vapour_pressure" 
   
    if type(q) = "fieldset" then
        v = __prepare_pressure_field_arg(q, p, "q", fn_name)
        p = v[1]
    end if 
    
    vp = __vapour_pressure_core(q, p)

    # This does not work. See issue METV-2734
    # if has_fields = 1 then
    #  vp = grib_set_long(vp, ["paramId", 3055])
    # end if
    
    return vp

end vapour_pressure

# it offers a faster way to compute vapour_pressure
# by omitting all the checks (for internal usage only!)
function vapour_pressure(q, p, check_args)
    if check_args then
        return vapour_pressure(p, q)
    else
        return __vapour_pressure_core(q, p)
    end if
end vapour_pressure

function __vapour_pressure_core(q, p)
    c = 1.607766154 # = 1/0.621981  
    if type(q) = "fieldset" then
        vp = nil
        for i=1 to count(q) do
            vp = vp & p[i] * q[i] * c /(1 + q[i]*(c -1))
        end for
    else
        vp = p * q * c /(1 + q*(c -1))
    end if
    return vp
end __vapour_pressure_core
