--Made by Chaobrother. This script is free to reuse and modify! Hopefully it will cut down on
--freeslot/thing starvation. Object spawn state swapping may crash with objects that have
--MF_RUNSPAWNFUNC.
--This is a script which changes a particular property of an object.
--Setup: Use Lua.ObjectSkin then a comma seperated list. Each object to change needs 3 arguments
--The first argument is the type of property to change: S_RAISESTATE, S_SPAWNSTATE, etc;.
--Changing the spawn state will also alter the current state.
--The second is the type of object to modify.
--The third is the new property.

--Lua.spawnskin merely changes the frame and sprite of an object on spawn.
--Like object skin enter your parameters as a comma seperated list.
--The first argument is the object to look for.
--The second is the new sprite prefix with SPR_ in the front.
--The third is the new frame.
if (objectskin_initialized) then return end -- Check if the script has already been run

local function tableparse(x)
	local y = {}
	local i = 0
	for word in x:gmatch('[^,%s]+') do
		y[i+1] = word 
		i = $+1
	end	
	return y
end

local stateswaptable = {}
local skinswaptable = {}
local restoretable = {}
addHook("MapChange",function()
	for k, v in pairs(restoretable)
		for i = 1,#v-1,2
			mobjinfo[k][tostring(v[i])] = v[i+1]
		end
	end
	restoretable = {}
	if mapheaderinfo[gamemap].objectskin
		stateswaptable = tableparse(mapheaderinfo[gamemap].objectskin)
		for i = 2,#stateswaptable-1,3
			if restoretable[_G[stateswaptable[i]]] == nil
				restoretable[_G[stateswaptable[i]]] = {}
			end
			table.insert(restoretable[_G[stateswaptable[i]]],stateswaptable[i-1])
			table.insert(restoretable[_G[stateswaptable[i]]],mobjinfo[_G[stateswaptable[i]]][stateswaptable[i-1]])
			mobjinfo[_G[stateswaptable[i]]][stateswaptable[i-1]] = _G[stateswaptable[i+1]]
		end
	end
	if mapheaderinfo[gamemap].spawnskin 
		skinswaptable = tableparse(mapheaderinfo[gamemap].spawnskin)
	end
end)

addHook("MobjSpawn",function(mo)
	if not mapheaderinfo[gamemap].spawnskin return end
	for i = 1,#skinswaptable,3
		if mo.type == _G[skinswaptable[i]] and mo.valid
			mo.sprite = _G[skinswaptable[i+1]]
			mo.frame = _G[skinswaptable[i+2]]
		end
	end
end)
rawset(_G, "objectskin_initialized", true) 