<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def match_rules(tree, rules, fun=None, multi=False):
 """Matches a Tree structure with the given query rules. Query rules are represented as a dictionary of template to action. Action is either a function, or a dictionary of subtemplate parameter to rules:: rules = { 'template' : { 'key': rules } } | { 'template' : {} } Args: tree (Tree):
 Parsed tree structure rules (dict):
 A dictionary of query rules fun (function):
 Function to call with context (set to None if you want to return context) multi (Bool):
 If True, returns all matched contexts, else returns first matched context Returns: Contexts from matched rules """

    if multi:
        context = match_rules_context_multi(tree, rules)
    else:
        context = match_rules_context(tree, rules)
        if not context:
            return None

    if fun:
        args = fun.__code__.co_varnames
        if multi:
            res = []
            for c in context:
                action_context = {}
                for arg in args:
                    if arg in c:
                        action_context[arg] = c[arg]
                res.append(fun(**action_context))
            return res
        else:
            action_context = {}
            for arg in args:
                if arg in context:
                    action_context[arg] = context[arg]
            return fun(**action_context)
    else:
        return context