#!perl

# This is a replacement 'man' command written in perl.
# It requires Perl 5 although it shouldn't be to hard to rewrite it for perl 4
# groff is also warmly recommended
# It does not use any special configuration files but just looks through the 
# directories in the environment variable MANPATH.
# In each dir mention in $MANPATH it looks for dirnames of the
# type manx/catx where x is the section "number" ( x can by just about
# any character). The files in manx is nroff style documents while
# those in catx are preformatted. If the file filename.whatever in manx
# is newer than the file filename.0 in catx the file in manx automatically
# gets processed. (No need to explicitly call [g]nroff for man-files anymore)
# This code is hereby placed into public domain.


use Getopt::Std;



getopts('as:M:m:');

$fname=shift @ARGV;
if(! $fname )
	{
	print "$0 [-a] [-s section] [-M path] [-m path] name\n";
	exit 0;
	}
	
$manpath=$ENV{'MANPATH'};

if(! $manpath )
	{
	$manpath='/usr/man/';
	}
	
$pager=$ENV{'PAGER'};
if(! $pager)
	{
	$pager='less -s';
	}


if($opt_M)
	{
	$manpath=$opt_M;
	}
	
if($opt_m)
	{
	$manpath= $opt_m . ":" . $manpath;
	}
	
	
	
	
@mandirs=split(/:/,$manpath);

foreach $mand ( @mandirs )
	{
	if(!opendir(MDIR,$mand) ) { print "Can't find directory $mand \n"; next ;}
	@allfiles=readdir(MDIR);
	closedir(MDIR);
	if($opt_s)
		{
		@mdirs=grep( /^man$opt_s$/ , @allfiles );
		}
	else
		{
		@mdirs=grep(  /^man.$/ , @allfiles);
		}
	foreach $md ( @mdirs )
		{
		if(! -d "$mand/$md" ) { next ; }
		$mext=substr($md,3);
		opendir(MD,"$mand/$md") || die;
		@mfiles=readdir(MD);
		closedir(MD);
		@mfiles=grep( /^\Q$fname\E\.[^.]*$/ , @mfiles);
		$mf="$mand/$md/" . $mfiles[0];
		$cf="$mand/cat$mext/" . $fname . ".0";
		if( -d "$mand/cat$mext" )
			{
			if( -f $mf && -s $mf)
				{
				if( -f $cf && -s $cf)
					{
					$ca=(stat($cf))[9];
					$ma=(stat($mf))[9];
					if ($ma > $ca )
						{
						print "Reformatting page...\n";
						system("groff -t -Tascii -mandoc $mf > $cf");
						}
					}
				else
					{
					print "Reformatting page...\n";
					system("groff -t -Tascii -mandoc $mf > $cf");
					}
				}
			if( -f $cf && -s $cf)
				{
				if($opt_a)
					{
					system("$pager $cf");
					}
				else
					{
					exec("$pager $cf");
					die "Can't execute $pager\n";
					}
				}
			}
		else
			{
			if( -f $mf && -s $mf)
				{
				if($opt_a)
					{
					system("groff -t -Tascii -mandoc $mf | $pager");
					}
				else
					{
					exec("groff -t -Tascii -mandoc $mf | $pager");
					}
				}	
			}
		}	
	}	
		

if(! $opt_a)
	{
	print "Couldn't find manpage\n";
	}
