#!/usr/bin/env perl
use strict;

my $counter;
my %mapping; # mapping of digits
my %footnote;

while (<DATA>) {
	for my $number (m/\[(\d+)\]/g) {
		if (exists($mapping{$number})) {
			s/\[$number\]/[$mapping{$number}]/;
			next;
		}

		$counter++;

		$mapping{$number} = $counter;

		s/\[$number\]/[$counter]/;
	}

	print;

	last if (m/^\@footnote?:/);
}

die "missing footer" if eof DATA;

while (<DATA>) {
	my ($number) = m/^\[(\d+)\]/g;

	unless (exists($mapping{$number})) {
		warn("ignoring unused note: $_\n");
		next;
	}

	s/^\[$number\]/[$mapping{$number}]/;

	$footnote{$mapping{$number}} = $_;
}

for my $number (sort { $a <=> $b } keys(%footnote)) {
	print $footnote{$number};
}

__DATA__
A great brown fox [13] jumped of a pile of lorem ipsum [4], [7]. He met
with a silver penguin, browsing the Linux Kernel Mailinglist [3]. They
debated whether to start C-programs with "main (int argc, char **argv)"
or with "main (int argc, char *argv[])". Brackets annoyed them [9999].
@footnote:
[13] Al Fabetus: "On characters and animals", 1888, self published.
[4] Lorem Ipsum, <a href="http://link.org/Lorem_Ipsum">Web Link</a>
[9999] Annoying Link.
[7] B. Fox: "More on Blind Text".
[3] Linux Kernel Maintainers: LKML
