#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 ************************************
# 
#=============================================================================
# Function      : saturation_mixing_ratio
#
# Syntax        : number saturation_mixing_ratio(t, p)
#                                          
# Category      : THERMODYNAMICS
#
# OneLineDesc   : Computes the saturation mixing ratio for a given temperature and pressure
#
# Description   : Computes the saturation mixing ratio for a given temperature and pressure
#
# Parameters    : t - temperature (K)
#		 		  p - pressure (Pa)
#           
# Return Value  : the saturation mixing ratio (kg/kg)
#
# Dependencies  : none
#
#===============================================================================

function saturation_mixing_ratio(t, p_or_phase)
    if type(p_or_phase) = "string" then
        return __saturation_mixing_ratio_pl(t, p_or_phase)
    else
        return saturation_mixing_ratio(t, p_or_phase, "water")
    end if
end saturation_mixing_ratio

function __saturation_mixing_ratio_pl(t: fieldset, phase: string)
    fn_name = "saturation_mixing_ratio"   
    p = __get_pressure_from_pl_arg(t, "t", fn_name)         
    return saturation_mixing_ratio(t, p, phase)  
end __saturation_mixing_ratio

function saturation_mixing_ratio(t, p, phase: string)
    fn_name = "saturation_mixing_ratio" 

    if type(t) = "fieldset" then
        v = __prepare_pressure_field_arg(t, p, "t", fn_name)
        p = v[1]
    end if 
    
    ws = __saturation_mixing_ratio_core(t, p, phase)
    return ws

end saturation_mixing_ratio

# it offers a faster way to compute saturation mixing ratio
# by omitting all the checks (for internal usage only!)
function saturation_mixing_ratio(t, p, phase:string, check_args)
    if check_args then
        return saturation_mixing_ratio(t, p, phase)
    else
        return __saturation_mixing_ratio_core(t, p, phase)
    end if
end saturation_mixing_ratio

function __saturation_mixing_ratio_core(t, p, phase:string)
    e = saturation_vapour_pressure(t, phase)
    if type(t) = "fieldset" then  
        ws = nil
        for i=1 to count(t) do
            ws = ws & 0.621981*e[i]/(p[i]-e[i])
        end for
        return ws
    else        
        return 0.621981*e/(p-e) 
    end if   
end __saturation_mixing_ratio_core
