#!/usr/local/bin/perl

### hdocu -- Hypertext-Based Documentation of installed Software
### (c) 1997 F.J. Leitner
### $Header: hdocu,v 1.2 98/05/20 13:50:11 fjl Exp $
###
### based on htmldoku (c) 1995, 1996 M. Kraess, F.J. Leitner
### and based on htmlman and htmlcheck (c) 1996 F.J. Leitner

### Default hdocu library directory
$HdLibDir = "/usr/local/lib/hdocu";

### Do you have rman (PolyglottMan) installed?
$rman = '/usr/local/bin/rman -f HTML -r \'../html%2$s/%1$s.%2$s.html\'';

### This pipe should emulate what "man" does with a file
### Only needed if rman is not available
$manfilter = '/usr/bin/neqn | /usr/bin/tbl -TX | /usr/bin/nroff -man | /usr/bin/col';


### Version
$RcsVersion=(split (" ", '$Revision: 1.2 $'))[1];

###--------------###
### COMMAND LINE ###
###--------------###

use Getopt::Long;
use File::Basename;

### opt_make and opt_rman are on by default
$opt_make="1";
$opt_rman="1";

GetOptions(
    "help",
    "verbose|v:i@",
    "version",
    "old!",
    "table!",
    "check!",
    "nocheckman",
    "make!",
    "rman!",
    "man|m!",
    "libdir=s",
    "in=s@",
    "mandir=s@",
    "pub:s@",
    "out|o=s",
) or exit;

if ( defined($opt_help)  && $opt_help ) {
    print
"
  hdocu v$RcsVersion -- documentation system for installed software
    -help             : show this message and stop
    -verbose [level]  : make hdocu more verbose
    -version          : show version of hdocu and stop
    -[no]old          : will allow the use of old-style INFO.LDV
    -[no]table        : use of HTML tables
    -[no]make         : do not generate new html files (on by default)
    -[no]man          : generate html versions of manpages
    -[no]rman         : rman makes prettier HTML Versions  (on by default)
    -[no]check        : run addition check for installed files
    -nocheckman       : do not check installed manpages
    -libdir directory : hdocu library directory (contains config file)
    -in directory     : where to look for INFO.LDV files
    -mandir directory : where to look for man files
    -pub [directory]  : ditto, but handled different
    -out directory    : where to put the html files
  Options may be abbreviated
  Multiple '-v' options will increase the level of verbosity
  You can specify multiple '-in' directories

";
    exit;
}

if ( defined($opt_version) && $opt_version ) {
    print "hdocu version $RcsVersion\n";
    exit;
}

### Level of verbosity can be controlled by setting it explicitly
###     or by incresing it through addition "-v" options
$verbose = 0;
if (defined @opt_verbose) {
    foreach $_ (@opt_verbose) {
        if ($_ > "0") {$verbose = $_; }
        else {$verbose++ ; }
    }
}

###---------------###
### CONFIGURATION ###
###---------------###

### Hdocu library directory
if ( defined $opt_libdir ) {
    $HdLibDir = $opt_libdir;
}

### Some default settings
$config{DOCUDIR} = "/usr/local/hdocu"; ### Out
$config{DIRLIST} = "/usr/local/src"; ### In list

### Read the config file
parse( "$HdLibDir/config", \%config );

### Read the defaults file
parse( "$HdLibDir/DEFAULT.LDV", \%default );

### Make lists from some multi-line configuration sections
@DIRLIST = split /\n/, $config{DIRLIST};
@PUBDIR = split /\n/, $config{PUBDIR};
@MANDIR = split /\n/, $config{MANDIR};

### Command line options may override config file settings
if (@opt_in) { @DIRLIST = @opt_in; }
if (@opt_pub) { @PUBDIR = @opt_pub; }
if (@opt_mandir) { @MANDIR = @opt_mandir; }
if (defined $opt_out) { $config{DOCUDIR} = $opt_out; }
if (defined $opt_old) { $config{OLDSTYLE} = ($opt_old ? "true" : "false"); }
if (defined $opt_table) { $config{USETABLE} = ($opt_table ? "true" : "false"); }

### Pubdirs should also go into DIRLIST!
@DIRLIST = (@DIRLIST , @PUBDIR);

###------###
### INIT ###
###------###

### maybe we have to convert the defaults file?
if ( lc($config{OLDSTYLE}) eq "true" ) { convertOldstyle(\%default); }

### Calculate relative path back to the root directory, like ../../..
### OLD
# @dirs = split /\//, $config{DOCUDIR};
# $backtoroot = "";
# for ($i=0 ; $i < $#dirs; $i++) { $backtoroot .= "../"; };
# chop $backtoroot;

### Set umask if configured
if( defined( $config{UMASK} ) ) { umask( $config{UMASK} ); }

### Ensure that user is in the right group
if( defined( $config{GROUP} ) ) {
    if( $( != (getgrnam($config{GROUP}))[2] ) {
        die "You are in the wrong group: execute \"newgrp $config{GROUP}\" first\n";
    }
}

if( $verbose >= 2) {
    print
"
Will be examining.: " . join(" ", @DIRLIST) . "
umask.............: " . umask() . "
Pubdirs...........: " . join(" ", @PUBDIR) . "
Libdir............: $HdLibDir
Write to directory: $config{DOCUDIR}
Table support.....: " . ( (lc($config{USETABLE}) eq "true") ? "on" : "off" ) . "
Old style INFO.LDV: " . ( (lc($config{OLDSTYLE}) eq "true") ? "allowed" : "not allowed" ) . "
Verbosity level...: $verbose

"
}

###-----###
### RUN ###
###-----###

$time = localtime(time);
 
if ($opt_make || (defined($opt_man) && $opt_man) ) {
    if ($verbose >= 2) { print "Reading template files...\n"; }
    readTemplates();
}
 
if ($opt_make) {
    if ($verbose >= 1) { print "Generating HTML files...\n"; }
    mainHdocuEngine();
}
if ( defined($opt_check) && $opt_check ) {
    if (! $opt_make) {
        if ($verbose >= 1) { print "Analysing INFO.LDV Files\n"; }
        mainHdocuEngine();
    }
    mainCheckEngine();
}
if ( defined($opt_man) && $opt_man ) {
    if ($verbose >= 1) { print "Converting MAN files...\n"; }
    mainManEngine();
}

###--------------###
### HDOCU ENGINE ###
###--------------###

sub mainHdocuEngine {
    ### Is the target directoty writeable?
    (-d $config{DOCUDIR} ) or die "Directory $config{DOCUDIR} doesn't exist!\n";
    (-w $config{DOCUDIR} ) or die "Can't write in $config{DOCUDIR}\n";

    ### Table layout: [0]=<TABLE...>, [1]=left Cell, [2] = right cell
    @htmlTable = split /\n/, $config{TABLELAYOUT};

    ### All directorys in @DIRLIST
    while ( @DIRLIST ) {
        ### Get names of all subdirs in current directory (except from "." and "..")
        $appsdirname = shift @DIRLIST;
        next if ($appsdirname eq "");
        if ($verbose >= 1) {print "Examine $appsdirname\n"; }

        opendir(DIR, $appsdirname);
        @subdirs = grep(!/^\.\.?$/, readdir(DIR));
        closedir(DIR);

        ### Calculate path to corresponding man-pages (will later be completed with the man section)
        $manpath = dirname($appsdirname) . "/man" ;

        ### Loop: alle subdirs
        SUBDIR: while ( @subdirs ) {
            $subdirname = shift @subdirs;
     
            ### Is it really a directory?
            (-d "$appsdirname/$subdirname") or next SUBDIR;

            ### who owns that subdir?
            $owner = (getpwuid( (stat("$appsdirname/$subdirname"))[4] ))[0];
 
            $infoLDV = "$appsdirname/$subdirname/INFO.LDV";

            ### Is there a lock on this directory?
            if (-r "${infoLDV}-not.here") { next SUBDIR; }

            ### Is there an INFO.LDV?
            if (! -r "$infoLDV") {
                print "No INFO.LDV in $appsdirname/$subdirname ($owner)\n";
                next SUBDIR;
            }

            ### Name of the hdocu file; files from pubdir are named differently
            $outfile = "$subdirname.html";
            if (grep /^$appsdirname$/, @PUBDIR) { $outfile = "pub_$outfile"; }
 
            ### Read INFO.LDV
            parse ( "$infoLDV", \%content );
            if ( lc($config{OLDSTYLE}) eq "true" ) { convertOldstyle(\%content); }
          
            if ( defined($opt_check) && $opt_check ) { checkIfExist($infoLDV, $owner, $manpath) }

            if ($opt_make) {
                ### Generate links to the manpages
                makeLinksToMan ();

                ### Link to whoever claims responslible
                makeLinksToOwner ();

                ### Add this file and its binaries, headers etc. to the proper index arrays
                addToIndexArrays ($outfile);

                ### Link Keywords to keyword list
                makeLinksToKeywordList ();

                ### Some listings should use line-breaks...
                $content{BIN} =~ s/\n/<BR>\n/g ;
                $content{LIB} =~ s/\n/<BR>\n/g ;
                $content{INC} =~ s/\n/<BR>\n/g ;
          
                ### Write the resulting HTML page to disc
                if ( lc($config{USETABLE}) eq "true" ) {
                    writeHdocuFile( $appsdirname, $outfile, $tml{hdocu_table} );
                } else {
                    writeHdocuFile( $appsdirname, $outfile, $tml{hdocu_notable} );
                }
            }
        }
    }

    if ($opt_make) {
        ### Generate the Index Files
        if ($verbose >= 1) {print "Creating Indices...\n"; }

        ### Indices and separators inside an index file
        ### Note the separator-mark "  ^-^"
        $indexAlpha = "";
        @separator = "";
        for $i (1, (A..Z)) {
        $indexAlpha .= "<A HREF=\"#$i\">$i</A>\n";
            push (@separator, "$i  ^-^\n" );
        }
        chomp $indexAlpha;

        $body = join "", sort {
            substr(lc($a),index($a,">")+1) cmp substr(lc($b),index($b,">")+1)
        } (@PktsHtml, @separator);
        writeIndexFile( "packet_index.html", $config{APPSTITLE}, \$body, \$indexAlpha);

        $body = join "", sort {lc($a) cmp lc($b)} (@KeysHtml, @separator);
        writeIndexFile( "key_index.html", $config{KEYSTITLE}, \$body, \$indexAlpha);

        $body = sortWithSeparator( \@BinsHtml, \$index );
        writeIndexFile( "bin_index.html", $config{BINSTITLE}, \$body, \$index);

        $body = sortWithSeparator( \@LibsHtml, \$index );
        writeIndexFile( "lib_index.html", $config{LIBSTITLE}, \$body, \$index);

        $body = sortWithSeparator( \@IncsHtml, \$index );
        writeIndexFile( "include_index.html", $config{INCSTITLE}, \$body, \$index);

        ### Sort the what's new index -- this is somehow awkward :-(
        ### The main sorting key should be the age, but eqal ages should sort alphabetically
        ### Lines look different whether we use tables or not
        if (lc($config{USETABLE}) eq "true") {
            ### Line starts with $htmlTable[1], followed by the age
            ### Name is preceeded by a link
            $body = join "", sort {
                (split(/<TD[^>]*>/, $a))[1] <=> (split(/<TD[^>]*>/, $b))[1]
                    or
                lc((split(/<A HREF[^>]*>/, $a))[1]) cmp lc((split(/<A HREF[^>]*>/, $b))[1])
            } @NewHtml;
        } else {
            ### Line starts with some whitespace, followed by the age
            ### Name is preceeded by a link
            $body = join "", sort {
                (split(/ +/, $a))[1] <=> (split(/ +/, $b))[1]
                    or
                lc((split(/<A HREF[^>]*>/, $a))[1]) cmp lc((split(/<A HREF[^>]*>/, $b))[1])
            } @NewHtml;
        }
        writeWhatsnewFile( "whats_new.html", $config{WHATSNEWTITLE}, \$body);
    }
}

### Sort pathArray, extract unique pathnames and add separators
### sortWithSeparator( Reference to array of filenames, Reference to index )
### index will become HTML code whose elements are pointing to separators
sub sortWithSeparator {
    my ($pathArray, $index) = @_ ;
    my ($pathWithComment, %pathHash, @indexArray) ;
    my ($path, $comment, $realPath, $dir) ;

    ### Make unique Pathnames: extract pathname from every file in list and take
    ###     it as a key for a dummy hashtable => equal pathnames will be overwritten.
    ### Proper sorting is achieved through special marks "  ^^" and "  ^-^"
    ###     where "  ^^" sorts before "  ^-^" and this marks separators
    %pathHash = "";
    @indexArray = "";
    foreach $pathWithComment (@$pathArray) {
        $comment="";
        ($path, $comment) = split( /\s/, $pathWithComment, 2 );
        $realPath=realpath($path);
        $dir=dirname($realPath) ;
        $pathHash{$dir}=1;
        ### insert end-of-path-marker "  ^^" to enable proper sorting
        substr( $realPath, length($dir), 0) = "  ^^" ;
        ### change element in pathArray
        $pathWithComment = "$realPath $comment";
    }
    foreach $path (keys %pathHash) {
        push @indexArray, "<A HREF=\"#$path\">[$path]</A>\n";
        ### Add seperator with separator-marker "  ^-^" (sorting, further processing)
        push @$pathArray, "$path  ^-^\n";
    }
    $$index = join "", sort @indexArray;
    return( join "", sort @$pathArray );
}

### Create an index file
### writeIndexFile(filename, title, reference to body, reference to html index text)
sub writeIndexFile {
    my ($filename, $title, $body, $index) = @_ ;

    open (OUTFILE, ">$config{DOCUDIR}/$filename") or 
        print "Couldn't write $config{DOCUDIR}/$filename", return;

    ### Every separator ends with "  ^-^"
    if ( lc($config{USETABLE}) eq "true" ) {
        ### remove both the path and the end-of-path-marker
        $$body =~ s:^.*  \^\^/::mg;
        ### force linebreaks: no more <pre>
        $$body =~ s:\n:<BR>\n:mg ;
        ### separators: add Anchor, remove <BR>, put in left column
        $$body =~ s:^(.*)  \^-\^<BR>:<TR VALIGN=TOP>\n$htmlTable[1]<A NAME=$1>$1</A></TD>\n$htmlTable[2]:mg ;
        ### table...
        $$body = $htmlTable[0] . $$body . "</TABLE>";
    } else {
        ### remove the end-of-path-marker
        $$body =~ s:  \^\^::g;
        ### separators: format and add Anchor
        $$body =~ s:^(.*)  \^-\^$:</PRE><H2><A NAME=$1>$1</A></H2><PRE>:mg ;
        $$body = "<PRE>\n" . $$body . "</PRE>";
    }

    $output = $tml{"index"};
    $output =~ s/_LOCALINDEX_/$$index/g;
    $output =~ s/_NAME_/$title/g;
    $output =~ s/_TIME_/$time/g;
    $output =~ s/_BODY_/$$body/g;

    print OUTFILE "$output";
    close OUTFILE;
}

### Create "what's new" file: writeIndexFile(filename, title,
###     reference to body, reference to html index text)
sub writeWhatsnewFile {
    my ($filename, $title, $body) = @_ ;

    open (OUTFILE, ">$config{DOCUDIR}/$filename") or 
        print "Couldn't write $config{DOCUDIR}/$filename", return;

    if ( lc($config{USETABLE}) eq "true" ) {
        $$body = $htmlTable[0] . $$body . "</TABLE>";
    } else {
        $$body = "<PRE>\n$$body</PRE>";
    }
    $output = $tml{"index"};
    $output =~ s/_LOCALINDEX_/$config{WHATSNEWMESSAGE}/g;
    $output =~ s/_NAME_/$title/g;
    $output =~ s/_TIME_/$time/g;
    $output =~ s/_BODY_/$$body/g;

    print OUTFILE "$output";
    close OUTFILE;
}

### Generate Output: Transform Template using content and config
### writeHdocuFile(appsDirName, outFileName, Template)
sub writeHdocuFile {
    my ($appsdir, $outfile, $output) = @_ ;

    open (OUTFILE, ">$config{DOCUDIR}/$outfile") or
        print "Couldn't write $config{DOCUDIR}/$outfile", return;

    foreach $kind ("NAME", "VERSION", "KEY", "USAGE", "DOCU", "BIN",
        "LIB", "INC", "MAN", "OWNER", "DATE", "SOURCE", "INSTALL")
    {
        $output =~ s/_${kind}_/$content{$kind}/g;
    }
    $output =~ s/_TIME_/$time/g;
        
    ### Additional comment if INFO.LDV was found in a pubdir
    if (grep /^$appsdir$/, @PUBDIR) {
        $output =~ s/_PUBMESSAGE_/$config{PUBMESSAGE}/g;
    } else {
        $output =~ s/_PUBMESSAGE_\n?//g;
    }
    ### Workaround: sometimes users will insert absolute links to 
    ###     images or html-files in the $config{DOCUDIR} file.
    ### Unfortunatly, perl doesn's seem to be able to treat only parts of a regular expression
    ###     case insensitive, so we have to emulate this.
    ### The following expression first matchs any <A HREF=" or <IMG SRC="
    ###     followed by the output directory. This part will remain ($1), the path removed
    ###     thus resulting in a relativized path.
    $output =~ s:(<(((a|A)\s+(HREF|Href|href))|((img|Img|IMG)\s+[^>]*(src|Src|SRC)))\s*=\s*\"?)$config{DOCUDIR}/?:$1:g ;

    print OUTFILE $output;
    close OUTFILE;
}

### Generate links to the manpages: modifies $content{MAN}
### makeLinksToMan( )
sub makeLinksToMan {
    my ($manlinks, $man, $manname, $mansec);

    $manlinks = "";
    foreach $man ( split /\n/, $content{MAN} ) {
        $manname = $man;
        ### Extract real man-name (no whitespaces!)
        $manname =~ s/\s//g;
        ### Man section is everything behind the dot
        $mansec = $manname;
        $mansec =~ s/^.*\./html/;
        ### Append hyperlink to MAN block
        $manlinks .= "<A HREF=\"man/$mansec/$manname.html\">$manname</A>\n";
    }
   chomp $manlinks;
   $content{MAN} = $manlinks;
}

### Generate hyperlinks to the owners: modifies $content{OWNER}
sub makeLinksToOwner {
    my ($ownerlinks, $owner);

    $ownerlinks = "";
    foreach $owner ( split /\n| /, $content{OWNER} ) {
        $owner =~ s/\s//g;
        $ownerlinks .= "<A HREF = \"mailto:$owner\@$config{MAILDOMAIN}\">" .
            (split(/,/, (getpwnam($owner))[6]))[0] . "</A>\n<BR>";
    }
    $ownerlinks =~ s/\n<BR>$//;
    $content{OWNER} = $ownerlinks;
}

### Generate hyperlinks to the owners: modifies $content{KEY}
sub makeLinksToKeywordList {
    my ($keyword, $keywordlinks);

    $keywordlinks = "";
    foreach $keyword ( split /\n/, $content{KEY} ) {
        $keywordlinks .= "[<A HREF = \"key_index.html#" . 
            uc(substr($keyword,0,1)) . "\">$keyword</A>]\n";
    }
    $content{KEY} = $keywordlinks;
}

### Generate index arrays, both plain and HTML encoded.
###     Name of outfile required for links to it.
### addToIndexArrays( outFileName );
sub addToIndexArrays {
    my ($outfile) = @_ ;
    my ($hlA, $hlB, $file );

    ### Link to this page - two parts for sections within HTML-Page
    $hlA = "<A HREF = \"$outfile" ;
    $hlB = "\">$content{NAME} $content{VERSION}</A>\n" ;

    ### make comment emphasised....
    $content{BIN} =~ s:^(.+?)[ \t](.*)$:$1 <EM>$2</EM>:mg;
    $content{LIB} =~ s:^(.+?)[ \t](.*)$:$1 <EM>$2</EM>:mg;
    $content{INC} =~ s:^(.+?)[ \t](.*)$:$1 <EM>$2</EM>:mg;
    ### Index entries: plain and HTML encoded
    push (@PktsHtml, "$hlA$hlB" );
    foreach $file (split /\n/, $content{KEY}) {
        push (@KeysHtml, "$file $hlA" . "#KEY" . $hlB); }
    foreach $file (split /\n/, $content{BIN}) {
        push (@BinsHtml, "$file $hlA" . "#BIN" . $hlB); }
    foreach $file (split /\n/, $content{LIB}) {
        push (@LibsHtml, "$file $hlA" . "#LIB" . $hlB); }
    foreach $file (split /\n/, $content{INC}) {
        push (@IncsHtml, "$file $hlA" . "#INC" . $hlB); }

    ### Add to what's new if modified within WHATSNEWPERIOD
    if( ($age = -M $infoLDV) < $config{WHATSNEWPERIOD}) {
        if ( lc($config{USETABLE}) eq "true" ) {
            push (@NewHtml, "<TR VALIGN=TOP>$htmlTable[1]" . int($age) . "$htmlTable[2]$hlA$hlB");
        } else {
            push (@NewHtml, "  " . sprintf("%2d",int($age)) . "  : $hlA$hlB");
        }
    }

    ### Default-entries for empty sections
    foreach $entry (KEY, USAGE, DOCU, BIN, LIB, INC,
        MAN, OWNER, DATE, SOURCE, INSTALL)
    {
        if ($content{$entry} eq "") { $content{$entry} = $default{$entry}; }
    }
}

###---------------###
### CHECK ENGINE ###
###---------------###

### check if all files are documented
sub mainCheckEngine {
    if ($verbose>=1) { print "Check if all files are documented\n"; }

    foreach $kind ("BIN", "LIB", "INC") {
        if ($verbose>=1) { print "Check $kind\n"; }

        ### Files that don't have to be documented are treated as if they were documented
        foreach $_ (split ("\n", $config{"NOCHECK$kind"})) { push (@{$kind}, $_); }

        ### Examine all dirs
        foreach $dir (split ("\n", $config{"CHECK$kind"})) {
            if ($verbose>=2) {print "Examine $dir\n";}

            ### Examine all files
            opendir( DIR, $dir );
            while ($file = readdir(DIR)) {
                next if ($file =~ /^\.\.?$/);
                $file = "$dir/$file";
                $filematch = quotemeta("$file");

                ### how often is it documented?
                $matches = grep( /^$filematch$/, @{$kind} );
                if ($matches == 1) {
                    ### remove from documented files list:
                    @{$kind} = grep( !/^$filematch$/, @${kind} );
                } else {
                    $owner = (getpwuid( (stat($file))[4] ))[0];
                    ### documented to often?
                    if ($matches > 1)  { print "$kind: $file documented $matches times ($owner)\n"; }
                    else { print "$kind: $file undocumented ($owner)\n"; }
                }
            }
            closedir (DIR);
        }
    }

    ### MAN is different: here we have one more level of directories!
    if ( ! (defined($opt_nocheckman) && $opt_nocheckman) ) {
        if ($verbose>=1) { print "Check MAN\n"; }
        foreach $mandir (@MANDIR) {
            if ($verbose>=2) {print "Examine $mandir\n";}

            opendir( MANDIR, $mandir );
            while ($dir = readdir(MANDIR)) {
                next if ($dir =~  /^\.\.?$/);
                next if ($dir !~  /^man/);
                if ($verbose>=2) {print "Examine $mandir/$dir\n";}

                opendir( DIR, "$mandir/$dir" );
                while ($file = readdir(DIR)) {
                    next if ($file =~ /^\.\.?$/);
                    $file = "$mandir/$dir/$file";
                    $filematch = quotemeta("$file");

                    ### how often is it documented?
                    $matches = grep( /^$filematch$/, @MAN );
                    if ($matches == 1) {
                        ### remove from documented files list:
                        @MAN = grep( !/^$filematch$/, @MAN );
                    } else {
                        $owner = (getpwuid( (stat($file))[4] ))[0];
                        ### documented to often?
                        if ($matches > 1)  { print "MAN: $file documented $matches times ($owner)\n"; }
                        else { print "MAN: $file undocumented ($owner)\n"; }
                    }
                }
                closedir (DIR);
            }
            closedir (MANDIR);
        }
    }
}

### Check if all referenced files really exist and remember them for further checks
sub checkIfExist {
    my ($infoLDV, $owner, $manpath) = @_ ;
    my ($file, $manname, $mansec);

    foreach $kind ("BIN", "LIB", "INC") {
        foreach $_ (split /\n/, $content{$kind}) {
            $file = realpath($_);
            if (! -e $file) {
                print "$kind in $infoLDV: $file does not exist ($owner)\n";
            } elsif( ($KIND eq "BIN") && (! -x $file) ) {
                print "$kind in $infoLDV: $file is not executable ($owner)\n";
            } else {
                push (@{$kind}, $file);
            }
        }
    }
    foreach $_ (split /\n/, $content{MAN} ) {
        $manname = $_;
        ### Extract real man-name (no whitespaces!)
        $manname =~ s/\s//g;
        ### Man section is everything behind the dot
        $mansec = $manname;
        $mansec =~ s/^.*\./man/;
        $file = "$manpath/$mansec/$manname";
	if (-r $file) {
	    push (@MAN, $file);
	} elsif (! -e $file) {
	    print "MANPAGES in $infoLDV: $file does not exist ($owner)\n";
	} else {
	    print "MANPAGES in $infoLDV: $file is not readable ($owner)\n";
	}
    }
}

###------------###
### MAN ENGINE ###
###------------###

sub mainManEngine {
    if ( ! -d "$config{DOCUDIR}/man" ) {
        print "Create $config{DOCUDIR}/man\n";
        ### Note that perl respects the umask
        mkdir( "$config{DOCUDIR}/man", 0777 );
    }
    if( ! -w "$config{DOCUDIR}/man" ) {
        print "Can't write in $config{DOCUDIR}/man\n";
        return;
    }

    foreach $mandir (@MANDIR) {
        if ($verbose>=2) {print "Convert $mandir\n";}

        opendir( MANDIR, $mandir );
        while ($subdir = readdir(MANDIR)) {
            next if ($subdir =~ /^\.\.?$/);
            next if ($subdir !~ /^man/);
            $sectiondir = "$mandir/$subdir";
            if ($verbose>=2) {print "Convert $sectiondir\n";}

            ### Calculate the Section Name
            $mansection = $subdir;
            $mansection =~ s/man//;

            ### Does this directory contain compressed files?
            ### This would be HP-UX Style!!!
            if ( $mansection =~ m:\.Z$: ) {
                $compressed = 1;
                ### remove .Z from section name
                $mansection =~ s:\.Z$:: ;
            } else {
                $compressed = 0;
            }

            ### useful section?
            if ( $mansection !~ /^\w/ ) {
                print "No man-dir: $sectiondir\n";
                next;
            }

            ### does the HTML dir exist?
            $htmldir = "$config{DOCUDIR}/man/html$mansection";
            if( ! -d "$htmldir" ) {
                ### Note that perl respects the umask
                if( mkdir( "$htmldir", 0777) ) {
                    print "Create $htmldir \n";
                } else {
                    print "Can't create $htmldir\n";
                    next;
                }
            }
            if( ! -w "$htmldir") {
                print "Can't write in $htmldir\n";
                next;
            }

            opendir( DIR, "$sectiondir" );
            while ($file = readdir(DIR)) {
                next if ($file =~ /^\.\.?$/);
                
                $man = "$sectiondir/$file";
                $html = "$htmldir/${file}.html";

                ### Check version based on age
                ### oder wenn man-page aktueller
                next if ( (-e "$html") && (-M "$man" > -M "$html") );
                next if (! -r "$man");

                ### Generate output
                print "Create $html\n";
                $output = $tml{man};
                $output =~ s/_NAME_/$file/g;
                $output =~ s/_TIME_/$time/g;
                ($out1, $out2) = split ("_BODY_", $output);

                if( $opt_rman ) {
                    if( $compressed ) {
                        open( MAN, "cat $man | uncompress | $rman |" ) or die "Can't fork: $!\n";
                    } else {
                        open( MAN, "cat  $man | $rman |" ) or die "Can't fork: $!\n";
                    }
                    open(HTML, ">$html");

                    print HTML "$out1\n";
                    ### insert converted man-page:
                    ### skip header
                    while( <MAN> !~ m:<BODY>:i ) {} ;
                    while( ($line = <MAN>) !~ m:</BODY>:i ) {
                        print HTML $line;
                    }
                    print HTML "$out2";
                    close(HTML);
                    close(MAN);
                }
                else
                {
                    if( $compressed ) {
                        open( MAN, "cat $man | uncompress | $manfilter |" ) or die "Can't fork: $!\n";
                    } else {
                        open( MAN, "cat  $man | $manfilter |" ) or die "Can't fork: $!\n";
                    }
                    open(HTML, ">$html");

                    print HTML "$out1<PRE>\n";
                    ### scan each line of converted man-file 
                    while( $line = <MAN>) {
                        print HTML manlinks( man2html($line), $sectiondir );
                    }
                    print HTML "</PRE>\n$out2";
                    close(HTML);
                    close(MAN);
                }
            }
        }
    }
}

### Insert man-links in given line
### manlinks( line, sectiondir )
sub manlinks {
    my( $line, $sectiondir ) = @_ ;
    my( $work, $reference, $noformat, $pre, $post );

    $work = $line;
    $line = "";

    ### Search for first candidate
    ### Format: wort boundary `\b'   -> start after a whitespace
    ###         remember `('         -> remember thsi group in $1
    ###         word `[a-zA-Z\-_]+'  -> name of a man-page (allowed characters)
    ###         HTML `(<\/?\w+>)*'   -> there might be HTML-tags like <B> or </B>
    ###         paranteses `\('      -> in front of a section number
    ###         word `\w+'           -> section number
    ###         parantheses `\)'     -> right after a section number
    ###         remember `)'         -> thus far $1
    ### break if nothing fits the pattern

    while( $work =~ /\b([a-zA-Z\-_]+(<\/?\w+>)*\(\w+\))/ ) {
        ### Remember reference
        $reference = $1;

        ### Is there a HTML Tag
        if ($2) {
            ### rebuild $reference
            ### HTML-Tag might be in front of, included in or after the reference
            $work =~ /((<\w+>)*[a-zA-Z\-_]+(<\/?\w+>)*\(\w+\)(<\/?\w+>)*)/;
            $reference = $1;
        }

        ### Remove HTML-Tag
        $noformat = $reference;
        $noformat =~ s/(<\/?\w+>)//g;

        ### Get manpage=$1 and section=$2:
        $noformat =~ /^([a-zA-Z\-_]+)\((\w+)\)/;

        ### generate Link if we can find a real manpage
        if( (-r "$sectiondir/../man$2/$1.$2") || (-r "$sectiondir/../man$2.Z/$1.$2") ) {
            $link = "<A HREF=\"../html$2/$1.$2.html\">$reference</A>";
        } else {
            $link = $reference;
        }

        ### mask and split reference
        $reference = quotemeta($reference);  # =~ s/(\W)/\\$1/g;
        ($pre, $post) = split(/$reference/,$work,2);

        $work = $post;
        $line = "$line$pre$link";
    }
    return "$line$work";
}

### convert given line of filtered manpage in HTML
### man2html( line )
sub man2html {
    my( $line ) = @_ ;
    my( $f_bold, $f_italic, $index, $c_bold, $c_italic );
    my( @In, @Out, @Format );

    ### Values of format-field
    $f_bold=1;
    $f_italic=2;

    ### Split line into single chars
    @In = split(//, $line);
    $line="";
    ### First stage: get format of chars
    @Out = ();
    @Format = ();

    for ($index=0; $index < @In; $index++) {
        ### No backspace -> regular char
        if ($In[$index] ne "\b") {
            push( @Out, $In[$index] );
            push( @Format, 0);
        }
        ### Now we have a backspace:
        ### Bold (twice the same char)
        elsif ($In[$index-1] eq $In[$index+1]) {
            $Format[$#Format] |= $f_bold;
            $index++;
        }
        ### Italic (preceeded by an underline)
        elsif ($In[$index-1] eq "_") {
            ### Use the second character
            splice( @Out, $#Out, 1, $In[$index+1] );
            ### Do not make "|" italic as it is used to represent tables
            if ($In[$index+1] ne "|") { $Format[$#Format] |= $f_italic; };
            $index++;
        }
        ### Italic (followed by an underline)
        elsif ($In[$index+1] eq "_") {
            if ($In[$index-1] ne "|") { $Format[$#Format] |= $f_italic; };
            $index++;
        }
        ### Some special pairs
        else {
            $pair = $In[$index-1] . $In[$index+1];
            ### Replace with +
            if (($pair eq "|-")||($pair eq "-|")||
                ($pair eq "|+")||($pair eq "+|")||
                ($pair eq "-+")||($pair eq "+-"))
            {
                splice( @Out, $#Out, 1, "+" );
                $index++;
            }
            ### Replace with *
            elsif (($pair eq "|=")||($pair eq "=|")||
                   ($pair eq "|*")||($pair eq "*|")||
                   ($pair eq "=*")||($pair eq "*="))
            {
                splice( @Out, $#Out, 1, "*" );
                $index++;
            }
            ### Replace with bold-o
            elsif (($pair eq "+o")||($pair eq "o+")) {
                splice( @Out, $#Out, 1, "o" );
                $Format[$#Format] |= $f_bold;
                $index++;
            }
            else {
                if ($verbose >= 1) {print "Unknown pair of characters: $pair\n"; }
            }
        }
    }

    ### Second stage: HTML-Tags
    ### "c_" is Context, "Value" is Level of nestet tags
    $c_bold = 0;
    $c_italic = 0;

    for ($index=0; $index < @Out; $index++) {
        if( $Format[$index] != $Format[$index-1] ) {
            ### End of italic inside of bold
            if ( ($c_italic > $c_bold ) && (! ($Format[$index] & $f_italic) ) ) {
                  ### Add HTML Tag
                  $line .= "</I>";
                  ### Remove format
                  $Format[$index] &= $f_bold;
                  $c_italic=0;
            };
            ### End of bold
            if ( $c_bold && (! ($Format[$index] & $f_bold)) ) {
                $line .= "</B>";
                $c_bold=0;
            };
            ### End of italic
            if ( $c_italic && (! ($Format[$index] & $f_italic)) ) {
                $line .= "</I>";
                $c_italic=0;
            };
            ### Beginning of bold
            if ( (!$c_bold) && ($Format[$index] & $f_bold) ) {
                $line .= "<B>";
                $c_bold=$c_italic+1;
            };
            # Beginning of italic
            if ( (!$c_italic) && ($Format[$index] & $f_italic) ) {
                $line .= "<I>";
                $c_italic=$c_bold+1;
            };
        }

        ### Some characters which are special to HTML
        if    ($Out[$index] eq "<") { $line .= "&lt;" }
        elsif ($Out[$index] eq ">") { $line .= "&gt;" }
        elsif ($Out[$index] eq "&") { $line .= "&amp;" }
        else  { $line .= $Out[$index]; }
    }
    return $line;
}


###-----------------###
### MISC. FUNCTIONS ###
###-----------------###

### Parse a file: parse(filename, reference to hashtable)
### Example: parse( "/this/file", \%hashtable );
sub parse {
    local ($filename, $result) = @_ ;

    (-r $filename ) or die "Could not open $filename\n";
    if ($verbose >= 3) {print "Parsing $filename\n"; }
    my $section = "NONE";
    %$result = "";

    open(FILE, "<$filename") or die "Could not open $filename";
    LINE: while(<FILE>) {
    	# Handle MS etc. end-of-line-marker (just remove carriage return)
    	$_ =~ s:\r+::;
        (/^\s*$/ || /^#.*/)	and do { next LINE; }; ###Comment or empty Line
        (/^_(\w+)/)		and do { $section = $1; $$result{$section} = ""; next LINE; }; ### New Section
        $$result{$section} .= $_;
    }
    close(FILE);

    ### Remove trailing newline from all sections
    ### Multi-line sections will still be separated by newlines!
    foreach $section (keys %$result) { chomp $$result{$section} };
}

### Calculate the real path from filename
### We can't use glob() as this function is called with non-existant files!
sub realpath {
    my ($path) = @_ ;
    my ($user, $home);

    ### remove trailing stuff: everything beyond the first whitespace
    ### and, if the filename ends with "/", delete this char as well
    $path =~ s:^(\S*).*:$1: ;
    $path =~ s:/$:: ;

    ### Is there a "~" ?
    if( $path =~ /^\~/ ) {
        ### get username after "~"
        $path =~ m:^\~(\w*)/:;
	$user = $1;
	### no user named -> current uid "$<"
	if( $user eq "" ) {
	    $home = (getpwuid($<))[7];
	} else {
	    $home = (getpwnam($user))[7];
	}
	### replace "~" with homedir
	$path =~ s:^\~(\w*)/:$home/: ;
    }
    return $path;
}

sub convertOldstyle {
    my ($content) = @_;

    ### You shouldn't mix old and new style in one file,
    ###     but you can use both styles in different files.
    ###     So we have to guess wich one is used:
    if ( defined $$content{PAKETNAME} || defined $$content{LOKALE_DOKU} )
    {
        $$content{NAME} = "$$content{PAKETNAME}";
        # VERSION
        $$content{KEY} = "$$content{KEYWORDS}";
        $$content{USAGE} = "$$content{LOKALE_DOKU}";
        $$content{DOCU} = "$$content{DOKU}";
        $$content{BIN} = "$$content{BINARIES}";
        # LIB
        $$content{INC} = "$$content{INCLUDE}";
        # MAN
        $$content{OWNER} = "$$content{BETREUER}";
        $$content{DATE} = "$$content{DATUM}";
        $$content{SOURCE} = "$$content{DISTRIBUTION}";
        $$content{INSTALL} = "$$content{INSTALLATIONSHINWEISE}";
    }
}

### Read the template files into the tml array
sub readTemplates {
    %tml = "";
    foreach $kind ("hdocu_table", "hdocu_notable", "index", "man") {
        $file = "$HdLibDir/${kind}.tml" ;
        (-f $file) or die "$file does not exist";
        open (TML, "<$file") or die "Could't open $file";
        $tml{$kind} = "" ;
        while (<TML>) { $tml{$kind} .= $_ ; } ;
        close TML;
    }
}
