#!/usr/bin/perl -w
#
# syntax: perl footnotes.pl sample4.txt > new.txt

use strict;

$|=0;

if (!@ARGV){
   print "usage: $0 old.txt > new.txt\n";
   exit 1;
}

my @broken;
my %mapindex;
my %txtindex;
my $stopp = 0;
my $count = 0;
my $msg = 'WARNING: footnote not defined!';

while (<>) {
   if ($stopp) {
       if ( /\[ (\d+) \] (.*)/x ) {
           $txtindex{$1} = $2;
       }
       next;
   }
   if ( /^\@footnotes:$/ ) {
       $stopp = 1;
       print $_;
       next;
   }
   while ( s/^ (.*?) \[ (\d+) \]//x ) {
       print $1;
       if ( exists $mapindex{$2} ) {
           print '[' . $mapindex{$2} . ']';
           next;
       }
       $mapindex{$2} = ++$count;
       print '['. $count. ']';
   }
   print $_;
}

for my $key ( sort { $mapindex{$a} <=> $mapindex{$b} } keys %mapindex ) {
   if ( exists $txtindex{$key} ) {
       printf ("[%s]%s\n", $mapindex{$key}, $txtindex{$key});
   }
   else {
       printf ("[%s] %s (old ref no %s)\n", $mapindex{$key}, $msg, $key);
       push (@broken, $mapindex{$key});
   }
}

if (@broken) {
   print STDERR "broken footnote(s): ", join(', ', @broken), "\n";
}

exit 0;

# eof