local c_code = [[
// Auto-generated by gencfuncs.lua

enum GateFuncs {
	GateFunc_None,
%s
};

%s

GateFunc sim_logic_functions[] = {
	0,
%s
};

]]

local lua_code = [[
-- Auto-generated by gencfuncs.lua

local cFuncsByName = {
%s
}

local cDataSizeByName = {
%s
}

return cFuncsByName, cDataSizeByName
]]
local function writeFile(fn, data)
	local f = io.open(fn, "wb") or error("Could not open file for writing: "..fn)
	f:write(data)
	f:close()
end

local function exportGates(gates)
	local gateList = {}
	local gateFuncList = {}
	local gateSizeList = {}
	for k, gate in pairs(gates) do
		table.insert(gateList, gate.name or error("gate "..k.." has no name"))
		table.insert(gateFuncList, gate.func or error("gate "..gate.name.." has no c function"))
		table.insert(gateSizeList, gate.size or 0)
	end
	
	local function map(t, f) local u = {}; for i, v in ipairs(t) do table.insert(u, f(v, i)) end; return u; end
	writeFile("compiled_sim_gates.c", string.format(c_code,
		table.concat(map(gateList, function(v, i) return string.format("\tGateFunc_%s,", v) end), "\n"),
		table.concat(map(gateList, function(v, i) return string.format("GATEFUNC(%s) {\n\t%s\n}", v, gateFuncList[i]:gsub("\n", "\n\t"):gsub("\n+$", ""):gsub("^\n+", "")) end), "\n"),
		table.concat(map(gateList, function(v, i) return string.format("\tGATEFUNCID(%s),", v) end), "\n")
	))
	writeFile("compiled_sim_gates.lua", string.format(lua_code,
		table.concat(map(gateList, function(v, i) return string.format("\t[\"%s\"] = %i,", v:lower(), i) end), "\n"),
		table.concat(map(gateList, function(v, i) return string.format("\t[\"%s\"] = %i,", v:lower(), gateSizeList[i]) end), "\n")
	))
end

local gates = {
	{ name = "Diode", func = "setport(2, getport(1));"  },
	{ name = "Not"  , func = "setport(2, !getport(1));" },
}
exportGates(gates)