#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 ************************************
# 

#=================================================================================
# Compute the saturation vapour pressure for a given temperature.
#
# OneLineDesc   : Computes the saturation vapour pressure for a given temperature
#
# Input: 
#       t: the temperature (K) 
# Return:
#       the saturation vapour pressure (Pa)           
#==============================================================================

function saturation_vapour_pressure(t)
    return saturation_vapour_pressure(t, "water")
end saturation_vapour_pressure

function saturation_vapour_pressure(t, phase)

    c1    = 611.21
    c3l   = 17.502
    c4l   = 32.19
    c3i   = 22.587
    c4i   = -0.7
    t0    = 273.16
    ti    = 250.16

    if phase = "water" then    
        return c1*exp(c3l*(t-t0)/(t-c4l))
    else if phase = "ice" then
        return c1*exp( c3i*(t-t0)/(t-c4i))
    else if phase = "mixed" then  
        #Saturation vapour pressure over water
        es_water = c1*exp(c3l*(t-t0)/(t-c4l))

        #Saturation vapour pressure over ice
        es_ice  = c1*exp( c3i*(t-t0)/(t-c4i))

        #fraction of liquid water
        # t <= ti => 0
        # t > ti and t < t0 => (t-ti)/(t0-ti))^2
        # t >=0 => 1
    
        alpha = (t > ti)*(t < t0) * ((t-ti)/(t0-ti))^2 + (t > t0)
   
        return alpha*es_water+(1.-alpha)*es_ice
    else
        fail("saturation_vapour_pressure(): invalid phase option=" & phase & "! Allowed values = ['water', 'ice', 'mixed']")
    end if

end saturation_vapour_pressure
