#!/usr/bin/perl -w
#
# mathq program, pg 44 from Johnson's "Elements of Programming with Perl"
#
# The code as it is here contains 
# a compile error, a runtime error, and at least one awkward behavior.
# See the textbook for details.
#
# --- LP (literate programming) pseudo code ---
# 
# <<mathq>>=
# display start up message
# LOOP: until user quits
#   <<generate a question and its solution>>
#   <<display question and get a valid response>>
#   <<test response and display right or wrong>>
# END LOOP
# display exit message
#
# <<generate a question and its solution>>=
# set first_number to 
# set second_number to random integer from 0 to 9
# IF operator is 1 THEN
#   <<create multipliation question and solution>>
# ELSE
#  <<create division question and solution>>
# END IF
#
# and so on
#
# -------------------------------------
#

use strict;
print "Welcome to the mathq program\n";
my $quit = 0;
until ($quit) {
  my $first_number  = int(rand(10));  # range: 0 to 9 inclusive
  my $second_number = int(rand(10));  # range: 0 to 9 inclusive

  # chose random operator codes: 0 is division
  #                              1 is multiplication
  my $operator      = int(rand(2));

  my $solution;
  my $question;
  if ($operator == 1){
    $solution = $first_number * $second_number;
    $question = "$first_number x $second_number = ? ";
  }
  else {
    $solution = $first_number * $second_number;
    ($solution, $first_number) = ($first_number, $solution);
    $question = "$first_number / $second_number = ? ";
  }

  # get valid user response
  my $response;               # this ";" was missing in original.
  my $is_valid = 0;
  until ($is_valid){
    print "$question\n";
    $response = <STDIN>;
    chomp($response);
    #valid input is 'q' or only digits
    if ($response eq 'q' or $response =~ m/^\d+$/){
      $is_valid = 1;
    }
    else {
      print "Invalid input: enter an integer or 'q' to quit\n";
    }
  }

  # test response
  if ($response eq 'q'){
    $quit = 1;
  }
  elsif ($response == $solution){     # OOPS! this is wrong
    print "Correct\n"
  }
  else {
    print "Incorrect: $question $solution\n"
  }

}

print "exiting mathq program\n";
