#!/usr/bin/perl -Tw use strict; ## table: write a table or a
 based on browser type

## system stuff
$|++;
$ENV{PATH} = "/usr/ucb:/bin:/usr/bin";

## HTML stuff
print "Content-type: text/html\n\n";

## the main program (in eval so we can trap problems)
eval {

  ## get the CGI data
  my $uri = $ENV{DOCUMENT_URI}; # valid only in SSI
  my $path = $ENV{PATH_INFO};   # stuff after cgi name
  my $agent = $ENV{HTTP_USER_AGENT}; # user agent

  ## validate this as an SSI
  die "missing document_uri" unless $uri;

  ## split the URI up, so we know where the file was
  my ($dir,$file) = $uri =~ m,(.*/)(.*),s;

  ## massage the directory to get the containing dir
  if ($dir =~ m,^/~(\w+)/(.*)$,s) {
    $dir = "/home/$1/public_html/$2"; # teleport specific
  } else {
    die "cannot translate dir";
  }

  ## go there
  chdir $dir or die "cannot cd to $dir: $!\n";

  ## open sourcefile
  my ($filename) = $path =~ m!^/?([-\w.]+)!;
  $filename .= ".table";        # ensure only "whatever.table"
  die "missing filename in $path" unless $filename and -f $filename;
  open F, $filename or die "cannot open $filename: $!";
  my @max_in_col;
  my @table;
  my $text = $agent =~ /Emacs-W3|Lynx/i; # you may wish to extend this list
  while () {
    chomp;
    my @row = split /\t/;

    if ($text) {
      ## save maximums
      for (0..$#row) {
        my $tmp = $row[$_];
        $tmp =~ s/<.*?>//g;     # don't count HTML markup
        $tmp = length $tmp;
        $max_in_col[$_] = $tmp if $max_in_col[$_] < $tmp;
      }
    }
    push(@table, [@row]);
  }
  if ($text) {
    my $format = join " | ", "", (map "%".(0-$_)."s", @max_in_col), "\n";
    print "
\n";
    for (@table) {
      printf $format, @$_;
    }
    print "
\n"; } else { print "\n"; for (@table) { print ""; print map "", @$_; print "\n"; } print "
$_
\n"; } }; ## if an error, say so: if ($@) { chomp $@; $_ = "[error: $@]"; s/&/&/g; s//>/g; s/\n/
/g; print; }