#Metview Macro

#  **************************** LICENSE START ***********************************
# 
#  Copyright 2021 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 static stability uused for the Q-vector computations3
#
# OneLineDesc   : Computes the static stability used for the Q-vector computations              
#
# **************************************************************************

function  static_stability(t)
    fn_name = "static_stability"   
    p = __get_pressure_from_pl_arg(t, "t", fn_name)       
    return static_stability(t, p)  
end static_stability      

function static_stability(t, p)

    fn_name = "static_sytability"
    has_pl_fields = 0

    R = 8.314462 # gas constant
    KAPPA=0.285611 #Rd/cp
    
    if count(p) < 2 then
        fail(fn_name  & ":number of levels (=" & count(p) & ") must be >=2")
    end if

    if type(t) = "fieldset" then
        v = __prepare_pressure_field_arg(t, p, "t", fn_name)
        p = v[1]
        has_pl_fields = v[2]
    end if     

    if type(t) = "fieldset" then
        r = nil
        dt = pressure_derivative(t)
        for i=1 to count(t) do
            r  = r & (R/p[i])*(KAPPA * t[i] - dt[i])
        end for
    else
        dt = pressure_derivative(t, p)
        r = R/p * (KAPPA * t - dt)
    end if

    return r
end static_stability    
    

