

--how far away it will count nearby lights
local assignLightsRange = 100

lightE = {}
decalE = {}
local newalr = assignLightsRange * assignLightsRange
walltorch = {}

--name any lights controlled by this entity the same + "light"
--name any decals controlled by this entity the same + "decal"
--i.e. name this "walltorch" and any nearby lights should be called "walltorchlight" and any decals named "walltorchdecal"
--there is also a range check so you can name all torches the same for easy placement
--but make sure they are outside the assignLightsRange 'range' of each other
function walltorch_init(e)
	SetActivated(e,0)
	walltorch[e] = e
	lightE[e] = {}
	decalE[e] = {}
end 

function walltorch_main(e)
	--set up the torch by finding nearby lights assigned to it (by name)
	if g_Entity[e]['activated'] == 0 then 		
		local tname = GetEntityName(e)
		local x1,y1,z1 = GetEntityPosAng(e)
		for a = 1, g_EntityElementMax do 
			if g_Entity[a] ~= nil then 
				local tname2 = GetEntityName(a)
				if tname2 == tname.."light" then 
					local x2,y2,z2 = GetEntityPosAng(a)
					if GetDistance(x1,y1,z1, x2,y2,z2) < newalr then 
						lightE[e][a] = a 
					end
				elseif tname2 == tname.."decal" then 
					local x2,y2,z2 = GetEntityPosAng(a)
					if GetDistance(x1,y1,z1, x2,y2,z2) < newalr then 
						decalE[e][a] = a 
					end
				end 
			end 
		end 
		SetActivated(e,1)
		
	--use SetActivated(e,1) to turn the torch & lights on (if it was off)
	elseif g_Entity[e]['activated'] == 1 then 
		for a,b in pairs (decalE[e]) do 
			Show(b)
		end 
		for a,b in pairs (lightE[e]) do
			--ShowLight(b)
			SetActivated(b,0)
		end 	
		SetActivated(e,2)
		
	--torch is actively on
	elseif g_Entity[e]['activated'] == 2 then 
		
		
	--use SetActivated(e,3) to turn the torch & lights off
	elseif g_Entity[e]['activated'] == 3 then 
		for a,b in pairs (decalE[e]) do 
			Hide(b)
		end 
		for a,b in pairs (lightE[e]) do
			--HideLight(b)
			SetActivated(b,2)
		end 
		SetActivated(e,4)
		
	--torch is off
	elseif g_Entity[e]['activated'] == 4 then 
		
	end 


end 

function LightTorch(e)
	SetActivated(e,1)
end 

function ExtinguishTorch(e)
	SetActivated(e,3)
end 

function GetDistance(tx1,ty1,tz1, tx2,ty2,tz2)
	local x3 = tx2-tx1 
	local y3 = ty2-ty1 
	local z3 = tz2-tz1 
	return x3*x3+y3*y3+z3*z3 
end