#!/usr/bin/perl -w

use strict 'vars';

sub Ord {
  my $chr = shift;
  unpack "C", $chr;
}

my %good_char;
{
  my @good_char = ('-', '.', '_', 0 .. 9, 'A' .. 'Z', 'a' .. 'z');
  for (@good_char) { $good_char{$_} = 1 }
}
my @hex = (0 .. 9, 'a' .. 'f');

my $dir = shift || '.';
opendir D, $dir
  or die "Couldn't open directory $dir: $!; aborting";

my $title = "Table of contents for $dir";

print "<html><head><title>$title</title></head>

<body><h1>$title</h1>
";

for my $f (sort readdir D) {
  my $url = escape_url($f);
  my $html = escape_html($f);
  print "<a href=\"$url\">$html</a><br>\n";
}

print "</body></html>\n\n";

################################################################


sub escape_url {
  my @chars = split //, $_[0];
  my $result = "";
  for (@chars) {
    my $ord = Ord($_);
    if ($good_char{$_}) {
      $result .= $_;
    } else {
      my $h0 = $ord % 16;
      my $h1 = ($ord - $h0) / 16;
      $result .= "%$hex[$h1]$hex[$h0]";
    }
  }
  return $result;
}

sub escape_html {
  my $t = shift;
  $t =~ s/&/&amp;/g;
  $t =~ s/</&lt;/g;
  $t =~ s/>/&gt;/g;
  return $t;
}
