--------------------- 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.      --
-----------------------Thank you-------------------------


Setting = {Next_Level = {}, Keys = {}, Name = ""}
function Setting:new (o)
	o = o or {}
	setmetatable(o, self)	
	self.__index = self
	return o
end

Settings = Setting:new({Next_Level = {}, Keys = {}, Name = "Global"})

function Settings_Parse(str, sTable)
	for block in string.gmatch(str, "[^{]+%b{}") do
		bname = string.match(block, "%s+([^%s]+)")
		local s = { Next_Level = {}, Keys = {}, Name = bname}
		sTable.Next_Level[bname] = s
		Settings_Parse(string.match(block, "%b{}"), s)		
		
	end
	str = string.match(str, "^{(.-)}$")
	if str == nil then
		return
	end	
	str = string.gsub(str, "[^{]+%b{}", "")	
	if not sTable.Keys then
		sTable.Keys = {}
	end
	for k,v in string.gmatch(str, "([^%s]+)%s+=%s+([^\n]+)") do
		sTable.Keys[k] = v:gsub("^%s*(.-)%s*$", "%1")	
	end
end

function Settings_Pre(File)
	Settings = Setting:new({Next_Level = {}, Keys = {}, Name = "Global"})
	local f = io.open(File, "r")
	if f == nil then
		return false
	end
	local Contents = f:read("*all")
	io.close(f)
	
	--strip comments
	
	Contents = string.gsub(Contents, "%/%*.-%*%/", "") -- /* */
	Contents = string.gsub(Contents, "%/%/[^\n]+", "")     -- //
	Contents = string.gsub(Contents, "%-%-[^\n]+", "")     -- --
	
	Settings_Parse(Contents, Settings)
	return true
end

if Settings_Pre("YaLB\\Settings.cfg") == false then 
	error("Failed to load \"YaLB\\Settings.cfg\"")
end

function Find_Block(...)  
	local next_block = Settings 
	for i,v in pairs(arg) do 
		if i == "n" then 
			return next_block 
		end 
		if next_block.Next_Level[v] ~= nil then 
			next_block = next_block.Next_Level[v] 
		else
			return nil
		end
	end 
	return next_block 
end