#!/usr/bin/perl

# Print a list of links to the scripts that have been made public.
# Currently this is files whose names end in .sql, .pl or .tsv.
# Bruno Wolff III
# Last updated October 13, 2012

# Turn off space seperators when including arrays in quoted text.
$" = '';

# Use this to clean stuff extracted from the database for html output
sub clean(@) {
  local $str = "@_";
  $str =~ s/&/&amp;/g;
  $str =~ s/</&lt;/g;
  $str =~ s/>/&gt;/g;
  $str =~ s/"/&quot;/g;
  return $str;
}

# Use this to convert REQUEST_URI to unescaped string
sub urldecode(@) {
  local $str = "@_";
  $str =~ s/\%[0-9a-fA-F]{2}/$urldhash{$&}/eg;
  return $str;
}

# Use this to make sure urls don't contain url specials
sub urlencode(@) {
  local $str = "@_";
  $str =~ s/[^-_A-Za-z0-9.$+!*'(),]/$urlehash{$&}/eg;
  return $str;
}

# One time build of data used by url decode
sub urlinit() {
  my $c;
  my $f;
  my $i;
  for ($i=0; $i<=255; $i++) {
    $c = chr($i);
    $f = sprintf('%%%.2X', $i);
    $urldhash{$f} = $c;
    $urldhash{lc($f)} = $c;
    $urlehash{$c} = $f;
  }
}
urlinit;

print << "EOF";
content-type: text/html; charset=UTF-8

<html>
<head>
<title>Scripts used to generate the AREA web pages</title>
</head>
<body>
EOF
{
    local *INPUT;
    if (open(INPUT, "links.html")) {
        print while (<INPUT>);
        close INPUT;
    }
} 
print << "EOF";
<h1>Scripts used to generate the AREA web pages</h1>
EOF

$flag = 0;
if (opendir(DOT, '.')) {
  @dir = readdir(DOT);
  foreach $name (sort @dir) {
    next if $name !~ m/\.(sql|pl|tsv)$/;
    $link = clean(urlencode($name));
    $name = clean($name);
    print "<ul>\n" if $flag == 0;
    print "<li><a href=\"$link\">$name</a>\n";
    $flag = 1;
  }
}
if ($flag == 0) {
  print "No scripts are available at this time.\n";
}
else {
  print "</ul>\n";
}

print << "EOF";
EOF
{
    local *INPUT;
    if (open(INPUT, "links.html")) {
        print while (<INPUT>);
        close INPUT;
    }
} 
{
    local *INPUT;
    if (open(INPUT, "sig.html")) {
        print while (<INPUT>);
        close INPUT;
    }
} 
print << "EOF";
</body>
</html>
EOF
