//
// "global" variables related to script
//
local skyboxmo = {} // table containing skybox mobjs
local numskyboxes = 0 // count number of skyboxes to prevent errors
local checkedskyboxes = false // variable to make sure joining a server mid-game doesn't CONSTANTLY recheck skyboxes

//
// ResetSkyboxStats
//
// Reset skybox lists and other vars
//
local function ResetSkyboxStats()
	//print("resetting stats...")
	skyboxmo = {}
	numskyboxes = 0
	checkedskyboxes = false
end

addHook("MapLoad", ResetSkyboxStats) // hook the function

//
// FindSkyboxes
//
// Collects all the skybox viewpoint mobjs in the map, and counts up the number in said map
//
local function FindSkyboxes()
	// collect the new viewpoints through map things, so we don't have to suffer lag
	for mapthing in mapthings.iterate
		if mapthing.type != mobjinfo[MT_SKYBOX].doomednum
			continue // not the right Map thing number
		end
		if mapthing.options & MTF_OBJECTSPECIAL
			continue // not a viewpoint
		end
		if not mapthing.mobj
			continue // ???? (skybox thing types should all have mobjs)
		end
		
		table.insert(skyboxmo, mapthing.mobj)
		numskyboxes = $1 + 1 // add to total
		//print("skybox found!")
	end
	
	checkedskyboxes = true // yes, you've checked for them now, don't bother us anymore
end

// minor function to make sure FindSkyboxes() is called ONLY when it hasn't been checked before
local function Stuff()
	if not checkedskyboxes
		FindSkyboxes()
		//print(numskyboxes+" skyboxes found!")
	end
end

addHook("ThinkFrame", Stuff) // hook the function

//
// SetSkyboxLE
//
// Used by any Linedef type 443s with the name "SETSKYBX" in front upper texture:
// Sets the skybox number determined by texture offsets for the triggering player.
// As a bonus, ML_NOCLIMB affects all players, if you like!
//
local function SetSkyboxLE(line, mobj)
	local id = line.frontside.textureoffset>>FRACBITS // front side's x-offsets, scaled down to regular integers
	
	if numskyboxes == 0
		print("ERROR: (SETSKYBX for line #"+#line+") No skyboxes in map!") // note: #line prints linedef number
	end
	
	if (id <= 0) or (id > numskyboxes)
		print("ERROR: (SETSKYBX for line #"+#line+") Skybox id is out of range!")
		//print("numskyboxes = "+numskyboxes)
	end
	
	if line.flags & ML_NOCLIMB
		// doesn't really matter what type of object triggered it here
		P_SetSkyboxMobj(skyboxmo[id]) // apply skybox to all players!
	else
		if not mobj.player
			return // only supposed to be triggered by a player!
		end
		P_SetSkyboxMobj(skyboxmo[id], mobj.player) // apply skybox to only the triggering player
	end
end

addHook("LinedefExecute", SetSkyboxLE, "SETSKYBX") // hook the function