#!/local/bin/perl -w

$html      = 1;
$sec       = 1;
$duplicate = 0;

while ($_ = $ARGV[0], /^-/) {
    shift;
    last if /^--$/;
    if (/^-man/)   { $html      = 0;  }
    if (/^-s(.+)/) { $sec       = $1; }
    if (/^-dup/)   { $duplicate = 1;  }
}
				# 
while (<>) {
    @Line = split;

    $i = 0;
    while (($word = $Line[$i]) !~ /\([135]\)/) {
	$last = $i;
	$i++;
    }

    $i = 0;
    if ($html == 1) {
	while (($word = $Line[$i]) !~ /\([135]\)/) {
	    if ($i > 0) {
	        ($command = $Line[0]) =~ s/(.+),/$1/;
		$word =~ s/(.+),/$1/;    # Remove trailing ','.

		if ($duplicate == 0) {
		    $item = "$word" .
			"    See <a href=\"${command}_$sec.html\">" .
			"$command</a>\n";
		} else {
		    $item = "$word <a href=\"${command}_$sec.html\">$word</a>"
			. "    @Line[$last+3..$#Line]\n";
		}
	    } else {
		$word =~ s/(.+),/$1/;    # Remove trailing ','.
		$item = "$word <a href=\"${word}_$sec.html\">$word</a>" .
		    "    @Line[$last+3..$#Line]\n";
	    }
	    push(@output, "$item\n");
	    $i++;
	}
    } else {
	while (($word = $Line[$i]) !~ /\([135]\)/) {
	    $buf = "";
	    $word =~ s/(.+),/$1/;    # Remove trailing ','.
	    $buf = $buf . "$word $Line[$last+1]";  # (1), (3) or (5)
	    $blanks = ' ' x (20 - length($word));
	    $buf = $buf . $blanks;

	    for ($wordNum = $last + 2; $wordNum <= $#Line; $wordNum++) {
		$buf = $buf . " $Line[$wordNum]";
	    }

	    push(@output, "$buf\n");
	    $i++;
	}
    }
}				# while

@sorted = sort @output;

if ($html == 1) {
    print STDOUT @sorted;
} else {
    print STDERR "$#sorted\n";

    @output    = ();
    $num_lines = $#sorted;
    $line_num  = 0;
    while ($line_num <= $num_lines) {

	$Line = shift @sorted;
	@Line = split(' ', $Line);

	$buf = join(' ', @Line[0..1]);
	$buf = $buf . ' ' x (20 - length($Line[0]));
	for ($wordNum = 2; $wordNum <= $#Line; $wordNum++) {
	    if (length($buf) + length($Line[$wordNum]) < 80) {
		$buf = $buf . " $Line[$wordNum]";
	    }
	    else {
		push(@output, "$buf\n");

		$buf = ' ' x 26;
		$buf = $buf . " $Line[$wordNum]";
	    }
	}

	push(@output, "$buf\n");
	$line_num++;
    }

    print STDOUT @output;
}
