#!/usr/bin/perl
#File: /home/kscott/dice.pl 
#Author:  
#Time-stamp: <12/31/2009 10:29:06 krowe@rastan.aoc.nrao.edu>

#./dice.pl -i100000 -d12 -d10 -v | grep -v total | grep -v average | awk '{print $4}' | sort -n | uniq -c | awk '{print $2, $1}' > 100000_d12_d10

#gnuplot>
#  set term jpeg
#  set output "100000_d12_d10.jpg"
#
#  set xlabel "Result"
#  set ylabel "Throws"
#  plot [0:80] [0:17000] "100000_d12_d10.count" with impulses lw 5

# should plot them all with the same values for x

$openended=1 ;			# default is open ended rolling

sub Usage
{
    print "Usage: $0 [-Dhnv] -i<itirations> -d<die> [-d<die> ...]\n" ;
    print "\n" ;
    print "This rolls open-ended dice.\n" ;
    print "\n" ;
    print "  -D  print debugging output.\n" ;
    print "  -h  print this help.\n" ;
    print "  -n  turn off open-ended rolling.\n" ;
    print "  -v  print verbose output.\n" ;
    print "  -i<itirations>\n" ;
    print "      itirations is the number of rolls of the dice to perform\n" ;
    print "  -d<dice>\n" ;
    print "      dice is the number of sides on a die.\n" ;
    exit 1 ;
}

sub Roll
{
    my $roll, $sub_total, $total = 0 ;

    foreach $die (@dice)
    {
	print "die is (d$die)\n" if($DEBUG) ;

	$roll = (int(rand($die)) + 1) ;
	print "roll is ($roll)\n" if($DEBUG) ;

	$sub_total = $sub_total + $roll ;

	while($roll == $die && $openended == 1)
	{
	    print "CRIT\n" if($DEBUG) ;
	    $roll = (int(rand($die)) + 1) ;
	    print "bonus roll is ($roll)\n" if($DEBUG) ;
	    $sub_total = $sub_total + $roll ;
	}
	print "sub_total is ($sub_total)\n" if($DEBUG) ;
	$total = $total + $sub_total ;
	$sub_total = 0 ;
    }
    return($total) ;
}

$i = 0 ;
while($_ = shift(@ARGV))
{
    if(/^-h/) { &Usage ; } 
    elsif(/^-D/) { $DEBUG=1 ; } 
    elsif(/^-n/) { $openended=0 ; } 
    elsif(/^-i(\d+)/) { $itirations=$1 ; }
    elsif(/^-d(\d+)/) { $dice[$i++]=$1 ; }
    elsif(/^-v/) { $VERBOSE=1 ; }
    else { &Usage ; }
}

# print "dice is (@dice)\n" ;
# print "itirations is ($itirations)\n" ;
# print "dice[0] is ($dice[0])\n" ;

$main_total = 0 ;
for($x = 1 ; $x <= $itirations ; $x++)
{
    $roll = &Roll ;
    print "roll $x is $roll\n" if($VERBOSE) ;
    $main_total += $roll ;
}

print "\n" ;
print "Total is $main_total\n" ;
printf("Arithmentic mean is %d\n", int($main_total/$itirations)) ;
# should calculate the median and the mode too.
