#!/usr/bin/perl -Tw

##
# Modified from
#   Figure 27.36 from _Internet & World Wide Web: How To Program_
#   by H.M. Deitel, P.J. Deitel, and T.R. Nieto
#   Published by Prentice Hall, (c) 2000 by Prentice-Hall, Inc.
##
# Fig. 27.36: read_cookies.pl
# Program to read cookies from the client's computer

use CGI qw/:standard/;
use CGI::Carp 'fatalsToBrowser';
use diagnostics;
use strict;
$| = 1;

print header;
print "<BODY BACKGROUND = \"~/image/Back/stars_bg.gif\">";
print "<BASEFONT FACE = \"ARIAL,SANS-SERIF\" SIZE = 3>";
print "<STRONG>The folowing data is saved in a cookie on your ";
print "computer.<STRONG><BR><BR>";

my %cookie = readCookies(); 

print "<TABLE ",
       "BORDER = \"5\" ",
       "CELLSPACING = \"0\" ",
       "CELLPADDING = \"10\">";

my $cookie_name;
foreach $cookie_name (keys %cookie)
{
   print "<TR>";
   print "   <TD BGCOLOR=#AAAAFF>$cookie_name</TD>";
   print "   <TD BGCOLOR=#AAAAAA>$cookie{$cookie_name}</TD>";
   print "</TR>";
}
print "</TABLE>";

print '<p><a href="'.
      'http://www.cs.dal.ca/~jamie/course/CS/4173/examples/perl/cookies/'.
      'cookie-colour.html">[return to the form]</a></p>';

sub readCookies
{
   my @cookie_values;
   my %cookies = (); # initialize to empty list

   @cookie_values = ($ENV{'HTTP_COOKIE'})
       ?split(/; /, $ENV{'HTTP_COOKIE'})
       :();

   foreach (@cookie_values)
   {
      my ($cookie_name, $cookie_value) = split ( /=/, $_ );
      $cookies{$cookie_name} = $cookie_value;
   } 
   
   return %cookies; 
}

