#!/usr/bin/perl

###############################################################################
#  sgmltlatex:
#  Processing SGML or LaTeX file for Thai language.
#  
#
#  by Poonlap Veeratanabutr <poon-v@fedu.uec.ac.jp>
#  $Id: sgmltlatex,v 1.1 1998/09/28 10:54:33 poon-v Exp poon-v $
###############################################################################
sub error {
    print STDERR "$0 - Processing SGML or LaTeX file for Thai language.\n";
    print STDERR "usage: $0 [-[t|d|p] sgml_file] [-l latex_file] \n";
    print STDERR "       -t , create latex_file file from sgml_file\n";
    print STDERR "       -d , create dvi file from sgml_file and leave latex_file\n";
    print STDERR "       -p , create Postscript file and leave latex_file\n";
    print STDERR "       -l , run latex on latex_file\n";
    exit( -1 );
}

# command line processing
if( $#ARGV != 1 ){
    &error;
} elsif ( $ARGV[0] eq "-l" ){
    $option = "l";
} elsif ( $ARGV[0] eq "-t" ){
    $option = "t";
} elsif ( $ARGV[0] eq "-d" ){
    $option = "d";
} elsif ( $ARGV[0] eq "-p" ){
    $option = "p";
} else {
    &error;
}
$file = $ARGV[1];
$tempfile = "$file" . ".tmp";

if( $option ne "l" ){
    if( system( "sgml2latex --output=tex $file" ) != 0 ){
	exit( -1 );
    }
    
# separate directory and file name from the given file name
    if( $file =~ /(.*)[\/](.+)$/ ){
	$dir = $1;
	$file = $2;
    }
    
    if( $file =~ m/(.+)\.sgml$/ ){
	$rootname = "$1";
    } else {
	$rootname = $file;
    }
    $file = $rootname . ".tex";
    
    print "Processing file $file\n";

    open( INPUT, "$file" );
    open( OUTPUT, ">" . "$tempfile" );
    $preamble = 1;
    while( <INPUT> ){
	if( $preamble == 1 ){
	    if( /^\\begin\s*{\s*document\s*}\s*$/ ){
		print OUTPUT "\\usepackage{thai}\n";
		$preamble = 0;
		break;
	    }
	    s/^\\usepackage.*{\s*inputenc.*}\n//;
	    s/^\\usepackage.*{\s*babel.*}\n//;
	    s/^\\usepackage.*{\s*t1enc.*}\n//;
	    print OUTPUT;
	    
	} else {
	    print OUTPUT;
	}
    }
    close( INPUT );
    close( OUTPUT );

    
} else {
    unless( $file =~ m/(.+)\.tex$/ ){
	print STDERR "$0 needs .tex file\n";
	&error;
    }
    rename( "$file", "$tempfile" );
}


if( $option eq "t" ){
    rename( "$tempfile", "$file" );
    exit( 0 );
} else {
    system( "cttex < $tempfile > $file" );
    system( "latex $file" );
    rename( "$tempfile", "$file" );
} 

if( $option eq "p" ){
    $psfile = "$rootname" . ".ps";
    $dvifile = "$rootname" . ".dvi";
    system( "dvips -o $psfile $dvifile" );
}

exit( 0 );

#EOF
    
    





