#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 from the specific humidity
#
# OneLineDesc   : Computes the relative humidity from the specific humidity
#
# Input: 
#       t: the temperature (K) 
#       q: the specific humidity (kg/kg)
#       p: the pressure (Pa)
# Return:
#       the relative humidity (%)           
#==============================================================================

function relative_humidity_from_specific_humidity(t, q)
    
    fn_name = "relative_humidity_from_specific_humidity"   
    p = __get_pressure_from_pl_arg(t, "t", fn_name)       
    return relative_humidity_from_specific_humidity(t, q, p)  

end relative_humidity_from_specific_humidity

function relative_humidity_from_specific_humidity(t, q, p)
    
    fn_name = "relative_humidity_from_specific_humidity"   
   
    if type(t) = "fieldset" then
        v = __prepare_pressure_field_arg(t, p, "t", fn_name)
        p = v[1]
    end if     

    # computation
    # We disable the argument check in vapour_pressure()
    # since all the arguments have been properly checked 

    svp = saturation_vapour_pressure(t, "mixed")
    e = vapour_pressure(q, p, 0)
    r = 100*e/svp
  
    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_specific_humidity
