#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 dewpoint for a given temperature and relative humidity
#
# OneLineDesc   : Computes the dewpoint for a given temperature and relative humidity
#
# Input: 
#       t: the temperature (K) 
#       r: the relative humidity (%)
# Return:
#       the dewpoint temperature in (K)          
#==============================================================================

function dewpoint_from_relative_humidity(t, r)

    fn_name = "dewpoint_from_relative_humidity"
    
    keys = nil
    if type(t) = "fieldset" then
        if type(r) <> "fieldset" then
            fail(fn_name & ": r argument must be a fieldset!")
        end if
        
        keys = grib_get(t, ["gridType", "paramId"])
        for i=1 to count(keys) do
            if keys[i][1] = "sh" then
                fail(fn_name & ": spherical harmonics fields are not supported! [t-field=]" & i)
            end if
        end for
        
        keys_r = grib_get(r, ["gridType"])
        for i=1 to count(keys) do
            if keys_r[i][1] = "sh" then
                fail(fn_name & ": spherical harmonics fields are not supported! [r-field=]" & i)
            end if
        end for
    end if     
     
    # The actual computation   
    c1    = 611.21
    c3l   = 17.502
    c4l   = 32.19
    es = saturation_vapour_pressure(t)
    e = r * es / 100
    t0 = 273.16
    v = log(e/c1)/c3l
    td = (v*c4l  - t0) / (v - 1)
    
    # Set paramId for the result 
    if type(t) = "fieldset" then
        for i=1 to count(r) do
            if keys[i][2] = "167" then              
                td[i] = grib_set(td[i], ["paramId", 168])
            else
                td[i] = grib_set(td[i], ["paramId", 3017]) 
            end if         
        end for
    end if
    
    return td

end dewpoint_from_relative_humidity
