#!perl         # just to get emacs into perl mode when editing this

package invertmap;

use strict;
use English '-no_match_vars';

$WARNING = 1;     # same as usual -w option
$INPUT_RECORD_SEPARATOR = undef;
$OUTPUT_RECORD_SEPARATOR = undef;

sub usage {
  die "Syntax:\n\tgmX invertmap <inputfile> <outputfile>\n(see html docs)\n";
}

(@ARGV != 2 or grep /^-h/i, @ARGV) and &usage;

my ($in, $out) = @ARGV;

my $read = GM::open $in;
$_ = <$read>;
close $read;

my %map = ();
for (split /\n\s*\n/) {
  my ($label, @thing) = split /\n(?!\s)/;
  for (@thing) {
    push @{$map{$_}}, $label;
  }
}

my $write = GM::open ">$out";
for my $thing (sort keys %map) {
  print $write "$thing\n";
  for (@{$map{$thing}}) {
    print $write "$_\n";
  }
  print $write "\n\n";
}
close $write;

print "Done.\n";
