#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 ************************************
# 

#=================================================================================
# Computes the specific humidity from a given temperature, relative humidity and pressure
#
# OneLineDesc   : Computes the specific humidity from a given temperature, relative humidity and pressure
#
# Input: 
#       t: the temperature in (K)
#       r: the relative humidity (%)
#       p: the pressure (Pa)
# Return:
#       q: the specific humidity (kg/kg)    
#==============================================================================

function specific_humidity_from_relative_humidity(t, r)
    fn_name = "specific_humidity_from_relative_humidity"   
    p = __get_pressure_from_pl_arg(t, "t", fn_name)       
    return specific_humidity_from_relative_humidity(t, r, p)      
end specific_humidity_from_relative_humidity

function specific_humidity_from_relative_humidity(t, r, p)

    fn_name = "specific_humidity_from_relative_humidity"   
    
    if type(t) = "fieldset" then
        v = __prepare_pressure_field_arg(t, p, "t", fn_name)
        p = v[1]
    end if     
   
    # The actual computation   
    svp = saturation_vapour_pressure(t, "mixed")
    e  = r * svp / 100
    c1 = 0.621981 
    c2 =  c1 - 1
    
    # In the finals step we need a loop for pressure level fields 
    # since p is a vector in this case!
    if type(t) = "fieldset" then
        q = nil
        for i=1 to count(e) do
            q = q & c1 * e[i] / (c2*e[i] + p[i])  
        end for
    else  
        q = c1 * e / (c2*e + p) 
    end if

    # Set paramId for the result 
    if type(q) = "fieldset" then
        q = grib_set(q, ["paramId", 133])
    end if
    
    return q

end specific_humidity_from_relative_humidity