#! /usr/bin/perl

# Script to tidy up the HTML file that is generated by xmlto. The
# following changes are made:
#
# 1. Create reverse links from chapter and section titles back to the TOC.
#
# 2. Turn <div class="literallayout"><p><br /> into <div class="literallayout">
#    and a matching </p></div> into </div> to get rid of unwanted vertical
#    white space.


$tocref = 1;

# Read in the xfpt.html file.

open(IN, "xfpt.html") || die "Failed to open xfpt.html for reading: $!\n";
@text = <IN>;
close(IN);

# Insert a newline after every > in the toc, because the whole toc is generated
# as one humungous line that is hard to check. Indeed, the start of the first
# chapter is also on the line, so we have to split if off first. Having
# inserted newlines, we split the toc into separate items in the vector.

for ($i = 0; $i < scalar(@text); $i++)
  {
  if ($text[$i] =~ /<title>The xfpt plain text to XML processor<\/title>/)
    {
    splice @text, $i, 1, (split /(?=<div class="chapter")/, $text[$i]);
    $text[$i] =~ s/>\s*/>\n/g;
    splice @text, $i, 1, (split /(?<=\n)/, $text[$i]);   
    last;
    }   
  }

# We want to create reverse links from each chapter and section title back to
# the relevant place in the TOC. Scan the TOC for the relevant entries. Add
# an id to each entry, and create tables that remember the new link ids. We
# detect the start of the TOC by <div class="toc" and the end of the TOC by
# <div class="chapter".

# Skip to start of TOC

for ($i = 0; $i < scalar(@text); $i++)
  {
  last if $text[$i] =~ /^<div class="toc"/;
  }

# Scan the TOC

for (; $i < scalar(@text); $i++)
  {
  last if $text[$i] =~ /^<div class="chapter"/;
  if ($text[$i] =~ /^<a href="(#[^"]+)">/)
    {
    my($ss) = $1;
    my($id) = sprintf "%04d", $tocref++;
    $text[$i] =~ s/<a/<a id="toc$id"/;
    $backref{"$ss"} = "toc$id";
    }
  }

# Scan remainder of the document

for (; $i < scalar(@text); $i++)
  {
  while ($text[$i] =~ 
      /^(.*)<a( xmlns="[^"]+")? id="([^"]+)"><\/a>(.*?)<\/h(.*)/)
    {
    my($ref) = $backref{"#$2"};
    $text[$i] = "$1<a$2 href=\"#$ref\" id=\"$3\">$4</a></h$5";
    }
    
  if ($text[$i] =~ /^(.*)<div class="literallayout"><p><br \/>/)
    {
    my($j); 
    $text[$i] = "$1<div class=\"literallayout\">\n";
    
    for ($j = $i + 1; $j < scalar(@text); $j++)
      {
      if ($text[$j] =~ /^<\/p><\/div>/)
        {
        $text[$j] =~ s/<\/p>//;
        last;
        }    
      }  
    }  
  }

# Write out the revised file

open(OUT, ">xfpt.html") || die "Failed to open xfpt.html for writing: $!\n";
print OUT @text;
close(OUT);

# End
