#!/usr/bin/perl

# my state is a message (from last time) and an amount (due) 

use CGI; 

$q = new CGI; 

print $q->header, $q->start_html; # I can print for debugging

# retrieve state 

$message = $q->param('message'); 
$amount  = $q->param('amount'); 

if ($message) { # existing user 

  $line = $q->param('line'); 

  $message = "I know you. "; 

  # update state 

  @tokens = split(' ', $line); 

  foreach $token (@tokens) { 
    # print $token, "<p>"; 
    if ($token eq "dime") {
      $amount -= 10; 
    } elsif ($token eq "dollar") {
      $amount -= 100; 
    } 
  } 

  if ($amount > 0) {
    $message = "I need $amount more.";  
  } else {
    $message = "Change: " . - $amount . "cents. <p>"; # and reinitialize 
    $message .= "Welcome. We sell stamps. 370 cents per book."; $amount = 370; 
  } 
} else { # new user 
  $message = "Welcome. We sell stamps. 370 cents per book."; $amount = 370; 
}
# save and report state are basically almost the same 
print qq{<form action="}, $ENV{SCRIPT_NAME}, qq{">
  $message <p> 
  Please enter the coins: <input type="text" name="line"> <p> 
  When finished please press <input type="submit" value="Proceed"> 
  <input type="hidden" name="amount" value="$amount"> 
  <input type="hidden" name="message" value="$message "> 
</form>}, $q->end_html;