--[System Functions]
--Functions pertaining to basic activities, like resolving the path of the currently executing script
-- or appending tables together.
--This should be called at startup, as a lot of other scripts use these functions.

--Basic Math
function math.sign(v)
	return (v >= 0 and 1) or -1
end
function math.round(v, bracket)
	bracket = bracket or 1
	return math.floor(v/bracket + math.sign(v) * 0.5) * bracket
end

--Function that resolves the path of the currently executing script.
fnResolvePath = function()

	local sStartPath = LM_GetCallStack(0)
	local iLen = string.len(sStartPath)

	--Determine where the last slash is
	local bFoundSlash = false
	local sLetter = ""
	for i = iLen, 1, -1 do
		sLetter = string.sub(sStartPath, i, i)
		if(sLetter == "/" or sLetter == "\\") then
			iLen = i
			bFoundSlash = true
			break
		end
	end

	--No slash found.  We can skip a step, and just return "/"
	if(bFoundSlash == false) then
		return ""
	end

	local sFinishPath = ""
	for i = 1, iLen, 1 do

		sLetter = string.sub(sStartPath, i, i)
		sFinishPath = sFinishPath .. sLetter
	end

	return sFinishPath
end

--Function that resolves the name of the currently executing script.
fnResolveName = function()
	
	local sStartPath = LM_GetCallStack(0)
	local iLen = string.len(sStartPath)

	--Determine where the last slash is
	local sLetter = ""
	for i = iLen, 1, -1 do
		sLetter = string.sub(sStartPath, i, i)
		if(sLetter == "/" or sLetter == "\\") then
			iLen = i
			break
		end
	end

	local sFinishPath = string.sub(sStartPath, iLen+1)

	return sFinishPath
end

--Function that appends two arrays (or tables) together.
-- Table2 is appended to the end of Table1. Table2 is unchanged.
function fnAppendTables(saTable1, saTable2)
	local iArrayLen2 = #saTable2
	for i = 1, iArrayLen2, 1 do
		table.insert(saTable1, saTable2[i])
	end

	return saTable1
end

--Function causes all subfolders in a folder to execute a specified file.
-- Relies on the SugarFileSystem, which can be Allegro or Boost.
fnExecAll = function(sCurrentPath, sFilePattern)

	--Scan
	FS_Open(sCurrentPath, false)

	--For each entry, appends the sFilePattern and try to run it.
	-- Ignore non-directories.  Directories end in '/'.
	sPath = FS_Iterate()
	while (sPath ~= "NULL") do

		--Check the last byte for '/'
		local iLength = string.len(sPath)
		if(string.byte(sPath, iLength) == string.byte("/")) then

			--Append the sFilePattern on the end and call it
			LM_ExecuteScript(sPath .. sFilePattern)

		end

		sPath = FS_Iterate()

	end

	--Clean
	FS_Close()

end
