#!/usr/bin/ksh
#Script to generate lottery numbers
#	1st parameter highest possible value
#	2nd parameter number of draws
#	3rd parameter number of balls
integer MAX_BALL=${1:-42}
integer NUM_DRAWS=${2:-1}
integer NUM_BALLS=${3:-6}
readonly MAX_BALL NUM_DRAWS NUM_BALLS
readonly SPACE=" "
readonly NEW_LINE="\012"
readonly BAD_PARAM=1
readonly SUCCESS=0
readonly INT_ENCOUNTERED=2
#Function to cleanup temp file
function cleanup
{
	if [[ -f $1 ]];then rm $1;fi
	exit INT_ENCOUNTERED
}

# Sanity check
if (( MAX_BALL < NUM_BALLS ))
then
	print -u2 "You bonehead!\a"
	print -u2 "You cannot have $NUM_BALLS unique balls ranging from 1 to $MAX_BALL!"
	print -u2 "RTFM!"
	print -u2 "
	1st parameter highest possible value
	2nd parameter number of draws
	3rd parameter number of balls"
	exit	$BAD_PARAM
fi

integer draw=1
integer next_ball
typeset -R2 next_ball
tmp_file=/tmp/${0##/}${$}
trap "cleanup $tmp_file" INT
# Generate the requested number of draws
while (( draw <= NUM_DRAWS ))
do
	integer ball=1
	touch $tmp_file
	## Generate 1 draw
	while (( ball <= NUM_BALLS ))
	do
		(( next_ball = RANDOM%MAX_BALL + 1 ))
		### Generate unique numbers
		while grep "^$next_ball$" $tmp_file > /dev/null
		do
			(( next_ball = RANDOM%MAX_BALL + 1 ))
		done
		### NOTE: Need quots for right justification
		print "$next_ball" >> $tmp_file
		ball=ball+1
	done
	## Display draw
	print -n "Your lucky quick pik is: "
	sort -n $tmp_file | tr "$NEW_LINE" "$SPACE"
	print ""
	rm $tmp_file
	draw=draw+1
done
exit $SUCCESS
