#!/usr/bin/perl
# ISDK - Information System Development Kit
# Copyright (C) 1998-1999 Szilard Hajba, Peter Vazsonyi
#
# 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

require "getopts.pl";

if (Getopts("hD:")) {
    if ($opt_h) {
	print STDERR "Usage: $0 [-h] [-D dir] file [...]\n";
    } else {
	while ($#ARGV>-1) {
	    $opt_D =~ s#/*$#/# if ($opt_D);
	    $state_pre=0;
	    open IN, "<".shift(@ARGV);

	    while (<IN>) {
		if (/^[ \/]\*(.)(.*)$/) {
		    $com=$1; $zilu=$2;
		    $zilu =~ s/([^\\]|^)\$(\w+)/${'VAR::'.$2}/g;
		    $zilu =~ s/\\\$/\$/g;
		    if (($com eq ':') && (!$state_pre)) {
			print OUT ".nf\n"; $state_pre=1;
		    } elsif (($com  ne ':') && ($state_pre)) {
			print OUT ".fi\n"; $state_pre=0;
		    }
		    if ($com eq '$') {
			$zilu =~ /(\w+)\W.*"(.*)"/;
			${"VAR::$1"}=$2;
		    } elsif ($com eq '+') {
			#$zilu =~ /(\w+)/;
			$filename=$zilu;
			close OUT; open OUT, ">$opt_D"."$zilu.$VAR::mansection";
			print OUT ".\\\" Copyright (c) 1998 Szilrd Hajba.\n.\\\" All rights reserved.\n.\\\"\n";
			print OUT ".TH $zilu $VAR::mansection \"$VAR::date\" \"\" \"$VAR::title\"\n";
		    } elsif ($com eq '^') {
			open PTR, ">$opt_D"."$zilu.$VAR::mansection";
			print PTR ".so man$VAR::mansection/$filename.$VAR::mansection\n";
			close PTR;
		    } elsif ($com eq '=') {
			print OUT ".SH $zilu\n";
		    } elsif ($com eq '-') {
			print OUT ".SS $zilu\n";
		    } elsif ($com eq '.') {
			print OUT ".TP\n.B $zilu\n";
		    } elsif ($com =~ /[ \t:]/) {
			$zilu =~ s/^\t/    /;
			$zilu =~ s/\\[Ll]{([^}:]*):([^}:]*)}/\\fI$1\\fR (see $2)/g;
			$zilu =~ s/\\[Ll][Pp]{([^}:]*):([^}:]*)}/\\fI$1 (see page $2($VAR::mansection))\\fR/g;
			$zilu =~ s/\\[Ll][Pp]{([^}:]*)}/\\fI$1($VAR::mansection)\\fR/g;
			$zilu =~ s/\\[Bb]{([^}]*)}/\\fB$1\\fR/g;
			$zilu =~ s/\\[Ii]{([^}]*)}/\\fI$1\\fR/g;
			print OUT "$zilu\n";
		    }
		} elsif (/^[ \/]\*$/) {
		    print OUT ".sp\n";
		}
	    }
	}
    }
} else {
    exit 1;
}
