#!/usr/bin/env perl
use strict;
$|++;

#my $ORDER_BY = "used";
my $ORDER_BY = "defined";

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

{
  my $counter = 1;
  while (<DATA>) {
    if (/^\@footnotes?:/) {
      push @parsed, $_;
      last;
    }
    while (s/^ (.*?) \[ (\d+) \]//x) {
      push @parsed, $1;
      push @parsed, $mapping{$2} ||= { used => $counter++ };
    }
    push @parsed, $_;
  }
}
die "missing footer" if eof DATA;
{
  my $counter = 1;
  while (<DATA>) {
    my ($number, $text) = /^ \[ (\d+) \] (.*)/x
      or (push @parsed, $_), next;
    my $item = $mapping{$number} or
      warn("ignoring unused note: $_"), next;
    $item->{defined} = $counter++;
    $item->{definition} = $text;
  }
}

for my $item (@parsed) {
  if (ref $item) {
    printf '[%s]', $item->{$ORDER_BY};
  } else {
    print $item;
  }
}
for my $itemkey (sort {
  $mapping{$a}{$ORDER_BY} <=> $mapping{$b}{$ORDER_BY}
} keys %mapping) {
  my $value = $mapping{$itemkey};
  printf "[%s]%s\n", $value->{$ORDER_BY}, $value->{definition};
}

__DATA__
A great brown fox [13] jumped of a pile of lorem ipsum [4], [7]. He
met with a silver penguin, browsing the Linux Kernel Mailinglist
[3]. They debated other the question whether to start a C-program with
"main (int argc, char **argv)" or with "main (int argc, char
*argv[])".  Square brackets annoyed them [9999].

@footnotes:

[13] Al Fabetus: "On characters and animals", 1888, self published.
[4] Lorem Ipsum, <a href="http://en.wikipedia.org/wiki/Lorem_ipsum">Web Link</a>
[9999] Annoying Link.
[7] B. Fox: "More on Blind Text".
[3] Linux Kernel Maintainers: LKML
