#!/usr/bin/perl -w 

# Run like this:
# % qdoc ; ./fixhtml html/*.html

use strict;
use vars qw( $QT $InTable %Map %Master $BASENAME );


BEGIN { 
    $QT = 2.3;
    $BASENAME = 'qtopia';
    
    $InTable = 0;
    %Map = ();

    my %Count = ();
    my @files = ();
    my $newname = '';
    my $path = '';
    foreach my $file ( @ARGV ) {
	next unless $file =~ /$BASENAME\S*\.html?$/i;
	open F, $file or die "failed to open '$file': $!\n";
	my $name = $file;
	$name =~ s,(.*/),,;
	$path = $1 if defined $1;
	my $master = '';
	$Map{$name} = $newname = $name;
	while ( <F> ) {
	    $master = $1 if /<!-- MASTER=([^ ]+)\s*-->/; 
	    if ( /<!-- PAGE=([^ ]+)\s*-->/ ) {
		$Count{$1}++;
		warn "duplicate page name '$1' for page '$name'\n"
		if $Count{$1} > 1; 
		$Map{$name} = $newname = $1;
		last;
	    }
	}
	close F;
	$newname = $path . $newname;
	$Master{$newname} = $master;
	rename( $file, $newname ) or 
	warn "failed rename('$file', '$newname')\n";
	push @files, $newname;
    }
    @ARGV = @files;
}

# Yes we go through the files twice; this is a cheap hack.
foreach my $file ( @ARGV ) {
    my $output = '';
    my $next = '';
    my $prev = '';
    open F, $file or die "failed to read '$file': $!\n";
    while ( <F> ) {
	$_ = '' if /^<!DOCTYPE/;
	$_ = '' if /^\s*<!--([^>]+)-->\s*/ and 
		   $1 ne ' NEXT ' and $1 ne ' UP ' and $1 ne ' PREV ';
	$_ = '' if /^\s*<meta[^>]+>\s*/;
	$_ = '' if /^<!-- PAGE=.*-->$/;
	s/<!-- PAGE=.*-->//;
	s/<p><\/p>//g;
	if ( /($BASENAME\S*\.html)/ ) {
	    warn "missing name for $1; probably a runaway \\omit\n" 
	    unless exists $Map{$1} and defined $Map{$1};
	}
	s/($BASENAME\S*\.html)/$Map{$1}/g;
	if ( /<a href="(.+?)">Prev:/ ) { 
	    $prev = qq{<a href="$1"><img src="back.png"></a>}; #"
	}
	if ( /<a href=".+">Home<\/a>.*href="([^"]+)/ ) {
	    $_ = '';
	    $next = qq{<a href="$1"><img src="forward.png"></a>};
	}
	if ( $QT < 3 ) { # Fixes HTML bug in Qt 2.3
	    s/<h4[^>]*>/<p><b>/g;
	    s/<\/h4>/<\/b>/g;
	}
	if ( /Home<\/a>\]<\/p>\s*$/ ) {
	    $_ = '';
	}
	if ( $file =~ /index\.html$/ ) {
	    if ( not $InTable and /^<table/ ) {
		$_ = '';
		$InTable = 1;
	    }
	    elsif ( $InTable ) {
		if ( /^<h1/ ) {
		    $InTable = 0;
		}
		else {
		    $_ = '';
		}
	    }
	}
	$output .= $_;
    }
    close F;
    $output =~ s/<!-- UP -->/<a href="$Master{$file}"><img src="up.png"><\/a>/sm
    if $Master{$file}; 
    if ( $prev ) {
	$output =~ s/<!-- PREV -->/$prev/sm;
    }
    elsif ( $Master{$file} ) {
	$output =~ s/<!-- PREV -->/<a href="$Master{$file}"><img src="back.png"><\/a>/sm;
    }
    $output =~ s/<!-- NEXT -->/$next/sm if $next;
    open F, ">$file" or die "failed to write '$file': $!\n";
    print F $output;
    close F;
}

