#!/usr/bin/perl -w

use strict;

sub Dir
{
    my ( $Opts, $Dirs, $DirNum ) = @_[0..2];

    $DirNum >= 0 and defined( $Dirs->[ $DirNum * 2 + 1 ] ) or
        do {Head($Opts); print "Wrong \"$DirNum\", possible attack!\n"; exit; };

    my $Dir = $Dirs->[ $DirNum * 2 + 1 ];
    my $Cont = "";
    my $Row;

    $Opts->{ 'title' } = $Dirs->[ $DirNum * 2];

    my $rh = $Opts->{'raw_head'};

    if( defined( $Opts->{'css'} ) )
    {
        if( ref( $Opts->{'css'} ) ne 'ARRAY' ) 
        { $Opts->{'css'} = [ $Opts->{'css'} ]; }

        foreach my $css ( @{$Opts->{'css'}} )
        {
            $Opts->{'raw_head'} .=
                "<link rel=\"stylesheet\" type=\"text/css\" href=\"$css\">\n";
        }
    }

    Head( $Opts );
    $Opts->{'raw_head'} = $rh;

    print "<body>\n";

    if( -R "${Dir}contents.m" ) { $Cont = "contents"; }
    elsif( -R "${Dir}Contents.m" ) { $Cont = "Contents"; }

    if( $Cont ne "" )
    { printf "<a href = \"" . HrefCont( $Opts, $Cont, $DirNum ) ."\" ".
          "target=\"mdsbody\"><h1>$Opts->{ 'title' }</h1></A>\n"; }
    else { printf "<h1>$Opts->{ 'title' }</h1>\n"; }

    opendir DIR, $Dir;
    my @files = sort( readdir( DIR ) );
    closedir DIR;

    foreach my $f ( @files ) {
        $f =~ /^[cC]ontents.m$/ and next;
        $f =~ /^(\w+.m)$/ and do {
            printf "&nbsp;&nbsp;<a href = \"" . 
                HrefInfo( $Opts, $DirNum, $1 ) . 
                "\" target=\"mdsbody\">$1</a><br>\n";
        }
    }

    if( -d "${Dir}private" )
    {
        opendir DIR, "$Dir/private";
        my @files = sort( readdir( DIR ) );
        closedir DIR;

        printf "<br>\n";

        foreach my $f ( @files ) {
            $f =~ /^(\w+.m)$/ and do {
                printf "<br>&nbsp;&nbsp;<a href = \" ". 
                    HrefInfo( $Opts, $DirNum, "private/$1" ) . 
                        "\" target=\"mdsbody\">private/$1</a>\n";
            }
        }
    }
    
    printf "</body></html>";
}

1;
