#!/usr/local/bin/perl
#
# Insert Next, ToC, Prev, and other links.
#
# The given configuration file contains ordering and 
# numbering information
#
# Bert Bos <bert@w3.org>
# $Id: mkchain,v 2.4 2006-10-09 18:55:52 ihickson Exp $

use Getopt::Std;
use lib 'bin';
use utils;

my $PROG = substr($0, rindex($0, "/") + 1);
my $USAGE = "Usage: $PROG [-r real-name] [-c configfile] [file [output]]\n";


getopts('r:c:') or die $USAGE;
if ($#ARGV >= 0) {$input = $ARGV[0]; shift;} else {$input = '-';}
if ($#ARGV >= 0) {$output = $ARGV[0]; shift;} else {$output = '-';}
if ($#ARGV >= 0) {die $USAGE;}

my $name = defined $opt_r ? $opt_r : $input;
my $configfile = defined $opt_c ? $opt_c : 'Project.cfg';

# Read configuratio and find info about current file
read_config($configfile);

defined $lookup{$name} or die "$PROG: $name not found in config file\n";
$chapno = $lookup{$name};

# Insert the links after the </TITLE> tag. (There better be one!)
open(IN, $input) or die "$PROG: cannot read file $input\n";
open(OUT, ">$output") or die "$PROG: cannot write to file $output\n";
my $done = 0;

while (<IN>) {
    /<\/title[^>]*>/io and do {
	print OUT $`;
	print OUT $&;
	for ($i = 0; $i <= $#stylesheet; $i++) {
	    print OUT "\n<link rel=\"stylesheet\" href=\"$stylesheet[$i]\"";
	    if ($styletype[$i] ne '') {print OUT " type=\"$styletype[$i]\"";}
	    print OUT ">";
	}
	if ($chapno > 0) {
	    print OUT "\n<link rel=\"prev\" href=\"$chapter[$chapno-1]\">";
	}
	if ($chapno < $#chapter) {
	    print OUT "\n<link rel=\"next\" href=\"$chapter[$chapno+1]\">";
	}
	if ($contents ne '') {
	    print OUT "\n<link rel=\"contents\" href=\"$contents\">";
	}
	for ($i = 0; $i <= $#links; $i++) {
	    print OUT "\n<link rel=\"$relations[$i]\" href=\"$links[$i]\"";
	    if ($tonavbar[$i] ne '') {print OUT " title=\"$tonavbar[$i]\"";}
	    print OUT ">";
	}
	print OUT $';
	$done = 1;
	last;
    };
    print OUT;
}

# Copy the rest of the file
while (<IN>) {
    print OUT;
}

if (! $done) {die "$PROG: $input had no <TITLE>; no links inserted\n";}

# Finalize
close(IN);
close(OUT);
