#!/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 "\\include{misc/macros}\n";

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

    print "\\newcommand{\\index}[1]{}\n";
    print "\\newcommand{\\tm}{\${}^{\\mbox{\\tiny\\sf TM}}\$}\n";
    print "\\newcommand{\\marginpar}[1]{}\n";
    print "\\newcommand{\\sf}[1]{\\texttt{#1}}\n";

    print "% include the definitions that we need.\n";
    print "\\include{misc/definitions}\n";
    print "\\include{version}\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;
    }

    print "\\end{document}\n";

# 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 ;




