#-*- mode: perl; perl-indent-level: 4; cperl-indent-level: 4 -*-

use File::Basename;
fileparse_set_fstype; # Unix, in case one gets anything else.

$ARGV[0] =~ /([^\/]*)$/;
my $pkg = $1;

open OUTFILE,">$ARGV[1]" || die "Couldn't open CONTENTS file";

while(<$ARGV[0]/man/*.Rd>){ &do_one; }
if(-d  "$ARGV[0]/man/unix") {
    while(<$ARGV[0]/man/windows/*.Rd>){ &do_one; }
}

sub do_one {
    my $file = basename($_, (".Rd", ".rd"));

    open(rdfile, "<$_");
    undef $text;

    while(<rdfile>){
	$text .= $_;
    }
    close rdfile;

    $text =~ /\\name\{\s*([^\}]+)\s*\}/s;
    my $rdname = $1;
    $rdname =~ s/\n/ /sg;

    $text =~ /\\title\{\s*([^\}]+)\s*\}/s;
    my $rdtitle = $1;
    $rdtitle =~ s/\n/ /sg;

    undef @aliases;
    while($text =~ s/\\alias\{\s*(.*)\s*\}//){
	$alias = $1;
	$alias =~ s/\\%/%/g;
	push @aliases, $alias;
    }

    undef @keywords;
    while($text =~ s/\\keyword\{\s*(.*)\s*\}//){
	$keyword = $1;
	$keyword =~ s/\\%/%/g;
	push @keywords, $keyword;
    }

    $, = " ";
    print OUTFILE "Entry: $rdname\n";
    print OUTFILE "Aliases: @aliases\n";
    print OUTFILE "Keywords: @keywords\n";
    print OUTFILE "Description: $rdtitle\n";
    print OUTFILE "URL: ../../../library/$pkg/html/$file.html\n\n";
}

