--------------------- Polite Notice ---------------------
-- YaLB was created by Daniel Astbury (jnz)            --
-- The source is avaliable to anyone, however          --
-- please do not take it can claim it yours.           --
-- Please follow my example and release your own cool  --
-- stuff!                                              --
-----------------------Thank you-------------------------


Commands = {}
Command = {Name = "", Triggers = "", Triggered = nil, IRC_Triggered = nil, Group = "", Help = ""}
    
function Command:new (o)
	o = o or {}
	setmetatable(o, self)	
	self.__index = self
	return o
end

function Add_Command(cName, cTriggered, cIRC_Triggered)
	local c = Command :new({Name = cName, Triggered = cTriggered, IRC_Triggered = cIRC_Triggered})	
	table.insert(Commands, c)
end

function Load_Command_Settings()
	if Settings.Next_Level['Commands'] ~= nil then
		for i,v in pairs(Settings.Next_Level['Commands'].Next_Level) do
			for key,value in pairs(Commands) do 
				if value.Name == i then
					value.Triggers = v.Keys['trigger']
					value.Help = v.Keys['help']
					value.Group = v.Keys['group']
				end
			end
		end
	end
end

function Remove_Command(cName)
	for key,value in pairs(Commands) do
		if value.Name == cName then
			table.remove(Commands, key)
		end
	end
end

function Remove_All_Commands()
	for key,value in pairs(Commands) do
		table.remove(Commands, key)
	end
end



function ChatMessage(PlayerId, Type, Message, Target)
	if Type == 2 or Players[PlayerId].Shunned then
		return 1
	end

	for key, value in pairs(Commands) do
		for word in string.gmatch(value.Triggers, "[^;]+") do 
			if string.lower(word) == string.lower(string.match(Message, "[^%s]+")) then
				if Command_Allowed(PlayerId, false, value, "") == true then
					value.Triggered(PlayerId, Type, Message, Target)
					return 0
				else
					PPage(PlayerId, "You do not have the appropriate permission to use that command.")
					return 1
				end
			end	
		end
	end
	local mute = Players[PlayerId].Muted
	if mute == 0 then
		mute = 1
	else
		mute = 0
	end
	return mute
end

function IRC_Command_Chat(Nick, Channel, Message)
	for key, value in pairs(Commands) do
		for word in string.gmatch(value.Triggers, "[^;]+") do 
			if string.lower(word) == string.lower(string.match(Message, "[^%s]+")) then
				if value.IRC_Triggered == nil then
					IRC_Send(Channel, "%s is game-only.", string.match(Message, "[^%s]+"))
				else
					if Command_Allowed(Nick, true, value, Channel) == true then
						value.IRC_Triggered(Nick, Channel, Message)
					else
						local stat = Status_Level(value.Group)
						if stat > 0 and stat <= Status_Level(Get_IRC_Status(Nick, Channel)) then
							value.IRC_Triggered(Nick, Channel, Message)
						else
							IRC_Send(Channel, "You do not have the appropriate permission to use that command.")
						end
					end
				end
			end	
		end
	end
end


function test_Game_Trigger(PlayerId, Type, Message, Target) 
	Console_Input(string.format("msg Hello %s", Get_Player_Name_By_ID(PlayerId))) 
end

function test_Trigger(Nick, Channel, Message)
	IRC_Send(Channel, "Hello %s!", Nick)
end

Add_Command("test", test_Game_Trigger, test_Trigger)

function help_Game_Trigger(PlayerId, Type, Message, Target)
	local com = string.match(Message, "%S+%s+([^\r\n]+)")
	if com == nil then
		local str_help = "Commands for " .. Get_Player_Name_By_ID(PlayerId) .. ": "
		tmp = 0
		for key, value in pairs(Commands) do
			if value.Triggered ~= nil and Command_Allowed(PlayerId, false, value, "") then
				if tmp == 1 and str_help ~= "" then
					str_help = str_help .. ", "
				else
					tmp = 1
				end
				str_help = str_help .. string.match(value.Triggers, "[^;]+")
				if string.len(str_help) > 50 then
					PPage(PlayerId, str_help)
					str_help = ""
				end
			end
		end
		if str_help ~= "" then
			PPage(PlayerId, str_help)
		end
	else
		for key, value in pairs(Commands) do
			for word in string.gmatch(value.Triggers, "[^;]+") do 
				if string.lower(word) == string.lower(com) then
					PPage(PlayerId, "%s", value.Help)
					return
				end	
			end
		end
	end
end

function help_IRC_Trigger(Nick, Channel, Message)
	local com = string.match(Message, "%S+%s+([^\r\n]+)")
	if com == nil then
		local str_help = "Commands for " .. Nick .. "@IRC: "
		tmp = 0
		for key, value in pairs(Commands) do
			if value.IRC_Triggered ~= nil and Command_Allowed(Nick, true, value, Channel) == true then
				if tmp == 1 and str_help ~= "" then
					str_help = str_help .. ", "
				else
					tmp = 1
				end
				str_help = str_help .. string.match(value.Triggers, "[^;]+")
				if string.len(str_help) > 50 then
					IRC_Send(Channel, str_help)
					str_help = ""
				end
			end
		end
		if str_help ~= "" then
			IRC_Send(Channel, str_help)
		end
	else
		for key, value in pairs(Commands) do
			for word in string.gmatch(value.Triggers, "[^;]+") do 
				if string.lower(word) == string.lower(com) then
					IRC_Send(Channel, "%s", value.Help)
					return
				end	
			end
		end
	end
end

Add_Command("help", help_Game_Trigger, help_IRC_Trigger)

function lua_Game_Trigger(PlayerId, Type, Message, Target)
	local str = string.match(Message, "%a+%s(.+)")
	if str == nil then
		IRC_Send(Channel, "!lua <Chunk>")
		return
	end
	local proc, err = loadstring(str)
	if proc == nil then
		Console_Input(string.format("msg %s", err))
	else
		local status, err = pcall(proc)
		if err then
			Console_Input(string.format("msg %s", err))
		end 
	end
end

function lua_IRC_Trigger(Nick, Channel, Message)
	local str = string.match(Message, "%a+%s(.+)")
	if str == nil then
		IRC_Send(Channel, "!lua <Chunk>")
		return
	end
	local proc, err = loadstring(str)
	if proc == nil then
		IRC_Send(Channel, "%s", err)
	else
		local status, err = pcall(proc)
		if err then
			IRC_Send(Channel, "%s", err)
		end 
	end
end

Add_Command("lua", lua_Game_Trigger, lua_IRC_Trigger)


function message_IRC_Trigger(Nick, Channel, Message)
	local Msg = string.match(Message, "%a+%s([^\r\n]+)%s$")
	if Msg == nil then
		IRC_Send(Channel, "!msg <Message>")
		return
	end
	Console_Input(string.format("msg (%s@IRC): %s", Nick, Msg))
end

Add_Command("message", nil, message_IRC_Trigger)

function gameinfo_IRC_Trigger(Nick, Channel, Message)
	local gdi = 0
	local nod = 0
	local gdiscore = 0
	local nodscore = 0
	
	local pTable = Get_All_Players()
	for i,p in pairs(pTable) do
		local team = Get_Team(p)
		if team == 0 then
			nod = nod + 1
			nodscore = nodscore + Get_Score(p)
		elseif team == 1 then
			gdi = gdi + 1
			gdiscore = gdiscore + Get_Score(p)
		end
	end
	
	local time_left = "No time limit."
	if The_Game().TimeLimit_Minutes ~= 0 then
		local currtimeleft = os.date("*t", GetTimeRemaining())
		time_left = string.format("%d:%d:%d", currtimeleft.hour, currtimeleft.min, currtimeleft.sec)
	end
	
	IRC_Send(Channel, "%s11Map: %s15%s %s08GDI: players:%d  points:%d  %s04Nod players:%d points:%d  %s11Time: %s15%s%s", string.char(3), string.char(3), string.match(Get_Current_Map(), "C&C_([^.]+).mix"), string.char(3), gdi, gdiscore, string.char(3), nod, nodscore, string.char(3), string.char(3), time_left, string.char(3))
end

Add_Command("gameinfo", nil, gameinfo_IRC_Trigger)

function vehiclelist_IRC_Trigger(Nick, Channel, Message)
	local str = ""
	local pTable = Get_All_Vehicles()
	for i,veh in pairs(pTable) do
		if Get_Vehicle_Mode(veh) ~= 4 then
			local team = Get_Object_Type(veh)
			local colour = 15
			if team == 0 then
				colour = 4
			elseif team == 1 then
				colour = 8
			end
			
			str = string.format("%s%s%.2d%s (%d%%)%s ", str, string.char(3), colour, Get_Translated_Preset_Name(veh), ((Get_Health(veh) + Get_Shield_Strength(veh)) / (Get_Max_Health(veh) + Get_Max_Shield_Strength(veh))*100), string.char(3))
		end
		if string.len(str) > 50 then
			IRC_Send(Channel, "%s", str)
			str = ""
		end
	end
	
	if str ~= "" then	
		IRC_Send(Channel, "%s", str)
	end
end

Add_Command("vehiclelist", nil, vehiclelist_IRC_Trigger)


function buildinglist_IRC_Trigger(Nick, Channel, Message)
	local str = ""
	local pTable = Get_All_Buildings()
	for i,bld in pairs(pTable) do
		local team = Get_Object_Type(bld)
		local colour = 15
		if team == 0 then
			colour = 4
		elseif team == 1 then
			colour = 8
		end
		
		str = string.format("%s%s%.2d%s (%d%%)%s ", str, string.char(3), colour, Get_Translated_Preset_Name(bld), ((Get_Health(bld) + Get_Shield_Strength(bld)) / (Get_Max_Health(bld) + Get_Max_Shield_Strength(bld))*100), string.char(3))
	
		if string.len(str) > 50 then
			IRC_Send(Channel, "%s", str)
			str = ""
		end
	end
	
	if str ~= "" then
		IRC_Send(Channel, "%s", str)
	end
end

Add_Command("buildinglist", nil, buildinglist_IRC_Trigger)

function setjoin_Game_Trigger(PlayerId, Type, Message, Target)
	Players[PlayerId].JoinMsg = string.match(Message, "%a+%s([^\r\n]+)%s$")
	PPage(PlayerId, "Your join message has been set.")
end

Add_Command("setjoin", setjoin_Game_Trigger, nil)

function seen_db_callback(userdata, argc, data, column)
	for k,v in pairs(data) do
		if column[k] == "COUNT(*)" then
			if v == "0" then
				IRC_Send(userdata, "Nick not found.")
			end
		end
		
		if column[k] == "LastSeen" then
			IRC_Send(userdata, "Player last seen on %s", os.date("%d %b %Y %H:%M:%S", tonumber(v)))
		end
		
	end	
end

function seen_IRC_Trigger(Nick, Channel, Message)
	local pq = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pq == nil then
		IRC_Send(Channel, "!seen <Player>")
	end
	db:Query(Channel, "seen_db_callback", string.format("SELECT COUNT(*),* FROM Players WHERE Nick = '%s';", pq))
end


Add_Command("seen", nil, seen_IRC_Trigger)

function fds_Game_Trigger(PlayerId, Type, Message, Target)
	local str = string.match(Message, "[^%s]+%s+([^\r\n%S]+)")
	if str == nil then
		PPage(PlayerId, "!fds <command>")
	else
		Console_Input(str)
	end
end

function fds_IRC_Trigger(Nick, Channel, Message)
	local str = string.match(Message, "[^%s]+%s+([^\r\n]+)")
	if str == nil then
		IRC_Send(Channel, "!fds <command>")
	else
		Console_Input(str)
	end
end

Add_Command("fds", fds_Game_Trigger, fds_IRC_Trigger)


gameover_Timer_Obj = 0

function gameover_Game_Trigger(PlayerId, Type, Message, Target)
	local extra = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	local extra_time = 0
	if extra ~= nil then
		for v in string.gmatch(Message, "(%d+%a)") do
			local number = string.match(v, "(%d+).")
			local letter = string.match(v, "%d+(.)")
			if number ~= nil and letter ~= nil then
				if string.lower(letter) == "s" then
					extra_time = extra_time + tonumber(number)
				end
			
				if string.lower(letter) == "m" then
					extra_time = extra_time + (tonumber(number)*60)
				end
			end
		end			
	end
	
	if extra_time > 0 then
		timec = os.date("*t", extra_time)
		local mplural = "s"
		local splural = "s"
		if timec.min == 1 then
			mplural = ""
		end
		
		if timec.sec == 1 then
			splural = ""
		end
		
		if timec.min > 0 and timec.sec > 0 then
			Console_Input(string.format("msg Gameover in %d minute%s, %d second%s.", timec.min, mplural, timec.sec, splural))
		elseif timec.sec > 0 then
			Console_Input(string.format("msg Gameover in %d second%s.", timec.sec, splural))
		elseif timec.min > 0 then
			Console_Input(string.format("msg Gameover in %d minute%s.", timec.min, mplural))
		end
		
		if gameover_Timer_Obj > 0 then
			Destroy_Object(gameover_Timer_Obj)
			gameover_Timer_Obj = 0
		end
		gameover_Timer_Obj = Create_Object("invisible_object", {X=0, Y=0, Z=0})
		
		Attach_Script_Once(gameover_Timer_Obj, "YaLB_Gameover", string.format("%d", extra_time))
	else
		Console_Input("gameover")
	end
end

function gameover_IRC_Trigger(Nick, Channel, Message)
	local extra = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	local extra_time = 0
	if extra ~= nil then
		for v in string.gmatch(Message, "(%d+%a)") do
			local number = string.match(v, "(%d+).")
			local letter = string.match(v, "%d+(.)")
			if number ~= nil and letter ~= nil then
				if string.lower(letter) == "s" then
					extra_time = extra_time + tonumber(number)
				end
			
				if string.lower(letter) == "m" then
					extra_time = extra_time + (tonumber(number)*60)
				end
			end
		end			
	end
	
	if extra_time > 0 then
		timec = os.date("*t", extra_time)
		local mplural = "s"
		local splural = "s"
		if timec.min == 1 then
			mplural = ""
		end
		
		if timec.sec == 1 then
			splural = ""
		end
		
		if timec.min > 0 and timec.sec > 0 then
			Console_Input(string.format("msg Gameover in %d minute%s, %d second%s.", timec.min, mplural, timec.sec, splural))
		elseif timec.sec > 0 then
			Console_Input(string.format("msg Gameover in %d second%s.", timec.sec, splural))
		elseif timec.min > 0 then
			Console_Input(string.format("msg Gameover in %d minute%s.", timec.min, mplural))
		end
		
		if gameover_Timer_Obj > 0 then
			Destroy_Object(gameover_Timer_Obj)
			gameover_Timer_Obj = 0
		end
		gameover_Timer_Obj = Create_Object("invisible_object", {X=0, Y=0, Z=0})
		Attach_Script_Once(gameover_Timer_Obj, "YaLB_Gameover", string.format("%d", extra_time))
	else
		Console_Input("gameover")
	end
end

Add_Command("gameover", gameover_Game_Trigger, gameover_IRC_Trigger)


function version_Game_Trigger(PlayerId, Type, Message, Target)
	PPage(PlayerId, "%s version %s running on %s", LUA_NAME, LUA_VERSION, _VERSION)
end

function version_IRC_Trigger(Nick, Channel, Message)
	IRC_Send(Channel, "%s version %s running on %s", LUA_NAME, LUA_VERSION, _VERSION)
end

Add_Command("version", version_Game_Trigger, version_IRC_Trigger)


function forceteamchange_Game_Trigger(PlayerId, Type, Message, Target)
	local pname = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pname == nil then
		PPage(PlayerId, "Please supply player's name to change teams")
	else
		local p = Find_Player(pname)
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "More than 1 player found.")
		else
			local cteam = Get_Team(p)
			if cteam == 0 then
				cteam = 1
			else
				cteam = 0
			end
			Console_Input(string.format("team2 %d %d", p, cteam))
			PPage(PlayerId, "%s has been changed to team %s.", Get_Player_Name_By_ID(p), Get_Team_Name(cteam))
			PPage(p, "You have been changed to team %s by %s.", Get_Team_Name(cteam), Get_Player_Name_By_ID(PlayerId))
			Apply_Damage(Get_GameObj(p), 999, "BlamoKiller", 0)
		end
	end
end

function forceteamchange_IRC_Trigger(Nick, Channel, Message)
	local pname = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pname == nil then
		IRC_Send(Channel, "Please supply player's name to change teams")
	else
		local p = Find_Player(pname)
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "More than 1 player found.")
		else
			local cteam = Get_Team(p)
			if cteam == 0 then
				cteam = 1
			else
				cteam = 0
			end
			Console_Input(string.format("team2 %d %d", p, cteam))
			IRC_Send(Channel, "%s has been changed to team %s.", Get_Player_Name_By_ID(p), Get_Team_Name(cteam))
			PPage(p, "You have been changed to team %s by %s@IRC.", Get_Team_Name(cteam), Nick)
			
		end
	end
end

Add_Command("forceteamchange", forceteamchange_Game_Trigger, forceteamchange_IRC_Trigger)

function kill_Game_Trigger(PlayerId, Type, Message, Target)
	local w = GetWords(Message)
	if w[2] == nil then
		PPage(PlayerId, "!kill <player> [vehicle|veh]")
	else
		local p = Find_Player(w[2])
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "More than 1 player found.")
		else
			if w[3] ~= nil then
				if string.lower(w[3]) == "veh" or string.lower(w[3]) == "vehicle" then
					local veh = Get_Vehicle(Get_GameObj(p))
					if veh > 0 then
						Apply_Damage(veh, 9999, "BlamoKiller", 0)
						PPage(p, "%s has killed your vehicle.", Get_Player_Name_By_ID(PlayerId))
						PPage(PlayerId, "%s's vehicle has been destroyed.", Get_Player_Name_By_ID(p))
					else
						PPage(PlayerId, "%s is not in a vehicle", Get_Player_Name_By_ID(p))
					end
				else
					PPage(PlayerId, "!kill <player> [vehicle|veh]")
				end
			else
				Apply_Damage(Get_GameObj(p), 9999, "BlamoKiller", 0)
				PPage(p, "%s@IRC has killed you.", Nick)
				PPage(PlayerId, "%s's has been killed.", Get_Player_Name_By_ID(p))
			end
		end	
	end
end

function kill_IRC_Trigger(Nick, Channel, Message)
	local w = GetWords(Message)
	if w[2] == nil then
		IRC_Send(Channel, "!kill <player> [vehicle|veh]")
	else
		local p = Find_Player(w[2])
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "More than 1 player found.")
		else
			if w[3] ~= nil then
				if string.lower(w[3]) == "veh" or string.lower(w[3]) == "vehicle" then
					local veh = Get_Vehicle(Get_GameObj(p))
					if veh > 0 then
						Apply_Damage(veh, 9999, "BlamoKiller", 0)
						PPage(p, "%s@IRC has killed your vehicle.", Nick)
						IRC_Send(Channel, "%s's vehicle has been destroyed.", Get_Player_Name_By_ID(p))
					else
						IRC_Send(Channel, "%s is not in a vehicle", Get_Player_Name_By_ID(p))
					end
				else
					IRC_Send(Channel, "!kill <player> [vehicle|veh]")
				end
			else
				Apply_Damage(Get_GameObj(p), 9999, "BlamoKiller", 0)
				PPage(p, "%s@IRC has killed you.", Nick)
			end
		end	
	end
end

Add_Command("kill", kill_Game_Trigger, kill_IRC_Trigger)

function time_Game_Trigger(PlayerId, Type, Message, Target)
	PPage(PlayerId, "%s", os.date("%X"))
end

function time_IRC_Trigger(Nick, Channel, Message)
	IRC_Send(Channel, "%s", os.date("%X"))
end

Add_Command("time", time_Game_Trigger, time_IRC_Trigger)


function auth_IRC_Trigger(Nick, Channel, Message)
	local Status = Is_Moderator(Nick, true, Channel)
	if Status == nil then
		IRC_Send(Channel, "You are not a moderator.")
	else
		local gnick = Moderator_Game_Nick(Nick)
		local p = Find_Player(gnick)
		if p == -1 then
			IRC_Send(Channel, "You are not in-game.")
		else
			local ircStatus = Get_IRC_Status(Nick, Channel)
			if ircStatus == nil then
				IRC_Send(Channel, "You have no status in this channel.")
			else
				local ircStatusLevel = Status_Level(ircStatus)
				local StatusLevel = Status_Level(Status)
				if ircStatusLevel < StatusLevel then
					Update_Player_Status(p, ircStatus)	
				else
					Update_Player_Status(p, Status)
				end
			end
		end
	end	
end

Add_Command("auth", nil, auth_IRC_Trigger)

function playerlist_IRC_Trigger(Nick, Channel, Message)
	local list = ""
	local playerFound = false
	
	for _,v in pairs(Get_All_Players()) do
		playerFound = true
		local team = Get_Team(v)
		local colour = 15
		if team == 0 then
			colour = 4
		elseif team == 1 then
			colour = 8
		end
		
		list = string.format("%s%s%.2d%s%s ", list, string.char(3), colour, Get_Player_Name_By_ID(v), string.char(3))
		if list:len() > 50 then
			IRC_Send(Channel, list)
		end
	end
	
	if playerFound == false then
		list = "No players."
	end
	
	if list ~= "" then
		IRC_Send(Channel, list)
	end	
end

Add_Command("playerlist", nil, playerlist_IRC_Trigger)


function addtempmod_Game_Trigger(PlayerId, Type, Message, Target)
	local pname = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pname == nil then
		PPage(PlayerId, "Please supply player's name.")
	else
		local p = Find_Player(pname)
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "More than 1 player found.")
		else
			local stat = Get_Player_Status(p)
			
			if stat ~= "" then
				PPage(PlayerId, "This player is already authorized")
			else
				PPage(PlayerId, "%s has been made a %s.", Get_Player_Name_By_ID(p), Status_Name("+"))
				PPage(p, "%s has make you a %s.", Player_Name_With_Status(PlayerId), Status_Name("+"))
				Update_Player_Status(p, "+")
			end	
		end	
	end
end

function addtempmod_IRC_Trigger(Nick, Channel, Message)
	local pname = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pname == nil then
		IRC_Send(Channel, "Please supply player's name.")
	else
		local p = Find_Player(pname)
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "More than 1 player found.")
		else
			local stat = Get_Player_Status(p)
			
			if stat ~= "" then
				IRC_Send(Channel, "This player is already authorized")
			else
				IRC_Send(Channel, "%s has been made a %s.", Get_Player_Name_By_ID(p), Status_Name("+"))
				PPage(p, "%s@IRC has make you a %s.", Nick, Status_Name("+"))
				Update_Player_Status(p, "+")
			end	
		end	
	end
end

Add_Command("addtempmoderator", addtempmod_Game_Trigger, addtempmod_IRC_Trigger)

function removetempmod_Game_Trigger(PlayerId, Type, Message, Target)
	local pname = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pname == nil then
		PPage(PlayerId, "Please supply player's name.")
	else
		local p = Find_Player(pname)
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "More than 1 player found.")
		else
			local stat = Get_Player_Status(p)
			
			if stat ~= "+" then
				PPage(PlayerId, "This player is not a %s", Status_Name("+"))
			else
				PPage(PlayerId, "%s has been demoted.", Get_Player_Name_By_ID(p))
				PPage(p, "%s has demoted you.", Player_Name_With_Status(PlayerId))
				Update_Player_Status(p, "")
			end	
		end	
	end
end

function removetempmod_IRC_Trigger(Nick, Channel, Message)
	local pname = string.match(Message, "[^%s]+%s+([^\r\n%s]+)")
	if pname == nil then
		IRC_Send(Channel, "Please supply player's name.")
	else
		local p = Find_Player(pname)
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "More than 1 player found.")
		else
			local stat = Get_Player_Status(p)
			
			if stat ~= "+" then
				IRC_Send(Channel, "This player is not a %s", Status_Name("+"))
			else
				IRC_Send(Channel, "%s has been demoted.", Get_Player_Name_By_ID(p))
				PPage(p, "%s@IRC has demoted you.", Nick)
				Update_Player_Status(p, "")
			end	
		end	
	end
end

Add_Command("removetempmoderator", removetempmod_Game_Trigger, removetempmod_IRC_Trigger)

sql_Command_tmp = {}
sql_Command_Columns = nil

function sql_db_callback(userdata, argc, data, column)
	if sql_Command_Columns == nil then
		sql_Command_Columns = column
	end
	table.insert(sql_Command_tmp, data)
end

function sql_Command(Nick, Channel, Message)
	local pq = string.match(Message, "[^%s]+%s+([^\n]+)")
	db:Query(Channel, "sql_db_callback", pq)
	
	if sql_Command_Columns == nil then
		return
	end
	
	local max_width_columns = {}
	local total_w = 0
	
	for i,v in pairs(sql_Command_Columns) do
		max_width_columns[i] = string.len(v)
	end
	
	for i,v in pairs(sql_Command_tmp) do
		for key,val in pairs(v) do
			if max_width_columns[key] < string.len(val) then
				max_width_columns[key] = string.len(val)
			end
		end
	end
	
	for i,v in pairs(max_width_columns) do
		total_w = total_w + v + 1
	end
	
	local header = ""
	for i,v in pairs(max_width_columns) do
		local tmp = string.format("%%-%ds", v+1)
		header = header .. string.format(tmp, sql_Command_Columns[i])
	end
	
	IRC_Send(Channel, header)
	IRC_Send(Channel, string.rep("-", total_w))
	
	local tmp_data = ""
	
	for key,data in pairs(sql_Command_tmp) do
		for i,v in pairs(max_width_columns) do
			local tmp = string.format("%%-%ds", v+1)
			if data[i] == nil then
				data[i] = ""
			end
			tmp_data = tmp_data .. string.format(tmp, data[i])
		end
		IRC_Send(Channel, tmp_data)
		tmp_data = ""
	end
	
	sql_Command_tmp = {}
	sql_Command_Columns = nil
end

Add_Command("sql", nil, sql_Command)

subnet_PlayerId = nil
subnet_Channel = nil
function sql_subnet_callback(userdata, argc, data, column)
	print(userdata)
	local a1,a2,a3,a4 = LongToIP(data[1])
	local b1,b2,b3,b4 = LongToIP(data[2])
	if subnet_PlayerId ~= nil then
		Console_Input(string.format("ppage %d %s is in subnet: %d.%d.%d.%d - %d.%d.%d.%d", subnet_PlayerId, userdata, a1, a2, a3, a4, b1, b2, b3, b4))
	end
	
	if subnet_Channel ~= nil then
		IRC_Send(subnet_Channel, "%s is in subnet: %d.%d.%d.%d - %d.%d.%d.%d", userdata, a1, a2, a3, a4, b1, b2, b3, b4)
	end	
	
	subnet_PlayerId = nil
	subnet_Channel = nil
end

function subnet_Game_Trigger(PlayerId, Type, Message, Target)
	local pNick = string.match(Message, "[^%s]+%s+(%a+)")
	if pNick == nil then
		IRC_Send(Channel, "!subnet <player or IP>")
		return 
	end
	local p = Find_Player(pNick)
	if p == -1 then
		local a1,a2,a3,a4 = string.match(Message, "[^%s]+%s+(%d+).(%d+).(%d+).(%d+)")
		if a1 ~= nil or a2 ~= nil or a3 ~= nil or a4 ~= nil then
			PPage(PlayerId, "Player not found and that doesn't look like a valid IP address.")
		else
			local lIP = IPToLong(a1,a2,a3,a4)
			subnet_PlayerId = PlayerId
			db:Query(string.format("%d.%d.%d.%d", a1, a2, a3, a4), "sql_subnet_callback", string.format("SELECT * FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
			
		end
	elseif p == -2 then
		PPage(PlayerId, "More than 1 player found.")
		return
	else
		local a1,a2,a3,a4 = string.match(Get_IP_Address(p), "(%d+).(%d+).(%d+).(%d+)")
		local lIP = IPToLong(a1,a2,a3,a4)
		subnet_PlayerId = PlayerId
		db:Query(string.format("%d.%d.%d.%d", a1, a2, a3, a4), "sql_subnet_callback", string.format("SELECT * FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
	end
	
	if subnet_PlayerId ~= nil then
		PPage(PlayerId, "Subnet was not found.")
		subnet_PlayerId = nil
	end
end	

function subnet_IRC_Trigger(Nick, Channel, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n]+)")
	if pNick == nil then
		IRC_Send(Channel, "!subnet <player or IP>")
		return
	end
	local p = Find_Player(pNick)
	if p == -1 then
		local a1,a2,a3,a4 = string.match(Message, "[^%s]+%s+(%d+).(%d+).(%d+).(%d+)")
		if a1 == nil or a2 == nil or a3 == nil or a4 == nil then
			IRC_Send(Channel, "Player not found and that doesn't look like a valid IP address.")
		else
			local lIP = IPToLong(a1,a2,a3,a4)
			subnet_Channel = Channel
			db:Query(string.format("%d.%d.%d.%d", a1, a2, a3, a4), "sql_subnet_callback", string.format("SELECT * FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
			
		end
	elseif p == -2 then
		IRC_Send(Channel, "More than 1 player found.")
		return
	else
		local a1,a2,a3,a4 = string.match(Get_IP_Address(p), "(%d+).(%d+).(%d+).(%d+)")
		local lIP = IPToLong(a1,a2,a3,a4)
		subnet_Channel = Channel
		db:Query(string.format("%d.%d.%d.%d", a1, a2, a3, a4), "sql_subnet_callback", string.format("SELECT * FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
	end
	
	if subnet_Channel ~= nil then
		IRC_Send(Channel, "Subnet was not found.")
		subnet_Channel = nil
	end
end


Add_Command("subnet", subnet_Game_Trigger, subnet_IRC_Trigger)

ban_columnID = nil
function sql_ban_ID_callback(userdata, argc, data, column)
	ban_columnID = tonumber(data[1])
end

ban_Affected = nil
function sql_ban_Affected_callback(userdata, argc, data, column)
	if ban_Affected == nil then
		ban_Affected = {}
	end
	
	table.insert(ban_Affected, data[1])
end

ban_IPStart = nil
ban_IPEnd = nil
function sql_ban_Range_callback(userdata, argc, data, column)
	ban_IPStart = data[1]
	ban_IPEnd = data[2]
end


function ban_Game_Trigger(PlayerId, Type, Message, Target)
	local Nick = Get_Player_Name_By_ID(PlayerId)
	local pNick,Reason = string.match(Message, "[^%s]+%s+([^%s\r\n]+)%s?([^\r\n]+)%s?$")
	if pNick == nil or Reason == nil then
		PPage(PlayerId, "!ban <Player> <Reason>")
	end
	if Reason == nil then
		Reason = "No reason."
	end
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Please be more specific.")
	else
		
		local a,b,c,d = string.match(Get_IP_Address(p), "(%d+).(%d+).(%d+).(%d+)")
		local lIP = IPToLong(a, b, c, d)
		db:Query("", "sql_ban_Range_callback", string.format("SELECT IPFrom,IPTO FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
		if ban_IPStart == nil or ban_IPEnd == nil then
			PPage(PlayerId, "Failed")
			return
		end
		
		db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('%s', '%s', '%s', '%s', '%s', '%s');", Players[p].Nick, Nick, Reason, Players[p].Serial, ban_IPStart, ban_IPEnd))
		db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
		db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE Serial = '%s' or (IP >= %s and IP <= %s);", Players[p].Serial, ban_IPStart, ban_IPEnd))
		
		Attach_Script_Once(Get_GameObj(p), "YaLB_Boot", string.format("\"You were banned by %s for %s\"", Nick, Reason))
		
		
		local nicks = Players[p].Nick
		if ban_Affected ~= nil then
			for i,v in pairs(ban_Affected) do
				if v ~= Players[p].Nick then
					nicks = nicks .. ", " .. v
				end
			end
		end
		
		PPage(PlayerId, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
		Log("Ban", string.format("%s was banned by %s for \"%s\"", Players[p].Nick, Nick, Reason))
		
		
		ban_IPStart = nil
		ban_IPEnd = nil
		ban_Affected = nil
		ban_columnID = nil
	end
end

function ban_IRC_Trigger(Nick, Channel, Message)
	local pNick,Reason = string.match(Message, "^[^%s]+%s+([^%s\n]+)%s?([^\r\n]+)%s?$")
	if pNick == nil or Reason == nil then
		IRC_Send(Channel, "!ban <Player> <Reason>")
	end

	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Please be more specific.")
	else
		
		local a,b,c,d = string.match(Get_IP_Address(p), "(%d+).(%d+).(%d+).(%d+)")
		local lIP = IPToLong(a, b, c, d)
		db:Query("", "sql_ban_Range_callback", string.format("SELECT IPFrom,IPTO FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
		if ban_IPStart == nil or ban_IPEnd == nil then
			IRC_Send(Channel, "Failed")
			return
		end
		
		db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('%s', '%s@IRC', '%s', '%s', '%s', '%s');", Players[p].Nick, Nick, Reason, Players[p].Serial, ban_IPStart, ban_IPEnd))
		db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
		db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE Serial = '%s' or (IP >= %s and IP <= %s);", Players[p].Serial, ban_IPStart, ban_IPEnd))
		
		Attach_Script_Once(Get_GameObj(p), "YaLB_Boot", string.format("You were banned by %s@IRC for %s", Nick, Reason))
		
		
		local nicks = Players[p].Nick
		if ban_Affected ~= nil then
			for i,v in pairs(ban_Affected) do
				if v ~= Players[p].Nick then
					nicks = nicks .. ", " .. v
				end
			end
		end
		
		IRC_Send(Channel, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
		Log("Ban", string.format("%s was banned by %s for \"%s\"", Players[p].Nick, Nick, Reason))
		
		
		ban_IPStart = nil
		ban_IPEnd = nil
		ban_Affected = nil
		ban_columnID = nil
	end
end

Add_Command("ban", ban_Game_Trigger, ban_IRC_Trigger)

function sban_IRC_Trigger(Nick, Channel, Message)
	local Serial,Reason = string.match(Message, "[^%s]+%s+([^%s\n]+)%s?([^\r\n]+)%s?$")
	if Serial == nil or Reason == nil then
		IRC_Send(Channel, "!sban <Serial> <Reason>")
	end

	if string.len(Serial) ~= 32 then
		IRC_Send(Channel, "That is an invalid serial.")
		return
	end
	
	db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('', '%s@IRC', '%s', '%s', '-1', '-1');", Nick, Reason, Serial))
	db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
	db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE Serial = '%s';", Serial))		
		
	local nicks = ""
	local nicks_tmp = false
	if ban_Affected ~= nil then
		for i,v in pairs(ban_Affected) do
			if nicks_tmp == true then
				nicks = nicks .. ", "
			end
			nicks = nicks .. v
			nicks_tmp = true
		end
	end
	if nicks == "" then
		nicks = "None."
	end
	Log("Ban", string.format("%s was banned by %s for \"%s\"", Serial, Nick, Reason))
	
	IRC_Send(Channel, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
	ban_Affected = nil
	ban_columnID = nil
end

Add_Command("serialban", nil, sban_IRC_Trigger)

dban_tmp = false
function sql_dban_callback(userdata, argc, data, column)
	if tonumber(data[1]) >= 1 then
		dban_tmp = true
	end
end

function dban_Game_Trigger(PlayerId, Type, Message, Target)
	local ID = tonumber(string.match(Message, "[^%s]+%s+([^%s\r\n]+)"))
	if ID == nil then
		PPage(PlayerId, "!dban <Ban ID>")
		return
	end
	
	db:Query("", "sql_dban_callback", string.format("SELECT COUNT(*) FROM Bans WHERE ID = %d;", ID))
	
	if dban_tmp ~= true then
		PPage(PlayerId, "Ban #%d does not exist.", ID)
	else
		PPage(PlayerId, "Ban #%d has been removed.", ID)
		db:Query("", "", string.format("DELETE FROM Bans WHERE ID = %d;", ID))
		Log("Ban", string.format("Ban", "Ban ID #%d was deleted", ID))
		dban_tmp = false
	end
end

function dban_IRC_Trigger(Nick, Channel, Message)
	local ID = tonumber(string.match(Message, "[^%s]+%s+([^%s\r\n]+)"))
	if ID == nil then
		IRC_Send(Channel, "!delban <Ban ID>")
		return
	end
	
	db:Query("", "sql_dban_callback", string.format("SELECT COUNT(*) FROM Bans WHERE ID = %d;", ID))
	
	if dban_tmp ~= true then
		IRC_Send(Channel, "Ban #%d does not exist.", ID)
	else
		IRC_Send(Channel, "Ban #%d has been removed.", ID)
		db:Query("", "", string.format("DELETE FROM Bans WHERE ID = %d;", ID))
		Log("Ban", string.format("Ban ID #%d was deleted", ID))
		dban_tmp = false
	end
end

Add_Command("deleteban", dban_Game_Trigger, dban_IRC_Trigger)


function bani_IRC_Trigger(Nick, Channel, Message)
	local ID = tonumber(string.match(Message, "[^%s]+%s+([^%s\r\n]+)"))
	if ID == nil then
		IRC_Send(Channel, "!baninfo <Ban ID>")
		return
	end
	
	local baninfo = Get_Ban_Infomation(ID)
	if baninfo == nil then
		IRC_Send(Channel, "Ban #%d does not exist.", ID)
		return
	end	
	local reason = baninfo[2]
	if reason ~= "" then
		reason = " for " .. reason
	end
	
	if baninfo[1] == "" then
		if baninfo[4] ~= "" then
			
			IRC_Send(Channel, "%s was banned by %s%s", baninfo[4], baninfo[3], reason)
		elseif baninfo[5] ~= "" and baninfo[6] ~= "" then
			IRC_Send(Channel, "%s - %s was banned by %s%s", LongToIP2(baninfo[5]), LongToIP2(baninfo[6]), baninfo[3], reason)
		else
		
		end
	else
		IRC_Send(Channel, "%s was banned by %s%s", baninfo[1], baninfo[3], reason)
	end
	
	db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE Serial = '%s' or (IP >= %s and IP <= %s);", baninfo[4], baninfo[5], baninfo[6]))		
		
	local nicks = ""
	local nicks_tmp = false
	if ban_Affected ~= nil then
		for i,v in pairs(ban_Affected) do
			if nicks_tmp == true then
				nicks = nicks .. ", "
			end
			nicks = nicks .. v
			nicks_tmp = true
		end
	end
	if nicks ~= "" then
		IRC_Send(Channel, "Ban #%d also affects: %s", ID, nicks)
	end
	ban_Affected = nil
end

Add_Command("baninfomation", nil, bani_IRC_Trigger)


function IPBan_IRC_Trigger(Nick, Channel, Message)
	local IP,Reason = string.match(Message, "[^%s]+%s+([^%s]+)%s+([^\r\n]+)")
	if IP == nil or Reason == nil then
		IRC_Send(Channel, "!ipban <IP> <Reason>")
		return
	end

	local lIP = IPToLong2(IP)
	if lIP == nil then
		IRC_Send(Channel, "That is not a valid IP address.")
		return
	end
	
	db:Query("", "sql_ban_Range_callback", string.format("SELECT IPFrom,IPTO FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
	if ban_IPStart == nil or ban_IPEnd == nil then
		IRC_Send(Channel, "Error")
		return
	end
	
	db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('', '%s@IRC', '%s', '', %s, %s);", Nick, Reason, ban_IPStart, ban_IPEnd))
	db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
	db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE IP >= %s and IP <= %s;", ban_IPStart, ban_IPEnd))		
	
	local nicks = ""
	local nicks_tmp = false
	if ban_Affected ~= nil then
		for i,v in pairs(ban_Affected) do
			if nicks_tmp == true then
				nicks = nicks .. ", "
			end
			nicks = nicks .. v
			nicks_tmp = true
		end
	end
	if nicks == "" then
		nicks = "None."
	end
		
	IRC_Send(Channel, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
	Log("Ban", string.format("%s was banned by %s for \"%s\"", IP, Nick, Reason))
	ban_Affected = nil
	ban_columnID = nil
	ban_IPStart = nil
	ban_IPEnd = nil
end

Add_Command("ipban", nil, IPBan_IRC_Trigger)


function RangeBan_IRC_Trigger(Nick, Channel, Message)
	local IPFrom,IPTo,Reason = string.match(Message, "[^%s]+%s+([^%s]+)%s+([^%s]+)%s+([^\r\n]+)")
	if IPFrom == nil or IPTo == nil or Reason == nil then
		IRC_Send(Channel, "!rban <IPFrom> <IPTo> <Reason>")
		return
	end
	
	local lIPf = IPToLong2(IPFrom)
	local lIPt = IPToLong2(IPTo)
	if lIPf == nil or lIPt == nil then
		IRC_Send(Channel, "They don't look like valid IP addresses.")
		return
	end
	
	db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('', '%s@IRC', '%s', '', %s, %s);", Nick, Reason, lIPf, lIPt))
	db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
	db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE IP >= %s and IP <= %s;", lIPf, lIPt))		
	
	local nicks = ""
	local nicks_tmp = false
	if ban_Affected ~= nil then
		for i,v in pairs(ban_Affected) do
			if nicks_tmp == true then
				nicks = nicks .. ", "
			end
			nicks = nicks .. v
			nicks_tmp = true
		end
	end
	if nicks == "" then
		nicks = "None."
	end
		
	IRC_Send(Channel, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
	Log("Ban", string.format("%s-%s was banned by %s for \"%s\"", IPFrom, IPTo, Nick, Reason))
	ban_Affected = nil
	ban_columnID = nil
end

Add_Command("rangeban", nil, RangeBan_IRC_Trigger)

function Kick_Game_Trigger(PlayerId, Type, Message, Target)
	local pname,Reason = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pname == nil or Reason == nil then
		PPage(PlayerId, "!kick <Nick> <Reason>")
	else
		local p = Find_Player(pname)
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "More than 1 player found.")
		else
			PPage(PlayerId, "%s has been kicked (auto-allow).", Get_Player_Name_By_ID(p))
			Attach_Script_Once(Get_GameObj(p), "YaLB_Boot", string.format("You were kicked (auto-allow) by %s for %s", Get_Player_Name_By_ID(PlayerId), Reason))
			Log("Kick", string.format("%s was kicked (auto allow) by %s for \"%s\"", Get_Player_Name_By_ID(p), Get_Player_Name_By_ID(PlayerId), Reason))
		end
	end
end

function Kick_IRC_Trigger(Nick, Channel, Message)
	local pname,Reason = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pname == nil or Reason == nil then
		IRC_Send(Channel, "!kick <Nick> <Reason>")
	else
		local p = Find_Player(pname)
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "More than 1 player found.")
		else
			IRC_Send(Channel, "%s has been kicked (auto-allow).", Get_Player_Name_By_ID(p))
			Attach_Script_Once(Get_GameObj(p), "YaLB_Boot", string.format("You were kicked (auto-allow) by %s@IRC for %s", Nick, Reason))
			Log("Kick", string.format("%s was kicked (auto allow) by %s@IRC for \"%s\"", Get_Player_Name_By_ID(p), Nick, Reason))
		end
	end
end

Add_Command("kick", Kick_Game_Trigger, Kick_IRC_Trigger)


function Mute_Game_Trigger(PlayerId, Type, Message, Target)
	local pname = string.match(Message, "%S+%s+([^\r\n]+)")
	if pname == nil then
		PPage(PlayerId, "!kick <Nick>")
	else
		local p = Find_Player(pname)
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "More than 1 player found.")
		else
			if Players[p].Muted == 0 then
				PPage(PlayerId, "%s has been muted.", Get_Player_Name_By_ID(p))
				PPage(p, "You have been muted by %s. You are no longer allowed to use team, public chat or radio commands.", Get_Player_Name_By_ID(PlayerId))
				Players[p].Muted = 1
			else
				PPage(PlayerId, "%s has been unmuted.", Get_Player_Name_By_ID(p))
				PPage(p, "You are have been unmuted.")
				Players[p].Muted = 0
			end
		end
	end
end


function Mute_IRC_Trigger(Nick, Channel, Message)
	local pname = string.match(Message, "%S+%s+([^\r\n]+)")
	if pname == nil then
		IRC_Send(Channel, "!kick <Nick>")
	else
		local p = Find_Player(pname)
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "More than 1 player found.")
		else
			if Players[p].Muted == 0 then
				IRC_Send(Channel, "%s has been muted.", Get_Player_Name_By_ID(p))
				PPage(p, "You have been muted by %s@IRC. You are no longer allowed to use team, public chat or radio commands.", Nick)
				Players[p].Muted = 1
			else
				IRC_Send(Channel, "%s has been unmuted.", Get_Player_Name_By_ID(p))
				PPage(p, "You are have been unmuted.")
				Players[p].Muted = 0
			end
		end
	end
end

Add_Command("mute", Mute_Game_Trigger, Mute_IRC_Trigger)


function Save_Game_Trigger(PlayerId, Type, Message, Target)
	local Team = string.match(Message, "%S+%s+(%S+)")
	if Team == nil then
		PPage(PlayerId, "!save <nod / gdi>")
		return
	end
	Team = string.lower(Team)
	
	local pos = Get_Position(Get_GameObj(PlayerId))
	if Team == "nod" then
		db:Query("", "", string.format("INSERT INTO Defences VALUES('%s', '%s', '%s', %f, %f, %f);", Get_Current_Map(), "Nod_Turret_MP_Improved", "nod", pos:GetX(), pos:GetY(), pos:GetZ()))
	elseif Team == "gdi" then
		db:Query("", "", string.format("INSERT INTO Defences VALUES('%s', '%s', '%s', %f, %f, %f);", Get_Current_Map(), "GDI_Guard_Tower", "gdi", pos:GetX(), pos:GetY(), pos:GetZ()+8))
	else
		PPage(PlayerId, "!save <nod / gdi>")
	end
end

Add_Command("save", Save_Game_Trigger, nil)

function db_logsearch_Callback(userdata, argc, data, column)
	IRC_Send(userdata, "[%s]: %s", os.date("%d %b %Y %H:%M:%S", tonumber(data[3])), data[2])
end

function LogSearch_IRC_Trigger(Nick, Channel, Message)
	local keyword = string.match(Message, "%S+%s+([^%s\r\n]+)")
	if keyword == nil then
		IRC_Send(Channel, "!logsearch <type>")
		return
	end
	
	db:Query(Channel, "db_logsearch_Callback", string.format("SELECT * FROM Log WHERE Infomation LIKE '%%%s%%' ORDER BY Time DESC LIMIT 5;", keyword))
end

Add_Command("logsearch", nil, LogSearch_IRC_Trigger)

function Moderators_Game_Trigger(PlayerId, Type, Message, Target)
	
	local str = "Moderators in-game: "
	local tmp = false
	for i,v in next, Players do
		if v.Status ~= nil and v.Status ~= "" then
			if tmp == false then
				str = str .. v.Status .. v.Nick
				tmp = true
			else
				str = str .. ", " .. v.Status .. v.Nick
			end
		end
	end
	if tmp == false then
		Console_Input("msg There are no moderators in-game.")
	else
		Console_Input(string.format("msg %s", str))
	end
end

Add_Command("moderators", Moderators_Game_Trigger, nil)


function Killme_Game_Trigger(PlayerId, Type, Message, Target)
	Apply_Damage(Get_GameObj(PlayerId), 9999, "BlamoKiller", 0)
end

Add_Command("killme", Killme_Game_Trigger, nil)


function amsg_Game_Trigger(PlayerId, Type, Message, Target)
	local msg = string.match(Message, "%S+%s+([^\r\n]+)")
	if msg == nil then
		PPage(PlayerId, "!amsg <Message>")
		return
	end
	
	Console_Input(string.format("amsg (From %s): %s", Get_Player_Name_By_ID(PlayerId), msg))
end

function amsg_IRC_Trigger(Nick, Channel, Message)
	local msg = string.match(Message, "%S+%s+([^\r\n]+)")
	if msg == nil then
		IRC_Send(Channel, "!amsg <Message>")
		return
	end
	
	Console_Input(string.format("amsg (From %s): %s", Nick, msg))
end

Add_Command("amsg", amsg_Game_Trigger, amsg_IRC_Trigger)


function nextmap_Game_Trigger(PlayerId, Type, Message, Target)
	Console_Input(string.format("msg Next map will be %s", Get_Next_Map()))
end

function nextmap_IRC_Trigger(Nick, Channel, Message)
	IRC_Send(Channel, "Next map will be %s", Get_Next_Map())
end

Add_Command("nextmap", nextmap_Game_Trigger, nextmap_IRC_Trigger)


function rules_Game_Trigger(PlayerId, Type, Message, Target)
	Console_Input("msg " .. Rules)
end

function rules_IRC_Trigger(Nick, Channel, Message)
	Console_Input("msg Server rules: " .. Rules)
end

Add_Command("rules", rules_Game_Trigger, rules_IRC_Trigger)


function website_Game_Trigger(PlayerId, Type, Message, Target)
	Console_Input("msg Server website: " .. Website)
end

function website_IRC_Trigger(Nick, Channel, Message)
	Console_Input("msg Server website: " .. Website)
end

Add_Command("website", website_Game_Trigger, website_IRC_Trigger)


function ping_Game_Trigger(PlayerId, Type, Message, Target)
	local p = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if p == nil then
		local c = 0
		local ping = 0
		for _,i in pairs(Get_All_Players()) do
			c = c + 1
			ping = ping + Get_Ping(i)
		end
		if c == 0 then
			PPage(PlayerId, "No players in-game.")
		else
			PPage(PlayerId, "Average ping: %.1f", ping / c)
		end
	else
		local pId = Find_Player(p)
		if pId == -2 then
			PPage(PlayerId, "Be more specific.")
		elseif pId == -1 then
			PPage(PlayerId, "Player not found.")
		else
			PPage(PlayerId, "%s's ping is: %d", Get_Player_Name_By_ID(pId), Get_Ping(pId))
		end
	end
end

function ping_IRC_Trigger(Nick, Channel, Message)
	local p = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if p == nil then
		local c = 0
		local ping = 0
		for _,i in pairs(Get_All_Players()) do
			c = c + 1
			ping = ping + Get_Ping(i)
		end
		if c == 0 then
			IRC_Send(Channel, "No players in-game.")
		else
			IRC_Send(Channel, "Average ping: %.1f", ping / c)
		end
	else
		local pId = Find_Player(p)
		if pId == -2 then
			IRC_Send(Channel, "Be more specific.")
		elseif pId == -1 then
			IRC_Send(Channel, "Player not found.")
		else
			IRC_Send(Channel, "%s's ping is: %d", Get_Player_Name_By_ID(pId), Get_Ping(pId))
		end
	end
end

Add_Command("ping", ping_Game_Trigger, ping_IRC_Trigger)


function refund_Game_Trigger(PlayerId, Type, Message, Target)
	local player,amount = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if player == nil or amount == nil then
		PPage(PlayerId, "!refund <Player> <Amount>")
		return
	end
	
	if tonumber(amount) == nil then
		PPage(PlayerId, "Invalid amount.")
		return
	end
	
	local pId = Find_Player(player)
	
	if pId == -2 then
		PPage(PlayerId, "Be more specific.")
	elseif pId == -1 then
		PPage(PlayerId, "Player not found.")
	else
		PPage(PlayerId, "%s has been refunded %d credits.", Get_Player_Name_By_ID(pId), amount)
		
		PPage(pId, "%s has refunded you with %d credits.", Get_Player_Name_By_ID(PlayerId), amount)
		Set_Money(pId, Get_Money(pId) + amount)
	end
end

function refund_IRC_Trigger(Nick, Channel, Message)
	local player,amount = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if player == nil or amount == nil then
		IRC_Send(Channel, "!refund <Player> <Amount>")
		return
	end
	
	if tonumber(amount) == nil then
		IRC_Send(Channel, "Invalid amount.")
		return
	end
	
	local pId = Find_Player(player)
	
	if pId == -2 then
		IRC_Send(Channel, "Be more specific.")
	elseif pId == -1 then
		IRC_Send(Channel, "Player not found.")
	else
		IRC_Send(Channel, "%s has been refunded %d credits.", Get_Player_Name_By_ID(pId), amount)
		
		PPage(pId, "%s@IRC has refunded you with %d credits.", Nick, amount)
		Set_Money(pId, Get_Money(pId) + amount)
	end
end

Add_Command("refund", refund_Game_Trigger, refund_IRC_Trigger)


function rehash_Game_Trigger(PlayerId, Type, Message, Target)
	if Settings_Pre("YaLB\\Settings.cfg") == false then 
		error("Failed to load \"YaLB\\Settings.cfg\"")
	end
	Remove_All_Commands()
	dofile("YaLB\\YaLB_Commands.Lua")
	dofile("YaLB\\YaLB_Scripts.Lua")
	dofile("YaLB\\YaLB_Ranks.Lua")
	
	Load_Command_Settings()
	Load_Moderators()
	Game_First_Load()
	Load_Ranks()
	PPage(PlayerId, "Settings rehashed.")
end

function rehash_IRC_Trigger(Nick, Channel, Message)
	if Settings_Pre("YaLB\\Settings.cfg") == false then 
		error("Failed to load \"YaLB\\Settings.cfg\"")
	end
	Remove_All_Commands()
	dofile("YaLB\\YaLB_Commands.Lua")
	dofile("YaLB\\YaLB_Scripts.Lua")
	dofile("YaLB\\YaLB_Ranks.Lua")
	
	Load_Command_Settings()
	Load_Moderators()
	Game_First_Load()
	Load_Ranks()
	IRC_Send(Channel, "Settings rehashed.")
end

Add_Command("rehash", rehash_Game_Trigger, rehash_IRC_Trigger)

function donate_Game_Trigger(PlayerId, Type, Message, Target)
	local to,amount = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if to == nil or amount ==  nil then
		PPage(PlayerId, "!donate <Player> <Amount>")
		return
	end
	
	local iamount = tonumber(amount)
	if iamount == nil or iamount <= 0 then
		PPage(PlayerId, "Invalid amount.")
		return
	end
	
	local p = Find_Player(to)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
		return
	elseif p == -2 then
		PPage(PlayerId, "Be more specific.")
		return
	end
	
	if Get_Team(p) ~= Get_Team(PlayerId) then
		PPage(PlayerId, "You can only donate to your team.")
		return
	end
	
	if Purchase_Item(Get_GameObj(PlayerId), iamount) == 1 then
		PPage(PlayerId, "You have donated %d to %s.", iamount, Get_Player_Name_By_ID(p))
		PPage(p, "%s has donated %d to you.", Get_Player_Name_By_ID(PlayerId), iamount)
		Set_Money(p, Get_Money(p)+iamount)	
	else
		PPage(PlayerId, "You don't have enough credits.")
	end
end

Add_Command("donate", donate_Game_Trigger, nil)

function rotation_Game_Trigger(PlayerId, Type, Message, Target)
	local rot = Get_Rotation()
	local str = "msg "
	local current = Get_Current_Map()
	
	for i,v in pairs(rot) do
		if v == current then
			str = string.format("%s [%s]", str, string.match(v, "C&C_([^.]+).mix") or v)
		else
			str = string.format("%s %s", str, string.match(v, "C&C_([^.]+).mix") or v)
		end
		if string.len(str) > 50 then
			Console_Input(str)
			str = ""
		end
	end
	
	Console_Input(str)
end

function rotation_IRC_Trigger(Nick, Channel, Message)
	local rot = Get_Rotation()
	local str = ""
	local current = Get_Current_Map()
	
	for i,v in pairs(rot) do
		if v == current then
			str = string.format("%s[%s] ", str, string.match(v, "C&C_([^.]+).mix") or v)
		else
			str = string.format("%s%s ", str, string.match(v, "C&C_([^.]+).mix") or v)
		end
		if string.len(str) > 50 then
			IRC_Send(Channel, str)
			str = ""
		end
	end
	
	IRC_Send(Channel, str)
end

Add_Command("rotation", rotation_Game_Trigger, rotation_IRC_Trigger)


function tmpban_Game_Trigger(PlayerId, Type, Message, Target)
	local Nick = Get_Player_Name_By_ID(PlayerId)
	local pNick,hours,days,months,Reason = string.match(Message, "[^%s]+%s+([^%s\r\n]+)%s+(%d+):(%d+):(%d+)%s+([^\r\n]+)%s?$")
	if pNick == nil or Reason == nil or hours == nil or days == nil or months == nil then
		PPage(PlayerId, "!ban <Player> <Hours:Days:Months> <Reason>")
		return
	end
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Please be more specific.")
	else
		
		local a,b,c,d = string.match(Get_IP_Address(p), "(%d+).(%d+).(%d+).(%d+)")
		local lIP = IPToLong(a, b, c, d)
		db:Query("", "sql_ban_Range_callback", string.format("SELECT IPFrom,IPTO FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
		if ban_IPStart == nil or ban_IPEnd == nil then
			PPage(PlayerId, "Failed")
			return
		end
		
		db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('%s', '%s', '%s', '%s', '%s', '%s');", Players[p].Nick, Nick, Reason, Players[p].Serial, ban_IPStart, ban_IPEnd))
		db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
		db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE Serial = '%s' or (IP >= %s and IP <= %s);", Players[p].Serial, ban_IPStart, ban_IPEnd))
		
		Attach_Script_Once(Get_GameObj(p), "YaLB_Boot", string.format("You were banned by %s for %s", Nick, Reason))
		
		
		local nicks = Players[p].Nick
		if ban_Affected ~= nil then
			for i,v in pairs(ban_Affected) do
				if v ~= Players[p].Nick then
					nicks = nicks .. ", " .. v
				end
			end
		end
		
		PPage(PlayerId, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
		Log("Ban", string.format("%s was banned by %s for \"%s\"", Players[p].Nick, Nick, Reason))
		
		months = tonumber(months)
		days = tonumber(days)
		hours = tonumber(hours)
		
		months = months * 4 * 7 * 24 * 60 * 60
		days = days * 24 * 60 * 60
		hours = hours * 60 * 60
		
		db:Query("", "", string.format("INSERT INTO TempBans(LinkID, Until) VALUES(%d, %d);", ban_columnID, os.time(os.date("*t"))+months+days+hours))		
		
		ban_IPStart = nil
		ban_IPEnd = nil
		ban_Affected = nil
		ban_columnID = nil
	end
end

function tmpban_IRC_Trigger(Nick, Channel, Message)
	local pNick,hours,days,months,Reason = string.match(Message, "[^%s]+%s+([^%s\r\n]+)%s+(%d+):(%d+):(%d+)%s+([^\r\n]+)%s?$")
	if pNick == nil or Reason == nil or hours == nil or days == nil or months == nil then
		IRC_Send(Channel, "!tban <Player> <Hours:Days:Months> <Reason>")
		return
	end
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Please be more specific.")
	else
		
		local a,b,c,d = string.match(Get_IP_Address(p), "(%d+).(%d+).(%d+).(%d+)")
		local lIP = IPToLong(a, b, c, d)
		db:Query("", "sql_ban_Range_callback", string.format("SELECT IPFrom,IPTO FROM IpCountry WHERE IPFrom <= %s and IPTO >= %s;", lIP, lIP))
		
		if ban_IPStart == nil or ban_IPEnd == nil then
			IRC_Send(Channel, "Failed")
			return
		end
		
		db:Query("", "", string.format("INSERT INTO Bans(Nick, WhoBy, Reason, Serial, IPStart, IPEnd) VALUES('%s', '%s', '%s', '%s', '%s', '%s');", Players[p].Nick, Nick, Reason, Players[p].Serial, ban_IPStart, ban_IPEnd))
		db:Query("", "sql_ban_ID_callback", "SELECT max(ID) FROM Bans;")
		db:Query("", "sql_ban_Affected_callback", string.format("SELECT DISTINCT Nick FROM PlayerLog WHERE Serial = '%s' or (IP >= %s and IP <= %s);", Players[p].Serial, ban_IPStart, ban_IPEnd))
		
		Attach_Script_Once(Get_GameObj(p), "YaLB_Boot", string.format("You were banned by %s for %s", Nick, Reason))
		
		
		local nicks = Players[p].Nick
		if ban_Affected ~= nil then
			for i,v in pairs(ban_Affected) do
				if v ~= Players[p].Nick then
					nicks = nicks .. ", " .. v
				end
			end
		end
		
		IRC_Send(Channel, "Ban #%d affects: %s", tonumber(ban_columnID), nicks)
		Log("Ban", string.format("%s was banned by %s for \"%s\"", Players[p].Nick, Nick, Reason))
		
		months = tonumber(months)
		days = tonumber(days)
		hours = tonumber(hours)
		
		months = months * 4 * 7 * 24 * 60 * 60
		days = days * 24 * 60 * 60
		hours = hours * 60 * 60
		
		db:Query("", "", string.format("INSERT INTO TempBans(LinkID, Until) VALUES(%d, %d);", ban_columnID, os.time(os.date("*t"))+months+days+hours))		
		
		ban_IPStart = nil
		ban_IPEnd = nil
		ban_Affected = nil
		ban_columnID = nil
	end
end

Add_Command("tempban", tmpban_Game_Trigger, tmpban_IRC_Trigger)

tmp_ban_ID = nil
function db_Get_Tmp_Ban(userdata, argc, data, column)
	tmp_ban_ID = tonumber(data[1])
end

function addtmpban_IRC_Trigger(Nick, Channel, Message)
	local BanID,hours,days,months = string.match(Message, "%S+%s+(%d+)%s+(%d+):(%d+):(%d+)")
	if BanID == nil or hours == nil or days == nil or months == nil then
		IRC_Send(Channel, "!addtempban <BanID> <Hours:Days:Months>")
		return
	end
	
	months = tonumber(months)
	days = tonumber(days)
	hours = tonumber(hours)
		
	months = months * 4 * 7 * 24 * 60 * 60
	days = days * 24 * 60 * 60
	hours = hours * 60 * 60
	
	local baninfo = Get_Ban_Infomation(tonumber(BanID))
	if baninfo == nil then
		IRC_Send(Channel, "Ban #%d does not exist.", ID)
		return
	end	
	db:Query("", "db_Get_Tmp_Ban", string.format("SELECT * FROM TempBans WHERE LinkID = %s;", BanID))
	if tmp_ban_ID ~= nil then
		db:Query("", "", string.format("UPDATE TempBans SET Until = %d WHERE ID = %s;", os.time(os.date("*t"))+months+days+hours, tmp_ban_ID))
		IRC_Send(Channel, "Changed ban #%d to be removed at %s", BanID, os.date("%d %b %Y %H:%M:%S", os.time(os.date("*t"))+months+days+hours))
	else
		db:Query("", "", string.format("INSERT INTO TempBans(LinkID, Until) VALUES(%s, %d);", BanID, os.time(os.date("*t"))+months+days+hours))
		IRC_Send(Channel, "Ban #%d will be removed at %s", BanID, os.date("%d %b %Y %H:%M:%S", os.time(os.date("*t"))+months+days+hours))
	end
	tmp_ban_ID = nil
end

Add_Command("addtmpban", nil, addtmpban_IRC_Trigger)

function ppage_IRC_Trigger(Nick, Channel, Message)
	local pNick, Msg = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pNick == nil or Msg == nil then
		IRC_Send(Channel, "!ppage <Nick> <Message>")
		return
	end
	
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		PPage(p, "(From %s@IRC): %s", Nick, Msg)
		local tcolour = 15
		local team = Get_Team(p)
		if team == 0 then
			tcolour = 4
		elseif team == 1 then
			tcolour = 8
		end
		
		IRC_Send(Channel, "Page sent to %s%.2d%s%s: %s", string.char(3), tcolour, Get_Player_Name_By_ID(p), string.char(3), Msg)
	end
end

Add_Command("ppage", nil, ppage_IRC_Trigger)

function pinfo_IRC_Trigger(Nick, Channel, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n]+)")
	if pNick == nil then
		IRC_Send(Channel, "!pinfo <Nick>")
		return
	end
	
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		local team = Get_Team(p)
		local tcolour = 15
		if team == 0  then
			tcolour = 4
		elseif team == 1 then
			tcolour = 8
		end
		
		IRC_Send(Channel, "%s%.2d%s : %s : %d points : %d kills : %d deaths : %d credits%s", string.char(3), tcolour, Get_Player_Name_By_ID(p), Get_Translated_Preset_Name(Get_GameObj(p)), Get_Score(p), Get_Kills(p), Get_Deaths(p), Get_Money(p), string.char(3))
	end
end

Add_Command("pinfo", nil, pinfo_IRC_Trigger)


function showpm_Game_Trigger(PlayerId, Type, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n]+)")
	if pNick == nil then
		PPage(PlayerId, "!showpm <Nick>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Be more specific.")
	else
		if Players[p].ShowPM == true then
			Players[p].ShowPM = false
			PPage(PlayerId, "%s's PMs will no longer be logged", Get_Player_Name_By_ID(p))			
		else
			Players[p].ShowPM = true
			PPage(PlayerId, "%s's PMs will be logged", Get_Player_Name_By_ID(p))	
		end
	end
end

function showpm_IRC_Trigger(Nick, Channel, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n]+)")
	if pNick == nil then
		IRC_Send(Channel, "!showpm <Nick>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		if Players[p].ShowPM == true then
			Players[p].ShowPM = false
			IRC_Send(Channel, "%s's PMs will no longer be logged", Get_Player_Name_By_ID(p))			
		else
			Players[p].ShowPM = true
			IRC_Send(Channel, "%s's PMs will be logged", Get_Player_Name_By_ID(p))	
		end
	end
end

Add_Command("showpm", showpm_Game_Trigger, showpm_IRC_Trigger)

function import_IRC_Trigger(Nick, Channel, Message)
	IRC_Send(Channel, "Importing new IpCountry database...")
	Import_Database()
	IRC_Send(Channel, "Importing finished.")
end

Add_Command("import", nil, import_IRC_Trigger)

function Get_BW_Game_Trigger(PlayerId, Type, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n]+)")
	if pNick == nil then
		PPage(PlayerId, "!getbw <Nick>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Be more specific.")
	else
		PPage(PlayerId, "%s's bandwidth is set at: %d", Get_Bandwidth(p))
	end
end

function Get_BW_IRC_Trigger(Nick, Channel, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n]+)")
	if pNick == nil then
		IRC_Send(Channel, "!getbw <Nick>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		IRC_Send(Channel, "%s's bandwidth is set at: %d", Get_Player_Name_By_ID(p), Get_Bandwidth(p))
	end
end

Add_Command("getbw", Get_BW_Game_Trigger, Get_BW_IRC_Trigger)

function Set_BW_Game_Trigger(PlayerId, Type, Message)
	local pNick,bw = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pNick == nil or bw == nil or tonumber(bw) == nil then
		PPage(PlayerId, "!setbw <Nick> <Bandwidth>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Be more specific.")
	else
		PPage(PlayerId, "%s's bandwidth has been set", Get_Player_Name_By_ID(p))
		Console_Inputf("setbw %d %s", p, bw)
	end
end

function Set_BW_IRC_Trigger(Nick, Channel, Message)
	local pNick,bw = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pNick == nil or bw == nil or tonumber(bw) == nil then
		IRC_Send(Channel, "!setbw <Nick> <Bandwidth>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		IRC_Send(Channel, "%s's bandwidth has been set", Get_Player_Name_By_ID(p))
		Console_Inputf("setbw %d %s", p, bw)
	end
end

Add_Command("setbw", Set_BW_Game_Trigger, Set_BW_IRC_Trigger)

function eteam_Game_Trigger(PlayerId, Type, Message)
	local nod = 0
	local gdi = 0
	
	local nodlist = {}
	local gdilist = {}
	for _,p in pairs(Get_All_Players()) do
		local team = Get_Team(p)
		if team == 0 then
			nod = nod + 1
			table.insert(nodlist, p)
		elseif team == 1 then
			gdi = gdi + 1
			table.insert(gdilist, p)
		end
	end
	
	if nod == 0 and gdi == 0 then
		PPage(PlayerId, "No players.")
	elseif nod > (gdi + 1) then
		while nod > (gdi + 1) do
			local player = table.remove(nodlist, math.random(#nodlist))
			Console_Inputf("team2 %d 1", player)
			PPage(player, "You have been switched to GDI to even the teams.")
			gdi = gdi + 1	
			nod = nod - 1	
		end
	elseif gdi > (nod + 1) then
		while gdi > (nod + 1) do
			local player = table.remove(gdilist, math.random(#gdilist))
			Console_Inputf("team2 %d 0", player)
			PPage(player, "You have been switched to Nod to even the teams.")
			nod = nod + 1
			gdi = gdi - 1		
		end
	else
		PPage(PlayerId, "Teams are even.")
	end	
end

function eteam_IRC_Trigger(Nick, Channel, Message)
	local nod = 0
	local gdi = 0
	
	local nodlist = {}
	local gdilist = {}
	for _,p in pairs(Get_All_Players()) do
		local team = Get_Team(p)
		if team == 0 then
			nod = nod + 1
			table.insert(nodlist, p)
		elseif team == 1 then
			gdi = gdi + 1
			table.insert(gdilist, p)
		end
	end
	
	if nod == 0 and gdi == 0 then
		IRC_Send(Channel, "No players.")
	elseif nod > (gdi + 1) then
		while nod > (gdi + 1) do
			local player = table.remove(nodlist, math.random(#nodlist))
			Console_Inputf("team2 %d 1", player)
			PPage(player, "You have been switched to GDI to even the teams.")
			gdi = gdi + 1	
			nod = nod - 1	
		end
	elseif gdi > (nod + 1) then
		while gdi > (nod + 1) do
			local player = table.remove(gdilist, math.random(#gdilist))
			Console_Inputf("team2 %d 0", player)
			PPage(player, "You have been switched to Nod to even the teams.")
			nod = nod + 1
			gdi = gdi - 1		
		end
	else
		IRC_send(Channel, "Teams are even.")
	end	
end

Add_Command("eteam", eteam_Game_Trigger, eteam_IRC_Trigger)

function allow_Game_Trigger(PlayerId, Type, Message)
	local nick = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if nick == nil then
		PPage(PlayerId, "!allow <Nick>")
		return
	end
	
	Console_Inputf("allow %s", nick)
	PPage(PlayerId, "%s has been allowed", nick)
end

function allow_IRC_Trigger(Nick, Channel, Message)
	local nick = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if nick == nil then
		IRC_Send(Channel, "!allow <Nick>")
		return
	end
	
	Console_Inputf("allow %s", nick)
	IRC_Send(Channel, "%s has been allowed", nick)
end

Add_Command("allow", allow_Game_Trigger, allow_IRC_Trigger)


function setnextmap_Game_Trigger(PlayerId, Type, Message)
	local map = string.match(Message, "%S+%s+([^\r\n%s]+)")
	local mapnum = nil
	local rot = Get_Rotation()
	for i,v in pairs(rot) do 
		if string.match(string.lower(v), string.lower(map)) ~= nil then
			if mapnum ~= nil then
				PPage(PlayerId, "Please be more specific.")
				return
			else
				mapnum = i
			end
		end
	end
	if mapnum == -1 then
		PPage(PlayerId, "Map not found.")
	else
		Console_Inputf("msg Next map will be %s", rot[mapnum])
		Set_The_Game({MapNumber = mapnum - 3})
	end
end

function setnextmap_IRC_Trigger(Nick, Channel, Message)
	local map = string.match(Message, "%S+%s+([^\r\n%s]+)")
	local mapnum = nil
	local rot = Get_Rotation()
	for i,v in pairs(rot) do 
		if string.match(string.lower(v), string.lower(map)) ~= nil then
			if mapnum ~= nil then
				IRC_Send(Channel, "Please be more specific.")
				return
			else
				mapnum = i
			end
		end
	end
	if mapnum == -1 then
		IRC_Send(Channel, "Map not found.")
	else
		Console_Inputf("msg Next map will be %s", rot[mapnum])
		Set_The_Game({MapNumber = mapnum - 2})
	end
end

Add_Command("setnextmap", setnextmap_Game_Trigger, setnextmap_IRC_Trigger)

function pamsg_Game_Trigger(PlayerId, Type, Message)
	local pNick, Msg = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pNick == nil or Msg == nil then
		PPage(PlayerId, "!pamsg <Player> <Message>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Be more specific.")
	else
		Console_Inputf("pamsg %d (From %s): %s", p, Get_Player_Name_By_ID(PlayerId), Msg)
	end	
end

function pamsg_IRC_Trigger(Nick, Channel, Message)
	local pNick, Msg = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if pNick == nil or Msg == nil then
		IRC_Send(Channel, "!pamsg <Player> <Message>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		Console_Inputf("pamsg %d (From %s@IRC): %s", p, Nick, Msg)
	end	
end

Add_Command("pamsg", pamsg_Game_Trigger, pamsg_IRC_Trigger)


function tpage_Game_Trigger(PlayerId, Type, Message)
	local sTeam, Msg = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if sTeam == nil or Msg == nil then
		PPage(PlayerId, "!tpage <Team:Nod/GDI> <Message>")
		return
	end
	
	local iTeam = -1
	if string.lower(sTeam) == "nod" then
		iTeam = 0
	elseif string.lower(sTeam) == "gdi" then
		iTeam = 1
	else
		PPage(PlayerId, "!tpage <Team:Nod/GDI> <Message>")
		return
	end
	
	Console_Inputf("tpage %d (From %s): %s", iTeam, Get_Player_Name_By_ID(PlayerId), Msg)
end

function tpage_IRC_Trigger(Nick, Channel, Message)
	local sTeam, Msg = string.match(Message, "%S+%s+(%S+)%s+([^\r\n]+)")
	if sTeam == nil or Msg == nil then
		IRC_Send(Channel, "!tpage <Team:Nod/GDI> <Message>")
		return
	end
	
	local iTeam = -1
	if string.lower(sTeam) == "nod" then
		iTeam = 0
	elseif string.lower(sTeam) == "gdi" then
		iTeam = 1
	else
		IRC_Send(Channel, "!tpage <Team:Nod/GDI> <Message>")
		return
	end
	
	Console_Inputf("tpage %d (From %s@IRC): %s", iTeam, Nick, Msg)
end

Add_Command("tpage", tpage_Game_Trigger, tpage_IRC_Trigger)


function scripts_Game_Trigger(PlayerId, Type, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if pNick == nil then
		local pList = ""
		local sent = false
		for i,v in pairs(Players) do
			pList = string.format("%s%s (%.2f) ", pList, v.Nick, v.Version or 0.0)
			if string.len(pList) > 50 then
				PPage(PlayerId, "%s", pList)
				pList = ""
				sent = true
			end
		end
		if pList ~= "" then
			PPage(PlayerId, "%s", pList)
		elseif sent == false then
			IRC_Send(Channel, "No players.")
		end
	else
		local p = Find_Player(pNick)
		if p == -1 then
			PPage(PlayerId, "Player not found.")
		elseif p == -2 then
			PPage(PlayerId, "Be more specific.")
		else
			PPage(PlayerId, "%s's scripts.dll version is: %.2f", Players[p].Version)
		end
	end
end

function scripts_IRC_Trigger(Nick, Channel, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if pNick == nil then
		local pList = ""
		local sent = false
		for i,v in pairs(Players) do
			pList = string.format("%s%s%.2d%s (%.2f)%s ", pList, string.char(3), Get_TeamIRCColour(Get_Team(i)), v.Nick, v.Version or 0.0, string.char(3))
			if string.len(pList) > 50 then
				IRC_Send(Channel, "%s", pList)
				pList = ""
				sent = true
			end
		end
		if pList ~= "" then
			IRC_Send(Channel, "%s", pList)
		elseif sent == false then
			IRC_Send(Channel, "No players.")
		end
	else
		local p = Find_Player(pNick)
		if p == -1 then
			IRC_Send(Channel, "Player not found.")
		elseif p == -2 then
			IRC_Send(Channel, "Be more specific.")
		else
			IRC_Send(Channel, "%s%.2d%s's%s scripts.dll version is: %.2f", string.char(3), Get_TeamIRCColour(Get_Team(p)), Players[p].Nick, string.char(3), Players[p].Version or 0.0)
		end
	end
end

Add_Command("scripts", scripts_Game_Trigger, scripts_IRC_Trigger)


function shun_Game_Trigger(PlayerId, Type, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if pNick == nil then
		PPage(PlayerId, "!shun <Player>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		PPage(PlayerId, "Player not found.")
	elseif p == -2 then
		PPage(PlayerId, "Be more specific.")
	else
		local player = Players[p]
		if player.Shunned then
			PPage(p, "You have been unshunned by %s. You can use commands.", Get_Player_Name_By_ID(PlayerId))
			PPage(PlayerId, "%s has been unshunned.", player.Nick)
			player.Shunned = false
		else
			PPage(p, "You have been shunned by %s. You can no longer use commands.", Get_Player_Name_By_ID(PlayerId))
			PPage(PlayerId, "%s has been shunned.", player.Nick)
			player.Shunned = true
		end
	end
end

function shun_IRC_Trigger(Nick, Channel, Message)
	local pNick = string.match(Message, "%S+%s+([^\r\n%s]+)")
	if pNick == nil then
		IRC_Send(Channel, "!shun <Player>")
		return
	end
	
	local p = Find_Player(pNick)
	if p == -1 then
		IRC_Send(Channel, "Player not found.")
	elseif p == -2 then
		IRC_Send(Channel, "Be more specific.")
	else
		local player = Players[p]
		if player.Shunned then
			PPage(p, "You have been unshunned by %s@IRC. You can use commands.", Nick)
			IRC_Send(Channel, "%s%.2d%s%s has been unshunned.", string.char(3), Get_TeamIRCColour(Get_Team(p)), player.Nick, string.char(3))
			player.Shunned = false
		else
			PPage(p, "You have been shunned by %s@IRC. You can no longer use commands.", Nick)
			IRC_Send(Channel, "%s%.2d%s%s has been shunned.", string.char(3), Get_TeamIRCColour(Get_Team(p)), player.Nick, string.char(3))
			player.Shunned = true
		end
	end
end


Add_Command("shun", shun_Game_Trigger, shun_IRC_Trigger)


function vlimit_Game_Trigger(PlayerId, Type, Message)
	local set = string.match(Message, "%S+%s+([^\r\n%s]+)")
	local nset = tonumber(set)
	if nset == nil then
		local read = MemoryRead(0x008127F8, 4)
		PPage(PlayerId, "The current vehicle limit is: %s", IPToLong(read[4], read[3], read[2], read[1]))
	else
		if nset < 0 then
			PPage(PlayerId, "Please enter a number bigger than 0.")
		else
			local a1,a2,a3,a4 = LongToIP(nset)
			MemoryWrite(0x008127F8, {a4, a3, a2, a1})
			PPage(PlayerId, "The vehicle limit has been set.")
		end
	end
end

function vlimit_IRC_Trigger(Nick, Channel, Message)
	local set = string.match(Message, "%S+%s+([^\r\n%s]+)")
	local nset = tonumber(set)
	if nset == nil then
		local read = MemoryRead(0x008127F8, 4)
		IRC_Send(Channel, "The current vehicle limit is: %s", IPToLong(read[4], read[3], read[2], read[1]))
	else
		if nset < 0 then
			IRC_Send(Channel, "Please enter a number bigger than 0.")
		else
			local a1,a2,a3,a4 = LongToIP(nset)
			MemoryWrite(0x008127F8, {a4, a3, a2, a1})
			IRC_Send(Channel, "The vehicle limit has been set.")
		end
	end
end

Add_Command("vlimit", vlimit_Game_Trigger, vlimit_IRC_Trigger)


function mlimit_Game_Trigger(PlayerId, Type, Message)
	local set = string.match(Message, "%S+%s+([^\r\n%s]+)")
	local nset = tonumber(set)
	if nset == nil then
		local read = MemoryRead(0x008127F8, 4)
		PPage(PlayerId, "The current vehicle limit is: %s", IPToLong(read[4], read[3], read[2], read[1]))
	else
		if nset < 0 then
			PPage(PlayerId, "Please enter a number bigger than 0.")
		else
			local a1,a2,a3,a4 = LongToIP(nset)
			MemoryWrite(0x008127F8, {a4, a3, a2, a1})
			PPage(PlayerId, "The vehicle limit has been set.")
		end
	end
end

function mlimit_IRC_Trigger(Nick, Channel, Message)
	local set = string.match(Message, "%S+%s+([^\r\n%s]+)")
	local nset = tonumber(set)
	if nset == nil then
		local read = MemoryRead(0x0070D355, 1)
		IRC_Send(Channel, "The current mine limit is: %s", read[1])
	else
		if nset < 0  or nset > 255 then
			IRC_Send(Channel, "Please enter a number bigger than 0 and smaller than 256.")
		else
			MemoryWrite(0x0070D355, {nset})
			IRC_Send(Channel, "The mine limit has been set.")
		end
	end
end

Add_Command("mlimit", mlimit_Game_Trigger, mlimit_IRC_Trigger)


function kicklog_IRC_Trigger(Nick, Channel, Message)
	local keyword = string.match(Message, "%S+%s+([^%s\r\n]+)")
	if keyword == nil then
		IRC_Send(Channel, "!kicklog <type>")
		return
	end
	
	db:Query(Channel, "db_logsearch_Callback", string.format("SELECT * FROM Log WHERE Type = 'Kick' AND  Infomation LIKE '%%%s%%' ORDER BY Time DESC LIMIT 5;", keyword))
end

Add_Command("kicklog", nil, kicklog_IRC_Trigger)

function banlog_IRC_Trigger(Nick, Channel, Message)
	local keyword = string.match(Message, "%S+%s+([^%s\r\n]+)")
	if keyword == nil then
		IRC_Send(Channel, "!banlog <type>")
		return
	end
	
	db:Query(Channel, "db_logsearch_Callback", string.format("SELECT * FROM Log WHERE Type = 'Ban' AND Infomation LIKE '%%%s%%' ORDER BY Time DESC LIMIT 5;", keyword))
end

Add_Command("banlog", nil, banlog_IRC_Trigger)


function rank_Game_Trigger(PlayerId, Type, Message)
	local RankResult = nil
	function rank_db_callback(userdata, argc, data, columns)
		RankResult = data[1]
	end

	local pNick = string.match(Message, "%S+%s+([^%s\r\n]+)")
	if pNick == nil then
		pNick = Get_Player_Name_By_ID(PlayerId)
	end
	
	db:Query("", "rank_db_callback", string.format("SELECT COUNT(*) FROM Ranks WHERE Points >= (SELECT Points FROM Ranks WHERE Nick = '%s');", string.gsub(pNick, "'", "")))
	
	if RankResult == nil then
		Console_Inputf("msg %s is not yet ranked.", pNick)
	else
		local postfix = "th"
		local num = tonumber(RankResult) % 10
		if num == 1 then
			postfix = "st"
		elseif num == 2 then
			postfix = "nd"
		elseif num == 3 then
			postfix = "rd"
		end
		
		db:Query("", "rank_db_callback", string.format("SELECT Points FROM Ranks WHERE Nick = '%s';", string.gsub(pNick, "'", "")))
		Console_Inputf("msg %s is ranked %s%s with %s points.", pNick, num, postfix, RankResult)
	end
end

function rank_IRC_Trigger(Nick, Channel, Message)
	local RankResult = nil
	function rank_db_callback(userdata, argc, data, columns)
		RankResult = data[1]
	end
	local pNick = string.match(Message, "%S+%s+([^%s\r\n]+)")
	if pNick == nil then
		IRC_Send(Channel, "!rank <Player>")
		return
	end
	
	db:Query("", "rank_db_callback", string.format("SELECT COUNT(*) FROM Ranks WHERE Points >= (SELECT Points FROM Ranks WHERE Nick = '%s');", string.gsub(pNick, "'", "")))
	
	if RankResult == nil then
		IRC_Send(Channel, "%s is not yet ranked.", pNick)
	else
		local postfix = "th"
		local num = tonumber(RankResult) % 10
		if num == 1 then
			postfix = "st"
		elseif num == 2 then
			postfix = "nd"
		elseif num == 3 then
			postfix = "rd"
		end
		
		db:Query("", "rank_db_callback", string.format("SELECT Points FROM Ranks WHERE Nick = '%s';", string.gsub(pNick, "'", "")))
		IRC_Send(Channel, "%s is ranked %s%s with %s points.", pNick, num, postfix, RankResult)
	end
end

Add_Command("rank", rank_Game_Trigger, rank_IRC_Trigger)


function findban_IRC_trigger(Nick, Channel, Message)
	local search = string.match(Message, "%S+%s+([^%s\r\n]+)")
	if search == nil then
		IRC_Send(Channel, "!banfind <Query>")
		return
	end
	local textSearch = true
	local a1,a2,a3,a4 = string.match(search, "(%d+)%.(%d+)%.(%d+)%.(%d+)")
	if a1 ~= nil and  a2 ~= nil and  a3 ~= nil and  a4 ~= nil then
		textSearch = false
		search = tonumber(IPToLong(a1,a2,a3,a4))	
	end
	
	local BanResult = {}
	
	function banfind_db_callback(userdata, argc, data, columns)
		if textSearch == true then
			local ret = string.match(data[2], search) --Nick
			if ret ~= nil then
				table.insert(BanResult, {Type=1, BanId=tonumber(data[1]), Nick=data[2], Serial=data[5], WhoBy=data[3], Reason=data[4], IPStart=tonumber(data[6]), IPEnd=tonumber(data[7])})
				return
			end
			
			ret = string.match(data[5], search) --Serial
			
			if ret ~= nil then
				table.insert(BanResult, {Type=2, BanId=tonumber(data[1]), Nick=data[2], Serial=data[5], WhoBy=data[3], Reason=data[4], IPStart=tonumber(data[6]), IPEnd=tonumber(data[7])})
				return
			end
		else
			local b1 = tonumber(data[6])
			local b2 = tonumber(data[7])
			if b1 ~= nil and b2 ~= nil then
				if b1 <= search and b2 >= search then
					table.insert(BanResult, {Type=3, BanId=tonumber(data[1]), Nick=data[2], Serial=data[5], WhoBy=data[3], Reason=data[4], IPStart=b1, IPEnd=b2})
					return
				end
			end
		end		
	end
	
	db:Query("", "banfind_db_callback", "SELECT * FROM Bans;")
	
	if #BanResult == 0 then
		IRC_Send(Channel, "No results found for your search.")
	else
		IRC_Send(Channel, "Results found (displaying first 5).")
		for i,v in pairs(BanResult) do
			if i > 5 then
				return
			end
			
			local what = v.Nick;
			if what == "" then
				what  = v.Serial
			end
			if what == "" then
				if v.IPStart ~= nil and v.IPEnd ~= nil then
					what = string.format("%s - %s", LongToIP2(v.IPStart), LongToIP2(v.IPEnd)) 
				end
			end
			
			btype = "nick"
			if v.Type == 2 then
				btype = "serial"
			elseif v.Type == 3 then
				btype = "ip"
			end
			
			if what == "" then
				IRC_Send(Channel, "Error, ban ID #%d is corrupted.")
			else
				IRC_Send(Channel, "ID = %d (Matched %s), %s was banned by %s for %s", v.BanId, btype, what, v.WhoBy, v.Reason)
			end
		end
	end
end

Add_Command("findban", nil, findban_IRC_trigger)