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

function dewpoint_from_specific_humidity(q)
    fn_name = "dewpoint_from_specific_humidity"   
    p = __get_pressure_from_pl_arg(q, "q", fn_name)       
    return dewpoint_from_specific_humidity(q, p)  
      
end dewpoint_from_specific_humidity

function dewpoint_from_specific_humidity(q, p)

    fn_name = "dewpoint_from_specific_humidity"   
    has_pl_fields = 0
    
    if type(q) = "fieldset" then
        v = __prepare_pressure_field_arg(q, p, "q", fn_name)
        p = v[1]
        has_pl_fields = v[2]
    end if     
   
    # The actual computation   
    c1    = 611.21
    c3l   = 17.502
    c4l   = 32.19
    t0 = 273.16
    
    # we disable the argument check in vapour_pressure()
    # since all the arguments have been properly checked 
    if has_pl_fields then
        e = nil
        for i=1 to count(q) do
            e = e & vapour_pressure(q[i], p[i], 0)  
        end for
    else  
        e = vapour_pressure(q, p, 0)
    end if
  
    v = log(e/c1)/c3l
    td = (v*c4l  - t0) / (v - 1)
    
    # Set paramId for the result 
    if type(q) = "fieldset" then
        td = grib_set(td, ["paramId", 3017])
    end if
    
    return td

end dewpoint_from_specific_humidity
