#Metview Macro

# **************************** LICENSE START ***********************************
#
# Copyright 2012 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 ************************************

#================================================
# utility function to get keyword args (used when
# called from Python)
#================================================

function __get_kwargs(fn_name: string, args: list, start_idx: number, options_or_keys)
    
    num = count(args) - start_idx + 1
    if mod(num,2) <> 0 then
        return nil
    end if
    
    if type(options_or_keys) = "list" then
        keys = options_or_keys
        options = ()
    else if type(options_or_keys) = "definition"  then
        keys = keywords(options_or_keys)
        options = options_or_keys
    else
        fail(fn_name & ": invalid argument passed to __get_kwargs!")
    end if
    
    for i=start_idx to count(args) by 2 do
        if type(args[i]) = "string" and args[i] in keys then
            options[args[i]] = args[i+1]
        else 
            fail(fn_name & ": invalid keyword=", args[i])
        end if 
    end for
    
    # turn "nil" str to nil, e.i. remove keys from definition
    loop k in keys
        if options[k] = "nil" then
            options[k] = nil
        end if
    end loop
    
    return options    
end  __get_kwargs
