#!/usr/local/bin/perl -w
# $Mu: tools/txt2man 1.1 1998/08/12 17:09:59 $
##
## txt2man
##	Formatted (by sgml2txt -f) text to man-page tool.
##
## Copyright (C) 1997 Eric A. Howe
##
## 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.
##
##   Authors:  Eric A. Howe (mu@trends.net)
##

##
## tools/yanksect --section 'Command Line Switches' < doc/mgv.sgml > _swh.sgml
## sgml2txt -f _swh.sgml
## tools/txt2man manpage.man < _swh.txt > manpage.1
## rm -f _swh.sgml _swh.txt
##
use strict;
use IO::File;

sub main($) {
	my $input = shift;
	my $line;
	my $switch;
	my %help;
	my @switches;
	my @parts;
	my $fp;

	while(defined($line = <STDIN>)) {
		chomp($line);
		if($line =~ m(^     -)) {
			$line          =~ s/^\s+//;
			$line          =~ s/"/\\"/g;
			$switch        = $line;
			$help{$switch} = [ ];

			@parts = split(/, /, $switch);
			if($#parts == 0) {
				push(@switches, $switch);
			}
			elsif($parts[1] eq "-no" . substr($parts[0], 1)) {
				push(@switches, "-[no]" . substr($parts[0], 1));
			}
			else {
				push(@switches, @parts);
			}
		}
		elsif($line =~ /^        (.*)/) {
			$line = $1;
			$line =~ s/``/\\fB/g;
			$line =~ s/''/\\fR/g;
			push(@{$help{$switch}}, $line);
		}
	}

	$fp = new IO::File("< $input") || die "can't open $input: $!\n";
	while($line = $fp->getline()) {
		if($line =~ /^\.\\"\.synopsis/i) {
			foreach $switch (sort @switches) {
				print ".RI [ \"$switch\" ]\n";
			}
		}
		elsif($line =~ /^\.\\"\.options/i) {
			foreach $switch (sort keys %help) {
				print ".TP\n.I \"$switch\"\n";
				print join("\n", @{$help{$switch}}), "\n";
			}
		}
		else {
			print $line;
		}
	}

	return 0;
}

exit(main($ARGV[0]));
