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

function relative_humidity_from_dewpoint(t, td)

    e = saturation_vapour_pressure(td)
    es = saturation_vapour_pressure(t)
    r = e/es
  
    if type(t) = "fieldset" then
        keys = grib_get(t, ["edition:l", "shortName"])
        for i=1 to count(r) do
            # note: for grib edition 1 we cannot set the 
            # the paramid to "2d" so we need to convert the field
            # into grib 2 to do so!        
            if keys[i][1] = 1 and keys[i][2] = "2t" then              
                r[i] = grib_set(r[i], 
                        ["edition",2, "paramId", 260242])
            else
                r[i] = grib_set(r[i], ["paramId", 157]) 
            end if         
        end for
    end if
    
    return r

end relative_humidity_from_dewpoint
