#!/usr/local/old/bin/perl
#############################################################################
#  
#   File: pizza.pl
#
#   Author:  Paul Coddington
#
#   Input: pizza-form.html
#          CGI input ('QUERY_STRING') 
#          QUERY_STRING: Entries = address; 
#                                  phone; 
#                                  topping: pepperoni, sausage, anchovies.
#
#   Output: HTML version of pizza order.
#
#   Description: Creates a pizza order from the information gained from
#                the pizza order form.
#
#
#############################################################################
#  
#   MAIN FUNCTION
#
#############################################################################

&PrintHeader;
&ReadEntry && 
&PrintResult;


#############################################################################
#  
#   SUBROUTINES
#
#############################################################################


sub ReadEntry {             
   &ReadParse;     # Read arguments passed from fill-out form
   $address = $in{'address'};
   $phone = $in{'phone'};
   $topping = $in{'topping'};
   return 1;
}


sub PrintResult {
  print "<TITLE> Pizza Order </TITLE>";
  print "<h1> Pizza Order </h1>";

  printf "<H3>\n";
  print "$topping pizza\n";
  printf "</H3>\n";

  print "<P>\n";
  print "Deliver to <B>$address</B> \n";
  print "<P>\n";
  print "Telephone <B>$phone</B> \n";
  print "<P>\n";
  $date = `date`;
  print "Order came in at <B>$date</B> \n";
  return 1;
}


##############################################################################
#
#  Get information from fill-out form.
#
##############################################################################


# Returns the magic line which tells WWW that this is an HTML document
sub PrintHeader {
  print "Content-type: text/html\n\n";
  print "\n";
}


# reads the arguments passed from the form
sub ReadParse {
    local ($i, $loc, $key, $val);

    if ($ENV{'REQUEST_METHOD'} eq "GET") {                      # Read in text
       $in = $ENV{'QUERY_STRING'};
    } elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
      for ($i = 0; $i < $ENV{'CONTENT_LENGTH'}; $i++) {
        $in .=getc;
      }
    }

    @in = split(/&/,$in);

    foreach $i (0 .. $#in) {
      $in[$i] =~ s/\+/ /g;                          # Convert plus's to spaces
      $in[$i] =~ s/%(..)/pack("c",hex($1))/ge;
                                # Convert %XX from hex numbers to alphanumeric
      $loc = index($in[$i], "=");                  # Split onto key and value.
      $key = substr($in[$i],0,$loc);
      $val = substr($in[$i],$loc+1);
      $in{$key} .= '\0' if (defined($in{$key})); # \0 is the multiple separator
      $in{$key} .= $val;
   }
   return 1; 
}


