#!/usr/bin/python

import sys
import re

def mkMap(lst):
    return dict([(ref, "[%d]" % (n+1)) for n, ref in enumerate(lst)])

def asNum(line):
    try:
        key = int(line[1:].split(']', 1)[0])
    except:
        key = line or None  # If line looks wrong, just return the raw line
    return key

def footnote(in_s, usebody=False):
    # compile regexps
    my_re1 = re.compile(r"\[\d+\]")
    my_re2 = re.compile(r"(\[\d+\])")
    foot_split = "\n@footnote:\n"
    body, foots = in_s.split(foot_split)
    links   = list(set(my_re1.findall(body)))
    targets = list(set(my_re1.findall(foots)))
    mapping = mkMap(links if usebody else targets) # Ref order of body xor foots
    # Replace source->target footnote numbers
    def numsub(m):
        return mapping.get(m.group(1), "not_found")
    body  = my_re2.sub(numsub, body )
    foots = my_re2.sub(numsub, foots)
    # May need to reorder target lines in foots
    if usebody:
        foots = '\n'.join(sorted(foots.splitlines(), key=asNum))
    return body + foot_split + "\n" + foots.strip()

def main():
    print footnote(sys.stdin.read(), usebody='-a' in sys.argv[1:])
    
if __name__ == '__main__':
    main()
