#! /usr/bin/env python

# Copyright (C) 2008, Mike Mueller <mmueller@python-academy.de>

"Minimal implementation."
import re
import sys

RE_NUMBER = re.compile(r"\[(\d+)\]")

def process(file_name):
    "Process all data."
    data = open(file_name).read()
    split_text = data.split("@footnote:")
    footnote_numbers = RE_NUMBER.findall(split_text[1])
    pairs = zip(footnote_numbers, range(1, len(footnote_numbers) + 1))
    number_dict = dict((number, counter) for number, counter in pairs)
    def callback(match):
        "Replace all old with new numbers."
        return '[%s]' % number_dict.get(match.group(1),
               'Error: no footnote found for number %s' % match.group(1))
    print RE_NUMBER.sub(callback, data),

if __name__ == '__main__':
    process(sys.argv[1])
