local function UpdateGateColor(gate)
    
    if not gate or not gate.valid or not gate.spawnpoint or not gate.spawnpoint.valid then
        return
    end
    
    local newColor = gate.spawnpoint.angle or SKINCOLOR_WHITE
    
    if gate.color ~= newColor then
        gate.color = newColor
    end
end

addHook("MobjThinker", function(mo)
    local success, err = pcall(UpdateGateColor, mo)
    if not success then
        print("Error in UpdateGateColor: " .. err)
    end
end, MT_STAGEGATE)

addHook("MobjSpawn", function(mo) -- Stage Gate Spawn
	if mo.type == MT_STAGEGATE
		mo.waittimer = 0
	end
	if mo.type == MT_STAGEGATE 
	and mo.state == S_PORTAL1
	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) -- Player Spawn Values
	if p and p.mo and p.mo.valid
		p.stageexittimer = 0
		p.stagetimer = 0
		p.jumpholdtimer = 0
		p.spinholdtimer = 0
		p.fadetimer = 0
		p.hubtimer = 0
	end
end)

addHook("MobjThinker", function(mo)
	if mo.type == MT_STAGEGATE 
		if mo.spawnpoint.args[0]
			mo.warp = mo.spawnpoint.args[0]
		end
		if mo.waittimer > 0
			mo.waittimer = $-1
		end
	end
end, MT_STAGEGATE)

addHook("PlayerThink", function(player) -- Player Stage Gate Control
	if player.selectingstage == true
		player.pflags = $|PF_FULLSTASIS
		if (player.cmd.buttons & BT_JUMP) and not player.jumpholdtimer -- Accept
			player.pflags = $ & ~ PF_FULLSTASIS
			G_SetCustomExitVars(player.mapselected, 1)
			G_ExitLevel()
			player.selectingstage = false
		end
		
		if (player.cmd.buttons & BT_USE) and not player.spinholdtimer -- Cancel
			player.pflags = $ & ~ PF_FULLSTASIS
			player.selectingstage = false
		end
	end
	if (player.cmd.buttons & BT_JUMP)
		player.jumpholdtimer = $+1
	else
		player.jumpholdtimer = 0
	end
		
	if (player.cmd.buttons & BT_USE)
		player.spinholdtimer = $+1
	else
		player.spinholdtimer = 0
	end
end)

addHook("TouchSpecial",function(special,toucher)
	--Use a Stage Gate if...
	if special.type == MT_STAGEGATE
		if special.state == S_PORTAL1 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)