#!/usr/bin/perl

# The program ex1.pl takes in two arguments from the browser, adds them,
# then prints out the answer.  Simple script to practice Perl.

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

# The following formats the incoming arguments and puts them into the
# vector $FORM with fields x and y

read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $value =~ s/\n/ /g; # replace newlines with spaces
    $FORM{$name} = $value;
}

# $z is simply the sum of $x and $y, the user's input from the web page

$z = $FORM{x} + $FORM{y};

# Print out the HTML document for the user's delight

print <<"EndOfHTML";
<html>
<head>
<title>Math 210 Perl Example 1</title>
</head>
<body>
<center><h2>Output for Example 1</h2>
<p><i>Your input</i>: <b> x = $in{x}, y = $in{y}</b>
<p><i>Answer</i>: </b>x + y = $z</b>
</center>
</body>
</html>
EndOfHTML