local d={}d.__index=d function d.new()local l=setmetatable({_bindable=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116"),_connections={},_args={},_threads=0;_id=0},d)return l end function d.Is(l)return type(l)=="\116\097\098\108\101"and getmetatable(l)==d end function d.Fire(d,...)local l=d._id d._id=d._id+1 d._args[l]={#d._connections+d._threads;{n=select("\035",...),...}}d._threads=0 d._bindable:Fire(l)end function d.Wait(d)d._threads=d._threads+1 local l=d._bindable.Event:Wait()local R=d._args[l]R[1]=R[1]-1 if R[1]<=0 then d._args[l]=nil end return table.unpack(R[2],1,R[2].n)end function d.Connect(l,d)local R=Connection.new(l,l._bindable.Event:Connect(function(R)local z=l._args[R]z[1]=z[1]-1 if z[1]<=0 then l._args[R]=nil end d(table.unpack(z[2],1,z[2].n))end))table.insert(l._connections,R)return R end function d.DisconnectAll(d)for d,l in ipairs(d._connections)do if l._conn then l._conn:Disconnect()end end d._connections={}d._args={}end function d.Destroy(d)d:DisconnectAll()d._bindable:Destroy()end return d


local Signal = {}
Signal.__index = Signal


function Signal.new()
	local self = setmetatable({
		_bindable = Instance.new("BindableEvent");
		_connections = {};
		_args = {};
		_threads = 0;
		_id = 0;
	}, Signal)
	return self
end


function Signal.Is(obj)
	return (type(obj) == "table" and getmetatable(obj) == Signal)
end


function Signal:Fire(...)
	local id = self._id
	self._id = self._id + 1
	self._args[id] = {#self._connections + self._threads, {n = select("#", ...), ...}}
	self._threads = 0
	self._bindable:Fire(id)
end


function Signal:Wait()
	self._threads = self._threads + 1
	local id = self._bindable.Event:Wait()
	local args = self._args[id]
	args[1] = args[1] - 1
	if (args[1] <= 0) then
		self._args[id] = nil
	end
	return table.unpack(args[2], 1, args[2].n)
end

function Signal:Connect(handler)
	local connection = Connection.new(self, self._bindable.Event:Connect(function(id)
		local args = self._args[id]
		args[1] = args[1] - 1
		if (args[1] <= 0) then
			self._args[id] = nil
		end
		handler(table.unpack(args[2], 1, args[2].n))
	end))
	table.insert(self._connections, connection)
	return connection
end


function Signal:DisconnectAll()
	for _,c in ipairs(self._connections) do
		if (c._conn) then
			c._conn:Disconnect()
		end
	end
	self._connections = {}
	self._args = {}
end


function Signal:Destroy()
	self:DisconnectAll()
	self._bindable:Destroy()
end

return Signal
