addHook("MobjSpawn", function(mo)
	if mo.type == MT_STAGEGATE
		mo.warptimer = 0
		mo.waittimer = 0
	end
	if mo.type == MT_PLAYER
	end
	if mo.type == MT_STAGEGATE -- Yes the stage gate is a stage gate
	and mo.state == S_STAGEGATE_ACTIVE
	and mo.tanation == nil
		local light = P_SpawnMobjFromMobj(mo, 0, 0, 0, MT_STAGEGATELIGHT)
			light.state = S_STAGEGATELIGHT
			light.tanation = mo
			light.blendmode = AST_ADD
		mo.tanation = light
	end
end)

addHook("PlayerSpawn", function(p)
	if p and p.mo and p.mo.valid
		p.stageexittimer = 0
		p.stagetimer = 0
		p.fadetimer = 0
		p.hubtimer = 0
	end
end)

addHook("MobjThinker", function(mo)
	if mo.type == MT_STAGEGATE -- Yes the stage gate is a stage gate
		if mo.spawnpoint.args[0]
			mo.warp = mo.spawnpoint.args[0]
		end
		if mo.spawnpoint.args[1] == 0
			mo.state = S_STAGEGATE_ACTIVE
			mo.tanation.frame = A
		end
		if mo.spawnpoint.args[1] == 1
			mo.state = S_STAGEGATENIGHT_ACTIVE
			mo.tanation.frame = B
		end
		if mo.spawnpoint.args[1] == 2
			mo.state = S_STAGEGATECUSTOM_ACTIVE
			mo.tanation.frame = C
			if mo.spawnpoint.args[2]
				mo.color = mo.spawnpoint.args[2]
				mo.tanation.color = mo.spawnpoint.args[2]
			end
		end
		if mo.waittimer > 0
			mo.waittimer = $-1
		end
	end
end, MT_STAGEGATE)

addHook("PlayerThink", function(player)
	if player.selectingstage == true
		player.pflags = $|PF_FULLSTASIS
		if (player.cmd.buttons & BT_JUMP) -- Accept
			player.pflags = $ & ~ PF_FULLSTASIS
			G_SetCustomExitVars(player.mapselected, 1)
			G_ExitLevel()
			player.selectingstage = false
		end
		
		if (player.cmd.buttons & BT_USE) -- Cancel
			player.pflags = $ & ~ PF_FULLSTASIS
			player.selectingstage = false
		end
	end
end)

addHook("TouchSpecial",function(special,toucher)
	--Use a Stage Gate if...
	if special.type == MT_STAGEGATE
		if special.state == S_STAGEGATE_ACTIVE or special.state == S_STAGEGATENIGHT_ACTIVE or special.state == S_STAGEGATECUSTOM_ACTIVE
			if toucher.player and toucher.player.valid
				if not toucher.player.selectingstage and not special.waittimer
					if special.warp == nil
						toucher.player.mapselected = special.angle/ANG1
					else
						toucher.player.mapselected = special.warp
					end
					toucher.player.selectingstage = true
				end
				special.waittimer = TICRATE/2
			end
		end
	end
	if special.type == MT_STAGEGATE
	return true
	end
end)