#! /usr/bin/perl
# Note: is used as follows:
#  ./sort-glossar <glossar.tex.master >glossar.tex
#
# To make a list of possible \refglossar{}{} do
#  ./sort-glossar <glossar.tex -list
#

$head = "";

sub readit {
  $state = 0;
  $in_header = 0;
  $in_body = 1;
  $in_entry = 2;
  $in_tail = 3;
  LINE: while (<STDIN>) {
    $line = $_;
    if ($state == $in_header) {
      $head = $head . $line;
      if ($line =~ /^\s*\%\%\%SORT_START/) {
        $state = $in_body;
      }
      next LINE;
    }
    if ($state == $in_entry) {
      $entries{$entry} = $entries{$entry} . $line;
      if ($line =~ /\s*\\end\{glossareintrag\}/) {
        $state = $in_body;
      }
      next LINE;
    }
    if ($state == $in_body) {
      if ($line =~ /\s*\%\%\%SORT\s+\{([^\}]+)\}/  ) {
        $entry = $1;
        $entries{$entry} = $line;
        $state = $in_entry;
        next LINE;
      }
      if ($line =~ /^\s*\%\%\%SORT_END/) {
        $state = $in_tail;
        $tail = $line;
      }
      next LINE;
    }
    if ($state == $in_tail) {
      $tail = $tail . $line;
    }
  }
}

sub printsorted_index {
  foreach $key (sort(keys %entries)) {
    @aux = split(/\n/, $entries{$key});
    $switch = 0;
    LINE: foreach $i (@aux) {
      if ($i =~ /\\begin\{glossareintrag\}\s*\{([^\}]*)\}/) {
        $rkey = $1;
        $switch = 1;
        next LINE;
      }
      if ($switch) {
        $i =~ /\{([^\}]*)\}/;
        print "\\refglossar\{$rkey\}\{$1\}\n";
        $switch = 0;
      }
    }
  }
}

sub printsorted {
  foreach $key (sort(keys %entries)) {
    print "\n\n$entries{$key}";
  }
}

readit();

if ($ARGV[0] eq "") {
  print $head;
  printsorted();
  print "\n\n$tail";
}
else {
  printsorted_index();
}

# EOF sort-glossar
