#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 dewpoint and pressure
#
# OneLineDesc   : Computes the specific humidity from a given dewpoint and pressure
#
# Input: 
#       td: the dewpoint temperature in (K)
#       p: the pressure (Pa)
# Return:
#       q: the specific humidity (kg/kg)    
#==============================================================================

function specific_humidity_from_dewpoint(td)
    fn_name = "specific_humidity_from_dewpoint"   
    p = __get_pressure_from_pl_arg(td, "td", fn_name)       
    return specific_humidity_from_dewpoint(td, p)      
end specific_humidity_from_dewpoint

function specific_humidity_from_dewpoint(td, p)

    fn_name = "specific_humidity_from_dewpoint"   
    has_pl_fields = 0
    
    if type(td) = "fieldset" then
        v = __prepare_pressure_field_arg(td, p, "td", fn_name)
        p = v[1]
        has_pl_fields = v[2]
    end if     
   
    # The actual computation   
    svp = saturation_vapour_pressure(td)
    epsilon = 0.621981
    c1 = (1/epsilon - 1)
    c2 = epsilon * svp
    if type(td) = "fieldset" and type(p) = "vector" then
        q = nil
        for i=1 to count(td) do
            q = q & c2[i] / (p[i] - c2[i] * c1)
        end for
    else
        q = c2 / (p - c2 * c1)
    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_dewpoint