#!/usr/bin/perl

use CGI qw/:standard/;
require ".commonFunctions";

$time = `./date.pl`;

opendir(ARCHIVE, "/com/web/docs/projects/dm/archive");
foreach $file (readdir(ARCHIVE)) {
  my %info = ();
  if ($file =~ /^\d+/) {
    open(INFO, "</com/web/docs/projects/dm/archive/$file/info.txt");
    foreach $line (<INFO>) {
      my ($key, $value) = split(": ", $line, 2);
      chomp($value);
      $info{$key} = $value;
    }
    close(INFO);
    if (!$info{"Deleted on"}) {
      $re = param('search'); 
      if ((!param('search')) ||
	  (($info{"Author(s)"} . $info{"Title"} . $info{"Keywords"}) =~ /$re/i)) {

      push @list, 
      "<!- $info{'Timestamp'} -->"
        . '<font color="red">' 
        . &ParseAuthors($info{"Author(s)"})
        . "</font><br>" 
        . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
        . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
        . '<a href="' 
        . "../cgi-bin/view.cgi?file=$file"
        . '">'
        . $info{"Title"}
        . "</a>"
        . "<br>"
      }    }
  }
}
close(ARCHIVE);

if (param('keywords') eq "sortbyauthor")  {
  @list = sort {substr($a, 23, 80) cmp substr($b, 23, 80)} @list;
} else {
  @list = sort {$b cmp $a} @list;
}

print &makeHeader(-title=>'Browse the DMA'),
    &makeToolbar("browse"),
    '<font face="Helvetica">',
    '<table><tr><td>Papers from</td><td><a href="http://www.ai.mit.edu/projects/dm/archive">DMA</a> as of ', $time, ':</td></tr></table><br><hr>';
if (param('search')) {
  print "Searching for \"", param('search'), "\":<hr>\n";
};
foreach $item (@list) {print "$item\n";}
print '<hr></font></body></html>', "\n";

print end_html;

sub ParseAuthors {
  my @atemp; 
  my @btemp;
  my @names;
  my $first;

  $first = $last = 0;

  @atemp = split/\s*;\s*/, $_[0];
  return $_[0] if($#atemp ==0);

  foreach $str (@atemp) {
    @btemp = split/\s*,\s*/, $str;
    if($first) {
      push @names, "$btemp[1] $btemp[0]";
    } else {
      push @names, $str;
    }
      $first=1;
  }

  $names[$#names]= "and ".$names[$#names];
  return join(" ", @names) if($#names == 1);

  return join(", ", @names);
}
