------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



function Scale()
	local magnitude = GrabMagnitude()
	
	--- Don't run this if we don't need to (resolution hasn't changed much)
	if (not magnitude) or (lastMagnitude and math.abs(lastMagnitude - magnitude) < differenceToScan) or (lastMagnitude and lastMagnitude >= bestResolution and magnitude >= bestResolution) then
		return
	end
	lastMagnitude = magnitude
	
	--- Calculate ratio
	local ratio = maxDownscale + ((math.min(magnitude, bestResolution) / bestResolution) * (1 - maxDownscale))
	
	
	--- Change 9Slices
	for _, gui in ipairs(_L.Player.Get("PlayerGui"):GetChildren()) do
		if gui.ClassName == "ScreenGui" and (not _L.Functions.SearchArray(blacklist, gui.Name)) then
			for i, v in ipairs(gui:GetDescendants()) do
				--- Yield to prevent microstuttering for lots of gui elements
				if i%200 == 0 then
					wait()
				end
				
				--- Adjust 9slice scaling ratio based on resolution
				if (v.ClassName == "ImageLabel" or v.ClassName == "ImageButton") and v.ScaleType == Enum.ScaleType.Slice then
					if not archive[v] then
						archive[v] = v.SliceScale
					end
					local base = archive[v]
					v.SliceScale = base * ratio
				end
			end
		end
	end
end


function GrabMagnitude()
	local resolution = _L.Player.Get("Camera").ViewportSize
	if resolution then
		local magnitude = resolution.Magnitude
		return magnitude
	end
end

