import re


def gather_fn_handles(mc_lines, warn):
    """Gets all footnote references (handles) occuring in main content
       excluding any occuring in XML comments."""
    fn_handles = set()
    in_comment = False
    for mcl in mc_lines:
        if re.match("^\s*<!---?\s*$", mcl):
            in_comment = True
        elif in_comment and re.match("^\s*---?>\s*$", mcl):
            in_comment = False
        elif not in_comment: # handle up to 3 footnotes in a single <sup></sup>
             fns1 = re.findall("<sup>\[([a-zA-Z0-9_-]*)\]</sup>", mcl)
             fn_handles = fn_handles.union(set(fns1))
             fns2 = re.findall("<sup>\[([a-zA-Z0-9_-]*)\],\[([a-zA-Z0-9_-]*)\]</sup>", mcl)
             for fn in fns2: fn_handles = fn_handles.union(set(fn))
             fns3 = re.findall("<sup>\[([a-zA-Z0-9_-]*)\],\[([a-zA-Z0-9_-]*)\],\[([a-zA-Z0-9_-]*)\]</sup>", mcl)
             for fn in fns3: fn_handles = fn_handles.union(set(fn))
             fns4p = re.findall("<sup>\[([a-zA-Z0-9_-]*)\],\[([a-zA-Z0-9_-]*)\],\[([a-zA-Z0-9_-]*)\],(.*)</sup>", mcl)
             if len(fns4p) >= 4:
                 print("Error: Max number of grouped footnotes between <sup>...</sup> is 3")
                 print("This occurred at or near this line...")
                 print(mcl)
                 if not warn:
                    print("Correct above issues and re-try...")
                    exit(1)
    return fn_handles