#! /usr/bin/perl -w
# O'Reilly's Perl script to chop mysql.xml into separate ch/apps/index files.
# The indexes are actually not used, they're created straight from the xrefs.
# Breaks the MySQL reference manual into chapters, appendices, and indexes.

use strict;

my $app_letter      = "a";                                  # Start appendix letters at "a"
my $chap_num        = 1;                                    # Start chapter numbers at one (there is no preface)
my $directory       = "mysql_refman_" . time;
my $ext             = ".xml";
my $line            = "";
my $output_name     = "";
my $start_text      = "";

mkdir $directory unless -d $directory;

while (defined $line) {
    if ($line =~ /(<chapter.+)/i ) {
        $start_text = $1;
        $output_name = sprintf("ch%02d%s", $chap_num, $ext);
        ++$chap_num;
        &process_file("chapter");
    }
    elsif ($line =~ /(<appendix.+)/i ) {
        $start_text = $1 ;
        $output_name = "app$app_letter$ext";
        ++$app_letter;
        &process_file("appendix");
    }
    elsif ($line =~ /(<index\s+id=")(.*?)(">.*)/i ) {
        $start_text = $1 . $2 . $3;
        $output_name = lc($2) . $ext;
        &process_file("index");
    }
    else {
        # Skip junk in between chapters, appendices and indexes.
        $line = <>;
    }
}

sub process_file {
    my $marker  = shift;
    my $path    = "$directory/$output_name";

    open (OUTPUT_FILE, ">$path") or die "Cannot open $path";

    print STDERR "Creating $path\n";

    # Print out XML PI
    print OUTPUT_FILE "<?xml version='1.0' encoding='ISO-8859-1'?>\n";
   
    # Print whatever happened to appear at the end of the previous chapter.
    print OUTPUT_FILE "$start_text\n" if $start_text;
    
    while (defined $line) {
        $line = <>;

        # Note: Anything after the terminating marker is lost, just like
        # lines in between chapters.
        if ($line =~ /(.*<\/\s*$marker\s*>)/i ) {
            print OUTPUT_FILE "$1\n" if $1;
            close OUTPUT_FILE;
            return;
        }
        print OUTPUT_FILE $line;
    }
}

exit 0;
