#!/usr/bin/perl -w
#
# dun_dacil on IRCnet   riccardo.mannella@df.unipi.it  
# Put the script in your .xchat folder and load it. Enjoy

# Distributed under GPL
# I'd appreciate comments on bugs, possible additions, etc.
# Script tested under Xchat 1.8.6 and 1.8.9
# Temp files (with current state of the quiz and questions asked)
#  are respectively  .dunquiz.tmp and .dunquiz.ques
#
# To switch to English, see the settings below
# v. 2.0  June 2002  Added support for teams play
# v. 1.0  Fall 2001 The quizzing game for Xchat
#
#Ideas taken from the Scramble game by thux and by Giorgos
#

my $script_name    = "dunquiz.pl";
my $script_version = "2.2";
IRC::register($script_name,$script_version, "", "");

IRC::print "::::::: Dun_quiz loaded :::::::\n";
IRC::add_command_handler("quiz", "quiz_game");
IRC::add_command_handler("unload", "unload");
IRC::add_message_handler("PRIVMSG", "catch_word");
IRC::add_message_handler("NICK", "catch_nick_change");
IRC::print "Type \00304 /quiz help \00300  to get help  \n";
IRC::print "+++++++++++++++++++++++++++++++\n";

# Add buttons
IRC::command "/delbutton TShow_Help";
IRC::command "/delbutton TWrong_Ans";
IRC::command "/delbutton TNext";
IRC::command "/delbutton TShow_Team";
IRC::command "/addbutton TShow_Help /quiz showhelp";
IRC::command "/addbutton TWrong_Ans /quiz wrong";
IRC::command "/addbutton TNext /quiz next";
IRC::command "/addbutton TShow_Team /quiz showteams";

sub unload 
{
IRC::command "/delbutton TShow_Help";
IRC::command "/delbutton TWrong_Ans";
IRC::command "/delbutton TNext";
IRC::command "/delbutton TShow_Team";
}

# Some defaults
# Language: set to 1 to quiz in English
my $englan=0;
 
# Set the quizzing channel here: it can be changed when the quiz starts,
#  type  /quiz help  to see how!
my $quizchannel="\#quiz.it";

# set a lock variable: it will number the questions asked
my $quiz_lock=-1;

# set the default points awarded for each question
my $award=1;

# zero the scores array
my @score=();

# set the team play default to zero (ie, no team play)
my $team_play=0;

# zero the team related quantities
my @team_names=();

# zero the DB entry
my @db_questions=();

# set the lock variable for DB questions
my $db_lock=-1;

# Approximate answers
my $approx=0;

# Award 1 point to second best (0:no 1:yes)
my $s_best=0;
my @s_b_nick=();

#
# Set time so that we will not be flooded with the rank requests
my $now = time;
my $starting_time=$now;
my $time_asked=$now;
my $now_team=$now;

sub print_out {
    IRC::print "@_\n";
}
sub command {
    IRC::command "@_";
}

# User commands types on the quiz channel
if ($englan == 1) {
# rankings
    $req_ran="!rank";
# personal score
    $req_sco="!score";
# current questions? (not shown again if shown in the last 20 secs)
    $req_que="!question"; 
# command to join a team: syntax   $join_team.team2join
    $join_team = "!join";
# command to hop/change team:    !hop.newteam
    $hop_team = "!hop";
# command to request team names and players in each team
    $ask_teams = "!teams";
} else {
    $req_ran = "!classifica";
    $req_sco = "!punti";
    $req_que = "!domanda";
    $join_team = "!squadra"; 
    $hop_team = "!salta";
    $ask_teams = "!squadre";
}

#Cosmetic things :)
my $dun_h="\00304,02 Dun_quiz \00309";

# Here, translations of the headings, chats etc. appearing in the script
if ($englan == 1) {
    $warn01="You must first join a team!";
    $head01="Teams available";
    $chat01="has";
    $chat02="points";
    $chat03="point";
    $head02="Leading three players:";
    $chat04="Position";
    $chat05="Team ranks:";
    $chat06="Current leader:";
    $chat07="Congratulations!";
    $chat08="got it right!!!";
    $chat09="The correct answer was";
    $chat10="It took";
    $chat11="seconds";
    $chat12="is correct, but you must first join a team, with";
    $chat13="The current question is:";
    $chat14="You already joined";
    $chat15="You are now in team";
    $chat16="starting on";
    $chat17="Are you ready?";
    $head03="Today, we play in teams! \00307 Teams are:";
    $chat18="Attention, question worth";
    $chat19="Question";
    $chat20="Hint:";
    $chat21="OK, ready to start again, we have now the correct answer!";
    $chat22="Scores have been reset";
    $chat23="Commands are:";
    $chat24="Teams play commands are:";
    $chat25="to join a team";
    $chat26="to change team";
    $chat27="to see the teams in play";
    $chat28="Hang on a second.. keyboards are no longer what they used to be!";
    $chat29="Be patient while I input the correct answer.... I will tell when ready!";
    $chat30="Gameover!";
    $chat31="Asked";
    $chat32="questions";
    $chat33="the quiz lasted";
    $chat34="Scrapped the point awarded to";
    $chat35="The question has been reset!";
    $chat36="The correct answer was:";
    $chat37="Additional point (3 times second best)";
} else {
    $chat35="Domanda annullata!";
    $chat36="La risposta giusta era:";
    $chat25="per entrare in squadra";
    $chat26="per cambiare squadra";
    $chat27="per conoscere le squadre in gioco";
    $chat28="Un attimo... queste tastiere, non sono piu` quelle di una volta";
    $chat29="Quiz sospeso mentre inserisco la risposta corretta.... pazientate!";
    $chat30="Gioco finito!";
    $chat31="Fatte";
    $chat32="domande";
    $chat33="durata del quiz";
    $chat34="Annullato il punto a";
    $chat18="Attenzione, domanda da";
    $chat19="Domanda";
    $chat20="Indizio:";
    $chat21="Ok Ok, ripartiamo ora, la risposta  giusta e` stata inserita!";
    $chat22="I punteggi sono stati riazzerati";
    $chat23="I comandi sono:";
    $chat24="I comandi per il gioco a squadre sono:";
    $chat10="Risposto dopo";
    $chat11="secondi";
    $chat12="e` corretta, ma devi prima entrare in una squadra con il comando";
    $chat13="La domanda e`:";
    $chat14="Sei gia` nella squadra";
    $chat15="Sei entrato nella squadra";
    $chat16="in funzione su";
    $chat17="Siete pronti?";
    $head03="Oggi giochiamo a squadre! \00307 Le squadre sono:";
    $warn01="Devi prima entrare in una squadra!";
    $head01="Squadre disponibili";
    $chat01="ha";
    $chat02="punti";
    $chat03="punto";
    $head02="Primi tre in classifica:";
    $chat04="Posizione";
    $chat05="Punteggio squadre:";
    $chat06="Primo in classifica:";
    $chat07="Congratulazioni!";
    $chat08="ha indovinato!!!";
    $chat09="La risposta giusta era";
    $chat37="Punto bradipo, tre volte peggior primo";
}

# Routine which updates the score
#  Called everytime a point is scored
sub update_score {
    $n2add=$_[0];
    my $updated = 0;
    if (@score == ()) {
	if ($team_play == 0) {
	    push (@score, $n2add, $award, "");
	} else {
# team play on, correct answer, but she/he is not in a team
	    command("/NOTICE $n2add $warn01");
	}
    } else {
	for (my $i=0; $i <= $#score; $i=$i+3) {
		if ($score[$i] eq $n2add) {
		    $score[$i+1] = $score[$i+1]+$award;
		    $updated = 1;
		}
	}
	if ( $updated == 0 ) {
	    if ($team_play == 0) {
		push (@score, $n2add, $award, "");
	    } else {
# see a few lines above
		command("/NOTICE $n2add $warn01");
	    }
	}
    }
}

# Routine to reset the score of a player ie after a wrong question
sub reset_score {
    for (my $i=0; $i <= $#score; $i=$i+3) {
	if ($score[$i] eq $_[0]) {
	    $score[$i+1] = $score[$i+1]-$award;
	}
    }
}



# Routine which returns a player's score
sub get_score {
    $n2check=$_[0];
    for (my $i=0; $i < $#score; $i=$i+3) {
	if ($score[$i] eq $n2check) {
	    return $score[$i+1];
	}
    }
    return 0;
}

# Routine to show the team names
sub show_team_names {
    my $whom2 = $_[0];
    command("$whom2 $dun_h $head01");
    for (my $i=0; $i <= $#team_names; $i=$i+2) {
# We need to show the teams, and the team members
	my $temp_out="$whom2 $dun_h \00307 $team_names[$i] \00304";
# search the player names
	for (my $k=0; $k <= $#score; $k=$k+3) {
	    if ($score[$k+2] eq $team_names[$i]) {
		$temp_out = "$temp_out $score[$k]";
	    }
	}
 	command("$temp_out");
    }
}

# Routine to print out a player's score
sub show_score {
   my $points = get_score("$_[0]");
   my $irc_nick = "$_[0]";
   if ($points != 1) {
       command("$dun_h \00307 $irc_nick\00304 $chat01 \002\00307 $points \00300\00304,02 $chat02.");
   } else {
       command("$dun_h \00307 $irc_nick\00304 $chat01 \002\00307 $points \00300\00304,02 $chat03.");
   }
}


# Routine to notice a player his/her score
sub notice_score {
   my $points = get_score($_[0]);
   my $irc_nick = $_[0];
   if ($points != 1) {
       command("/NOTICE $irc_nick $irc_nick \00304 $chat01 $points $chat02.");
   } else {
       command("/NOTICE $irc_nick $irc_nick \00304 $chat01 $points $chat03.");
   }
}

# Routine to print out the rankings
sub show_rank {
     $whom2=$_[0];

# first, swap ranks into a temporary area
    for (my $i=0; $i < $#score; $i=$i+1) {
	$temp[$i] = $score[$i];
    }


# now reorder
    for (my $i=0; $i < $#score-2; $i=$i+3) {
	for (my $j=$i+3; $j < $#score; $j=$j+3) {
	    if ($temp[$j+1] > $temp[$i+1]) {
		$a = $temp[$j];
		$temp[$j] = $temp[$i];
		$temp[$i] = $a;
		$a = $temp[$j+1];
		$temp[$j+1] = $temp[$i+1];
		$temp[$i+1] = $a;
	    }
	}
    }

# do a similar thing for the teams
    for (my $i=0; $i <= $#team_names; $i=$i+2) {
# fist, zero the score for the team
	$team_names[$i+1] = 0;
# next, search the players of this team
        for (my $j=0; $j <= $#score; $j=$j+3) {
	    if ($score[$j+2] eq $team_names[$i]) {
		$team_names[$i+1] = $team_names[$i+1] + $score[$j+1];
	    }
	}
    }

# Swap in a temporary area
    for (my $i=0; $i <= $#team_names; $i=$i+1) {
	$temp1[$i] = $team_names[$i];
    }

    for (my $i=0; $i < $#team_names-2; $i=$i+2) {
	for (my $j=$i+2; $j < $#team_names; $j=$j+2) {
	    if ($temp1[$j+1] > $temp1[$i+1]) {
		$a = $temp1[$j];
		$temp1[$j] = $temp1[$i];
		$temp1[$i] = $a;
		$a = $temp1[$j+1];
		$temp1[$j+1] = $temp1[$i+1];
		$temp1[$i+1] = $a;
	    }
	}
    }

# we have the thing nicely ordered. Output the first three
    if ($team_play == 0) {
	my $max_i = 9;
	command("$whom2 $dun_h  $head02");
	my $j = 1;
	for (my $i=0; $i < $max_i; $i=$i+3) {
	    if ($i < $#score) {
		command("$whom2 \00307 $chat04 $j: \00304 $temp[$i] \00302 $chat02 $temp[$i+1]");
		$j = $j + 1;
	    }
	}
    } else {
	my $max_i = $#team_names;
	command("$whom2 $dun_h $chat05");
	my $j = 1;
	for (my $i=0; $i <= $max_i; $i=$i+2) {
	    command("$whom2 \00307 $chat04 $j: \00304 $temp1[$i] \00302 $chat02 $temp1[$i+1]");
	    $j = $j + 1;
	}
	command("$whom2 $dun_h \00307 $chat06 \00304 $temp[0] \00303 $chat02 $temp[1]");
    }
}

# Routine to handle nick changes
sub catch_nick_change {
    my $line = join('', @_);
    $line =~ m/:(.+?)\!(.+?) NICK :(.*)/;
    my $oldnick = $1;
    my $newnick = $3;
    for (my $i=0; $i <= $#score; $i=$i+3) {
	if ($score[$i] eq $oldnick) {
	    $score[$i] = $newnick;
	}
    }
    for (my $i=0; $i <= $#s_b_nick; $i=$i+2) {
	if ($s_b_nick[$i] eq $oldnick) {
	    $s_b_nick[$i] = $newnick;
	}
    }
}


# Routine to catch what the users say, and act accordingly
sub catch_word {
    $irc_message = shift(@_);
    if ($quiz_lock < 0) {
	return 0;
    }
    $irc_message =~ m/:(.*)!(\S+) PRIVMSG (.*) :(.*)/i;
    if ($3 ne $quizchannel) {
	return 0;
    }
    $irc_nick = $1;
    $message = lc($4);

# Second best
    if (($s_best == 1) && ($line_b ne "") && (($message eq lc($line_b) && $approx==0) || ($approx==1 && index($message,lc($line_b))>-1))) { 
	$line_b="";
	$hint_b="";
	$nick_old="";
	my $updated = 1;
	if ( $team_play > 0 ){
	    $updated = 0;
	    for (my $i=0; $i <= $#score; $i=$i+3) {
		if ($score[$i] eq $irc_nick) {
		    $updated = 1;
		}
	    }
	}
#	print_out("Inside the 2nd best routine $irc_nick");
	if( $updated == 1 ) {
	    $open = time-$open;
	    if ($open > 2) {
		return 0;
	    }
	    print_out("1/3 for $irc_nick");
	    my $i_s_best=-1;
	    for (my $i=0; $i <= $#s_b_nick; $i=$i+2) {
		if ($s_b_nick[$i] eq $irc_nick) {
		    $i_s_best = $i;
		}
	    }
	    if ($i_s_best == -1) {
		push (@s_b_nick, $irc_nick, "1");
		return 0;
	    }
	    if ($s_b_nick[$i_s_best+1] < 2) {
		$s_b_nick[$i_s_best+1] = $s_b_nick[$i_s_best+1]+1;
		return 0;
	    }
# We are here, third time we score second best
	    $s_b_nick[$i_s_best+1] = 0;

# EN command("\00304,02 Congratulations.\002\00307 $irc_nick \00300\00304,02 got it!!!");
	    command("\00304,02 $chat07\002\00307 $irc_nick \00300\00304,02 $chat37");

	    $award=1;
	    update_score("$irc_nick");
#	    show_score("$irc_nick");

	    open(SAVEQUIZ,">.dunquiz.tmp");
	    print SAVEQUIZ "$quiz_lock\n";
	    print SAVEQUIZ "$starting_time\n";
	    print SAVEQUIZ "$quizchannel\n";
	    print SAVEQUIZ "$team_play\n";
	    print SAVEQUIZ "$#score\n";
	    print SAVEQUIZ "$#team_names\n";

	    for (my $k=0; $k <= $#score; $k=$k+1) {
		print SAVEQUIZ "$score[$k]\n";
	    }
	    for (my $k=0; $k <= $#team_names; $k=$k+1) {
		print SAVEQUIZ "$team_names[$k]";
	    }
            close(SAVEQUIZ);
	} else {
# $irc_nick got it right, but he is in no team, so let's tell her
	    command("/NOTICE $irc_nick \002\00308 $line_b \00300\00311,02 $chat12 $join_team.teamname");
	}
        return 0;
    } 


    if ($line_a ne "" && (($message eq lc($line_a) && $approx==0) || ($approx==1 && index($message,lc($line_a))>-1))) { 
#    if ($message eq lc($line_a) && $line_a ne "") {
# perhaps he/she is in no team?
	my $updated = 1;
	if ( $team_play > 0 ){
	    $updated = 0;
	    for (my $i=0; $i <= $#score; $i=$i+3) {
		if ($score[$i] eq $irc_nick) {
		    $updated = 1;
		}
	    }
	}
	if( $updated == 1 ) {
	    $open = time-$open;
# EN command("\00304,02 Congratulations.\002\00307 $irc_nick \00300\00304,02 got it!!!");
	    command("\00304,02 $chat07\002\00307 $irc_nick \00300\00304,02 $chat08");
# EN command("$dun_h The correct answer was \002\00308 $line_a \00300\00311,02 (guessed after \00304 $open \00311 seconds)");
	    command("$dun_h $chat09 \002\00308 $line_a \00300\00311,02 ($chat10 \00304 $open \00311 $chat11)");
	    update_score("$irc_nick");
	    show_score("$irc_nick");
# Save the question
	    print SAVEQUES "$line_a\:\:$hint\n";
	    $irc_nick_saved=$irc_nick;
# zero the temp space where answer/question are kept
# Prepare for second best
	    if ($s_best == 1) {
		$line_b = $line_a;
		$hint_b = $hint;
		$open = time;
		$nick_old = $irc_nick;
	    }
	    $line_a = "";
	    $hint = "";
# Backup the current status to the disk
	    open(SAVEQUIZ,">.dunquiz.tmp");
	    print SAVEQUIZ "$quiz_lock\n";
	    print SAVEQUIZ "$starting_time\n";
	    print SAVEQUIZ "$quizchannel\n";
	    print SAVEQUIZ "$team_play\n";
	    print SAVEQUIZ "$#score\n";
	    print SAVEQUIZ "$#team_names\n";
	    for (my $k=0; $k <= $#score; $k=$k+1) {
		print SAVEQUIZ "$score[$k]\n";
	    }
	    for (my $k=0; $k <= $#team_names; $k=$k+1) {
		print SAVEQUIZ "$team_names[$k]";
	    }
            close(SAVEQUIZ);
	} else {
# $irc_nick got it right, but he is in no team, so let's tell her
	    command("/NOTICE $irc_nick \002\00308 $line_a \00300\00311,02 $chat12 $join_team.teamname");
	}
        return 0;
    } 



    if ($message eq $req_sco) {
	notice_score("$irc_nick");
        return 0;
    } 
# The user wants to know the open question
    if ($message eq $req_que) {
# If more than 20 seconds since last time it was shown, show again on chan
# Otherwise, notice the user
	$time_now=time;
	if($time_now > $time_asked+20) {
	    command("$dun_h $chat13 \002\00303 $hint");
	    $time_asked=$time_now;
	} else {
	    command("/NOTICE $irc_nick $irc_nick, $chat13 \002\00303 $hint");
	}
        return 0;
    }
# The user wants to know the ranks
    if ($message eq $req_ran) {
# Check if at least 40 seconds have gone since last request
	$now_aux=time;
	if($now_aux>$now+40) {
	    $whom2="";
	    $now=$now_aux;
	} else {
	    $whom2="/NOTICE $irc_nick";
	}
# and now call the routine to show the ranks
        show_rank($whom2);
	return 0;
    }

# This handles the team play (join, hop, teams)
    if ($team_play > 0) {
        $b = $message;
# check if it is a joining
	if (index($b,$join_team) > -1) {
            $a = $b;
	    $a=~ m/$join_team\.(.+)/;
	    $team = $1;
# check if it is allowed as a team
	    for (my $i=0; $i <= $#team_names; $i=$i+2) {
		if ($team eq $team_names[$i]) {
# OK, it corresponds, now check if the user is already on a team
		    for (my $k=0; $k <= $#score; $k=$k+3) {
			if ($irc_nick eq $score[$k]) {
# too bad, it already joined a team!
			    command("/NOTICE $irc_nick $chat14 $score[$k+2]");
			    return 1;
			}
		    }
# We got here, it means the player has not joined any team
# We inizialise the thing for him/her
		    push (@score, $irc_nick, 0, $team);
		    command("/NOTICE $irc_nick $chat15 $team ");
		    return;
		}
	    }
	    return;
	}

# check if it is a hopping
	if (index($b,$hop_team) > -1) {
            $a = $b;
	    $a=~ m/$hop_team\.(.+)/;
	    $team = $1;
# check if it is allowed as a team
	    for (my $i=0; $i <= $#team_names; $i=$i+2) {
		if ($team eq $team_names[$i]) {
# OK, it corresponds, now check if the user is already on a team
		    for (my $k=0; $k <= $#score; $k=$k+3) {
			if ($irc_nick eq $score[$k]) {
			    $score[$k+2] = $team;
			    command("/NOTICE $irc_nick $chat15 $score[$k+2]");
			    return 0;
			}
		    }
# We got here, it means the player has not joined any team before
# We inizialise the thing for him/her
		    push (@score, $irc_nick, 0, $team);	    
		    command("/NOTICE $irc_nick :$chat15 $team");
		    return 0;
		}
	    }
            return 1;
	}
	if (index($b,$ask_teams) > -1) {
# show the team names
            $now_aux=time;
	    if($now_aux>$now_team+20) {
		$whom2="";
		$now_team=$now_aux;
	    } else {
		$whom2="/NOTICE $irc_nick";
	    }
	    show_team_names($whom2);
	}
	return 0;
    }
    return 0;

}
# End of the routine which handles the messages on the channel


# Main routine to quiz
sub quiz_game {
    $a = shift(@_);
    $b = $a;
    if ($b eq "start") {
        $starting_time=time;
	command("/MSG $quizchannel $dun_h $chat16 \00307 $quizchannel");
	command("$dun_h \00309 $chat17 \00304 dun_quiz by \00304 dun_dacil");
	$quiz_lock=0;
	$line_a="";
	splice(@score,0,$#score);
        open(SAVEQUES,">>.dunquiz.ques");
	return 1;
    }
    $b = $a;
    $temp="";
    $b =~ m/(\s*)start(\s*)(\#.+)/;
    if ($3 ne "") {
        $starting_time=time;
	$quizchannel=$3;
	command("/MSG $quizchannel $dun_h $chat16 \00307 $quizchannel");
	command("$dun_h \00309 $chat17 \00304 dun_quiz by \00304 dun_dacil");
	$quiz_lock=0;
	splice(@score,0,$#score);
	$line_a="";
	return 1;
    }
# Handle the help request
    if ($b eq "help") {
	print_out("Commands for dun_quiz.pl");
        print_out("/quiz <command> [options]                    ");
	print_out("  start [#channel]           ---> Start the game");
	print_out("  question::answer[::points] ---> Ask \"question\" with answer \"answer\" ");
        print_out("  rank                       ---> Show the ranks");
        print_out("  say <something>            ---> Say something on chan");
	print_out("  hint <something>           ---> Give a hint to the players");
	print_out("  approximate                ---> Toggle approximate answers ON/OFF");
        print_out("  showme                     ---> Shom me the answer I entered");
	print_out("  reset_rank                 ---> Reset the ranks");
	print_out("  reset_question             ---> Scrap the current question");
	print_out("  reset_score                ---> Cancel last point awarded");
	print_out("  reask                      ---> Show the current question again");
        print_out("  wrong                      ---> Tell ppl there is a wrong answer, changing it");
        print_out("  answer::new_answer         ---> Set answer to \"new_answer\" and carry on the game");
        print_out("  stop                       ---> Close the game");
	print_out("  resume                     ---> Resume a game from backup on disk");
        print_out("  help                       ---> Print this help");
	print_out("  showhelp                   ---> Show the commands to the players");
	print_out("  showteams                  ---> Show the teams names");
	print_out("  teams::t1::t2[::t3]        ---> Initialize a team game (team names are \"t1\" etc. )");
	print_out("  load::file.in              ---> Load questions from file.in");
	print_out("  next                       ---> Ask next question in DB ");
	print_out("  secondbest                 ---> Toggle additional point to 2nd best ON/OFF");
        print_out("code by dun_dacil");
	return 1;
    }

# Load the status from the backup
    if ($b eq "resume") {
	if (open FILE,".dunquiz.tmp") {
	    $icount = 0;
	    my $jteams = 0;
	    my $jscore = 0;
	    my $nscores = 1;
	    my $nteams = 1;
            while (<FILE>) {
		chop;
		if ($icount == 0) {
		    $quiz_lock = $_;
		}
		if ($icount == 1) {
		    $starting_time = $_;
		}
		if ($icount == 2) {
		    $quiz_channel = $_;
		}
		if ($icount == 3) {
		    $team_play = $_;
		}
		if ($icount == 4) {
		    $nscores = $_;
		}
		if ($icount == 5) {
		    $nteams = $_;
		}
		if (($icount >= 6) && ($icount <= 6+$nscores)) {
		    $score[$jscore] = $_;
		    $jscore = $jscore +1;
		}
		if (($icount > 6+$nscores) && ($icount <=  6+$nscores+$teams)) {
		    $team_names[$jteams] = $_;
		    $jteams = $jteams + 1;
		}
		$icount = $icount + 1;
                print_out("$icount $_\n");
	    }
		    
	} else {
	    print_out("I cannot resume");
	    return 1;
	}
	close(FILE);
        open(SAVEQUES,">>.dunquiz.ques");
	return 1;
    }

# If we got here and the lock<0, something is wrong :)  Jump out
    if ($quiz_lock < 0) {
	print_out("You must first start a quiz!");
	print_out("To start, type \00307 /quiz start [#channel]");
	print_out("Type \00307 /quiz help  \003  to get some help");
        return 1;
    }
    $b=$a;

# Load a DB question?
    $b =~ m/(\w+)::(.+)/;
    if ($1 eq "load") {
	$b=$2;
	if ($b eq "") {
	    print_out("You must specify the DB file!");
	    return 1;
	}
	print_out("Loading from $2");
	$filein=$b;
	if (open FILE,$b) {
	    $db_lock=0;
	    @db_questions=();
	    while (<FILE>) {
		chop;
		$c = $_;
		$c =~ m/(.+)::(.+)/;
		if ($2 eq "") {
		    print_out("Malformed entry $b");
		    return 1;
		}

		$hint = $1;
		$line_a = $2;
		$award= 1;
		$c = $hint;
		$c =~ m/(.+)::(.+)/;
		if ($1 ne $hint) {
		    $award=$line_a;
		    $hint=$1;
		    $line_a=$2;
		}
# OK we have things nicely ordered here
#		print_out("$line_a $hint $award");
		push (@db_questions, $hint, $line_a, $award); 
		$db_lock=$db_lock+1;

	    } 
	    
	    close(FILE);
	    print_out("Loaded $db_lock questions from $filein");
	} else {
	    print_out("I cannot find $b");
	    return 1;
	}
	
	return 1;
    }
    
    
    $b = $a;

# Check if we have a team contest
    $b =~ m/(\w+)::(.+)/;
    if ($1 eq "teams") {
	if ($team_play > 0) {
	    print_out("There is already a team game in progress: close it first!");
	    return 0;
	}
# OK! we have a team game!
	$b=$2;
	print_out("$b");
	$c = $b;
	$c =~ m/(.+)::(.+)/;
	if($1 eq $b) {
# only one team? no good!
	    print_out("You entered only one team! You need at least two teams!");
	    return 1;
	}
	$team_play = 1;
	$team_names[0] = $2;
	$last_team = $1;
# Loop to extract all team names
	for (my $i=0; $i < 10; $i=$i+1) {
	    $b = $last_team;
	    $c = $b;
	    $c =~ m/(.+)::(.+)/;
#	    print_out("inside the loop $b $last_team $c $1 $2");
	    if (index($c,"::")>0) {
		$team_names[2*$team_play] = $2;
		$team_play = $team_play + 1;
		$last_team = $1;
	    }
	}
	$team_names[2*$team_play] = $last_team;
	$team_play = $team_play + 1;
        command("$dun_h $head03");
	show_team_names();
        return 1;
    }
    $b = $a;

# Ask questions from DB
    if ($b eq "next") {
	if ($db_lock > 0) {
	    $i1 = 3*($db_lock-1);
	    $i2 = $i1 + 1;
	    $i3 = $i1 + 2;
	    $line_a=$db_questions[$i1];
	    $hint=$db_questions[$i2];
	    $award=$db_questions[$i3];
	    $db_lock=$db_lock-1;
	    $quiz_lock=$quiz_lock+1;
	    command("$dun_h $chat18 \002\00307 $award \00300\00304 $chat02");
	    command("$dun_h $chat19 ($quiz_lock): \002\00307 $hint");
	    print_out("Answer:\00307 $line_a \00300 Points: \00307 $award");
	    $open=time;
	    $time_asked=time;
	    $line_b="";
	    return 1;
	} else {
	    print_out("No more questions in DB");
	    return 1;
	}

    }
# Check if it is a question
    $b =~ m/(.+)::(.+)/;
    if ($2 ne "" && $1 ne "answer") {
	if ($line_a ne "") {
	    print_out("Hey hey, you already asked \00307 $hint \00300 with answer \00307 $line_a ");
	    return 1;
	}
        $hint = $1;
        $line_a = $2;
	$award= 1;
	$c = $hint;
	$c =~ m/(.+)::(.+)/;
        if ($1 ne $hint) {
	    $award=$line_a;
	    $hint=$1;
	    $line_a=$2;
	}
        $quiz_lock=$quiz_lock+1;
	command("$dun_h $chat18 \002\00307 $award \00300\00304 $chat02");
	command("$dun_h $chat19 ($quiz_lock): \002\00307 $hint");
	print_out("Answer:\00307 $line_a \00300 Points: \00307 $award");
        $open=time;
	$time_asked=time;
	$line_b="";
	$nick_old="";
	return 1;
    } 
    $b = $a;
    $b =~ m/(\w+) (.+)/;

# Check if it is a hint
    if ($1 eq "hint") {
	if($line_a ne "") {
	    command("$dun_h $chat20 \00300\00307 $2");
	} else {
	    print_out("No open question!");
	}
        return 1;
    }
    $b = $a;
    $b =~ m/(\w+) (.+)/;

# Check if the quizzer wants to say something on the channel
    if ($1 eq "say") {
	command("$dun_h $2");
        return 1;
    }
    $b = $a;
    $b =~ m/(\w+)::(.+)/;

# The quizzer changed the answer, carry on
    if ($1 eq "answer") {
	if ($line_a ne "") {
	    $line_a = $2;
	    command("$dun_h $chat21");
	    command("$dun_h $chat18 \002\00307 $award \00300\00304 $chat02");
	    command("$dun_h $chat19 ($quiz_lock): \002\00307 $hint");
	} else {
	    print_out("Well, there is no open question! Ask a question, first!");
	}
	return 1;
    }
    $b = $a;

# Tell the channel the current question
    if ($b eq "reask" ) {
	if ($line_a ne ""){
	    command("$dun_h $chat19: \00307 $hint");
	} else {
	    print_out("There is no open question!");
	}
	return 1;

# Reset the ranks
    } elsif ($b eq "reset_rank" ) { 
	@score = ();
	@s_b_nick = ();
	command("$dun_h $chat22");
	return 1;
    }

# Tell the channel the current ranks
    if ($b eq "rank") {
        show_rank();
	return 1;
    }

    if ($b eq "approximate") {
        if ($approx==1) {
	    $approx=0;
	    print_out("Approximate answers are now OFF");
	} else {
	    $approx=1;
	    print_out("Approximate answers are now ON");
	}
	return 1;
    }

    if ($b eq "secondbest") {
        if ($s_best==1) {
	    $s_best=0;
	    print_out("Secondbest is now OFF");
	} else {
	    $s_best=1;
	    print_out("Secondbest is now ON");
	}
	return 1;
    }

# Show mw what I typed for answer
    if ($b eq "showme") {
        print_out("Current correct answer is: $line_a");
        return 1;
    }

# Tell channel the teams
    if ($b eq "showteams" and $team_play > 0) {
	show_team_names();
    }

# Show some help lines to the players
    if ($b eq "showhelp") {
	command("$dun_h \00309 $chat23 \00304$req_sco, $req_ran, $req_que ");
	if ($team_play > 0) {
	    command("$dun_h $chat24 \00304 $join_team.team\00309 $chat25,\00304 $hop_team.team\00309 $chat26, \00304$ask_teams\00309 $chat27");
	}
	return 1;
    }

# Tell the channel we have a wrong question, changing it
    if ($b eq "wrong") {
	if ($line_a ne "") {
	    command("$dun_h \00304,02 $chat28");
	    command("$dun_h \00304,02 $chat29");
	} else {
	    print_out("There is no open question!");
	}
	return 1;
    }

# Close the game
    if ($b eq "stop") {
        command("\00304,02 $chat30");
	$line_a = "";
        show_rank();
	if ( $team_play > 0 ) {
	    $team_play=0;
	    show_rank();
	}
# Work out the quiz duration
        $duration=time-$starting_time;
        ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=gmtime($duration);
        $str_out="";
        if ( $hour > 0 ) {
	    $str_out = "$hour hr,";
	}
	if ($min > 0) {
	    $str_out = "$str_out $min min,";
	}
        if ($sec > 0) {
	    $str_out = "$str_out $sec sec";
	}
        command("$dun_h $chat31 \00307 $quiz_lock \00304 $chat32,\00309 $chat33 \00304 $str_out");
	$quiz_lock=-1;
	splice(@score,0,$#score);
        @score=(); 
	@team_names=();
	@s_b_nick=();
	close(SAVEQUES);
	command("$dun_h dunquiz by \00307 dun_dacil\00304 meet him on \00307 \#quiz.it @ ircnet");
	return 1;
    }
    if ($b eq "reset_question" ) {
	if ($line_a ne "") {
	    command("$dun_h $chat35");
	    command("\00304,02 $chat36 \002\00307 $line_a");
	    $hint="";
	    $line_a="";
	} else {
	    print_out("There is no open question!");
	}
	return 1;
    }

# Scrap the last point awarded
    if ($b eq "reset_score") {
	command("\00309,02 Dun_quiz\00304 $chat34 \002\00307 $irc_nick_saved");
	reset_score($irc_nick_saved);
        get_score($irc_nick_saved);
        show_score($irc_nick_save);
	$quiz_lock=$quiz_lock-1;
	return 1;
    }
    return 1;
}	    




