-- The argument must be an integer:

function fix(num)
	num = tostring(num)
	num = (num:reverse())
	local newNum = ""
	for i = 1,#num do
		if ((i%3) == 0) then	-- Modulo trick to determine if a number is divisible by 3
			newNum = (newNum .. num:sub(i,i) .. ",")
		else
			newNum = (newNum .. num:sub(i,i))
		end
	end
	newNum = newNum:reverse()
	if (newNum:sub(1,1) == ",") then
		newNum = newNum:sub(2)	-- Quick-fix to correct a mistake in the loop above
	end
	return newNum	-- Returns a string, NOT a number!
end

function count()
	if (active) then
		awaiting = (awaiting+1)
		return
	end
	active = true
	wait()	-- When using 'DescendantRemoving,' the brick removing isn't always gone by the time the function is called, so this gives it some time to be removed
	baseParts = {}	-- Clear table
	local function scan(parent)
		for _,v in pairs(parent:GetChildren()) do	-- Easiest way to get all parts is to quickly scan through with loops
			if (v:IsA("BasePart")) then
				table.insert(baseParts,v)
			end
			if (((#baseParts%1000) == 0) and (#baseParts ~= 0)) then	-- Add in a quick wait every 1k bricks to stop an unneccessary lag-attack
				wait()
			end
			scan(v)
		end
	end
	scan(game.Workspace)
	local n = #baseParts
	script.Parent.Count.Text = (fix(n) .. (n == 1 and " Brick" or " Bricks"))	-- Not many people realize what you can do with 'and' and 'or'
	for i = 1,awaiting do
		count()
	end
	awaiting = 0
	active = false
end

function setup()	-- Yes, I add pointless functions to capture events. It feels more organized
	count()
	game.Workspace.DescendantAdded:connect(count)
	game.Workspace.DescendantRemoving:connect(count)
end

setup()
