#!/usr/bin/perl

$|=1;

$cupcost = 3;			# 100 cups
$sugarcost = 4;			# 5 lbs sugar
$juicecost = 3;			# 1 quart lemon juice

$money = 10.01;
$cups = 0;
$sugar = 0;
$lemonjuice = 0;
$pitcher = 0;
$sfrac = 0;
$jfrac = 0;
$spitcher = .25;
$jpitcher = .15;
$temp = 85;
$dct = 0;

while(1){
    print "Lemondade Stand> ";
    $cmd = (<STDIN>);
    chop($cmd);
    if(($cmd eq "cups")||
       ($cmd eq "c")){
	if($money > $cupcost){
	    $money -= $cupcost;
	    $cups += 100;
	    print "Bought 100 cups\n";
	}
	else{
	    print "Not enough money\n";
	}
    }
    elsif(($cmd eq "sugar") ||
	  ($cmd eq "s")){
	if($money > $sugarcost){
	    $money-=$sugarcost;
	    $sugar+=5;
	    print "Bought 5 lbs. sugar\n";
	}
	else{
	    print "Not enough money\n";
	}
    }
    elsif(($cmd eq "juice") ||
	  ($cmd eq "j")){
	if($money > $juicecost){
	    $money -= $juicecost;
	    $lemonjuice++;
	    print "Bought 1 quart juice\n";
	}
	else{
	    print "Not enough money\n";
	}
    }
    elsif(($cmd eq "status") ||
	  ($cmd eq "x")){
	print "Money: \$$money\n";
	print "Cups: $cups\n";
	print "Sugar: $sugar lbs\n";
	print "Juice: $lemonjuice quarts\n";
	print "Day # $dct\n";
    }
    elsif($cmd eq "day"){
	&runday();
	$dct++;
    }
    elsif($cmd =~ /^price (.+)/){
	$price = $1;
	print "Price set to $price\n";
    }
}

sub runday {
    $temp -=rand(4);
    $temp += rand(5);
    $temp = int(((3*$temp)+85)/4+.5);
    $npcust = 100 + rand(100);
    print "Lemonade for sale: \$$price\n";
    print "It's $temp degrees out today...\n";
    $cct=0;
    $higherct = $lowerct= 0;
    for($i = 1; $i < $npcust; $i++){
	if($pitcher <=0){
	    if(($sugar > $spitcher) &&
	       ($lemonjuice > $jpitcher)){
		$pitcher += 20;	# 
		$sugar -= $spitcher;
		$lemonjuice -= $jpitcher;
	    }
	    else{
		print "Out of lemonade fixin's!\n";
		last;
	    }
	}
	$bp = rand(.30);
	$wp = $bp + ($temp/100) - .85;
	
	if($price < $wp){
	    if($cups > 0){
		$cct++;
		$cups--;
		$pitcher--;
		$money += $price;
	    }
	    else{
		print "But you have run out of cups...\n";
	    }
	}
	if(($price-.05) < $wp){
	    $lowerct++;
	}
	if(($price+.05) < $wp){
	    $higherct++;
	}
    }
    $earnings = $cct*$price;
    if(($lowerct*($price-.05)) > $earnings){
	print "You would have made more (", $lowerct*($price-.05), ") at a lower price\n";
    }
    if(($higherct*($price+.05)) > $earnings){
	print "You would have made more (", $higherct*($price+.05), ") at a higher price\n";
    }
    print "$cct customers (\$$earnings earnings).\nCould have sold to $lowerct/$higherct if your price had been lower/higher.\n$pitcher servings wasted\n";
    $pitcher = 0;
}
