#!/usr/bin/perl 
#
# Given a single chapter .tex file, generate a single chapter
#

use Getopt::Long;
use Fcntl ;
use FileHandle ;

#
# Add the LaTex Header information
#
#
sub addHeader {
    print "\\documentclass[twoside,a4paper]{book}\n";
    print "\\usepackage{graphics}\n";
    print "\\usepackage{makeidx}\n";
    print "\\usepackage{tlk2e}\n";
    print "\\include{misc/macros}\n";

    print "\\parindent 0cm\n";
    print "% the book itself\n";
    print "\\begin{document}             % End of preamble and beginning of text.\n";

    print "% include the definitions that we need.\n";
    print "\\include{misc/definitions}\n";
    print "\\include{version}\n";

    print "% The main part of the book\n";
    print "\\mainmatter\n";
}

#
# Add the LaTex Footer information
#
sub addFooter {
    print "\\end{document}\n";
}

# convert the asci file into a database
#
sub generateChapter {
    my ($chapter, $texfile) = (@_) ;

# check the arguments
    if ($texfile eq "") {
	die "ERROR: supply a text file name: $!\n";
    } else {
	if (! -f $texfile) {
	    die "ERROR: $texfile: $!\n";
	}
    }

# tell the world the good news
    print STDERR "Generating Chapter from tex file $texfile\n";

# Add the appropriate LaTeX stuff into the front of the file
    addHeader() ;

# Put in the chapter number
    print "\\setcounter{chapter}{$chapter}\n";

# open the text file and copy over its contents
    open TEXFILE, $texfile or die "Can't open text file: $!\n";
    while ($line = <TEXFILE>) {
	print $line;
    }

# Add the footer
    addFooter() ;

# close everything
    close TEXFILE ;
}

#
# --------------------------------------------------------
# main()
#
#
$chapter = "1";

&GetOptions(
	    "chapter=s" => \$chapter, "c=s" => \$chapter
	    ) ;

#
# Set the counter 1 less than it needs to be (it gets incremented
# by the \chapter command
#
$chapter--;

#
# Go generate the file
#
if ("@ARGV") {
    generateChapter($chapter, @ARGV);
} 

# all's well that ends well
exit 0 ;




