#!/usr/bin/perl
print "Content-type:text/html\n\n";

open(INF,"survey.out") or dienice("Couldn't open survey.out for reading: $! \n");

@data = <INF>;
close(INF);

# First we initialize some counters and hashes for storing the
# summarized data.
$count = 0;
$ratings = 0;
$commentary = "";
%howreach_counts = ();
%involved = ();

%howreach = (0 => "",
             1 => "Typed the URL directly",
             2 => "Site is bookmarked",
             3 => "A search engine",
             4 => "A link from another site",
             5 => "From a book",
             6 => "Other" );

foreach $i (@data) {
   chomp($i);
   ($name,$email,$how,$rating,$boxes,$comments) = split(/\|/,$i);

   # this is the same as $count = $count + 1;
   $count++;

   $ratings = $ratings + $rating;

   # since some wisecrackers think it's cute to add html tags to their
   # comments, we're ripping them out here.
   $comments =~ s/</&lt;/g;
   $comments =~ s/>/&gt;/g;

   # the following appends "$comments\n" to the end of the $commentary
   # string. The .= construct is just a way to concatenate strings.
   # we only want to do this if the $comments are not blank...
   if ($comments ne "") {
       $commentary .= "$comments<p><hr>\n"; 
   }

   $howreach_counts{$how}++;

   @invlist = split(/,/,$boxes);
   foreach $j (@invlist) {
      $involved{$j}++;
   }
}

if ($count > 0) {		# don't divide by zero!
    $avg_rating = int($ratings / $count);
} else {
    $avg_rating = 0;
}

 
# Now we can print out a web page summarizing the data.
print <<EndHTML;
<html><head><title>Survey Results</title></head>
<body>
<h2 align="CENTER">Survey Results</h2>

Total visitors: $count<p>

Average rating for this site: $avg_rating<p>

How people reached this site:<br>
<ul>
   <li>(did not answer) - $howreach_counts{0}
   <li>$howreach{1} - $howreach_counts{1}
   <li>$howreach{2} - $howreach_counts{2}
   <li>$howreach{3} - $howreach_counts{3}
   <li>$howreach{4} - $howreach_counts{4}
   <li>$howreach{5} - $howreach_counts{5}
   <li>$howreach{6} - $howreach_counts{6}
</ul>

Involvement in <br>
<ul>
   <li>Website Design: $involved{'des'}
   <li>Web Server Administration: $involved{'svr'}
   <li>Electronic Commerce: $involved{'com'}
   <li>Web Marketing/Advertising: $involved{'mkt'}
   <li>Web-related Education: $involved{'edu'}
</ul><p>

Comments:<p>
$commentary
EndHTML

sub dienice {
   my($msg) = @_;
   print "<h2>Error</h2>\n";
   print $msg;
   exit;
}