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

# footnote renumbering by order of occurance (Linux-Magazin 10/2008)
# (sys+cpu ~23%, mem ~28% of RLS' version)
# Author: Horst-W. Radners, utilizing a version by Randal L. Schwartz

my %mapping;   # hash mapping old to new numbering

# read and print text-part line-by-line,
# changing note-refs to ascending new numbering on the fly
my $num_new = 0;
while (<>) {
   last if /^\@footnote:/;
   s/\[ (\d+) \]/'[' . ($mapping{$1} ||= ++$num_new) . ']'/egx;
   print;
}
die(' *** missing footer') if eof;
print "\@footnote:\n";

# read and store footnotes in memory for reordered printing
my @fnote;   # array of notes, indexed by new numbering
while (<>) {
   my ( $num_old, $text ) = /^ \[ (\d+) \] \s* (.*)/x
      or print, next;
   my $num_new = $mapping{$num_old}
      or warn(" *** ignoring unused note: $_"), next;
   $fnote[$num_new] = $text;
}

# print footnotes, sorted by new numbering
foreach my $num ( 1 .. $#fnote ) {
   unless ( defined $fnote[$num] ) {
      warn(" *** ignoring dangling ref w/o note: $num");
      next;
   }
   print "[$num] $fnote[$num]\n";
}
