#!/usr/bin/env perl
# fast reimplementation, only handle order in text, single s/// per line.
use strict;

my %mapping;			# mapping of digits
my @definitions;

my $counter = 1;
while (<>) {
  if (/^\@footnotes?:/) {
    print;
    last;
  }
  s/\[(\d+)\]/'['.($mapping{$1} ||= $counter++).']'/ge;
  print;
}
die "missing footer" if eof;
while (<>) {
  /^ \[ (\d+) \] (.*)/x
    or print, next;
  exists $mapping{$1} or
    warn("ignoring unused note: $_"), next;
  $definitions[$mapping{$1}] = $2;
}

for my $i ( 1..$#definitions ) {
  print "[$i]$definitions[$i]\n";
}
