--Replicates the control sector spaghetti in sublime bastion for easier useage and less lag.
--Front X and Y offsets determine sector and fof tag, respectively.
--Back X offset determines the alpha "index" to start at or it starts at 0 alpha.
--Back Y offset determines the duration each increment is visible (max/min increments last duration^2)
--or base duration is 6 tics (36 tics at 0 and 255 alpha)

local fadetable = { 1, 36, 73, 109, 146, 189, 219, 256 }
local bastionindex = {}

--This function needs an upper unpegged delay of at least 1 to work. Use 10 to be safe.
local function bastionfadefof(l,mo,s)
	local initindex
	local basedur
	if l.backside
		if l.backside.textureoffset != 0
			initindex = l.backside.textureoffset/FRACUNIT
		else
			initindex = 1
		end
		if l.backside.rowoffset != 0
			basedur = l.backside.rowoffset/FRACUNIT
		else
			basedur = 6
		end
	else
		initindex = 1
		basedur = 6
	end
	local sectortag = l.frontside.textureoffset/FRACUNIT
	local foftag = l.frontside.rowoffset/FRACUNIT
	for s in sectors.iterate
			if s.tag != sectortag continue end
			for rover in s.ffloors()
				if rover.sector.tag != foftag continue end
				table.insert(bastionindex, {sector = s,fof = rover, index = initindex,
											ticker = basedur, doreverse = (initindex >= #fadetable), basetic = basedur,
											duplicheck = false})
			end
	end
end


addHook("LinedefExecute", bastionfadefof,"SBFADFOF")

addHook("ThinkFrame", function()
	if leveltime == 0
		bastionindex = {}
	end
	if leveltime >= 1
		--print(#bastionindex)
		for k,v in ipairs(bastionindex) do
			if v.index == nil or v.index == 0 
				v.index = 1
			end
			if v.index <= 1 and v.duplicheck == false 
				v.doreverse = false
				--v.ticker = v.basetic * v.basetic
				v.ticker = 2*v.basetic
				v.index = 1
				v.duplicheck = true
			end
			if v.index >= #fadetable and v.duplicheck == false
				v.doreverse = true
				v.ticker = v.basetic * v.basetic
				v.index = #fadetable
				v.duplicheck = true
			end
			if v.ticker >= 0
				v.fof.alpha = fadetable[v.index]
				v.ticker = $1-1
			end
			if v.doreverse == true and v.ticker <= 0
				v.index = $1 - 1
				v.duplicheck = false 
			end
			if v.doreverse == false and v.ticker <= 0
				v.index = $1 + 1
				v.duplicheck = false 
			end
			if v.ticker <= 0
				--[[if (v.index == 2 and v.doreverse == false)  or (v.index == (#fadetable - 1) and v.doreverse == true)
					v.ticker = 0
				else 	
					v.ticker = v.basetic
				end]]
				v.ticker = v.basetic
			end
		end
	end	
end)

addHook("MapLoad", function(map)
	
end)