#!/usr/bin/perl -w
use strict;
use English;

use constant EXTENSION => '.bak';

my $oldargv;
my $nr;
my $index_formalpara;
my $index_title;
my @line;
my $prefix;
my $postfix;

sub new_file()
{
  my $backup = $ARGV . EXTENSION;
  unlink $backup;
  rename($ARGV, $backup);
  open(ARGVOUT, ">$ARGV");
  select(ARGVOUT);
  $oldargv = $ARGV;

  $nr = -1;
  $index_title = undef;
  undef @line;
}

LINE: while(<>)
{
  if (!defined($oldargv))
  {
    new_file;
  }
  elsif ($ARGV ne $oldargv)
  {
    print @line;
    new_file;
  }
  $line[++$nr] = $_;
  if (m/^\s*<formalpara[\s>]/)
  {
    $index_formalpara = $nr;
    next LINE;
  }
  if (m/^(\s*<title>[^<:]+)[^<]*(<\/title>.*)/)
  {
    if (defined($index_formalpara) && $nr - 1 == $index_formalpara)
    {
      $index_title = $nr;
      $prefix = $1;
      $postfix = $2;
      next LINE if (!($prefix =~ m/\s-\s/));
    }
    # printf STDERR "%s (%d): %s", $ARGV, $nr, $line[$nr];
    $index_title = undef;
    next LINE;
  }
  if (m/fileref="\.\.\/([^"]+)"/ && defined($index_title))
  {
    my $file = $1;
    $file =~ s/\.\.\///g;
    $line[$index_title] = "$prefix: $file$postfix\n";
    $index_title = undef;
  }
}
print @line;
