#
# mkquest.awk, 18 Apr 05

function rand_line(line_str)
{
print rand() " " line_str >> TEMP_FILE
}

BEGIN {
	TEMP_FILE="q" systime()
	included_hashes=0
	print ".pl +11.5i"
	print ".po 1.2i"
	print ".ll 6.5i"
	}

$0 == "----" {
	print ".bp"
	num_oh_sets=0
	num_oh=0
	next
	}

$0 == "****" {
	if (in_info_list == 0)
	   {
	   in_info_list=1
	   print "" > TEMP_FILE
	   }
	else
	   {
	   in_info_list=0
	   close(TEMP_FILE)
	   system("sort -g < " TEMP_FILE " | awk -f mklist.awk")
	   }
	next
	}

# Two sets of questions include ####
# Make sure we always use information from one #### sequence
$0 == "####" {
	if (included_hashes == 1)
	   in_info_list=2
	if ((included_hashes == 0) && (rand() > 0.5))
	   {
	   in_info_list=2
	   included_hashes=2
	   }
	else
	   included_hashes=1
	next
	}

# A 50% chance of using information sequence after the ====
$0 == "====" {
	if (rand() > 0.5)
	   {
	   close(TEMP_FILE)
	   print "" > TEMP_FILE
	   }
	else
	   in_info_list=2
	next
	}

$1 == "\@" {
	num_oh_sets++
	num_oh=0
	next
	}

$1 == "o" {
	$1=""
	oh_sets[num_oh_sets]=oh_sets[num_oh_sets] " | " $0
	num_oh++
	next
	}

$0 == "" {
	if (num_oh != 0)
	   {
	   rand_oh_set=int(rand()*num_oh_sets-0.0000001)
#	   print num_oh_sets " " rand_oh_set " " oh_sets[rand_oh_set]
	   split(oh_sets[rand_oh_set], oh_str, "|")
	   print ".RS"
	   print ".IP 1)"
	   print oh_str[2]
	   print ".IP 2)"
	   print oh_str[3]
	   print ".RE"
	   num_oh=0
	   num_oh_sets=0
	   delete oh_sets
	   }
	print ""
	next
	}

in_info_list == 1 {
	if (split($0, info_opt, "|") == 2)
	   {
	   if (rand() > 0.5)
	      rand_line(info_opt[1])
	   else
	      rand_line(info_opt[2])
	   }
	else
	   rand_line($0)
	next
	}

in_info_list == 2 {
	next
	}

	{
	print $0
	next
	}

END {
	system("rm " TEMP_FILE)
	}
