
local function getBit(gate, val)
	local gatedata = Gate.getdata(gate)
	
	--print("get bit", val)
	if gatedata.listenState=="wait" then
		if val==1 then
			gatedata.listenState = "getbits"
			gatedata.bitsReceived = 0
			--print("", "state = listen")
		end
	elseif gatedata.listenState=="getbits" then
		gatedata.valReceived = gatedata.valReceived + math.pow(2, textbrick2_bitsNeeded-1-gatedata.bitsReceived)*val
		gatedata.bitsReceived = gatedata.bitsReceived+1
		
		--print("", "append", gatedata.bitsReceived-1, val)
		
		if gatedata.bitsReceived==textbrick2_bitsNeeded then
			
			gatedata.listenState = "terminate"
		end
	elseif gatedata.listenState=="terminate" then
		if val==1 then
			--print("", "terminate")
			
			local printid = gatedata.valReceived
			local printname = textbrick2_idxToPrint[printid]
			
			Gate.cb(gate, printname)
			
			--print("", "set print", string.format("%02x", printid), printname)
		end
		
		gatedata.listenState = "wait"
		
		gatedata.bitsReceived = 0
		gatedata.valReceived = 0
	end
end

local function changeTo(gate, val)
	local gatedata = Gate.getdata(gate)
	
	local tick = Gate.gettick(gate)
	local ticks = tick-gatedata.lastTickChanged
	
	local bits = math.min(ticks, 10)
	for i = 1, bits do
		getBit(gate, val)
	end
	
	gatedata.lastTickChanged = tick
end

return function(gate)
	if Gate.getportisrising(gate, 1) then
		changeTo(gate, 0)
	elseif Gate.getportisfalling(gate, 1) then
		changeTo(gate, 1)
	end
end
