-------------------------------
-- SSTRP
-- Author: MNWRP
--
-- util.lua
-- Contains important server functions.
-------------------------------

-- Oh, don't mind me.. just adding a useful function.
function string.explode(str)

	local rets = {};
	
	for i=1, string.len(str) do
	
		rets[i] = string.sub(str, i, i);
		
	end
	
	return rets;

end

function ReferenceFix(data)

	if(type(data) == "table") then
	
		return table.Copy(data);
		
	else
	
		return data;
		
	end
	
end

function NilFix(val, default)

	if(val == nil) then
	
		return default;
	
	else
	
		return val;
		
	end
	
end

function InitTime() -- Load the time from a text file or default value, this occurs on gamemode initialization.

	local clumpedtime = "1 1 2012 1"
	
	if(file.Exists("SSTRP/time.txt")) then
	
		clumpedtime = file.Read("SSTRP/time.txt")
		
	else
	
		file.Write("SSTRP/time.txt", "1 1 2012 1")
		
	end
	
	local unclumped = string.Explode(" ", clumpedtime)
	ClockDay = tonumber(unclumped[1])
	ClockMonth = tonumber(unclumped[2])
	ClockYear = tonumber(unclumped[3])
	ClockMins = tonumber(unclumped[4])
	
	SetGlobalString("time", "Loading..")
	
end

function SaveTime()

	local clumpedtime = ClockDay .. " " .. ClockMonth .. " " .. ClockYear .. " " .. ClockMins
	file.Write("SSTRP/time.txt", clumpedtime)
	
end

function SendTime()

	local nHours = string.format("%02.f", math.floor(ClockMins / 60));
	local nMins = string.format("%02.f", math.floor(ClockMins - (nHours*60)));
	
	if(tonumber(nHours) > 12) then 
	
		nHours = nHours - 12
		timez = "PM";
		
	else
	
		timez = "AM";
		
	end
	
	if(tonumber(nHours) == 0) then
	
		nHours = 12
		
	end
	
	SetGlobalString("time", ClockMonth .. "." .. ClockDay .. "." .. ClockYear .. " - " .. nHours .. ":" .. nMins .. timez)
	
end

function FindPlayer(name)

	local ply = nil;
	local count = 0;
	
	for k, v in pairs(player.GetAll()) do
	
		if(string.find(v:Nick(), name) != nil) then
			
				ply = v;
				
		end
			
		if(string.find(v:Name(), name) != nil) then
			
			ply = v;
				
		end
			
	end
	
	return ply;
	
end