#!/usr/bin/env perl
# all in memory
use strict;

my %mapping;			# mapping of digits
my @definitions;
undef $/;			# read in one go

my $counter = 1;
my $part = 0;
for( split /(\n\@footnotes:\n)/, <> ) {
  if( ++$part == 1 ) {
    s/\[(\d+)\]/'['.($mapping{$1} ||= $counter++).']'/ge;
    print;
  } elsif( $part == 2 ) {
    print;
  } else {
    for( split /^/ ) {
      /^ \[ (\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";
}
