###################################
## The #Homicide Efnet Trivia Bot #
###################### Ophmisu ####
############ by WSergio ###########

set tgver $team(Version)
proc versiune {} {
global tgver
return "$tgver"
}
set tgchan $team(chan)
set tgpath $team(dir)
set tgrel "versiunea"
set qpath $team(path,dir_questions)
set QuestionFilePrefix "intrebari_"
set tgqdb "$qpath/${QuestionFilePrefix}00"
set tgscf "$tgpath/scor.txt"
set tgerrfil "$tgpath/greseli.txt"
set tgerremail "ophmisu@yahoo.com"
set tgerrmailtmp "$tgpath"
set c_getscore "!scor"
set settings(web1) "http://homicide.biz.tm"
set settings(web2) "http://poze.homicide.biz.tm"


#  How many points to give a person for a correctly answered
#  question.
set tgpointsperanswer 1

# do not edit #
set qcurrentquestion ""
#set tgplaying 0
# indice bonus
set bonus 0
# incr bonus
set bid 0
set bpt $tgpointsperanswer
set hbonus ""



# ciclul bonusului
set bcy 5
set bcyd 0
# maxim bonus
set bpts 15


set ofile "$tgpath/records.txt"
set qtotal ""

#####################################################################
# Commands:                                                         #
# The default channel commands are:                                 #
#                                                                   #
# COMMAND   FLAGS   DESCRIPTION                                     #
# !sugestie -|-     gives another hint to the current question.     #
# !sari     o|o     skips the question and selects a new one.       #
# !start    -|-     starts the game (if it's not running).          #
# !stop     o|o     stops the game (if it's running).               #
# !top10    -|-     shows the top 10 scores on channel.             #
#                                                                   #
# The default /msg commands (and flags required for their use) are: #
#                                                                   #
# COMMAND   FLAGS   DESCRIPTION                                     #
# ajutor     n/a     gives help.                                    #
# eroare     n/a     report errors in questions/answers.            #
# reset      m|m     reset score table.                             #
# reguli     n/a     show the channel's rules (customisable).       #
# scor       n/a     looks up someone's score.                      #
# concurent  n/a     tells you who is ranked one above you.         #
#####################################################################

set cmdgenhtml "!genhtml"

#  The character that seperates the question and the answer in the
#  question/answer file.
set tgqdbsep "*"

#  What you set here defines how the bot expects the question/answer
#  pairs to be arranged.
#  If set to 1, bot expects lines in the format:
#    question<seperator>answer
#  If set to 0, bot expects lines in the format:
#    answer<seperator>question
set tgqdbquestionfirst 1

#  How to send error reports. Set to 1 to send error report to an
#  e-mail address of your choice, or 0 to record errors in a file.
#  Sending via e-mail requires that the bot have access to the "mail"
#  program. If the bot doesn't have access to this program (e.g. if
#  you're running the bot on the Windows platform), then set this to
#  0 to have errors recorded in a file.
set tgerrmethod 0

#  How often (in seconds) does the html file get updated. Set to 0
#  to disable HTML page.
set tghtmlrefresh 0

#  The font to use on the html page.
set tghtmlfont "verdana,helvetica,arial"


#  The maximum number of hints to give before the question 'expires'
#  and the bot goes on to another one. This EXCLUDES the first hint
#  given as the question is asked (i.e. the hint which shows no letters,
#  only placeholders).
set tgmaxhint 6

#  Should the bot show the question on each hint (1) or only on the first (0)?
set tgalwaysshowq 0

#  Show questions in all CAPS (1) or not (0)?
set tgcapsquestion 0

#  Show answers in all CAPS (1) or not (0)?
set tgcapsanswer 0

#  Show hints in all CAPS (1) or not (0)?
set tgcapshint 0

#  The minimum number of correct answers in a row by one person which
#  puts them on a winning streak. Setting this to 0 will disable the
#  winning streak feature.
set tgstreakmin 4

#  The number of missed (i.e. unanswered, not skipped) questions to allow
#  before automatically stopping the game. Setting this to 0 will cause the
#  game to run until somebody uses the stop command, or the bot dies, gets
#  killed, pings out, or whatever.
set tgmaxmissed 6

#  The character to use as a placeholder in hints.
set tghintchar "\00313*\00300"

#  The time in seconds between hints.
set tgtimehint 16

#  The time in seconds between a correct answer, 'expired' or skipped question
#  and the next question being asked.
set tgtimenext 12

#  Phrases to use when the question has 'expired'. Must also be a TCL list.
set tgnobodygotit [list "Nimeni nu a gasit raspunsul." "Hello? E cineva acasa?" "Ar trebui sa va straduiti mai mult!" "Sunt oare prea grele intrebarile?" "Vorbesc cumva singur?" "Nu cred ca se pot castiga puncte in felul asta!" "Iar dormiti mai?" "Trezirea!" "Adormitilor..." "Ce e cu voi mai?" "V-ati pierdut din IQ?" "Alo!? V-ati dat la asl pls?" "Nimeni, nimic bun..." "Slabutz..." "Subtire..." "Subtirel..." "Iar dormiti?" "Iar stati ca bananele?" "Banane ce sunteti..." "Nehalitilor" "Nemancatilor" "Aiuritilor..." "Joc singur?" "Nici macar pe google nu ati gasit?" "Naspa treaba..." "Nasol..." "Of..." "Mda..." "Timeout! Asta e!" "Timpul a expirat!" "Nu ati stiut nici unul raspunsul corect!" "V-ati pierdut talentu'?" "Mai cu talent!" "Mai cu talent, ca inchide la non-stop!" "Praf..." "Deplorabil :>" "Ce e cu voi ma?" "Nimic..." "Nimeni..." "Timeout!" "Varza..."]

#  Phrases to use when the question expired and there's another one coming up.
#  Yep, you guessed it... another TCL list.
set tgtrythenextone [list "Sa vedem daca o stiti si pe asta..." "Pregatiti-va pentru urmatoarea..." "Poate o sa o stiti pe urmatoarea..." "Incercati sa o aflati pe urmatoarea..." "Urmatoarea intrebare..." "Hai alta..." "Hai una mai usoara..." "Urmatoarea..." "Hai sa incercam alta..." "Pregatiti-va psihic pentru urmatoarea." "Mana pe taste, vine urmatoarea..." "Păzea! Vine urmatoarea intrebare..." "Pârtie! Vine urmatoarea intrebare!" "Chinuiti-va la urmatoarea intrebare..."]

#  Will the bot calculate the time it took to get the correct
#  answer (1) or not (0)? (requires TCL 8.3 or higher).
set tgtimeanswer 1

#  Will the bot show the correct answer if nobody gets it (1) or not (0)?
set tgshowanswer 1

#  When someone answers a question, will the bot show just that person's score (0)
#  or will it show all players' scores (1) (default). This is useful in channels with
#  a large number (>20) players.
set tgshowallscores 0

#  Use bold codes in messages (1) or not (0)?
set tgusebold 0

#  Send private messages using /msg (1) or not (0)?
#  If set to 0, private messages will be sent using /notice
set tgpriv2msg 0

#  Word to use as /msg command to give help.
#  e.g. set tgcmdhelp "helpme" will make the bot give help when someone
#  does "/msg <botnick> ajutor"
set tgcmdhelp "ajutor"

#  Channel command used to start the game.
set tgcmdstart "+$nick"

#  Flags required to be able to use the start command.
set tgflagsstart "R|-"

#  Channel command used to stop the game.
set tgcmdstop "-$nick"

#  Flags required to be able to use the stop command.
set tgflagsstop "o|v"

#  Channel command used to give a hint.
set tgcmdhint "!!"

#  Flags required to be able to use the hint command.
set tgflagshint "R|-"

#  Disable the !sugestie command x seconds after someone uses it. This
#  prevents accidental double hints if two people use the command in
#  quick succession.
set tgtempnohint 5

#  Channel command used to skip the question.
set tgcmdskip "!sari"

#  Flags required to be able to use the skip command.
set tgflagsskip "-|v"

#  Channel command for showing the top 10 scores.
set tgcmdtop10 "!top"

#  Flags required to use the top 10 command.
set tgflagstop10 "R|-"

#  Channel command for showing the top20 scores.
set tgcmdtop20 "!top20"

#  Flags required to use the top 20 command.
set tgflagstop20 "R|-"

#  /msg command used to reset scores.
set tgcmdreset "reset"

#  Flags required to be able to use the reset command.
set tgflagsreset "m|m"

#  Require password for resetting scores?
#  If enabled, you must use /msg bot reset <password> to reset scores.
#  The password is the one set by a user using '/msg bot pass'.
set tgresetreqpw 1

#  /msg command for looking up somebody's score.
set tgcmdlookup "scor"

#  /msg command for looking up your target.
#  (i.e. the person ranked one higher than you).
set tgcmdtarget "concurent"
#  /msg command for reporting errors in questions and/or answers.
set tgcmderror "eroare"
set tgcmderror2 "!gresita"

#  /msg command to show channel's rules.
set tgcmdrules "reguli"

#  Channel's rules.
set tgrules "Fara reclama, fara profanari, fara certuri, fara scripturi active sau flood. Incalca aceste reguli si fi gata sa ai ban. Detalii pe site $::settings(web1) - Distractie placuta! :>"

#  Number of minutes between reminders of how to report errors.
set tgerrremindtime 60
set offmode "\0030,4Datorita inactivitatii, jocul a fost oprit automat. \002Pentru a reincepe jocul urla dupa $botnick!!!\0030,4\002"
#  COLOURS
#  The colour codes used are the same as those used by mIRC:
#  00:white        01:black        02:dark blue    03:dark green
#  04:red          05:brown        06:purple       07:orange
#  08:yellow       09:light green  10:turquoise    11:cyan
#  12:light blue   13:magenta      14:dark grey    15:light grey
#
#  Always specify colour codes as two digits, i.e. use "01" for
#  black, not "1".
#  You can specify a background colour using "00,04" (white text
#  on red background).
#  To disable a colour, use "".
#  Note that disabling some colours but not others may yield
#  unexpected results.

#set tgrose1 "\0033,1-\0039{\0034@"
#set tgrose2 "\0034,1@\0039}\0033-"
set tgrose1 "\00314,1-{\00315@"
set tgrose2 "\00315,1@\00314}-"


set tgcolourstart "01"		;#Game has started.
set tgcolourstop "04"		;#Game has stopped.
set tgcolourskip "01"		;#Question has been skipped.
set tgcolourerr "04"		;#How to report errors.
set tgcolourmiss "01"		;#Nobody answered the question.
set tgcolourqhead "14"		;#Question heading.
set tgcolourqbody "1,14"		;#Question text
set tgcolourhint "14,1"		;#Hint.
set tgcolourstrk "14"		;#Person is on a winning streak.
set tgcolourscr1 "0,4"		;#Score of person in first place.
set tgcolourscr2 "11,12"		;#Score of person in second place.
set tgcolourscr3 "9,3"		;#Score of person in third place.
set tgcolourrset "04"		;#Scores have been reset.
set tgcolourstend "02"		;#Winning streak ended.
set tgcolourmisc1 "14"		;#Miscellaneous colour #1.
set tgcolourmisc2 "04"		;#Miscellaneous colour #2.
set tgcolourmisc3 "15"          ;#Miscellaneous colour #3.
set tgcolourmisc4 "0,14"
set tgcolourmisc5 "9,1"
# DELETE THE FOLOWING LINE! If not, your botwill die!

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                   #
#    Any editing done beyond this point is done at your own risk!   #
#                                                                   #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
proc CreSet {} {
        set ot [open "$::ofile" a+]
        close $ot
}
proc IsSet {opt} {
        if {[file exists $::ofile]==1} {
			set is 0
			set ot [open "$::ofile"]
			fconfigure $ot -buffering line
			gets $ot data
			while {$data != ""&&$is == 0} {
					set v1 [lindex $data 0]
					if {$v1==$opt} { set is 1 }
					gets $ot data
			}
			close $ot
			return $is
        } else {
			putlog "$::ofile does not exists bai, creating..."
			DefSet
	}
}

proc GetSet {opt} {
	if {[file exists $::ofile]==1} {
		set ret "0"
		set found 0
		if {$opt=="speed"} { set ret "Nobody 10000" }
		if {$opt=="consec"} { set ret "Nobody 0" }
		set ot [open "$::ofile"]
		fconfigure $ot -buffering line
		gets $ot data
		while {$data != ""&&$found == 0} {
			set v1 [lindex $data 0]
			set v2 [lindex $data 1]
			#putlog "v1: $v1 ==? opt: $opt v2: $v2"			
			if {$v1==$opt} {
				set ret $v2
				set found 1
				}
			gets $ot data
		}
        close $ot
		return $ret
        } else {
                putlog "$::ofile does not exists bai, creating..."
                DefSet
        }
}

proc PutSet {opt val} {
if {[file exists $::ofile]==1} {
		if {[IsSet $opt]==0} {
				set ot [open "$::ofile" a+]
	#        	set data [read -nonewline $ot]
			puts $ot "$opt \"$val\"" 
				close $ot


		} else { ModSet $opt $val }
	} else {
			putlog "$::ofile does not exists bai, creating..."
			DefSet
	}
}
proc ModSet {opt nval} {
        if {[file exists $::ofile]==1} {
		set ofile2 "$::tgpath/txt/opt.tmp"
                file delete -force $ofile2
		file copy -force $::ofile $ofile2
		file delete -force $::ofile
                set ot [open "$::ofile" a+]
		set ot2 [open "$ofile2" r]
                fconfigure $ot2 -buffering line
                gets $ot2 data
                while {$data != ""} {
                        set v1 [lindex $data 0]
                        set v2 [lindex $data 1]
                        if {$v1==$opt} {
				#putlog "v1: $v1 - v2: $v2 -> nval: $nval"
				set v2 "$nval"
			}
                        puts $ot "$v1 \"$v2\""
                        gets $ot2 data
                }
                close $ot
		close $ot2
                file delete -force $ofile2
        } else {
                putlog "$::ofile does not exists bai, creating..."
                DefSet
        }
}
proc CheckSet {} {
	if {[file exists $::ofile]==0} {
			putlog "$::ofile does not exists bai, creating..."
			DefSet
	}				
}

proc RandS {file} {
	global tgpath
        set file $tgpath/txt/$file
        set fp [open $file "r"]
        set data [read -nonewline $fp]
        close $fp
        set lines [split $data "\n"]
        set numlines [llength $lines]
        set num [rand $numlines]
        set randline [lindex $lines $num]
        eval "set randline  \"$randline\""
        return "$randline"
}

proc DefSet {} {
	CreSet
	PutSet intc 0
	PutSet intp 0
	PutSet bonusuri 0
	PutSet speed "Nimeni 1000"
	PutSet consec "Nimeni 0"
	PutSet EtapaCurenta 0
}

set tsetid "!setid"
proc SetID {nick uhost hand chan text} {
	global tggetscores tgscores tgscf tsetid tgscoresbyname
	set name [lindex [info level [info level]] 0]
	set head \[\002$name\002\]
	if {[llength $text]==2} {
		set from [lindex $text 0]
		set from2 [strlwr $from]
		set to [strlwr [lindex $text 1]]
		tggetscores
	        if {[info exists tgscoresbyname([strlwr $from])]} {
        	        if {![info exists tgscoresbyname([strlwr $to])]} {
				set scornou [string map [list $from2 $to $from $to] $tgscores]
			        set _sfile [open $tgscf w]
	        		puts $_sfile "$scornou"
		        	close $_sfile
				puthelp "privmsg $chan :$head Noul ID setat: $from -> $to"
	        		return
        	        } else { puthelp "privmsg $chan :$head Eroare: $to exista deja in tabela de scor!" }

	        } else { puthelp "privmsg $chan :$head Eroare: $from nu exista in tabela de scor!" }


 	}  else { puthelp "privmsg $chan :$head Eroare: sintaxa corecta este: $tsetid <id> <id nou>" }
}
#bind pub o|o $tsetid SetID

proc GetScore {nick host hand chan arg} {
        global tgchan tggetscores tgscores tgranksbynum
        global tgranksbyname tgrealnames tgscoresbyname

        if {[strlwr $tgchan]==[strlwr $chan]} {
                set msg "\00300,01\002 Scor\002 "
                set inexistent ""
                set N [llength $arg]
                if {$N==0} { set Nicks $nick
                } else { set Nicks $arg }
                tggetscores
                set ics 2
                foreach CNick $Nicks {
                                if {[info exists tgscoresbyname([strlwr $CNick])]} {
                                if {[expr $ics%2]==0} { set hra "\00315,14"
                                } else { set hra "\00301,14" }
                                incr ics
                                set scor $tgscoresbyname([strlwr $CNick])
                                set rank $tgranksbyname([strlwr $CNick])
                                append msg "$hra $rank) \002$CNick\002 $scor *"
                        } else { append inexistent "$CNick " }
                }
		if {$N==0} { 
			set _extra "\00305\[predecesor: \002$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))\002 ($tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))])) & succesor \002$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))\002 ($tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))]))\0031\]" 
			append msg " $_extra"			
		}
                if {$inexistent != ""} {
                        set inexistent "\0031,14($inexistent"
                        append inexistent "- nici un punct)"
                }
                tggamemsg "$msg $inexistent"
        }
}



#Misc checks & var initialisations
if {[info tclversion]<8.2} {
	putlog "\002[file tail [info script]]\002 failed to load: in order to use this script, eggdrop needs to be compiled to use tcl 8.2 or higher (recommended: latest stable version)."
	return
}
if {$tgtimeanswer==1&&[info tclversion]<8.3} {
	putlog "\002[file tail [info script]]\002 warning: timing of answers has been automatically disabled. this feature requires tcl 8.3 or higher."
	set tgtimeanswer 0
}
if {![info exists alltools_loaded]||$allt_version<205} {
	putlog "\002[file tail [info script]]\002 failed to load: please load alltools.tcl v1.14 or higher (available with eggdrop 1.6.13 or higher) before attempting to load this script."
	return
}
# if {[utimerexists tghtml]!=""} {killutimer $tghtmlrefreshtimer}
#if {$tghtmlrefresh>0} {
#	set tghtmlrefreshtimer [utimer $tghtmlrefresh tghtml]
#}
if {![file exists $tgqdb]} {
	putlog "\002[file tail [info script]]\002 failed to load: $tgqdb does not exist."
	exit
}
if {[llength [split $tgchan]]!=1} {
	putlog "\002[file tail [info script]]\002 failed to load: too many channels specified."
	return
}
if {![info exists tgplaying]} {
	set ctcp-version "${ctcp-version} (with ro.tcl $tgver ($tgrel) from $::settings(web1))"
	set tgplaying 0
}
if {![info exists tghintnum]} {set tghintnum 0}
if {![info exists tgmissed]} {set tgmissed 0}

#Binds
bind pubm $tgflagsstart "$tgchan %$tgcmdstart" tgstart
bind pubm $tgflagsstop "$tgchan %$tgcmdstop" tgstop
proc tgbindhintcmd {} {
	global tgflagshint tgcmdhint
	bind pubm $tgflagshint "$::tgchan %$tgcmdhint" tgforcehint
}
proc tgunbindhintcmd {} {
	global tgflagshint tgcmdhint
	unbind pubm $tgflagshint "$::tgchan %$tgcmdhint" tgforcehint
}
tgbindhintcmd
bind pubm $tgflagsskip "$tgchan %$tgcmdskip" tgskip
#bind pubm $tgflagstop10 "$tgchan %$tgcmdtop10" tgshowtop10
#bind pubm $tgflagstop10 "$tgchan %!top10" tgshowtop10
#bind pubm $tgflagstop20 "$tgchan %$tgcmdtop20" tgshowtop20
#bind join -|- "$tgchan *" tgjoinmsg
#bind msg - $tgcmdhelp tggivehelp
#bind msg - $tgcmdlookup tgscorelookup
#bind msg - $tgcmdtarget tgtargetlookup
#bind msg - $tgcmderror tgerror
bind pubm - "$tgchan %$tgcmderror2*" tgerror2

#bind msg - $tgcmdrules tgrulesmsg
bind msg $tgflagsreset "$tgcmdreset" tgresetscores
bind kick - "$tgchan $botnick" tgbotgotkicked
bind evnt - disconnect-server tgbotgotdisconnected
# bind pubm m|- "$tgchan %$cmdgenhtml" tghtml
#bind pub - $c_getscore GetScore

#starts the game if it isn't running.
proc tgstart {nick host hand chan text} {
	global tgplaying tgstreak tgchan tgerrremindtime tgerrremindtimer tgmissed
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==0} {
			tggamemsg "[tgcolstart]Jocul a fost pornit de $nick! (Homicide Trivia versiunea \002[versiune]\002 @ WSergio)"
			tgnextq
			set tgplaying 1
			set tgstreak 0
			set tgmissed 0
			set tgerrremindtimer [timer $tgerrremindtime tgerrremind]
		}
	}
}
proc tgastart {chan nick} {
	global tgplaying tgstreak tgchan tgerrremindtime tgerrremindtimer tgmissed tgrel tgver
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==0} {
			tggamemsg "[tgcolstart]Pornirea automata a fost declansata de \002$nick\002! (Homicide Trivia versiunea \002[versiune]\002 @ WSergio)"
			tgnextq
			set tgplaying 1
			set tgstreak 0
			set tgmissed 0
			set tgerrremindtimer [timer $tgerrremindtime tgerrremind]
			#putlog "Homicide Trivia $tgrel $tgver - pornire automata declansata de $nick"
			if {$::team(topic_change)} {
				if {[topic $tgchan]==$::offmode} { utimer 10 [putserv "topic $tgchan :[proc:randomtopic]"] }
			}
		}
	}
}
set stopper ""
#stops the game if it's running.
proc tgstop {nick host hand chan text} {
	global tghinttimer tgnextqtimer tgplaying tgchan tgcurrentanswer tgstreak tgstreakmin
	global tgerrremindtimer tgrebindhinttimer
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==1} {
			tggamemsg "[tgcolstop]Jocul a fost oprit de $nick! \002(Homicide Trivia versiunea [versiune] @ WSergio)"
			set ::stopper $nick
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
			set tgstreak 0
			set tgplaying 0
			catch {unbind pubm $::team(flags) "$tgchan *" tgcheckanswer}
			if {[utimerexists tghint]!=""} {killutimer $tghinttimer}
			if {[utimerexists tgnextq]!=""} {killutimer $tgnextqtimer}
			if {[timerexists tgerrremind]!=""} {killtimer $tgerrremindtimer}
			if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
		}
	}
}

#gives a hint if there is currently a question to answer.
proc tgforcehint {nick host hand chan text} {
	global tghinttimer tgnextqtimer tgplaying tgchan tgcurrentanswer tgstreak tgstreakmin
	global tgtempnohint tgmaxhintcurrent tghintnum tgrebindhinttimer tgtempnohint
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==1&&[utimerexists tghint]!=""} {
			killutimer $tghinttimer
			tghint
			tgunbindhintcmd
			if {$tghintnum<$tgmaxhintcurrent} {
				set tgrebindhinttimer [utimer $tgtempnohint tgbindhintcmd]
			}
		}
	}
}

#skips the current question if one has been asked.
proc tgskip {nick host hand chan text} {
	global tghinttimer tgnextqtimer tgplaying tgchan tgcurrentanswer tgstreak
	global tgstreakmin tgtimenext tgrebindhinttimer
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==1&&[utimerexists tghint]!=""} {
			tggamemsg "[tgcolskip]Sar peste aceasta intrebare dupa cum m-a rugat [tgcolmisc2]$nick[tgcolskip]."
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin&&[strlwr [lindex [split $tgstreak ,] 0]]==[strlwr $nick]} {
				tgstreakend
				set tgstreak 0
			}
			catch {unbind pubm $::team(flags) "$tgchan *" tgcheckanswer}
			killutimer $tghinttimer
			if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
			set tgnextqtimer [utimer $tgtimenext tgnextq]
		}
	}
}

#reminds channel how to report errors in questions/answers
proc tgerrremind {} {
	global tgerrremindtimer tgerrremindtime botnick tgcmderror
	tggamemsg "[RandS remind]"
	set tgerrremindtimer [timer $tgerrremindtime tgerrremind]
}

#bot got kicked. stop the game.
proc tgbotgotkicked {nick host hand chan targ text} {
	tgquietstop
}

#bot got disconnected. stop the game.
proc tgbotgotdisconnected {disconnect-server} {
	tgquietstop
}

#stops the game without telling the channel.
proc tgquietstop {} {
	global tgplaying tgstreak tgchan tgcurrentanswer tghinttimer tgnextqtimer tgerrremindtimer
	global tgrebindhinttimer
	if {$tgplaying==1} {
		set tgstreak 0
		set tgplaying 0
		catch {unbind pubm $::team(flags) "$tgchan *" tgcheckanswer}
		if {[utimerexists tghint]!=""} {killutimer $tghinttimer}
		if {[utimerexists tgnextq]!=""} {killutimer $tgnextqtimer}
		if {[timerexists tgerrremind]!=""} {killtimer $tgerrremindtimer}
		if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
	}
}

proc Lines {que} {
	set qstream [open $que r]
	set ret [llength [split [read -nonewline $qstream] "\n"]]
	close $qstream;
	return $ret;
}

#reads the question database.
set qcurrentdb ""
proc tgreadqdb {} {
	global tgqdb tgquestionstotal tgquestionslist
	set quefiles [glob -nocomplain -type f -directory $::qpath $::QuestionFilePrefix*]
	set quefiles [lsort $quefiles]
	set quelen [llength $quefiles]
	set tgqdb [lindex $quefiles [rand [llength $quefiles]]]
	set ::qcurrentdb [lindex [split $tgqdb "/"] end]
	set ::qtotal [expr ($quelen-1)*20000 + [Lines [lindex $quefiles [expr $quelen-1]]]]
	#putquick "privmsg #pula :chosed $tgqdb, qtotal: $qtotal"
#putquick "privmsg #pula :[expr ($quelen-1)*20000+[Lines [lindex quefiles [expr $quelen-1]]]   ]"
	set tgquestionstotal 0
	set tgquestionslist ""
	set qfile [open $tgqdb r]
	set tgquestionslist [split [read -nonewline $qfile] "\n"]
	set tgquestionstotal [llength $tgquestionslist]
	close $qfile
}

        binary scan A c A
        binary scan z c z
 
proc RandChar [list length [list min $A] [list max $z]] {
	set range [expr {$max-$min}]
	set ch [expr {$min+int(rand()*$range)}]
	return [binary format c $ch]
}

set CurrentQuestion ""
set CurrentQuestionAnswer ""
set CurrentQuestionNumber ""
set CurrentQuestionDB ""
set LastQuestion ""
set LastQuestionAnswer ""
set LastQuestionNumber ""
set LastQuestionDB ""
#selects the next question.
proc tgnextq {} {
	global tgqdb tgcurrentquestion tgcurrentanswer tgquestionnumber
	global tgquestionstotal tghintnum tgchan tgquestionslist tgqdbsep tgqdbquestionfirst
	global tgcapsquestion tgcapsanswer 
	PutSet intp "[expr [GetSet intp]+1]"
	incr ::bid
	if {$::bid>$::bcyd} {
		set ::bonus 0
		set ::bid 0
		set ::bcyd [expr $::bcy + [rand 2]]
		# rand 10
	}
	if {$::bid==$::bcyd} {
		set ::bonus 1
		PutSet bonusuri "[expr [GetSet bonusuri]+1]"
	}
   if {$::bonus==1} {
	set min 2
	set max 10
	set ::bpt [expr {int(rand()*($::bpts-2+1))+2}]
				set ::hbonus "$::tgrose2\00300,04 +BONUS:\00309 $::bpt \00300Puncte "
		} else {
				set ::bpt $::tgpointsperanswer
				set ::hbonus ""
		}
	if {[info exists ::qcurrentdb]} { set ::LastQuestionDB $::qcurrentdb }
	tgreadqdb
	set ::CurrentQuestionDB $::qcurrentdb
	if {[info exists ::CurrentQuestion]} {
		set ::LastQuestion $::CurrentQuestion
		set ::LastQuestionAnswer $::CurrentQuestionAnswer
		
	}
	set tgcurrentquestion ""
	set tgcurrentanswer ""
	while {$tgcurrentquestion == ""} {
		if {[info exists ::tgquestionnumber]} {
			set ::LastQuestionNumber $tgquestionnumber 
		}
		set tgquestionnumber [rand [llength $tgquestionslist]]
		set ::CurrentQuestionNumber $tgquestionnumber
		
		set tgquestionselected [lindex $tgquestionslist $tgquestionnumber]
		set tgcurrentquestion [lindex [split $tgquestionselected $tgqdbsep] [expr $tgqdbquestionfirst^1]]
		set ::CurrentQuestion $tgcurrentquestion
		set anticp ""
		foreach word [split $tgcurrentquestion] {
			# MODIFY THIS SHIT if you wanna schimbi si culorile intrebarilor!
			append anticp "$word\00314[RandChar 30]\00301"
		}
		
		set tgcurrentquestion $anticp
		if {$tgcapsquestion==1} {
			set tgcurrentquestion [strupr $tgcurrentquestion]
		}
		set tgcurrentanswer [string trim [lindex [split $tgquestionselected $tgqdbsep] $tgqdbquestionfirst]]
		set ::CurrentQuestionAnswer $tgcurrentanswer
		if {$tgcapsanswer==1} {
			set tgcurrentanswer [strupr $tgcurrentanswer]
		}
	}
	unset tghintnum
	tghint
	bind pubm $::team(flags) "$tgchan *" tgcheckanswer
	return
}

#shows timed hints.
proc tghint {} {
	global tgmaxhint tghintnum tgcurrentanswer tghinttimer tgchan botnick tgrose1 tgrose2
	global tgtimehint tghintchar tgquestionnumber tgquestionstotal
	global tgcurrentquestion tghintcharsused tgnextqtimer tgtimenext tgstreak tgstreakmin
	global tgnobodygotit tgtrythenextone tgmissed tgmaxmissed tgcmdstart tgshowanswer
	global tgtimestart tgtimeanswer tgalwaysshowq tgmaxhintcurrent tgtempnohint tgcapshint
	if {![info exists tghintnum]} {
		set tghintnum 0
		regsub -all -- "\[^A-Za-z0-9\]" $tgcurrentanswer "" _hintchars
		set tgmaxhintcurrent [expr [strlen $_hintchars]<=$tgmaxhint?[expr [strlen $_hintchars]-1]:$tgmaxhint]
		catch {tgunbindhintcmd}
		if {$tgmaxhintcurrent>0} {
			set tgrebindhinttimer [utimer $tgtempnohint tgbindhintcmd]
		}
	} else { incr tghintnum }
	if {$tghintnum >= [expr $tgmaxhintcurrent+1]} {
		incr tgmissed
		set _msg ""
		append _msg "[tgcolmiss][lindex $tgnobodygotit [rand [llength $tgnobodygotit]]]"
		if {$tgshowanswer==1} {
			append _msg " Raspunsul corect era [tgcolmisc2]$tgcurrentanswer[tgcolmiss]."
		}
		if {$tgmaxmissed>0&&$tgmissed>=$tgmaxmissed} {
			append _msg " \0034Aceasta a fost $tgmissed-a intrebarea fara raspuns! Datorita inactivitatii, jocul a fost oprit automat. \002Pentru a reincepe jocul urla dupa $botnick!!!\0034\002"
			if {$::team(topic_change)} { utimer 20 [putserv "TOPIC $tgchan :$::offmode"] }
			tgquietstop
		} else {
			append _msg " [lindex $tgtrythenextone [rand [llength $tgtrythenextone]]]"
		}
		tggamemsg "[tgcolmiss]$_msg"
		if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
		set tgstreak 0
		catch {unbind pubm $::team(flags) "$tgchan *" tgcheckanswer}
		if {$tgmaxmissed==0||$tgmissed<$tgmaxmissed} {
			set tgnextqtimer [utimer $tgtimenext tgnextq]
		}
		return
	} elseif {$tghintnum == 0} {
		set i 0
		set _hint {}
		set tghintcharsused {}
		foreach word [split $tgcurrentanswer] {
			regsub -all -- "\[A-Za-z0-9\]" $word $tghintchar _current
			lappend _hint $_current
		}
		if {$tgtimeanswer==1} {
			set tgtimestart [clock clicks -milliseconds]
		}
	} elseif {$tghintnum == 1} {
		set i 0
		set _hint {}
		while {$i<[llength [split $tgcurrentanswer]]} {
			set _word [lindex [split $tgcurrentanswer] $i]
			set j 0
			set _newword {}
			while {$j<[strlen $_word]} {
				if {$j==0} {
					append _newword [stridx $_word $j]
					lappend tghintcharsused $i,$j
				} else {
					if {[string is alnum [stridx $_word $j]]} {
						append _newword "$tghintchar"
					} else {
						append _newword [stridx $_word $j]
						lappend tghintcharsused $i,$j
					}
				}
				incr j
			}
			lappend _hint $_newword
			incr i
		}
		} else {
			set i 0
			set _hint {}
			while {$i<[llength [split $tgcurrentanswer]]} {
				set _word [lindex [split $tgcurrentanswer] $i]
				set j 0
				set _newword {}
				set _selected [rand [strlen $_word]]
				regsub -all -- "\[^A-Za-z0-9\]" $_word "" _wordalnum
				if {[strlen $_wordalnum]>=$tghintnum} {
					while {[lsearch $tghintcharsused $i,$_selected]!=-1||[string is alnum [stridx $_word $_selected]]==0} {
					 set _selected [rand [strlen $_word]]
					}
				}
				lappend tghintcharsused $i,$_selected
				while {$j<[strlen $_word]} {
					if {[lsearch $tghintcharsused $i,$j]!=-1||[string is alnum [stridx $_word $j]]==0} {
						append _newword [stridx $_word $j]
					} else {
						if {[string is alnum [stridx $_word $j]]} {
							append _newword $tghintchar
						}
				}
				incr j
			}
			lappend _hint $_newword
			incr i
		}
	}
	if {$tgcapshint==1} {
		set _hint [strupr $_hint]
	}
	#tggamemsg "[tgcolqhead]» Intrebarea [expr $tgquestionnumber+1]/$::qtotal/$::qcurrentdb «"
	if {$tgalwaysshowq==1||$tghintnum==0} {
		tggamemsg [textparse "[tgcolqhead]» Intrebarea <|[fcolor 01][expr $tgquestionnumber+1]|>[tgcolqhead]/$::qtotal/$::qcurrentdb «"]
		tggamemsg "[tgcolqbody]$::hbonus$tgrose1[tgcolqbody] $tgcurrentquestion $tgrose2"

	}
	# [expr $tghintnum?"":""]
	tggamemsg "$tgrose1[tgcolhint] $tghintnum/$tgmaxhintcurrent:[tgcolmisc3] [join $_hint]"
	set tghinttimer [utimer $tgtimehint tghint]
}

#triggered when someone uses !top10 command
proc tgshowtop10 {nick host hand chan text} {
	global tgscores tgchan tgscorestotal tgranksbyname
	if {[strlwr $chan]==[strlwr $tgchan]} {
		tggetscores
		if {$tgscorestotal>0} {
			if {$tgscorestotal>9} {
				set _max 9
			} else {
				set _max [expr $tgscorestotal-1]
			}
			set i 0
			while {$i<=$_max} {
				set _item [lindex $tgscores $i]
				set _nick [join [lindex [split $_item ,] 2]]
				set _score [join [lindex [split $_item ,] 0]]
				set _rank "$tgranksbyname([strlwr $_nick])"
				if {$i==0} {
					append _scores "[tgcolscr1] $_rank) $_nick $_score"
				} elseif {$i==1} {
					append _scores "[tgcolscr2] $_rank) $_nick $_score"
				} elseif {$i==2} {
					append _scores "[tgcolscr3] $_rank) $_nick $_score"
				} else {
					if {[expr $_rank%2]==0} { set hra "\00315,14"
					} else { set hra "\00301,14" }
					append _scores "$hra * $_rank) $_nick $_score"
				}
				incr i
			}
			tggamemsg "[tgcolmisc4]\002 Top 10\002: $_scores \0030,14... (Total: $tgscorestotal jucatori) @ Tabela extinsa -> \0039$::settings(web1)\0039"
		} else {
			tggamemsg "[tgcolmisc1]Tabela de scor este goala."
		}
	}
}



#triggered when someone uses !top20 command
proc tgshowtop20 {nick host hand chan text} {
	global tgscores tgchan tgscorestotal tgranksbyname
	if {[strlwr $chan]==[strlwr $tgchan]} {
		tggetscores
		if {$tgscorestotal>0} {
			if {$tgscorestotal>19} {
				set _max 19
			} else {
				set _max [expr $tgscorestotal-1]
			}
			set i 0
			while {$i<=$_max} {
				set _item [lindex $tgscores $i]
				set _nick [join [lindex [split $_item ,] 2]]
				set _score [join [lindex [split $_item ,] 0]]
				set _rank "$tgranksbyname([strlwr $_nick])"
				if {$i==0} {
					append _scores "[tgcolscr1] $_rank) $_nick $_score"
				} elseif {$i==1} {
					append _scores "[tgcolscr2] $_rank) $_nick $_score"
				} elseif {$i==2} {
					append _scores "[tgcolscr3] $_rank) $_nick $_score"
				} else {
					if {[expr $_rank%2]==0} { set hra "\00315,14"
					} else { set hra "\00301,14" }
					append _scores "$hra * $_rank) $_nick $_score"
				}
				incr i
			}
			tggamemsg "[tgcolmisc4]\002 Top 20\002: $_scores \0030,14... (Total: $tgscorestotal jucatori) @ \0030Tabela extinsa -> \0039$::settings(web1)\0039"
		} else {
			tggamemsg "[tgcolmisc1]Tabela de scor este goala."
		}
	}
}




#checks if anyone has said the correct answer on channel.
proc tgcheckanswer {nick host hand chan text} {
	global tgcurrentanswer bonus
	if {[strlwr $tgcurrentanswer] == [tgstripcodes [strlwr [string trim $text]]]} {		
		w:CorrectAnswer $nick $hand $chan $::bpt
		tgcorrectanswer $nick $bonus
		# putlog "CURRENT BONUS: $bonus"
	}
}

#triggered when someone says the correct answer.
proc tgcorrectanswer {nick bonus} {
	global tgcurrentanswer tghinttimer tgtimenext tgchan tgnextqtimer tgstreak tgstreakmin
	global tgscoresbyname tgranksbyname tgranksbynum tgscorestotal tgmissed
	global tgtimestart tgshowallscores tgrealnames tgscoresbyrank tgtimeanswer
	PutSet intc "[expr [GetSet intc]+1]"

	set tgmissed 0
	#tgshowscores $nick
	catch {unbind pubm $::team(flags) "$tgchan *" tgcheckanswer}
	killutimer $tghinttimer
	set tgnextqtimer [utimer $tgtimenext tgnextq]
}

proc tgcorrectanswer2 {nick bonus} {
	global tgcurrentanswer tghinttimer tgtimenext tgchan tgnextqtimer tgstreak tgstreakmin
	global tgscoresbyname tgranksbyname tgranksbynum tgscorestotal tgmissed
	global tgtimestart tgshowallscores tgrealnames tgscoresbyrank tgtimeanswer
	PutSet intc "[expr [GetSet intc]+1]"
	tggetscores
	if {![info exists tgranksbyname([strlwr $nick])]} {
		set _oldrank 0
	} else {
		set _oldrank $tgranksbyname([strlwr $nick])
	}
	tgincrscore $nick
	tggetscores
	set _newrank $tgranksbyname([strlwr $nick])
	set _timetoanswer ""
	if {$tgtimeanswer==1} {
		set _timetoanswer [expr [expr [clock clicks -milliseconds]-$tgtimestart]/1000.00]
	}
	set hv ""
	if {$_timetoanswer<[lindex [GetSet speed] 1]} {
		PutSet speed "$nick $_timetoanswer"
		append hv "(\002RECORD NOU\002) [lindex [GetSet speed] 1]"
	} else { append hv "$_timetoanswer" }
	set _msg "[tgcolmisc1][RandS tgcongrats] \002[tgcolmisc2]$nick\002[tgcolmisc1]! [RandS corect] [tgcolmisc2]$tgcurrentanswer[tgcolmisc1].[expr $tgtimeanswer==1?" Viteza: [tgcolmisc2]$hv[tgcolmisc1] secunde.":""]"
	if {$_newrank<$_oldrank} {
		if {$_newrank==1} {
			append _msg " \002Esti acum pe primul loc!\002"
		} else {
			if {$tgshowallscores==0} {
				append _msg " \002Ai avansat [expr $_oldrank - $_newrank] [expr [expr $_oldrank - $_newrank]==1?"loc":"locuri"]!\002"
			} else {
				append _msg " Esti pe locul [tgcolmisc2]$tgranksbyname([strlwr $nick])[tgcolmisc1] din [tgcolmisc2]$tgscorestotal[tgcolmisc1], in spatele lui [tgcolmisc2]$tgrealnames($tgranksbynum([expr $_newrank-1]))[tgcolmisc1] cu [tgcolmisc2]$tgscoresbyrank([expr $_newrank-1])[tgcolmisc1]."
			}
		}
	}
	append _msg " Acumulari:"
	if {$::bonus==1} { append _msg " \00304\002+BONUS: $::bpt Puncte.\002"
	} elseif {$::bonus==0} { append _msg "\00304 1 [tgcolmisc1]Punct." }
	if {$tgstreak!=0} {
		if {[lindex [split $tgstreak ,] 0]==[strlwr $nick]} {
			set tgstreak [strlwr $nick],[expr [lindex [split $tgstreak ,] 1]+1]
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} {
				set crasp [lindex [split $tgstreak ,] 1]
				set hc ""
				if {$crasp>[lindex [GetSet consec] 1]} {
					PutSet consec "$nick $crasp"
					append hc "(\002RECORD NOU\002) "
				}
				append hc "$crasp"
				append _msg " [tgcolstrk]Raspunsuri corecte consecutive: [tgcolmisc2]$hc."
			}
		} else {
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
			set tgstreak [strlwr $nick],1
		}
	} else {
		set tgstreak [strlwr $nick],1
	}
        tggamemsg "$_msg"

	set tgmissed 0
	tgshowscores $nick
	catch {unbind pubm $::team(flags) "$tgchan *" tgcheckanswer}
	killutimer $tghinttimer
	set tgnextqtimer [utimer $tgtimenext tgnextq]
}


#read current scores from file, sort and store in variable.
proc tggetscores {} {
	global tgscf tgscorestotal tgscores tgscoresbyname tgranksbyname tgranksbynum
	global tgrealnames tgscoresbyrank
	if {[file exists $tgscf]&&[file size $tgscf]>2} {
		set _sfile [open $tgscf r]
		set tgscores [lsort -dict -decreasing [split [gets $_sfile]]]
		close $_sfile
		set tgscorestotal [llength $tgscores]
	} else {
		set tgscores ""
		set tgscorestotal 0
	}
	if {[info exists tgscoresbyname]} {unset tgscoresbyname}
	if {[info exists tgranksbyname]} {unset tgranksbyname}
	if {[info exists tgrealnames]} {unset tgrealnames}
	if {[info exists tgranksbynum]} {unset tgranksbynum}
	set i 0
	while {$i<[llength $tgscores]} {
		set _item [lindex $tgscores $i]
		set _nick [lindex [split $_item ,] 2]
		set _lwrnick [lindex [split $_item ,] 3]
		set _score [lindex [split $_item ,] 0]
		set tgscoresbyname($_lwrnick) $_score
		set tgrealnames($_lwrnick) $_nick
		set tgranksbyname($_lwrnick) [expr $i+1]
		set tgranksbynum([expr $i+1]) $_lwrnick
		set tgscoresbyrank([expr $i+1]) $_score
		incr i
	}
	return
}

#increment someone's score.
proc tgincrscore {who} {
	global tgscores tgscf tgpointsperanswer tgscorestotal tgscoresbyname
	tggetscores
	if {$tgscorestotal>0} {
		set i 0
		if {![info exists tgscoresbyname([strlwr $who])]} {
			append _newscores "1,[expr 1000000000000.0/[unixtime]],$who,[strlwr $who] "
		}
		while {$i<[llength $tgscores]} {
			set _item [lindex $tgscores $i]
			set _nick [lindex [split $_item ,] 2]
			set _time [lindex [split $_item ,] 1]
			set _score [lindex [split $_item ,] 0]
			if {[strlwr $who]==[strlwr $_nick]} {
				append _newscores "[expr $_score + $::bpt],[expr 1000000000000.0/[unixtime]],$who,[strlwr $who][expr [expr [llength $tgscores]-$i]==1?"":"\ "]"
			} else {
				append _newscores "$_score,$_time,$_nick,[strlwr $_nick][expr [expr [llength $tgscores]-$i]==1?"":"\ "]"
			}
			incr i
		}
	} else {
		append _newscores "1,[expr 1000000000000.0/[unixtime]],$who,[strlwr $who]"
	}
	set _sfile [open $tgscf w]
	puts $_sfile "$_newscores"
	close $_sfile
	return
}

#shows the current scores on channel.
proc tgshowscores {nick} {
	global tgscores tgchan tgscorestotal tgshowallscores tgranksbyname tgranksbynum
	global tgscoresbyname tgrealnames tgscoresbyrank
	tggetscores
	set i 0
	if {$tgshowallscores} {
		while {$i<[llength $tgscores]} {
			set _item [lindex $tgscores $i]
			set _nick [lindex [split $_item ,] 2]
			set _score [lindex [split $_item ,] 0]
			if {$i==0} {
				append _scores "[tgcolscr1]$_nick $_score"
			} elseif {$i==1} {
				append _scores ", [tgcolscr2]$_nick $_score"
			} elseif {$i==2} {
				append _scores ", [tgcolscr3]$_nick $_score"
			} elseif {[onchan $_nick $tgchan]} {
				append _scores ", [tgcolmisc1]$_nick $_score"
			}
			incr i
		}
		tggamemsg "[tgcolmisc1]The scores: $_scores"
	} else {
		if {$tgranksbyname([strlwr $nick])==1} {
			set _tgt "."
		} else {
			set _tgt ", in urma lui [tgcolmisc2]$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))[tgcolmisc1] cu [tgcolmisc2]$tgscoresbyrank([expr $tgranksbyname([strlwr $nick])-1])[tgcolmisc1]."
		}
		set col0 "\00304"
		set col1 "\00312"
		set col2 "\00302"
		set sep1 "«"
		set sep2 "»"
		 
		set ncur "$nick"
		set scur "$tgscoresbyname([strlwr $nick])"
		
		set lcur "$tgranksbyname([strlwr $ncur])"
		set hcur "\002$col1 $lcur) $ncur $scur\002"

		set stare "[tgcolmisc1]Stare:"
		if {$tgranksbyname([strlwr $nick])==1} {
			set hcur "\002$col0 $lcur) $ncur $scur\002"
			set rcol [expr {int(rand()*15)}]
			append stare "$hcur \002\003$rcol\([RandS sef]\)\002 "
			if {$tgscorestotal>1} {
				set nsuc "$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))"
				set ssuc "$tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))])"
				set lsuc "$tgranksbyname([strlwr $nsuc])"
				set hsuc "$col2$lsuc) $nsuc $ssuc"
				append stare "$sep2 $hsuc[tgcolmisc1] ..."
			}
		} else {
			if {$tgranksbyname([strlwr $nick])==$tgscorestotal} {
				set npre "$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))"
				set spre "$tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))])"    
				set lpre "$tgranksbyname([strlwr $npre])"
				set hpre "$col2$lpre) $npre $spre"
				append stare " ... $hpre $sep1$hcur[tgcolmisc1]"

		} else {

	                set npre "$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))"
	                set spre "$tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))])"    
			set lpre "$tgranksbyname([strlwr $npre])"
			set hpre "$col2$lpre) $npre $spre"
	                set nsuc "$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))"
        	        set ssuc "$tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))])"
			set lsuc "$tgranksbyname([strlwr $nsuc])"
			set hsuc "$col2$lsuc) $nsuc $ssuc"
			append stare " ... $hpre $sep1$hcur $sep2 $hsuc[tgcolmisc1] ..."
		}
	}
	tggamemsg "$stare"


	}
}

#reset current scores.
proc tgresetscores {nick host hand text} {
	global tgscf tgscorestotal tgscores tgplaying tgresetreqpw EtapaCurenta tgrose1 tgrose2
	if {($tgresetreqpw==1 && [passwdok $hand $text]) || $tgresetreqpw==0} {
		tggamemsg "[tgcolrset]$tgrose1\00304 Etapa a [expr $EtapaCurenta-1]-a s-a incheiat! $tgrose2"
		tggamemsg "$tgrose1 Statistici: \00309[GetSet intp]\00300 intrebari puse, \00309[GetSet intc]\00300 raspunsuri corecte si \00309[GetSet bonusuri]\00300 bonusuri oferite! $tgrose2"
		tggamemsg "$tgrose1 Au participat \00309$::tgscorestotal\00300[expr $::tgscorestotal>19?" de":""] [expr $::tgscorestotal==1?"jucator":"jucatori"] contra\00309 $::qtotal \00300de intrebari $tgrose2"
		tggamemsg "$tgrose1 Recordul de viteza este detinut de \00309[lindex [GetSet speed] 0]\00300 cu \00309[lindex [GetSet speed] 1]\00300 secunde. $tgrose2"
		tggamemsg "$tgrose1 Recordul in raspunsuri corecte consecutive il detine \00309[lindex [GetSet consec] 0]\00300 cu \00309[lindex [GetSet consec] 1]\00300 raspunsuri. $tgrose2"
		if {[file exists $tgscf]&&[file size $tgscf]>2} {
			set _sfile [open $tgscf w]
			puts $_sfile ""
			close $_sfile
			set tgscores ""
			set tgscorestotal 0
		}
		tggamemsg "[tgcolrset]$tgrose1\00309,4 A inceput etapa a $::EtapaCurenta-a!\00308 Tabela de scor a fost stearsa de\002 $nick!\002 $tgrose2"
		DefSet
		file delete -force $::melttop(file)
	}
}

#triggered when a winning streak ends.
proc tgstreakend {} {
		global tgstreak tgrealnames
		#tggamemsg "[tgcolstend]Cam atat cu [tgcolmisc2]$tgrealnames([lindex [split $tgstreak ,] 0])[tgcolstend] si castigul sau..."
		return
}

#triggered when someone joins trivia chan.


proc tgjoinmsg {nick host hand chan} {
	global botnick tgplaying tgcmdhelp tgcmdstart tgflagsstart tgcmdstop tgflagsstop tgchan tgranksbyname tgscoresbyname tgrealnames tgranksbynum
	global tgscorestotal
	if {$nick != $botnick} {
		set _msg ""
		tggetscores
		if {[info exists tgscoresbyname([strlwr $nick])]} {
			if {$tgranksbyname([strlwr $nick])==1&&$tgscorestotal>3} { 
				tggamemsg "[tgcolstrk]\002<> \0034$nick\002 este pe PRIMUL LOC cu \002$tgscoresbyname([strlwr $nick])\002 de puncte\0031. \[succesor: \002$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))\002 ($tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))]))\]\0031"
			} elseif { $tgranksbyname([strlwr $nick]) < 21&&$tgranksbyname([strlwr $nick]) > 1&&$tgscorestotal>3}  { tggamemsg "[tgcolstrk]\002<> $nick\002 se afla in \002Top20\002, fiind pe locul \002$tgranksbyname([strlwr $nick])\002 cu \002$tgscoresbyname([strlwr $nick])\002 de puncte\0031 \[predecesor: \002$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))\002 ($tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))])) & succesor \002$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))\002 ($tgscoresbyname([strlwr $tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])+1]))]))\0031\]"
			}
		}
	if {$tgplaying==0} { tgastart $chan $nick }
	}
}














#triggered when someone /msgs the bot with the score lookup command.
proc tgscorelookup {nick host hand text} {
	global tgscoresbyname tgranksbyname tgscorestotal tgrealnames
	if {$text==""} { set text $nick } else { set text [lindex [split $text] 0] }
	tggetscores
	if {![info exists tgscoresbyname([strlwr $text])]} {
		if {[strlwr $text]==[strlwr $nick]} {
			set _who "[tgcolmisc1]Esti"
		} else {
			set _who "[tgcolmisc2]$text [tgcolmisc1]nu este"
		}
		[tgpriv] $nick "[tgbold]$_who [tgcolmisc1]pe lista scorurilor."
	} else {
		if {[strlwr $text]==[strlwr $nick]} {
			set _who "[tgcolmisc1]Ai"
		} else {
			set _who "[tgcolmisc2]$tgrealnames([strlwr $text]) [tgcolmisc1]are"
		}
		[tgpriv] $nick "[tgbold]$_who [tgcolmisc2]$tgscoresbyname([strlwr $text])[tgcolmisc1] puncte fiind pe locul[tgcolmisc2] $tgranksbyname([strlwr $text]) [tgcolmisc1]din [tgcolmisc2]$tgscorestotal[tgcolmisc1]."
	}
}

#triggered when someone /msgs the bot with the target lookup command.
proc tgtargetlookup {nick host hand text} {
	global tgscoresbyname tgranksbyname tgscorestotal tgranksbynum tgrealnames
	tggetscores
	if {![info exists tgscoresbyname([strlwr $nick])]} {
		[tgpriv] $nick "[tgbold][tgcolmisc1]You are not on the score list yet."
	} elseif {$tgranksbyname([strlwr $nick])==1} {
		[tgpriv] $nick "[tgbold][tgcolmisc1]You are in first place!"
	} else {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Esti pe [tgcolmisc2]$tgscoresbyname([strlwr $nick])[tgcolmisc1]. Concurentul tau este [tgcolmisc2]$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1])) [tgcolmisc1]cu [tgcolmisc2]$tgscoresbyname($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))[tgcolmisc1], pe locul [tgcolmisc2][expr $tgranksbyname([strlwr $nick])-1] [tgcolmisc1]din [tgcolmisc2]$tgscorestotal[tgcolmisc1]."
	}
}

#triggered when someone /msgs the bot with the error reporting command.
proc tgerror {nick host hand text} {
	global tgquestionstotal tgquestionslist tgerrmethod tgerrfil tgerremail tgerrmailtmp
	if {$text==""||![string is int [lindex [split $text] 0]]} {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Trebuie sa specific numarul intrebarii."
		return
	}
	tgreadqdb
	set _qnum [lindex [split $text] 0]
	if {$_qnum>$tgquestionstotal} {
		[tgpriv] $nick "[tgbold][tgcolmisc1]No such question."
		return
	}
	set _qques [lindex [split [lindex $tgquestionslist [expr $_qnum-1]] |] 1]
	set _qans [lindex [split [lindex $tgquestionslist [expr $_qnum-1]] |] 0]
	set _desc [join [lrange [split $text] 1 end]]
	if {$_desc==""} { set _desc "No further info given for this error." }
	if {$tgerrmethod==1} {
		set _fname $tgerrmailtmp\trivia[rand 100000].tmp
		set _file [open $_fname w]
	} else {
		set _file [open $tgerrfil a]
	}
	puts $_file ""
	puts $_file "Error report generated [strftime %A,\ %d\ %B\ %Y\ @\ %H:%M:%S]"
	puts $_file "Reported by:\t$nick!$host"
	puts $_file "Question #:\t$_qnum"
	puts $_file "Question:\t$_qques"
	puts $_file "Answer:\t\t$_qans"
	puts $_file "Comments:\t$_desc"
	puts $_file "------------------------------"
	close $_file
	if {$tgerrmethod==1} {
		exec mail -s "trivia.tcl error report from $nick" $tgerremail < $_fname
		file delete $_fname
		[tgpriv] $nick "[tgbold][tgcolmisc1]Multumesc! Eroarea a fost raportata."
	} else {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Multumesc! Eroarea a fost raportata."
	}
}

proc tgerror2 {nick host hand chan text} {
	global tgquestionstotal tgquestionslist tgerrmethod tgerrfil tgerremail tgerrmailtmp
	set args [expr [llength $text] - 1]
	if {$args!=2} {
		notice $nick "[fcolor 04]<|Eroare|>: comanda <|[lindex $text 0]|> se foloseste astfel: !gresita <|NUMAR_INTREBARE  DESCRIERE_GRESEALA|>"
		return
	}
	set ReportDescription [join [lrange [split $text] 2 end]]
	set ReportNumber [expr [lindex $text 1] - 1 ]
	if {$ReportNumber!=$::CurrentQuestionNumber&&$ReportNumber!=$::LastQuestionNumber} {
		notice $nick "[fcolor 04]<|Eroare|>: Fie ai specificat un numar de intrebare eronat, fie ai raportat greseala prea tarziu si intrebarea indicata ($ReportNumber) a trecut!"
		return 
		
	}
	set _file [open $tgerrfil a]
	puts $_file ""
	puts $_file "Greseala raportata in data: [strftime %d\/%m\/%Y\ @\ %H:%M:%S]"
	puts $_file "Raportata de: $nick!$host"
	if {$ReportNumber==$::CurrentQuestionNumber} {
		puts $_file "Numarul     : $::CurrentQuestionNumber/$::CurrentQuestionDB"
		puts $_file "Intrebare   : $::CurrentQuestion"
		puts $_file "Raspuns     : $::CurrentQuestionAnswer"
		set ReportDB $::CurrentQuestionDB
	} elseif {$ReportNumber==$::LastQuestionNumber} {
		puts $_file "Numarul     : $::LastQuestionNumber/$::LastQuestionDB"
		puts $_file "Intrebare   : $::LastQuestion"
		puts $_file "Raspuns     : $::LastQuestionAnswer"
		set ReportDB $::LastQuestionDB
	}
	puts $_file "Descriere   : $ReportDescription"
	puts $_file "------------------------------"	
	puts $_file ""
	puts $_file "Greseala raportata in data: [strftime %d\/%m\/%Y\ @\ %H:%M:%S]"
	puts $_file "Raportata de: $nick!$host"
	puts $_file "Numarul     : $::tgquestionnumber/$::qcurrentdb"
	puts $_file "Intrebare   : $::qcurrentquestion"
	puts $_file "Raspuns     : $::tgcurrentanswer"
	puts $_file "Descriere   : $ReportDescription"
	puts $_file "------------------------------"
	close $_file
	say $chan "[fcolor 12]Multumesc pentru raportarea greselii, $nick! (Intrebarea nr. [expr $ReportNumber+1]/$ReportDB)"
	DoUpload $chan $::tgerrfil
}

#triggered when someone /msgs the bot with the rules command.
proc tgrulesmsg {nick host hand text} {
	global tgrules
	[tgpriv] $nick "Regulile canalului: $tgrules"
}

#triggered when someone /msgs the bot with the help command.
proc tggivehelp {nick host hand {text ""}} {
	global botnick tgcmdlookup tgcmdhelp tgcmdstart tgcmdstop tgchan tgflagsstop
	global tgcmdstop tgflagshint tgcmdhint tgflagsskip tgcmdskip tgflagsreset tgcmdreset
	global tgcmdtarget tgcmderror tgcmdrules tgflagsstart
	if {$text==""} {
		[tgpriv] $nick "Ai access la urmatoarele comenzi prin /MSG:"
		[tgpriv] $nick "Pentru a le folosi introdu /MSG $botnick <comanda>"
		[tgpriv] $nick "  \002[strupr $tgcmdrules]\002"
		[tgpriv] $nick "   -- Afiseaza regulile canalului."
		[tgpriv] $nick "  \002[strupr $tgcmdlookup]\002 \[nick\]"
		[tgpriv] $nick "   -- Afiseaza locul si scorul lui \[nick\], daca il specifici."
		[tgpriv] $nick "    In caz contrar iti va afisa propriul loc si scor."
		[tgpriv] $nick "  \002[strupr $tgcmdtarget]\002"
		[tgpriv] $nick "   -- Afiseaza locul si scorul urmatorului jucator"
		[tgpriv] $nick "    cu scor imediat urmator."
		[tgpriv] $nick "  \002[strupr $tgcmderror]\002 <numar> \[descriere\]"
		[tgpriv] $nick "   -- Raporteaza o greseala la intrebarea <numar>"
		[tgpriv] $nick "    Descrierea e optionala dar este de ajutor."
		if {[matchattr $hand $tgflagsreset $tgchan]} {
			[tgpriv] $nick "  \002[strupr $tgcmdreset]\002"
			[tgpriv] $nick "   -- Reseteaza scorul."
		}
		[tgpriv] $nick "Pentru o lista de comenzi pe canal foloseste /MSG $botnick [strupr $tgcmdhelp] PUBCMDS"
	}
	if {[strlwr $text]=="pubcmds"} {
		[tgpriv] $nick "Ai acces la urmatoarele comenzi pe canal:"
		if {[matchattr $hand $tgflagsstart $tgchan]} {
			[tgpriv] $nick "  \002$tgcmdstart\002 -- porneste trivia."
		}
		if {[matchattr $hand $tgflagsstop $tgchan]} {
			[tgpriv] $nick "  \002$tgcmdstop\002 -- opreste trivia."
		}
		if {[matchattr $hand $tgflagshint $tgchan]} {
			[tgpriv] $nick "  \002$tgcmdhint\002 -- afiseaza o sugestie."
		}
		if {[matchattr $hand $tgflagsskip $tgchan]} {
			[tgpriv] $nick "  \002$tgcmdskip\002 -- sare peste intrebarea curenta."
		}
		[tgpriv] $nick "Pentru o lista a comenzilor prin /MSG foloseste /MSG $botnick [strupr $tgcmdhelp]"
	}
}

# Returns text without colour, bold, etc. control codes.
# This is a stripped down version of the proc in MC_8's mc.moretools.tcl.
proc tgstripcodes {text} {
	regsub -all -- "\003(\[0-9\]\[0-9\]?(,\[0-9\]\[0-9\]?)?)?" $text "" text
	set text "[string map -nocase [list \002 "" \017 "" \026 "" \037 ""] $text]"
	return $text
}
proc tggamemsg {what} {
	global tgchan
	putquick "PRIVMSG $tgchan :[tgbold]$what"
}

proc tgbold {} {
	global tgusebold
	if {$tgusebold==1} { return "\002" }
}
proc tgcolstart {} {
	global tgcolourstart
	if {$tgcolourstart!=""} { return "\003$tgcolourstart" }
}
proc tgcolstop {} {
	global tgcolourstop
	if {$tgcolourstop!=""} { return "\003$tgcolourstop" }
}
proc tgcolskip {} {
	global tgcolourskip
	if {$tgcolourskip!=""} { return "\003$tgcolourskip" }
}
proc tgcolerr {} {
	global tgcolourerr
	if {$tgcolourerr!=""} { return "\003$tgcolourerr" }
}
proc tgcolmiss {} {
	global tgcolourmiss
	if {$tgcolourmiss!=""} { return "\003$tgcolourmiss" }
}
proc tgcolqhead {} {
	global tgcolourqhead
	if {$tgcolourqhead!=""} { return "\003$tgcolourqhead" }
}
proc tgcolqbody {} {
	global tgcolourqbody
	if {$tgcolourqbody!=""} { return "\003$tgcolourqbody" }
}
proc tgcolhint {} {
	global tgcolourhint
	if {$tgcolourhint!=""} { return "\003$tgcolourhint" }
}
proc tgcolstrk {} {
	global tgcolourstrk
	if {$tgcolourstrk!=""} { return "\003$tgcolourstrk" }
}
proc tgcolscr1 {} {
	global tgcolourscr1
	if {$tgcolourscr1!=""} { return "\003$tgcolourscr1" }
}
proc tgcolscr2 {} {
	global tgcolourscr2
	if {$tgcolourscr2!=""} { return "\003$tgcolourscr2" }
}
proc tgcolscr3 {} {
	global tgcolourscr3
	if {$tgcolourscr3!=""} { return "\003$tgcolourscr3" }
}
proc tgcolrset {} {
	global tgcolourrset
	if {$tgcolourrset!=""} { return "\003$tgcolourrset" }
}
proc tgcolstend {} {
	global tgcolourstend
	if {$tgcolourstend!=""} { return "\003$tgcolourstend" }
}
proc tgcolmisc1 {} {
	global tgcolourmisc1
	if {$tgcolourmisc1!=""} { return "\003$tgcolourmisc1" }
}
proc tgcolmisc2 {} {
	global tgcolourmisc2
	if {$tgcolourmisc2!=""} { return "\003$tgcolourmisc2" }
}
proc tgcolmisc3 {} {
        global tgcolourmisc3
        if {$tgcolourmisc3!=""} { return "\003$tgcolourmisc3" }
}

proc tgcolmisc4 {} {
        global tgcolourmisc4
        if {$tgcolourmisc4!=""} { return "\003$tgcolourmisc4" }
}
proc tgcolmisc5 {} {
        global tgcolourmisc5
        if {$tgcolourmisc5!=""} { return "\003$tgcolourmisc5" }
}

proc tgpriv {} {
	global tgpriv2msg
	if {$tgpriv2msg==1} { return "putmsg" } else { return "putnotc" }
}


set ttrivia "!trivia"
proc Trivia {nick uhost hand chan text} {
	set name [lindex [info level [info level]] 0]
	set head \[\002$name\002\]
	set tcol1 "\00312\002"
	set tcol1b "\00302\002"
	set tcol2 "\00301\002"
	set tt ""
	tggetscores
	tgreadqdb
	set _teams [expr $::Total(Teams)==1?"echipa":"echipe"]
	set _indiv [expr $::Total(Individuals)==1?"individual":"individuali"]
	append tt0 "Suntem in etapa a $tcol1$::EtapaCurenta$tcol2-a, avem $tcol1$::Total(General)$tcol2[expr $::Total(General)>19?" de":""] [expr $::Total(General)==1?"jucator":"jucatori"] ($tcol1$::Total(Teams)$tcol2 $_teams, $tcol1$::Total(Individuals)$tcol2 $_indiv) contra $tcol1$::qtotal$tcol2 de intrebari"
	append tt "Am pus $tcol1[GetSet intp]$tcol2 intrebari si am primit $tcol1[GetSet intc]$tcol2 raspunsuri corecte."
	append tt " Am oferit $tcol1[GetSet bonusuri]$tcol2 bonusuri (maxim: $tcol1b$::bpts$tcol2 ciclu: $tcol1b$::bcy$tcol2)."
	append tt " Recordul de viteza este detinut de $tcol1[lindex [GetSet speed] 0]$tcol2 cu $tcol1[lindex [GetSet speed] 1]$tcol2 secunde."
	append tt " Recordul in raspunsuri corecte consecutive il detine $tcol1[lindex [GetSet consec] 0]$tcol2 cu $tcol1[lindex [GetSet consec] 1]$tcol2 raspunsuri."
	set LastRegistered [GetSet LastRegistered]
	if {$LastRegistered==0} { set LastRegistered "<|n/a|>" } else {
		set LastRegistered [split $LastRegistered ";"]
		set LastRegistered "<|[lindex $LastRegistered 0]|> ([lindex $LastRegistered 1])"
	}
	set LastRegisteredTeam [GetSet LastRegisteredTeam]
	if {$LastRegisteredTeam==0} { set LastRegisteredTeam "<|n/a|>" } else {
		set LastRegisteredTeam [split $LastRegisteredTeam ";"]
		set LastRegisteredTeam "<|[lindex $LastRegisteredTeam 0]|> de <|[lindex $LastRegisteredTeam 1]|> ([lindex $LastRegisteredTeam 2])"
	}	
	set tt2 "Ultimele inregistrari - nume de jucator: $LastRegistered; - nume de echipa: $LastRegisteredTeam."
	tggamemsg "$head \002Statistici\002: $tt0"
	tggamemsg "$head \002Statistici\002: $tt"
	tggamemsg "$head \002Statistici\002: [textparse $tt2]"
}
bind pub - $ttrivia Trivia



putlog "========================================="
putlog "* Homicide Trivia $tgrel $tgver incarcata"
putlog "* Trivia personalizata de WSergio pentru #Homicide (efnet)"
putlog "* $::settings(web1) :: $::settings(web2)"
putlog "========================================="
