freeslot("MT_YUEMBLEM", "SPR_YEML", "S_YUEMBLEM", "S_YUEMBLEMGET", "sfx_yusfxz")

--I've moved the MAINCFG stuff to Lua for compactness' sake.
mobjinfo[MT_YUEMBLEM] = {
spawnstate = S_YUEMBLEM,
deathstate = S_YUEMBLEMGET,
deathsound = sfx_yusfxz,
radius = 8*FRACUNIT,
height = 16*FRACUNIT,
flags = MF_NOCLIPTHING,
}
states[S_YUEMBLEM] = {
sprite = SPR_YEML,
frame = A,
duration = -1,
nextstate = S_YUEMBLEM
}
states[S_YUEMBLEMGET] = {
sprite = SPR_YEML,
frame = A,
duration = 50,
nextstate = S_NULL
}
sfxinfo[sfx_yusfxz] = {flags = SF_X8AWAYSOUND|SF_X2AWAYSOUND|SF_X4AWAYSOUND,} --Far reaching sound.

local TOTALEMBLEMS = 0 --The amount of emblems that exist in a map.
local SAEMBLEMS = true

--Find every emblem, then assign numbers to each emblem on load.
addHook("MapLoad", function()
	TOTALEMBLEMS = 0 --Reset remaining emblems count.
	if SAEMBLEMS != true or (titlemapinaction) return end --
	
	local EMBLEMS = {}
	local EMBLEMMAPTHINGNUM = mobjinfo[MT_EMBLEM].doomednum
	for mt in mapthings.iterate do --Scan for every emblem.
		if (mt.type == EMBLEMMAPTHINGNUM)
		or mt.mobj and (mt.mobj.type == MT_EMBLEM) 
			TOTALEMBLEMS = $+1
			EMBLEMS[TOTALEMBLEMS] = mt
		end
	end
	
	if TOTALEMBLEMS != 0
	
		table.sort(EMBLEMS, function(a, b) return a.angle < b.angle end) --Put the emblems in the right order first!
		
		local X,Y,Z --Coordinates to spawn at. Manipulated later.
		for i = 1,#EMBLEMS
			local mt = EMBLEMS[i] if not (mt and mt.valid) continue end --
			if mt.mobj and mt.mobj.valid
				X,Y,Z = mt.mobj.x,mt.mobj.y,mt.mobj.z
			else
				X,Y,Z = mt.x<<16,mt.y<<16,mt.z<<16
			end
			local ghs = P_SpawnMobj(X,Y,Z,MT_YUEMBLEM)
			ghs.yuemblem = i --Assigned emblem number!
			ghs.yuemblemMOBJ, ghs.yuemblemMAPTHING = mt.mobj, mt
			ghs.yuemblemZ = mt.z --Backup height incase both both mobjs disappear in 3 tics.
			ghs.yuemblemtotal = TOTALEMBLEMS
		end
	end
end)


--Always set this on spawn.
addHook("MobjSpawn", function(s)
	s.renderflags = RF_SEMIBRIGHT|RF_PAPERSPRITE --Mildly shiny papersprite
	s.scale = 110000 --These are beeg emblems.
	s.shadowscale = 60250 --Cast a shadow.
	s.yuemblemangle = 0
	s.yuemblemZtime = 3
end, MT_YUEMBLEM)

--The Adventure emblem itself
addHook("MobjThinker", function(s) if not s.valid return end --

	if s.yuemblemZtime
		s.yuemblemZtime = max($-1,0)		
		if not s.yuemblemZtime --After 2 tics, move yourself up to your correct Z location and become collectible.	
			if s.yuemblem != nil
				if s.yuemblemMOBJ and s.yuemblemMOBJ.valid --If we have a proper mobj, simply attach to that instead.
					s.eflags = s.yuemblemMOBJ.eflags
					s.z = s.yuemblemMOBJ.z
				elseif s.yuemblemZ != nil --Otherwise, use the mapthing!
					local ZHEIGHT = (s.yuemblemMAPTHING) and  s.yuemblemMAPTHING.z or s.yuemblemZ
					if s.yuemblemMAPTHING and s.yuemblemMAPTHING.options and (s.yuemblemMAPTHING.options & MTF_OBJECTFLIP)
						s.z = s.ceilingz + ZHEIGHT<<16
						s.flags2 = $|MF2_OBJECTFLIP
					else
						s.z = s.floorz + ZHEIGHT<<16
					end
				end
			end
			s.spriteyoffset = 19<<16
			s.flags = MF_NOGRAVITY|MF_NOCLIPHEIGHT|MF_SPECIAL
		end
	end
	
	local ADDANG = ANG10
	if not s.health --If we don't have health, that means we we were collected!
		ADDANG = ANGLE_45
		if (s.fuse < 36) --Fade away gracefully.
			s.frame = A|FF_TRANS90-((s.fuse<<16)/4)
		end
		--Spawn sparkles!
		local RNG,RNG2,RNGZ = P_RandomRange(-19,19) or 2,P_RandomRange(19,-19) or 2,P_RandomRange(1,45) 
		local SCALERNG = P_RandomRange(-20000,20000)
		for i = -1,1,2
			if i == 1 RNG,RNG2 = -$,-$ end
			local ghs = P_SpawnMobjFromMobj(s, RNG<<16,RNG2<<16,RNGZ<<16, MT_THOK)
			ghs.sprite = SPR_NSPK
			ghs.frame = (leveltime%3==0) and B|FF_TRANS10 or A|FF_TRANS10
			ghs.renderflags = RF_FULLBRIGHT|RF_NOCOLORMAPS
			ghs.blendmode = AST_ADD
			ghs.dispoffset = 150
			ghs.fuse,ghs.tics = 15,99
			ghs.spritexscale = FRACUNIT+SCALERNG
			ghs.spriteyscale = ghs.spritexscale 
			ghs.color = (leveltime%2) and SKINCOLOR_SUPERSKY5 or SKINCOLOR_SILVER
			ghs.colorized = true
			P_SetObjectMomZ(ghs, -2<<16, true)
			ghs.scale = $/((leveltime%5==0) and 3 or 4)
			ghs.destscale = 1
			ghs.scalespeed = ghs.scale/16
		end
	end
	s.momz = 0 --We spawn without the MF_NOGRAVITY flag, which only gets added later, so...
	s.yuemblemangle = $+ADDANG
	s.angle = s.yuemblemangle
end, MT_YUEMBLEM)


--Hide yourself! They can't know we're secretly still here...!
addHook("MobjThinker", function(s) if not s.valid or SAEMBLEMS!=true return end
	s.spriteyoffset = 9999<<16
	s.flags = $|MF2_DONTDRAW
end, MT_EMBLEM)

--Broadcast serverwide message upon collection. You got one, you absolute chad!
addHook("TouchSpecial", function(s, v)
	if v and v.valid and v.player
	and s.valid and s.health
	
		s.health,s.fuse = 0,45
		s.state = S_YUEMBLEMGET
		s.destscale = 99<<16
		S_StartSound(s, sfx_yusfxz)
		
		local p = v.player
		P_AddPlayerScore(p, 5000)
		
		if s.yuemblem != nil --Make sure it's an actually assigned emblem.
			print("\x82"+p.name+"\x80 has collected Emblem\x87 "+s.yuemblem+"\x80"+"! (of "+s.yuemblemtotal+")")
			TOTALEMBLEMS = max($-1,0)
			if TOTALEMBLEMS
				if TOTALEMBLEMS == 1
					print("There is\x87 "+TOTALEMBLEMS+"\x80 emblem remaining!")
				else
					print("There are\x87 "+TOTALEMBLEMS+"\x80 emblems remaining!")
				end
			else
				P_FlashPal(p, PAL_RECYCLE, 3)
				print("\x83"+"ALL EMBLEMS in this stage have been gathered!")
				S_StartSound(nil, sfx_nxbump)
			end
		end
		return true --
	end
end, MT_YUEMBLEM)

COM_AddCommand("SAEmblems", function() 
	SAEMBLEMS = (not SAEMBLEMS)
	print("SA-emblems are now set to\x82 "+SAEMBLEMS+"!\x80 (Active upon map change/reset)")
end, COM_ADMIN)

addHook("NetVars", function(network) --Sync emblem count and SAemblems value.
	TOTALEMBLEMS = network($) 
	SAEMBLEMS = network($)
end)