#!/usr/bin/env perl
# fast reimplementation, only handle order in text, buffering.
use strict;

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

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

for my $i ( 1..$#definitions ) {
  $buffer .= "[$i]$definitions[$i]\n";
  if( 16 * 1024 < length $buffer ) {
    syswrite STDOUT, $buffer;
    $buffer = '';
  }
}
syswrite STDOUT, $buffer;
