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

#=================================================================================
# Internal utility function to make mvl derivative computations easier.
#
# OneLineDesc   : Internal utility function
#
# Input: 
#       fn_name: name of the caller function
#       args: arguments of the caller function
# Return:
#       list with 4 elements: 
#           1: fieldset
#           2: mode: "fdiff"/"felem"
#           3: poles_missing: "on"/"off"
#           4: vector_mode: "on"/"off"
#==============================================================================


function __prepare_gradient_arg(_fn_name, _fs_num, _args)
        
    _r = []
    if _fs_num <=0 or _fs_num > 3 then
       fail(_fn_name & ": invalid arguments = " & _args)
    end if

    for i=1 to _fs_num do
        _fs = nil        
        _fs  = _args[i]
        if type(_fs) <> "fieldset" then
            fail(_fn_name & ": positional argument #" & i & " must be a Fieldset!")
        end if
        _r = _r & [_fs]
    end for

    if mod(count(_args) - _fs_num, 2) <> 0 then 
        fail(_fn_name & ": invalid number of arguments!")
    end if

    _mode = "fdiff"
    _pole_missing = "off"
    _vector_mode = "off"
    for _i=_fs_num+1 to count(_args) by 2 do
        _key = _args[i]
        _val = _args[i+1]
        if _key = "mode" then
            _mode = _val
        else if _key = "poles_missing_values" then 
            _pole_missing = _val
        else if _key = "vector" then 
            _vector_mode = _val
        else
            fail(_fn_name & ": unexpected keyword argument = " & _key)
        end if
    end for
    if _mode not in ["fdiff", "felem"] then
        fail(_fn_name & ": mode must be 'fdiff' or 'felem'")
    end if
    # print("mode=", mode)
    # print("pole_missing=", pole_missing)
    # print("vector_mode=", vector_mode)
    
    _r = _r & [_mode, _pole_missing, _vector_mode]
    return _r

end __prepare_gradient_arg
