--- Scan for GUIs to add to index

local function Scan(instance, parent)
	--- Calculates which gui instance is more important (based on dependance and class)
	local function MoreImportant(a, b)
		local aHeight, aCurr = 0, a
		local bHeight, bCurr = 0, b
		repeat  aCurr = aCurr.Parent  aHeight = aHeight + 1  until aCurr.Parent == playerGui
		repeat  bCurr = bCurr.Parent  bHeight = bHeight + 1  until bCurr.Parent == playerGui
		if aHeight == bHeight then
			for i, v in ipairs(whitelistedClasses) do
				if v == a.ClassName then
					aHeight = i
				elseif v == b.ClassName then
					bHeight = i
				end
			end
		end
		return (aHeight < bHeight and a or b)
	end
	
	--- Iterate through gui instance children
	for _, child in ipairs(instance:GetChildren()) do
		if child.ClassName == "ScreenGui" and (not _L.Functions.SearchArray(blacklistedGuis, child.Name)) then
			GUI[child.Name:gsub("%s+", "")] = {Gui = child}
			Scan(child, child)
		elseif child:IsA("GuiObject") and parent then
			local exists = GUI[parent.Name:gsub("%s+", "")][child.Name:gsub("%s+", "")]
			if (not exists) or (exists and MoreImportant(child, exists) == child) then
				GUI[parent.Name:gsub("%s+", "")][child.Name:gsub("%s+", "")] = child
			end
			Scan(child, parent)
		end
	end
end

Scan(playerGui)

playerGui.ChildAdded:Connect(function(child)
	if child.ClassName == "ScreenGui" and (not _L.Functions.SearchArray(blacklistedGuis, child.Name)) then
		GUI[child.Name:gsub("%s+", "")] = {Gui = child}
		Scan(child, child)
	end
end)

