#!/usr/bin/perl
#
# tbl2html - convert troff tbl text to HTML
#
# Copyright 1997-2002  Daniel Quinlan
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

require "newgetopt.pl";
&NGetOpt("break", "tr", "help");

$usage = 'usage: tbl2html [options]
        --break       break table rows with <BR>
        --tr          break table rows with <TR> (default, but often ugly)
        --help        print this help message
';

$opt_tr = 1;

if ($opt_help) {
    print $usage;
    exit 0;
}

sub tbl2html {
    $center = 0;
    $expand = 0;
    $box = 0;
    $allbox = 0;
    $doublebox = 0;
    $tab = "\t";
    $eqn_start = '~';
    $eqn_end = '~';
    $linesize = 0;		# unset
    $line = 0;
    $data_format = 0;		# data format specification

    $_ = <>;
    if (/;$/) {
	# parse optional global table format
	/center/ &&
	    do { $center = 1; };
	/expand/ &&
	    do { $expand = 1; };
	/box/ &&
	    do { $box = 1; };
	/allbox/ &&
	    do { $allbox = 1; };
	/doublebox/ &&
	    do { $doublebox = 1; };
	/tab\((.)\)/ &&
	    do { $tab = $1; };
	/delim\((.)(.)\)/ &&
	    do {
		$eqn_start = $1;
		$eqn_end = $2;
	    };
	/linesize\([0-9]+\)/ &&
	    do {
		$linesize = $1;
	    };

	# read next line (data format specification)
	$_ = <>;
    }
    $data = "";
    for (;;) {
	$data .= $_;
	last if /\.$/;
	$_ = <>;
    }
    chomp($data);

    # print table header
    print "<TABLE";
    print " BORDER=\"1\"" if ($allbox || $box || $doublebox || $opt_tr);
    print ">\n";

    # read table data
    if ($opt_break) {
	while (<>) {
	    chomp;
	    if ($_ eq "_") {
		&printcells;
		undef(@out);
		next;
	    }
	    @cells = split(/$tab/);
	    $col = 0;
	    for $cell (@cells) {
		$out[$col] .= $cell . "<BR>\n";
		$col++;
	    }
	}
    }
    else {
	while (<>) {
	    chomp;
	    if ($_ eq "_") {
		print "<TR>\n";
		next;
	    }
	    print "<TR>\n";
	    @cells = split(/$tab/);
	    for $cell (@cells) {
		print "<TD>", $cell, "\n";
	    }
	}
    }
    &printcells;
    print "</TABLE>\n";
}

sub printcells {
    print "<TR>\n";
    for $cell (@out) {
	print "<TD>\n", $cell;
    }
}

&tbl2html;
