###################################################################
#
#-----------============= Solid Services =============-------------
#                     www.solidservices.ro
#                   #solidservices @Undernet
#
###################################################################
#bine ati venit!ati ajuns in faza in care trebuie sa precizati    #
#unde se va juca trivia  | modificati mai jos in loc de #canal    #
#puneti canalul unde vreti sa jucati trivia                       #                  
###################################################################

set tgchan "#BlueCat"

##################################################################
#                                                                #
#daca ati modificat canalul mai trebuie sa salvati modificarile! #
# nu este necesar sa faceti alte modificari daca nu prea stiti   #
# programare TCL                                                 #
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# salvarea modificarilor se face apasand tastele CTRL + X        #
# apoi apasati Y apoi tasta ENTER                                #
# EGGDROPUL de trivie va porni cu datele introduse de Dvs        #
#                                                                #
##################################################################







set tgpointsperanswer 20
set tgmaxhint 3
set tgqdb "scripts/intrebari"
set tgqdbsep "*"
set tgqdbquestionfirst 1
set tgscf "scripts/trivia.score"
set tgerrmethod 0
set tgerrfil "scripts/trivia.errors"
set tgerremail "none@none.com"
set tgerrmailtmp "/tmp"
set tghtmlfile "public_html/mychan.html"
set tghtmlrefresh 0
set tghtmlfont "verdana,helvetica,arial"
set tgalwaysshowq 0
set tgcapsquestion 0
set tgcapsanswer 0
set tgcapshint 0
set tgstreakmin 3
set tgmaxmissed 0
set tgcongrats [list "Norocosule" "Bine gandit" "Ce norocos esti" "Bun asa" "Raspuns corect" "Ma uimesti" "Bineee" "Bravo"]
set tgnobodygotit [list "Nimeni n`are noroc." "Bahh!!!Mai traieste cineva?" "Mai bagatzi o fisa si mai incerctazi odata!" "Nu stie nimeni?" "Ce frumos e sa intrebi si sa nu primesti raspuns"]
set tgtrythenextone [list "Ia sa vad daca sunteti in stare sa raspundeti la urmatoarea..." "Sunt Pregatit sa ma uimitzi la urmatoarea intrebare..." "Off, hai ca va mai dau o shansa" "Hai ca mai vine una :P "]
set tgtimeanswer 1
set tgshowanswer 1
set tgshowallscores 0
set tgusebold 0
set tgpriv2msg 1
set tgcmdhelp "?"
set tgcmdstart "!start"
set tgflagsstart "-|-"
set tgcmdstop "!stop"
set tgflagsstop "-|-"
set tgcmdhint "!hint"
set tgflagshint "-|-"
set tgtempnohint 4
set tgcmdskip "!skip"
set tgflagsskip "o|o"
set tgcmdtop10 "!top10"
set tgflagstop10 "-|-"
set tgcmdreset "!reset"
set tgflagsreset "o|o"
set tgresetreqpw 1
set tgcmdlookup "score"
set tgcmdtarget "target"
set tgcmderror "error"
set tgcmdrules "rules"
set tgrules "Nu injura, nu te purta urat cu ceilalti, respecta operatorii, nu floda.Aici e tirania cozi de maimutza. Have fun. :-)"
set tgerrremindtime 15
set tghintchar "*"
set tgtimehint 15
set tgtimenext 10

#  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

set tgcolourstart "13"          ;#Game has started.
set tgcolourstop "06"           ;#Game has stopped.
set tgcolourskip "10"           ;#Question has been skipped.
set tgcolourerr "02"            ;#How to report errors.
set tgcolourmiss "01"           ;#Nobody answered the question.
set tgcolourqhead "10"          ;#Question heading.
set tgcolourqbody "00,04"          ;#Question text
set tgcolourhint "04"           ;#Hint.
set tgcolourstrk "00,12"           ;#Person is on a winning streak.
set tgcolourscr1 "02"           ;#Score of person in first place.
set tgcolourscr2 "12"           ;#Score of person in second place.
set tgcolourscr3 "03"           ;#Score of person in third place.
set tgcolourrset "04"           ;#Scores have been reset.
set tgcolourstend "12"          ;#Winning streak ended.
set tgcolourmisc1 "03"          ;#Miscellaneous colour #1.
set tgcolourmisc2 "12"          ;#Miscellaneous colour #2.


# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                   #
#    Any editing done beyond this point is done at your own risk!   #
#                                                                   #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#Misc checks & var initialisations
set tgver "by #BlueCat"
set tgrel "Trivia by #BlueCat!"
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."
	return
}
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 trivia.tcl $tgver ($tgrel) from www.eggdrop.za.net)"
	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 join -|- "$tgchan *" tgjoinmsg
bind msg - $tgcmdhelp tggivehelp
bind msg - $tgcmdlookup tgscorelookup
bind msg - $tgcmdtarget tgtargetlookup
bind msg - $tgcmderror tgerror
bind msg - $tgcmdrules tgrulesmsg
bind msg $tgflagsreset "$tgcmdreset" tgresetscores
bind kick - "$tgchan $botnick" tgbotgotkicked
bind evnt - disconnect-server tgbotgotdisconnected

#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]Multumesc pentru !start $nick. Trivia incepe. Trivia by #solidservices !"
			tgnextq
			set tgplaying 1
			set tgstreak 0
			set tgmissed 0
			set tgerrremindtimer [timer $tgerrremindtime tgerrremind]
		}
	}
}

#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]Trivia a fost oprita de $nick. Trivia powered by www.solidservices.ro"
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
			set tgstreak 0
			set tgplaying 0
			catch {unbind pubm -|- "$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]Se sare la urmatoarea intrebare ca asha vrea [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 -|- "$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 "[tgcolerr]Anuntz: pentru a raporta erori, scrieti /msg $botnick $tgcmderror <numar> \[descriere\]"
	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 -|- "$tgchan *" tgcheckanswer}
		if {[utimerexists tghint]!=""} {killutimer $tghinttimer}
		if {[utimerexists tgnextq]!=""} {killutimer $tgnextqtimer}
		if {[timerexists tgerrremind]!=""} {killtimer $tgerrremindtimer}
		if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
	}
}

#reads the question database.
proc tgreadqdb {} {
	global tgqdb tgquestionstotal tgquestionslist
	set tgquestionstotal 0
	set tgquestionslist ""
	set qfile [open $tgqdb r]
	set tgquestionslist [split [read -nonewline $qfile] "\n"]
	set tgquestionstotal [llength $tgquestionslist]
	close $qfile
}

#selects the next question.
proc tgnextq {} {
	global tgqdb tgcurrentquestion tgcurrentanswer tgquestionnumber
	global tgquestionstotal tghintnum tgchan tgquestionslist tgqdbsep tgqdbquestionfirst
	global tgcapsquestion tgcapsanswer
	tgreadqdb
	set tgcurrentquestion ""
	set tgcurrentanswer ""
	while {$tgcurrentquestion == ""} {
		set tgquestionnumber [rand [llength $tgquestionslist]]			
		set tgquestionselected [lindex $tgquestionslist $tgquestionnumber]
		set tgcurrentquestion [lindex [split $tgquestionselected $tgqdbsep] [expr $tgqdbquestionfirst^1]]
		if {$tgcapsquestion==1} {
			set tgcurrentquestion [strupr $tgcurrentquestion]
		}
		set tgcurrentanswer [string trim [lindex [split $tgquestionselected $tgqdbsep] $tgqdbquestionfirst]]
		if {$tgcapsanswer==1} {
			set tgcurrentanswer [strupr $tgcurrentanswer]
		}
	}
	unset tghintnum
	tghint
	bind pubm -|- "$tgchan *" tgcheckanswer
	return
}

#shows timed hints.
proc tghint {} {
	global tgmaxhint tghintnum tgcurrentanswer tghinttimer tgchan
	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 {[catch {incr tghintnum}]!=0} {
		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]
		}
	}
	if {$tghintnum >= [expr $tgmaxhintcurrent+1]} {
		incr tgmissed
		set _msg ""
		append _msg "[tgcolmiss][lindex $tgnobodygotit [rand [llength $tgnobodygotit]]]"
		if {$tgshowanswer==1} {
			append _msg " Raspunsul era : [tgcolmisc2]$tgcurrentanswer[tgcolmiss]."
		}
		if {$tgmaxmissed>0&&$tgmissed>=$tgmaxmissed} {
			append _msg " Este intrebarea cu nr $tgmissed care a fost neraspunsa! Jocul este inchis automat.Pentru a porni scrieti $tgcmdstart"
			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 -|- "$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]/$tgquestionstotal [expr $tghintnum?"(Hint $tghintnum/$tgmaxhintcurrent)":""] "
	if {$tgalwaysshowq==1||$tghintnum==0} {
		tggamemsg "[tgcolqbody]$tgcurrentquestion"
	}
	tggamemsg "[tgcolhint]Indiciu: [join $_hint]"
	set tghinttimer [utimer $tgtimehint tghint]
}

#triggered when someone uses !top10 command
proc tgshowtop10 {nick host hand chan text} {
	global tgscores tgchan tgscorestotal
	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]]
				if {$i==0} {
					append _scores "[tgcolscr1]$_nick $_score"
				} elseif {$i==1} {
					append _scores ", [tgcolscr2]$_nick $_score"
				} elseif {$i==2} {
					append _scores ", [tgcolscr3]$_nick $_score"
				} else {
					append _scores ", [tgcolmisc1]$_nick $_score"
				}
				incr i
			}
			tggamemsg "[tgcolmisc1]Primi 10 dexteri : $_scores"
		} else {
			tggamemsg "[tgcolmisc1]Score Lista cu scoruri e goala."
		}
	}
}

#checks if anyone has said the correct answer on channel.
proc tgcheckanswer {nick host hand chan text} {
	global tgcurrentanswer
	if {[strlwr $tgcurrentanswer] == [tgstripcodes [strlwr [string trim $text]]]} {
		tgcorrectanswer $nick
	}
}

#triggered when someone says the correct answer.
proc tgcorrectanswer {nick} {
	global tgcurrentanswer tghinttimer tgtimenext tgchan tgnextqtimer tgstreak tgstreakmin
	global tgscoresbyname tgranksbyname tgranksbynum tgcongrats tgscorestotal tgmissed
	global tgtimestart tgshowallscores tgrealnames tgscoresbyrank tgtimeanswer
	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 _msg "[tgcolmisc1][lindex $tgcongrats [rand [llength $tgcongrats]]] [tgcolmisc2]$nick[tgcolmisc1]! Raspunsul era [tgcolmisc2]$tgcurrentanswer[tgcolmisc1].[expr $tgtimeanswer==1?" Ai nimerit-o in [tgcolmisc2]$_timetoanswer[tgcolmisc1] secunde.":""]"
	if {$_newrank<$_oldrank} {
		if {$_newrank==1} {
			append _msg " Acum esti pe locul intâi!"
		} else {
			if {$tgshowallscores==0} {
				append _msg " Ai urcat o pozitie in top , dar mai ai pana la primul loc!"
			} else {
				append _msg " Acum esti pe locul [tgcolmisc2][ordnumber $tgranksbyname([strlwr $nick])][tgcolmisc1] din [tgcolmisc2]$tgscorestotal[tgcolmisc1], in urma lui [tgcolmisc2]$tgrealnames($tgranksbynum([expr $_newrank-1]))[tgcolmisc1] cu [tgcolmisc2]$tgscoresbyrank([expr $_newrank-1])[tgcolmisc1] ."
			}
		}
	}
	tggamemsg "$_msg"
	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} {
				tggamemsg "[tgcolstrk][tgcolmisc2]$nick[tgcolstrk] e multiplu castigator! [tgcolmisc2][lindex [split $tgstreak ,] 1] [tgcolstrk] raspunsuri la rand ! Bravo creiere ;)"
			}
		} else {
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
			set tgstreak [strlwr $nick],1
		}
	} else {
		set tgstreak [strlwr $nick],1
	}
	set tgmissed 0
	tgshowscores $nick
	catch {unbind pubm -|- "$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+$tgpointsperanswer],[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 ", si se afla in urma lu` [tgcolmisc2]$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))[tgcolmisc1] care are [tgcolmisc2]$tgscoresbyrank([expr $tgranksbyname([strlwr $nick])-1])[tgcolmisc1] ."
		}
		tggamemsg "[tgcolmisc2]$nick [tgcolmisc1]acum are [tgcolmisc2]$tgscoresbyname([strlwr $nick]) [tgcolmisc1][expr $tgscoresbyname([strlwr $nick])==1?"punct":"puncte"] si e pe locul [tgcolmisc2][ordnumber $tgranksbyname([strlwr $nick])] [tgcolmisc1]din [tgcolmisc2]$tgscorestotal[tgcolmisc1]$_tgt"
	}
}

#reset current scores.
proc tgresetscores {nick host hand text} {
exec rm -rf scripts/trivia.score
exec touch scripts/trivia.score
}

#triggered when a winning streak ends.
proc tgstreakend {} {
		global tgstreak tgrealnames
		tggamemsg "[tgcolstend]Cam atat pentru [tgcolmisc2]$tgrealnames([lindex [split $tgstreak ,] 0]) [tgcolstend] castigator a multe intrebari la rand."
		return
}
proc tgjoinmsg {nick host hand chan} {
        global botnick tgplaying tgcmdhelp tgcmdstart tgflagsstart tgcmdstop tgflagsstop tgchan
        if {$nick != $botnick} {
                set _msg ""
                append _msg "Bine ai venit pe canalul  $chan . Fii in top Trivia ca nici nu stii ce te asteapta. Momentan Trivia este "
                if {$tgplaying==1} {
                        append _msg " \002pornita\002."
                } else {
                        append _msg " \002oprita\002."
                }
                if {[matchattr $hand $tgflagsstart $tgchan]&&$tgplaying==0} {
                        append _msg " Pentru a porni jocul, scrie \002$tgcmdstart\002 pe canalul $tgchan."
                }
                append _msg " Scrie \002/MSG $botnick [strupr $tgcmdhelp]\002 daca ai nevoie de ajutor , sau apeleaza la un operator on line. Distractie placuta si bafta la puncte (Nu uita : Best IRC Shell Provider \00312#Solidservices\003 . Enjoy:-)"
                [tgpriv] $nick "$_msg"
        }
}
#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]is"
		}
		[tgpriv] $nick "[tgbold]$_who [tgcolmisc1] nu este in lista de scoruri."
	} 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, locul [tgcolmisc2][ordnumber $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]Nu esti in lista de scoruri inca."
	} elseif {$tgranksbyname([strlwr $nick])==1} {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Esti cel mai voinic de pe canal , primu`n top!"
	} else {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Esti pe locul [tgcolmisc2]$tgscoresbyname([strlwr $nick])[tgcolmisc1]. Tinta ta este [tgcolmisc2]$tgrealnames($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1])) [tgcolmisc1]cu [tgcolmisc2]$tgscoresbyname($tgranksbynum([expr $tgranksbyname([strlwr $nick])-1]))[tgcolmisc1], locul [tgcolmisc2][ordnumber [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 specificat numarul intrebarii!."
		return
	}
	tgreadqdb
	set _qnum [lindex [split $text] 0]
	if {$_qnum>$tgquestionstotal} {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Intrebare inexistenta."
		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 "Nu exista detalii privind eroarea" }
	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]Mersi! Eroarea raportata de tine este trimisa sefului!"
	} else {
		[tgpriv] $nick "[tgbold][tgcolmisc1]Mersi! Ma voi uita cit de repede pot pe eroare!"
	}
}

#triggered when someone /msgs the bot with the rules command.
proc tgrulesmsg {nick host hand text} {
	global tgrules
	[tgpriv] $nick "Regulile canalului sunt: $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 acces la urmatoarele comenzi:"
		[tgpriv] $nick "Sa folosesti, /MSG $botnick <command>"
		[tgpriv] $nick "  \002[strupr $tgcmdrules]\002"
		[tgpriv] $nick "   -- Regulile canalului."
		[tgpriv] $nick "  \002[strupr $tgcmdlookup]\002 \[nick\]"
		[tgpriv] $nick "   -- Arata locul si scorul \[nick\], daca este specificat,"
		[tgpriv] $nick "    in caz contrar arata scorul si pozitia ta."
		[tgpriv] $nick "  \002[strupr $tgcmdtarget]\002"
		[tgpriv] $nick "   -- Arata scorul si locul"
		[tgpriv] $nick "    celui din fata ta."
		[tgpriv] $nick "  \002[strupr $tgcmderror]\002 <number> \[description\]"
		[tgpriv] $nick "   -- Raporteaza eroare in cazul intrebarii <number>"
		[tgpriv] $nick "    Descrierea nu este obligatorie, dar ajutatoare"
		if {[matchattr $hand $tgflagsreset $tgchan]} {
			[tgpriv] $nick "  \002[strupr $tgcmdreset]\002"
			[tgpriv] $nick "   -- Reseteaza tabelul de scoruri."
		}
		[tgpriv] $nick "Pentru lista comenzilor publice , /MSG $botnick [strupr $tgcmdhelp] PUBCMDS"
	}
	if {[strlwr $text]=="pubcmds"} {
		[tgpriv] $nick "Ai acces la urmatoarele comenzi publice:"
		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 -- Hint."
		}
		if {[matchattr $hand $tgflagsskip $tgchan]} {
			[tgpriv] $nick "  \002$tgcmdskip\002 -- sare peste intrebare."
		}
		[tgpriv] $nick "Pentru o lista a comenzilor private, /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 tgpriv {} {
	global tgpriv2msg
	if {$tgpriv2msg==1} { return "putmsg" } else { return "putnotc" }
}

#this generates an html file with all the people on the chan with
#their score, as well as a list of all scores, sorted by rank
proc tghtml {} {
	global tgchan botnick tghtmlfile tghtmlrefresh server tgscoresbyname tgranksbyname
	global tgscorestotal tgranksbyname tgrealnames tgscoresbyrank tgranksbynum tgplaying
	global tgquestionstotal tghtmlrefreshtimer tghtmlfont
	tggetscores
	tgreadqdb
	set _file [open $tghtmlfile~new w]
	puts $_file "<!DOCTYPE HTML PUBLIC \"-/W3C/DTD HTML 4.01 Transitional/EN\">"
	puts $_file "<html>"
	puts $_file " <head>"
	puts $_file "  <title>$botnick's trivia channel: $tgchan on [lindex [split $server :] 0]</title>"
	puts $_file "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
	puts $_file "  <meta http-equiv=\"refresh\" content=\"$tghtmlrefresh\">"
	puts $_file "  <meta name=\"generator\" content=\"trivia.tcl script for eggdrop. http://www.eggdrop.za.net/\">"
	puts $_file "  <style type=\"text/css\">"
	puts $_file "  <!--"
	puts $_file "  body,td{font-family:$tghtmlfont;font-size:13px;}"
	puts $_file "  a{text-decoration:none;color:#09f;}"
	puts $_file "  -->"
	puts $_file "  </style>"
	puts $_file " </head>"
	puts $_file " <body>"
	puts $_file "  <h1>$tgchan on [lindex [split $server :] 0]</h1>"
	puts $_file "  <hr size=\"1\" noshade>"
	if {![onchan $botnick $tgchan]} {
		puts $_file "  <p>Hmmm... for some reason I'm not on $tgchan at the moment. Please try again later.</p>"
	} else {
		puts $_file "  <p>Trivia game is currently <b>[expr $tgplaying==1?"on":"off"]</b>. There are <b>$tgquestionstotal</b> questions in the database."
		puts $_file "  <p>People on $tgchan right now:<br>"
		puts $_file "  <table width=\"50%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\"><tr><td><table width=\"100%\" cellspacing=\"3\" border=\"0\">"
		puts $_file "   <tr>"
		puts $_file "    <td><b>Nick</b></td>"
		puts $_file "    <td><b>Score</b></td>"
		puts $_file "    <td><b>Rank</b></td>"
		puts $_file "    <td><b>Idle</b></td>"
		puts $_file "   </tr>"
		foreach nick [lsort [chanlist $tgchan]] {
			puts $_file "   <tr>"
			puts $_file "    <td>[expr [isop $nick $tgchan]?"@":""][expr [isvoice $nick $tgchan]?"+":""]$nick[expr [string match $nick $botnick]?" (that's me!)":""]</td>"
			if {[info exists tgscoresbyname([strlwr $nick])]} {
				puts $_file "    <td>$tgscoresbyname([strlwr $nick])</td>"
			} else {
				puts $_file "    <td>-</td>"
			}
			if {[info exists tgranksbyname([strlwr $nick])]} {
				puts $_file "    <td>$tgranksbyname([strlwr $nick])</td>"
			} else {
				puts $_file "    <td>-</td>"
			}
			puts $_file "   <td>[expr [getchanidle $nick $tgchan]>10?"[getchanidle $nick $tgchan]m":"-"]</td>"
			puts $_file "   </tr>"
		}
		puts $_file "  </table></td></tr></table>"
	}
	if {$tgscorestotal>0} {
		puts $_file "  <p><small>There [expr $tgscorestotal==1?"is":"are"] currently <b>$tgscorestotal</b> [expr $tgscorestotal==1?"nick":"nicks"] in the score table:<br>"
		set _rank 1
		while {$_rank<=$tgscorestotal} {
			puts $_file "  <b>$_rank</b>. $tgrealnames($tgranksbynum($_rank)) $tgscoresbyrank($_rank)<br>"
			incr _rank
		}
	} else {
		puts $_file "  <p><small>There are currently no nicks in the score table.<br>"
	}
	puts $_file "  </small></p>"
	puts $_file "  <hr size=\"1\" noshade>"
	puts $_file "  <small>Generated on [strftime %A,\ %d\ %B\ %Y\ @\ %H:%M:%S] by <a href=\"http://www.eggdrop.za.net/\">trivia.tcl</a> for <a href=\"http://www.eggheads.org\">eggdrop</a>.<br>"
	puts $_file "  This page is automatically updated (and refreshed if supported by your browser) every [expr $tghtmlrefresh==1?"secunda":"$tghtmlrefresh secunde"].</small>"
	puts $_file " </body>"
	puts $_file "</html>"
	close $_file
	file rename -force $tghtmlfile~new $tghtmlfile
	set tghtmlrefreshtimer [utimer $tghtmlrefresh tghtml]
}

putlog "======================================================="
putlog "* trivia.tcl $tgver ($tgrel) loaded."
tgreadqdb
putlog "* $tgquestionstotal questions in $tgqdb ([file size $tgqdb] bytes)"
putlog "======================================================="
