#!/usr/bin/env perl
# Randall array
use strict;
use constant {
    USED => 0,
    DEFINED => 1,
    DEFINITION => 2
};

my $ORDER_BY = USED;
#my $ORDER_BY = DEFINED;

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

{
  my $counter = 1;
  while (<>) {
    if (/^\@footnotes?:/) {
      push @parsed, $_;
      last;
    }
    while (s/^ (.*?) \[ (\d+) \]//x) {
      push @parsed, $1;
      push @parsed, $mapping{$2} ||= [$counter++];
    }
    push @parsed, $_;
  }
}
die "missing footer" if eof;
{
  my $counter = 1;
  while (<>) {
    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];
}
