--elimination, original work by Amperbee aka Rapidgame7#1949
--this is elimination R2 which I have finally gotten enough courage to release by freeman#7626
--the original script is by Amperbee, this is mostly just a heavily modified version of it
--that i've done with permission from them (and they have been kind enough to allow me to re-release it)

-- Rewritten by GenericHeroGuy for Sunflower's Garden
-- A few rewrittes by Spee to make it Eggman Themed

--hannu has invented and or used this method below for optimization
--i have been told it is faster but I still want to die
local TICRATE = TICRATE
local FRACUNIT = FRACUNIT
local INT32_MAX = INT32_MAX
local k_position = k_position
local SPR_FPRT = SPR_FPRT
local FF_FULLBRIGHT = FF_FULLBRIGHT

local themes = {}
local current_theme = 1

COM_AddCommand("elim_theme", function(p, ...)
	if #themes == 0 then
		CONS_Printf(p, "There are no themes currently")
		return
	end

	if not ... then
		CONS_Printf(p, "List of available themes:")
		
		for i = 1, #themes do
			CONS_Printf(p, "\t"..i..": "..themes[i].name)
		end
		
		CONS_Printf(p, "\nCurrent theme is "..themes[current_theme].name)
		return
	end
	
	local query = table.concat({...}, " "):lower()
	local num = tonumber(query)
	
	if num ~= nil then
		if num < 1 or num > #themes then
			CONS_Printf(p, "Bad theme number, try using number between 1 and "..#themes)
			return
		end
		
		current_theme = num
		
		CONS_Printf(p, "Set elimination theme to "..themes[num].name)
		return
	end
	
	local matches = {}
	
	for i = 1, #themes do
		if themes[i].name:lower():find(query) then
			table.insert(matches, { name = themes[i].name, number = i, })
		end
	end
	
	if #matches == 0 then
		CONS_Printf(p, "Can't find theme called "..query)
	elseif #matches > 1 then
		CONS_Printf(p, "Multiple matches found:")
		
		for i = 1, #matches do
			CONS_Printf(p, "\t"..matches[i].number..": "..matches[i].name)
		end
		
		CONS_Printf(p, "Try using more precise query")
	else
		CONS_Printf(p, "Set elimination theme to "..matches[1].name)
		
		current_theme = matches[1].number
	end
end, COM_LOCAL)

local function addTheme(def)
	def.warningsounds = $ or {}
	def.playerkillsounds = $ or {}
	def.lastmansounds = $ or {}
	def.startsounds = $ or {}
	def.name = def.name or "ElimTheme"..#themes
	
	table.insert(themes, def)
end

rawset(_G, "elim_addTheme", addTheme)
rawset(_G, "elim_getCurrentTheme", function() return themes[current_theme] end)

local function startSoundList(origin, listname, player)
	-- Always roll RNG
	local rng = P_RandomFixed()
	
	-- No themes?
	if #themes == 0 then return end
	
	local list = themes[current_theme][listname]
	
	assert(list)

	if #list == 0 then return end
	
	S_StartSound(origin, list[(rng % #list) + 1], player)
end

-- sound effects
local elimsound = sfx_kc48 -- when someone blows up
local pingsound = sfx_kc3d -- when you're about to blow up
local overstart = sfx_s3ka4 -- when overtime starts
local overalarm = sfx_s3k86 -- when your ears are bleeding and everything is horrible and you want to die
local otheralarm = sfx_s3k89 -- a more pleasant sound for everyone else
local overelim = sfx_noooo2 -- when someone blows up in overtime
local pregamesound = sfx_cdfm66 -- when elimination starts pregame

-- warning sign
freeslot("S_ELIMWARNING1","S_ELIMWARNING2", "SPR_EPIC")
states[S_ELIMWARNING1] = {
	sprite = SPR_EPIC,
	frame = A|FF_FULLBRIGHT,
	tics = 23,
	nextstate = S_ELIMWARNING2
}
states[S_ELIMWARNING2] = {
	sprite = SPR_EPIC,
	frame = B|FF_FULLBRIGHT,
	tics = 3,
	nextstate = S_ELIMWARNING1
}

-- F-Zero explosion spinout
addHook("PlayerSpin", function(p, inflictor, source)
	if not (inflictor and inflictor.type == MT_FZEROBOOM) then return end
	p.spinsourcetype = MT_FZEROBOOM
	if not hitfeed then return end

	-- source is probably nil
	if not p.mo then return end

	local s = nil
	if inflictor.pref and inflictor.pref.valid and inflictor.pref ~= p then
		s = {{inflictor.pref.name, inflictor.pref.skincolor}, {skins[inflictor.lastskin].facemmap, inflictor.pref.skincolor}, inflictor.pref}
	end
	local v = {{p.name, p.mo.hf_overridenamecolor or p.skincolor}, {skins[p.mo.skin].facemmap, p.skincolor}, p}

	local icon = "ICO_FIRE"
	HF_SendHitMessage(s, v, icon)
end)

-- Spinout timer is set AFTER the PlayerSpin hok finishes executing ... so we have to set the timer in a different hook
addHook("MobjThinker", function(mo)
	if mo.player.spinsourcetype == MT_FZEROBOOM then
		mo.player.kartstuff[k_spinouttimer] = 30
		mo.player.spinsourcetype = nil
	end
end, MT_PLAYER)

addHook("MobjThinker", function(mo)
	if leveltime % 3 == 0 and mo.extravalue2 == 9 then mo.extravalue2 = 8 end -- thin the smoke a bit
end, MT_FZEROBOOM)

addHook("MobjThinker", function(mo)
	if mo.sprite == SPR_FPRT then mo.frame = FF_FULLBRIGHT end -- Remove transparency from the fire for performance improvements
end, MT_THOK) -- Yes the fire are fucking thoks with switched sprites lol

states[S_FZSLOWSMOKE2] = {SPR_SMOK, 1, 30, nil, 0, 0, S_NULL} -- make the smoke shorter-lived

-- wheter the burning remains of someone's kart is dangerous or not
local el_fire = CV_RegisterVar({
	name = "elim_firespinout",
	defaultvalue = "On",
	flags = CV_NETVAR|CV_CALL,
	possiblevalue = CV_OnOff,
	func = function(var)
		if var.value == 1 then
			mobjinfo[MT_FZEROBOOM].flags = MF_PAIN|MF_SPECIAL|MF_DONTENCOREMAP
			mobjinfo[MT_FZEROBOOM].radius = 16*FRACUNIT -- give it an actual hitbox
			mobjinfo[MT_FZEROBOOM].height = 32*FRACUNIT
		else
			mobjinfo[MT_FZEROBOOM].flags = MF_NOBLOCKMAP|MF_DONTENCOREMAP
			mobjinfo[MT_FZEROBOOM].radius = FRACUNIT
			mobjinfo[MT_FZEROBOOM].height = FRACUNIT
		end
	end
})

-- wheter those burning remains produce sound
local el_fire = CV_RegisterVar({
	name = "elim_firesound",
	defaultvalue = "Off",
	flags = CV_NETVAR|CV_CALL,
	possiblevalue = CV_OnOff,
	func = function(var)
		if var.value == 1 then
			mobjinfo[MT_FZEROBOOM].attacksound = sfx_kc51
		else
			mobjinfo[MT_FZEROBOOM].attacksound = 0
		end
	end
})

-- turns elim on or off
local el_enabled = CV_RegisterVar({
	name = "elimination",
	defaultvalue = "On",
	flags = CV_NETVAR|CV_SHOWMODIF,
	possiblevalue = CV_OnOff
})

-- time in seconds between eliminations
local el_time = CV_RegisterVar({
	name = "elim_time",
	defaultvalue = 15,
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

-- number of seconds after race start before elimination starts
local el_stime = CV_RegisterVar({
	name = "elim_starttime",
	defaultvalue = 60,
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

--amount of tics the elim timer will wait for someone clearly in last
--to be decided before auto-killing everyone in last :mrkill:
local el_overtime = CV_RegisterVar({
	name = "elim_overtime",
	defaultvalue = 6*TICRATE,
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

--amount of tics a player must be in last place to be eliminated by timer
--this is added/removed to every tic, so it doesnt have to be uninterrupted time
local el_safetynet = CV_RegisterVar({
	name = "elim_safetynet",
	defaultvalue = 3*TICRATE,
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

--minimum number of players in-game not spectating to start an elimination match
local el_minplayers = CV_RegisterVar({
	name = "elim_minplayers",
	defaultvalue = 2,
	flags = CV_NETVAR|CV_SHOWMODIF,
	possiblevalue = { MIN = 2, MAX = #players }
})

-- when players left drops to this value or below, SPB is disabled from rolling
-- 0 turns this functionality off
local el_spbgone = CV_RegisterVar({
	name = "elim_spbgone",
	defaultvalue = 0,
	flags = CV_NETVAR,
	possiblevalue = { MIN = 0, MAX = #players }
})

--when the SPB stops rolling, if this is on lightning shields will also stop rolling
local el_lightninggone = CV_RegisterVar({
	name = "elim_lightninggone",
	defaultvalue = "Off",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

--timescaling will try to linearly scale the elim timer depending on number of
--players racing when the pre-game timer expires
local el_timescaling = CV_RegisterVar({
	name = "elim_timescaling",
	defaultvalue = "Off",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

-- minimum number of players that scaling starts at
-- (at or below this, you'll use the max time)
local el_scalingminplayers = CV_RegisterVar({
	name = "elim_scalingminplayers",
	defaultvalue = 2,
	flags = CV_NETVAR,
	possiblevalue = { MIN = 1, MAX = #players }
})

-- maximum number of players scaling stops at
-- (at or above this, you'll use min time)
local el_scalingmaxplayers = CV_RegisterVar({
	name = "elim_scalingmaxplayers",
	defaultvalue = 12,
	flags = CV_NETVAR,
	possiblevalue = { MIN = 1, MAX = #players }
})

-- minimum elimination timer (used at scalingmaxplayers)
local el_scalingmintime = CV_RegisterVar({
	name = "elim_scalingmintime",
	defaultvalue = 7,
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

-- maximum elimination timer (used at scalingminplayers)
local el_scalingmaxtime = CV_RegisterVar({
	name = "elim_scalingmaxtime",
	defaultvalue = 25,
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

-- if set, players items are stripped instead of dropped
-- this would've been named elim_dropitems and stripping made the default,
-- but that name makes the netid conflict with allowexitlevel
-- I FUCKING LOVE THIS GAME
local el_stripitems = CV_RegisterVar({
	name = "elim_stripitems",
	defaultvalue = "Off",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

--clients can use this to turn announcement drawing on/off if its too much for them
local el_announcements = CV_RegisterVar({
	name = "elim_announcements",
	defaultvalue = "On",
	flags = CV_SHOWMODIF,
	possiblevalue = CV_OnOff
})

-- controls screen flashing intensity
local el_flashintensity = CV_RegisterVar({
	name = "elim_flashintensity",
	defaultvalue = 2,
	flags = CV_SHOWMODIF,
	possiblevalue = { MIN = 0, MAX = 10 }
})

-- allow elimination to start pre-game
local el_pregamestart = CV_RegisterVar({
	name = "elim_pregamestart",
	defaultvalue = "On",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

-- maximum scale of bouncing animation during overtime
local el_overbounce = CV_RegisterVar({
	name = "elim_overbounce",
	defaultvalue = 3,
	possiblevalue = { MIN = 0, MAX = 10 }
})

local announcements = {
	[0] = "", -- lol
	"%s got eliminated",
	"%s got obliterated",
	"%s got deleted",
	"%s got destroyed",
	"%s got defeated",
	"%s got killed",
	"%s got massacred",
	"%s got karted to death",
	"%s got reduced to atoms",
	"%s got evaporated",
	"%s went poof",
	"%s has exploded",
	"%s is out",
	"%s is ded",
	"%s is dead",
	"%s is kil",
	"%s is kill",
	"%s is done",
	"%s went out",
	"%s went to sleep",
	"%s lost",
	"press f for %s",
	"rip %s",
	"rip in peace %s",
	"rest in peace, %s",
	"goodbye, %s",
	"bye %s",
	"babai %s",
	"cya %s",
	"peace out, %s",
	"see you, %s",
	"sayonara, %s",
	"au revoir, %s",
	"adios, %s",
	"farewell, %s",
	"namaste, %s",
	"hasta la vista, %s",
	"it's over for %s",
	"get out of here, %s",
	"gtfo %s",
	"haha %s go boom",
	"%s\nsee you space cowboy",
	"%s, it's time to wait",
	"try again next race, %s",
	"see you next race, %s",
	"%s\nso long partner",
	"%s bit the dust",
	"you're too slow, %s",
	"c'mon, step it up %s",
	"%s has been slain",
	"it's no use, %s",
	"i pity you, %s",
	"%s got their butt kicked",
	"go to your room, %s",
	"%s, go take a break",
	"break time for %s",
	"%s wasn't fast enough",
	"oh my god %s, waaaaaaa",
	"%s got the boot",
	"%s got booted out of the race",
	"Arivederchi, %s",
	"%s is going to heaven",
	"%s is going to hell",
	"%s got lost in the sauce",
	"%s wasn't gamer enough",
	"%s didn't make it",
	"gg %s",
	"ggs %s",
	"ggwp %s",
	"you'll get them next time, %s",
	"mission failed, %s",
	"game over\n%s",
	"%s didn't get a promotion",
	"%s got chatbugged",
	"%s got pingspiked",
	"%s got eradicated",
	"%s flew too low",
	"%s frikin died",
	"%s didn't survive",
	"%s\nyou lose",
	"%s got rekt",
	"%s lived and learned",
	"%s vanished",
	"%s disappeared",
	"%s got syncbombed",
	"%s stopped working",
	"curiosity killed the %s",
	"%s vanished into the void of space",
	"shoot... %s failed",
	"see you later, %s",
	"you can't catch me, %s",
	"you guys always leave %s behind",
	"hey, give %s some slack",
	"%s, lackluster performance i'd say",
	"%s, you are one pathetic creature",
	"wait for %s, maria",
	"I don't think so, %s",
	"%s, you are weak",
	"%s, loss unacceptable",
	"%s, that was pathetic",
	"get out of my way, %s",
	"guess %s is out",
	"c'mon %s, you can do better",
	"lucky for you, %s let you win",
	"%s got annihilated",
	"%s violently exploded",
	"%s alt f4'd",
	"thanos snapped %s out of existence",
	"the world was too tough for %s",
	"%s won't be missed",
	"%s will be missed",
	"%s got game ended",
	"%s self destructed",
	"%s got fragged",
	"%s got resynced",
	"%s died from an unfortunate event",
	"wave blew up %s",
	"%s left this plane of existence",
	"%s wrongdrifted",
	"I rate %s 7 out of 10",
	"%s got cooked",
	"%s is now spectating",
	"omae wa mou\nshindeiru\n%s",
	"time to afk, %s",
	"%s, grab a snack and relax",
	"%s went into orbit",
	"%s, you picked the wrong netgame fool",
	"%s is gonna go play minecraft",
	"%s ragequitted",
	"%s is sleeping with the fishes",
	"%s made an ouchie",
	"%s will be remembered",
	"that ain't %s",
	"%s got wombo combo'd",
	"%s\ninsert more credits to continue",
	"what was %s fighting for",
	"%s divided by 0",
	"%s had a whoopsie",
	"%s failed at life",
	"%s fell out of the world",
	"%s had a bad time",
	"%s got dunked on",
	"%s went boom",
	"%s ascended",
	"%s got censored",
	"%s felt the burn",
	"%s was purged",
	"%s was diagnosed with karted",
	"%s fell rock bottom",
	"guess %s will die",
	"%s crashed",
	"playtime is over for %s",
	"have a rotten day, %s",
	"%s got assassinated",
	"%s won't be remembered",
	"%s got the bad ending",
	"%s got isekai'd",
	"Yippee Ki-Yay, %s",
	"See you never, %s",
	"Boom goes %s",
	"KAPOW %s",
	"GET OUT OF MY HOUSE %s",
	"LUL %s",
	"OMEGALUL %s",
	"Sorry not sorry, %s",
	"Sorry %s",
	"Here's a tissue, %s",
	"%s was sent back to school",
	"%s passes their turn and goes to prison",
	"%s got grounded",
	"%s got claimed by death",
	"%s got outplayed",
	"%s is doomed",
	"%s didn't git gud",
	"%s got owned",
	"%s got pwned",
	"eyes on the road, %s",
	--"%s didn't play on difficulty",
	"%s got murdered",
	"%s asked for the v2 release date",
	"it really do be like that, %s",
	"there goes %s",
	"%s was sponsored by\nRAID SHADOW LEGENDS",
	"%s can't lose here",
	"nice driving, %s",
	--"hippity hoppity, %s is gone-ity",
	"%s got a call from their mom",
	"%s lagged",
	"Time to put %s to rest",
	"cya later alligator, %s",
	"%s ate one too many bananas",
	"wtf %s",
	"wth %s",
	"%s is gonna meet god",
	"%s is gonna meet satan",
	"%s commited sudoku",
	"%s didn't get the right item",
	"fission mailed, %s",
	"%s was a worthless consumer model",
	"%s please",
	"%s pls",
	"%s, please wait",
	"%s, be patient",
	"you did good, %s",
	"how was your game, %s",
	"we live in a society, %s",
	"try switching to metal sonic, %s",
	"hahahaha\n%s soccer",
	"suspect %s apprehended",
	"%s played at 512 draw distance",
	"%s played it like it was mario kart",
	"%s is going back to mario kart",
	"%s got denied",
	"%s got BSOD'd",
	"%s was typing during the race",
	"%s had a bruh moment",
	"%s didn't leave the danger zone",
	"%s was lost in thoughts",
	"no SPB was required for %s",
	"later %s",
	"%s was never real",
	"%s who?",
	"%s became nothing",
	"%s was arrested for DUI",
	"%s was just your imagination",
	"%s woke up from a bad dream",
	"%s didn't get the right item",
	"%s shouldn't have picked that character",
	"%s thought it was normal speed",
	"%s broke the ping limit",
	"%s opened their heart",
	"begone, %s",
	"%s blames the ping",
	"%s had controller issues",
	"Too much SPEEN for %s",
	"You know, %s has the blues",
	"%s has been erased from history",
	"Your free trial of existing has ended, %s",
	"You gotta get better at this, %s",
	"Even without wings, %s can still fly",
	"%s went to Brazil",
	"Please fucking cry now %s",
	"%s was just a regular hedgehog after all",
	"Git gud %s",
	"Become proficient, %s",
	"%s TO DIE WHY", -- G: Seems like a reference to something...
	"Watch out %s, you're gonna crash! AHHH!",
	"%s is now off to the gulag",
	"%s is dead. Not big suprise",
	"Stay free, %s",
	"%s savoured it thoroughly",
	"%s bites the dust",
	"%s was banished to the shadow realm",
	"The future refused to change for %s",
	"%s took a tumble",
	"%s threw the match... how pitiful",
	"%s uninstalled",
	"%s got in one fight and their mom got scared",
	"So long, space %s",
	"%s noclipped out of reality",
	"%s is pining for the fjords",
	"%s wasn't carried by AiAi",
	"%s didn't lawnmower hard enough",
	"%s wasn't able to conduct ME TRAIN",
	"%s scaled these announcements",--I am so fucking done trying to scale these motherfuckers holy shit -- Generic: about that
	"%s didn't escape from the city",
	"music made %s loose control",
	"maybe in another life, %s",
	"%s failed the vibe check",
	"%s SIGSEGV'D",
	"%s ate those words",
	"bye, have a beautiful time %s",
	"%s was VAC banned from secure server",
	"%s was no contest",
	"%s, license and registration please",
	"%s was not the imposter",
	"%s was the imposter",
	"%s couldn't escape crossing fate",
	"%s kneels",
	"%s repacked bonuschars.kart",
	"%s was claimed by the zone",
	"%s unlocked easy difficulty",
	"%s entered absolute territory",
	"witness me, %s",
	"%s rides eternal, shiny and chrome",
	--"%s gained PF-TIMEOVER", --second thought this one isn't really funny
	"%s left the game <sync failure>",
	"%s deleted system32", -- fixed it
	"%s blocked low",
	"%s blocked high",
	"this is the wrong room, %s",
	"%s, your legs are not okay",
	"in water, %s will drown",
	"%s is going home in a box",
	"texture %s has no width!",
	"%s committed existn't",
	"%s was jeckpoint'd",
	"%s modified useodds",
	--"%s: out of memory allocating 78169235 bytes", --too long and not funny
	"%s attained escape velocity",
	"%s had p.spectator set to true",
	"orbinaut plus %s creates corpse",
	"end of the line, %s",
	"%s choked",
	"%s rolled an SPB",
	"%s got a single shoe in 12th",
	"%s has no mouth and must scream",
	"god issued a total recall on %s",
	"%s can't drive 55",
	"%s downloaded a car",
	"SORRY\n\nNOTHING", --heh
	"%s didn't get on the ball",
	"mighty putty fixes everything but %s",
	"flex tape couldn't seal %s",
	"%s was forsaken",
	"%s is gonna carry that weight...",
	"%s committed persona 3",
	"%s never saw it coming",
	"i can't believe %s is dead",
	"error code 404, %s not found",
	"%s is out of touch",
	"%s was marked for death",
	"wake me up, %s",
	"%s can't wake up",
	"%s had rapid mid-drive disassembly",
	"%s was hit by the kitchen sink",
	"Soap trusted you, %s",
	"THINK, %s! THINK!",
	"Nothin' personnel, %s",
	"%s contracted ligma",
	"%s took a calculated risk",
	"try some record attack, %s",
	"patch notes:\n- removed %s",
	"%s didn't fly so good",
	"%s doesn't feel so good",
	"%s failed to boostquench",
	"mmm, no, very unwise, %s",
	"women want %s, fish fear them",

	-- GenericHeroGuy's personal selection
	"Do you have games on your phone %s",
	"The town wasn't big enough for %s",
	"It's-a time for you to die, %s",
	"What happened to %s",
	"Where in the world is %s",
	"%s was griefing",
	"%s yanked the cartridge",
	"%s couldn't go on",
	"%s... How could you?",
	"%s became a ghost",
	"%s will get their revenge",
	"Your time is up, %s",
	"%s!\nDon't leave me here!",
	"%s got jumpscared",
	"The world wasn't ready for %s",
	"Wrong place, wrong time, %s",
	"What's that beeping sound, %s?", -- beeping, not ticking, smh
	"%s melted their tires",
	"Your reign of terror ends here, %s",
	"%s... It's over...",
	"An applause for %s",
	"%s ran out of gas",
	"It's a bad day for %s",
	"Sucks to be you, %s",
	"Drink some water, %s",
	"%s forgot to plug in the charger",
	"%s got caught cheating",
	"This game requires an expansion pak, %s",
	"Z_CheckHeap: Block %s lacks proper backlink",
	"%s triggered an invalid opcode exception",
	"Failed to allocate memory for %s",
	"%s does not sync in netgames",
	"I warned you, %s",

	-- some more
	"%s was texting while driving",
	"%s was buying clothes at the soup store",
	"%s, say cheese!",
	"%s was using motion controls",
	"What a shame, %s",
	"%s's batteries fell out",
	"%s, there's a bomb under your kart!",
	"What's with those spinning signs, %s?",

	-- some more again
	"%s was not prepared for the chaos",
	"What was %s cooking?",
	"Connection terminated, %s",
	"%s has been terminated",
	"%s forgot to take a break every 15 minutes",
	"Get real %s",
	"%s fought in vain",
	"You tried, %s",
	">%s",
	"This won't be the last time you see %s",
	"%s will return",
	"%s returned to monke",
	"%s did not continue the game",
	"CONGLATURATION %s !!!",
	"Nope, not this time %s",
	"%s's computer was struck by cosmic rays",
	"%s wasn't feeling up to it",
	"Owari Da, %s",
	"%s, look at the time! It's death o'clock!",
	"Hey, don't feel bad %s",
	"%s wasn't paying attention",
	"This has gotta work, %s", -- E
	"You win some, you lose some, %s", -- O
	"%s's luck failed them", -- D
	"%s is like the 21st person I've ever met who's making me break a sweat", -- M
	-- hooray, 400 announcements!
	-- see you in the 32-player event!
	-- G, 2023-09-23
}

local elim = {}
local starttime = 6*TICRATE + (3*TICRATE/4) -- leveltime when race actually starts (~235)
-- number of orbiting warning signs
local NUM_ORBITS = 8
-- boy do i wish i had unsigned integers right about now
-- result has wrong sign but it doesn't matter
local ORBIT_OFFSET = (ANGLE_180 / NUM_ORBITS) << 1

local function getOrbitCoords(p, i)
	local ang = (leveltime * (ANG2*3)) + (ORBIT_OFFSET * i)
	local spd = FixedMul(max(elim.curtime, min(el_safetynet.value - p.elim.inlasttime, elim.curtime + el_overtime.value))/2*FRACUNIT, p.mo.scale)
	return FixedMul( cos(ang), spd ), FixedMul( sin(ang), spd )
end

-- fuck it, just give every player their own set of warnings
local function addWarnings(p)
	for i = 1, NUM_ORBITS do
		local x, y = getOrbitCoords(p, i)
		local mo = P_SpawnMobj(p.mo.x + x, p.mo.y + y, p.mo.z, MT_THOK)
		mo.flags = MF_NOBLOCKMAP|MF_NOCLIP|MF_NOCLIPHEIGHT|MF_DONTENCOREMAP
		mo.state = S_ELIMWARNING1
		p.elim.warnings[i] = mo
	end
	p.elim.haswarnings = true
end

local function removeWarnings(p)
	for i = 1, NUM_ORBITS do
		P_RemoveMobj(p.elim.warnings[i])
	end
	p.elim.haswarnings = false
end

-- count players and team numbers
local function elimCountPlayers()
	elim.liveplayers, elim.team1players, elim.team2players = 0, 0, 0
	for p in players.iterate do
		if p.elim.isplaying and not p.elim.iseliminated then
			elim.liveplayers = $ + 1
			if elim.friendly and FRIENDMOD_TeamBattle() then
				if p.FRteam == 1 then
					elim.team1players = $ + 1
				end
				if p.FRteam == 2 then
					elim.team2players = $ + 1
				end
			end
		end
	end
end

-- blow up some poor guy
local function eliminatePlayer(p, losesound)
	-- gain access to mobj
	p.spectator = false
	local el = p.elim

	if el.haswarnings then
		removeWarnings(p)
	end
	el.iseliminated = true
	el.eliminatedtime = p.realtime
	el.eliminatedpos = p.kartstuff[k_position]
	el.inlast = false
    local timestring = string.format("%i'%02i\34%02i",G_TicsToMinutes(p.realtime,true),G_TicsToSeconds(p.realtime),G_TicsToCentiseconds(p.realtime))
	chatprint("\x87<SERVER> "+p.name+" was eliminated at "+timestring+" in position "+elim.liveplayers)
	elim.liveplayers = $ - 1
	if elim.friendly and FRIENDMOD_TeamBattle() then
		if p.FRteam == 1 then
			elim.team1players = $ - 1
		end
		if p.FRteam == 2 then
			elim.team2players = $ - 1
		end
	end
	table.insert(elim.deadnames, SG_Xcolorcode(p)..p.name.."\x80")

	if losesound then K_PlayLossSound(p.mo) end

	-- remove all items
	if el_stripitems.value == 1 then
		K_StripItems(p)
	else
		K_DropItems(p)
	end
	K_StripOther(p)

	-- spawn the actual explosion
	K_SpawnMineExplosion(p.mo, p.skincolor or SKINCOLOR_KETCHUP)
	local boom = P_SpawnMobj(p.mo.x, p.mo.y, p.mo.z, MT_FZEROBOOM)
	boom.scale = p.mo.scale
	boom.angle = p.mo.angle
	boom.target = p.mo

	p.spectator = true
	p.powers[pw_flashing] = TICRATE
	if elim.on and not replayplayback then p.pflags = $ | PF_WANTSTOJOIN end
end

-- note to future addon authors:
-- PLEASE put your player variables in a table!
-- otherwise, you can't rename variables without breaking compatibility!
local function elimResetPlayer(p)
	p.elim = {}
	local el = p.elim
	el.isplaying = false -- if the player is participating. set at/before round start, never touched again
	el.iseliminated = false -- has been eliminated?
	el.eliminatedtime = 0 -- time of elimination
	el.eliminatedpos = 0 -- position when eliminated
	el.lastmanannounce = 0 -- timer for LAST MAN STANDING message
	el.inlast = false -- in last place
	el.inlasttime = 0 -- how long player has been in last (for safetynet)
	el.haswarnings = false -- has orbiting warning signs of doom
	el.warnings = {}

	-- trap access to non-existent variables
	setmetatable(el, {
		__index = function() error("Elimination: Attempt to read non-existent player variable", 2) end,
		__newindex = function() error("Elimination: Attempt to write non-existent player variable", 2) end
	})
end

-- section 4, type 14. hope nobody claimed this already!
local function replaceFinishLine()
	-- print("First lap complete, taking over finish line")
	elim.replacedfinish = true
	for sector in sectors.iterate do
		if (sector.special & 0xF000) >> 12 == 10 then
			sector.special = ($ & 0x0FFF) | 14 << 12
		end
	end
end

-- set various cvars
local function elimEnable(playercount)
	elim.on = true
	elim.startingtime = starttime + (el_stime.value * TICRATE) -- refresh start time
	hud.disable("gametypeinfo")
	hud.disable("time")
	hud.disable("freeplay")
	rawset(_G, "ELIMINATION_Active", true)

	-- UPDATE: doesn't work if basenumlaps is changed because numlaps change is delayed due to NetVars(tm)
	-- if numlaps <= 1 then replaceFinishLine() end

	-- enable or disable SPB
	if el_spbgone.value > 0 and playercount <= el_spbgone.value then
		COM_BufInsertText(server, "selfpropelledbomb 0")
		print("\133SPB Disabled: below player count \131("..playercount.."/"..el_spbgone.value..")")
		if el_lightninggone.value then
			COM_BufInsertText(server, "thundershield 0")
		end
	end
end

-- restore various cvars
local function elimRestore()
	COM_BufInsertText(server, "selfpropelledbomb "..tostring(elim.oldspb))
	COM_BufInsertText(server, "thundershield "..tostring(elim.oldthunder))
	COM_BufInsertText(server, "allowteamchange 1")
	rawset(_G, "ELIMINATION_Active", false)
	hud.enable("gametypeinfo")
	hud.enable("time")
	hud.enable("freeplay")
end

-- reset elim table and stuff
addHook("MapChange", function()
	if elim and elim.on then elimRestore() end

	elim = {
		on = false, -- whether elimination is activated for this round
		started = false, -- set to true when leveltime > starttime + stime
		lastsound = false, -- once the last two players are alive, play this
		friendly = false, -- friendmod detected loaded or not
		pally = false, -- palscript loaded or not
		startingtime = starttime + (el_stime.value * TICRATE), -- when the round starts
		oldspb = false, -- whether SPB was enabled before round start
		oldthunder = false, -- whether thunder shield was enabled before round start
		canpregamestart = el_enabled.value, -- wheter pregame start can occur
		numstarposts = 0, -- number of checkpoints, which we have to count manually for better or worse

		lastpos = 0, -- current "last position"
		liveplayers = 0, -- players alive
		startplayers = 0,
		team1players = 0, -- players in team 1
		team2players = 0, -- players in team 2
		pingtime = 0, -- timer for annoying pinging
		replacedfinish = false, -- wheter the finish line has been replaced with a custom special yet

		curtime = 0, -- elimination timer, counts down and eliminates someone when hitting 0
		nexttime = 0, -- starting value for timer
		lastman = false, -- if the last man standing in a team battle has been announced

		gameover = false, -- is the round over?
		wintimer = 0, -- timer for round end, will eventually exit level
		giveup = 0, -- ...

		diedname = "", -- name of dead player(s)
		deadnames = {}, -- names of players that died
		deathtime = 0, -- timestamp when someone died
		announcementnum = 0, -- which announcement to display
	}

	-- trap access to non-existent variables
	setmetatable(elim, {
		__index = function() error("Elimination: Attempt to read non-existent variable", 2) end,
		__newindex = function() error("Elimination: Attempt to write non-existent variable", 2) end
	})

	-- save SPB and thunder shield state
	elim.oldspb = CV_FindVar("selfpropelledbomb").value
	elim.oldthunder = CV_FindVar("thundershield").value

	--if CV_FindVar("fr_enabled") and FRIENDMOD_CheckTeams() and FRIENDMOD_TeamBattle() then elim.friendly = true end
	--if CV_FindVar("ps_enabled") and PALSCRIPT_CheckTeams() and PALSCRIPT_TeamBattle() then elim.pally = true end
	if elim.friendly and elim.pally then
		print("\131WARNING: Elimination detected both friendmod and palscript loaded. I strongly suggest you don't do this.")
	end
end)

-- reset even more stuff on map load
addHook("MapLoad", function()
	-- count players at start of round and reset them
	local playercount = 0
	for p in players.iterate do
		elimResetPlayer(p)
		p.toadlauncher = false
		if not p.spectator or p.pflags & PF_WANTSTOJOIN then
			playercount = $ + 1
		end
	end

	if el_enabled.value then
		if playercount >= el_minplayers.value then elimEnable(playercount) end

		-- count the number of checkpoints
		local checkpoints = {}
		for mapthing in mapthings.iterate do
			if mapthing.type == 502 then
				checkpoints[mapthing.angle/360] = true
			end
		end
		for _ in pairs(checkpoints) do
			elim.numstarposts = $ + 1
		end
	end
end)

-- a winner has been chosen...
local function elimRoundEnd()
	for p in players.iterate do
		p.exiting = 1
		if not p.spectator then
			S_ChangeMusic("KBWIN", false, p)
			P_PlayVictorySound(p.mo)
			local exitsign = P_SpawnMobj(p.mo.x, p.mo.y, p.mo.z + (mapobjectscale * 400), MT_SIGN)
			exitsign.target = p.mo
			exitsign.state = S_SIGN1
			exitsign.movefactor = p.mo.floorz
			exitsign.movecount = 1
			if p.elim.haswarnings then
				removeWarnings(p)
			end
		else
			S_ChangeMusic("KBOK", false, p)
		end
	end
end

-- end elimination, go to intermission
local function elimExit()
	for p in players.iterate do
		if not p.elim.isplaying then continue end
		p.elim.warnings = {} -- broken in battle or something idk

		-- rejoin everyone who was eliminated, and set their elimination time
		if p.pflags & PF_WANTSTOJOIN then p.spectator = false end
		if p.elim.iseliminated then
			p.pflags = $ & ~(PF_WANTSTOJOIN|PF_TIMEOVER)
			p.exiting = 1
			-- since the intermission completely fucking ignores everyone's actual position,
			-- we'll set everyone's time to how long they've been eliminated for
			p.realtime = ($ - p.elim.eliminatedtime) or 1
			-- normally the game takes care of music when using ExitLevel, but sometimes it doesn't work?
			S_ChangeMusic("RACENT", true, p)
		else -- not eliminated
			chatprint("\x83<SERVER> " .. p.name .. " survived!")
			p.realtime = 0
			S_ChangeMusic("KRWIN", true, p)
		end
	end

	elimRestore()
	elim.on = false
	G_ExitLevel()
end

local function elimThinker()
	-- how many are in last place?
	local lastposcount = 0

	-- some real spaghetti here...
	if G_RaceGametype() then
		elim.lastpos = 0
		for p in players.iterate do
			if not p.elim.isplaying or p.elim.iseliminated then continue end
			elim.lastpos = max($, p.kartstuff[k_position])
		end
		for p in players.iterate do -- another one
			if not p.elim.isplaying or p.elim.iseliminated then continue end
			if p.kartstuff[k_position] == elim.lastpos then
				p.elim.inlast = true
				lastposcount = $ + 1
			else
				p.elim.inlast = false
			end
		end
	else -- if only battle points were in kartstuff...
		elim.lastpos = INT32_MAX
		for p in players.iterate do
			if not p.elim.isplaying or p.elim.iseliminated then continue end
			elim.lastpos = min($, p.marescore)
		end
		for p in players.iterate do -- another one
			if not p.elim.isplaying or p.elim.iseliminated then continue end
			if p.marescore == elim.lastpos then
				p.elim.inlast = true
				lastposcount = $ + 1
			else
				p.elim.inlast = false
			end
		end
	end

	-- remove SPB from item rotation?
	-- (cvar will still read as set for a few tics, so check once a second)
	local spbvar = CV_FindVar("selfpropelledbomb")
	if leveltime % TICRATE == 0 and spbvar.value == 1 and el_spbgone.value > 1 and elim.liveplayers <= el_spbgone.value then
		COM_BufInsertText(server, "selfpropelledbomb 0")
		print("\133ELIMINATION: SPB disabled for the last "..el_spbgone.value.." players!")
		if el_lightninggone.value then
			COM_BufInsertText(server, "thundershield 0")
		end
	end

	elim.curtime = $ - 1 -- Take some of that TIMER JUICE
	elim.pingtime = $ + 1
	local annoytime = max(2, elim.curtime / 8) -- Don't want to deafen people

	for p in players.iterate do
		local el = p.elim
		-- last man announcement counter
		if el.lastmanannounce > 0 then el.lastmanannounce = $ - 1 end

		if el.isplaying and not el.iseliminated then
			local eliminatenow = false
			local alarmsound = elim.curtime <= 0 and (elim.curtime + el_overtime.value) % TICRATE == 0

			if el.inlast then
				if el.inlasttime < el_safetynet.value then
					el.inlasttime = $ + 1
				end
				-- ping sound
				if elim.pingtime > annoytime then
					S_StartSound(p.mo, pingsound)
				end
				-- eggman taunts you for approaching death
				if elim.liveplayers >= 3 and elim.curtime == 5 * TICRATE and P_RandomChance(FRACUNIT/4) then
					startSoundList(nil, "warningsounds", p)
				end
				-- if timer is up, only one(?) player is in last place, and has no safety net, eliminate them
				-- if that doesn't work, it's overtime
				-- very lazy hcombi support here, hope i'm checking the right thing lol
				if (elim.curtime <= 0 and lastposcount <= ((hcombi and hcombi.combi_on) and 2 or 1) and el.inlasttime == el_safetynet.value)
				or (elim.curtime == -(el_overtime.value)) then
					eliminatenow = true
				end
				-- play overtime alarm once a second for the person in last
				if (not eliminatenow) and alarmsound then
					S_StartSound(nil, (p == consoleplayer and overalarm or otheralarm))
				end
			else -- not in last
				if el.inlasttime > 0 then
					el.inlasttime = $ - 1
				end
			end

			-- if player is eliminated or spectates, blow 'em up
			if eliminatenow or p.spectator then
			local timestring = string.format("%i'%02i\34%02i",G_TicsToMinutes(p.realtime,true),G_TicsToSeconds(p.realtime),G_TicsToCentiseconds(p.realtime))
			chatprint("\x87<SERVER> "+p.name+" was eliminated by HP at "+timestring+" in position "+elim.liveplayers)
				eliminatePlayer(p, true)
				if elim.liveplayers >= 2 and P_RandomChance(FRACUNIT/3) then
					startSoundList(nil, "playerkillsounds", p)
				end
			end

			-- warning signs
			if not el.haswarnings and el.inlast then
				addWarnings(p)
			end
			if el.haswarnings and not el.inlast then
				removeWarnings(p)
			end
			if el.haswarnings then
				for i = 1, NUM_ORBITS do
					local x, y = getOrbitCoords(p, i)
					P_MoveOrigin(el.warnings[i], p.mo.x + x, p.mo.y + y, p.mo.z)
				end
			end
		end
	end

	-- reset ping timer
	if elim.pingtime > annoytime then
		elim.pingtime = 0
	end
	
	-- last players alive
	if elim.startplayers >= 3 and elim.liveplayers == 2 and not elim.lastsound and not elim.friendly then
		elim.lastsound = true
		startSoundList(nil, "lastmansounds", p)
	end

	-- friendmod: check if only the last player on a team remains
	if elim.friendly and FRIENDMOD_TeamBattle() and not elim.lastman then
		if elim.team1players == 1 or elim.team2players == 1 then
			for p in players.iterate do
				if not p.elim.iseliminated
				and (elim.team1players == 1 and p.FRteam == 1)
				or (elim.team2players == 1 and p.FRteam == 2) then
					elim.lastman = true
					p.elim.lastmanannounce = 6 * TICRATE
					startSoundList(nil, "lastmansounds", p)
				end
			end
		end
	end

	-- ending conditions
	if (elim.liveplayers <= ((hcombi and hcombi.combi_on) and 2 or 1))
	or (elim.friendly and FRIENDMOD_TeamBattle() and (elim.team1players <= 0 or elim.team2players <= 0))
	or (elim.pally and PALSCRIPT_AllFinishCheck()) then
		elim.gameover = true
	end
end

-- the chaos will soon begin
local function elimPregameThinker()
	for p in players.iterate do
		-- did someone spec pregame?
		if p.elim.isplaying and not p.elim.iseliminated and p.spectator then
			p.elim.isplaying = false
		end
		-- did someone join pregame?
		if not p.elim.isplaying and not p.spectator then
			p.elim.isplaying = true
		end
	end
end

-- the chaos begins
local function elimStart()
	elim.started = true

	-- count friendmod team players
	elimCountPlayers()
	
	-- keep the max amount of players in mind
	elim.startplayers = elim.liveplayers

	startSoundList(nil, "startsounds")
	COM_BufInsertText(server, "allowteamchange 0")
	print("Team change privilege revoked.")

	-- do we use time scaling?
	if el_timescaling.value == 1 then
		local timescaled

		-- count players who are participating this round
		local pcount = 0
		for p in players.iterate do
			if p.elim.isplaying then
				pcount = $ + 1
			end
		end

		-- first, check if players is at min or max
		if pcount <= el_scalingminplayers.value then
			timescaled = el_scalingmaxtime.value
		elseif pcount >= el_scalingmaxplayers.value then
			timescaled = el_scalingmintime.value
		else -- apparently not, time for some math

			-- get amount of time to subtract per player.
			local playerdiff = el_scalingmaxplayers.value - el_scalingminplayers.value
			local timediff = el_scalingmaxtime.value - el_scalingmintime.value
			local timeperplayer = (timediff * TICRATE) / playerdiff
			-- more players = faster eliminations
			timescaled = max(
				el_scalingmaxtime.value - ((timeperplayer * (pcount - el_scalingminplayers.value)) / TICRATE),
				el_scalingmintime.value
			)
		end

		elim.nexttime = timescaled * TICRATE
		print("Starting Players: " + pcount)
		print("Elimination time is " + timescaled + " seconds per player this round.")
	else
		elim.nexttime = el_time.value * TICRATE
	end

	-- kick off the timer
	elim.curtime = elim.nexttime
end

COM_AddCommand("elim_kill", function(p, num)
	if not num then
		CONS_Printf(p, "\133Usage: \128'elim_kill <playernum>'")
		return
	end

	num = tonumber($)
	if num >= 0 and num < #players and players[num] then
		eliminatePlayer(players[num], true)
		elim.deathtime = leveltime
		elim.diedname = SG_Xcolorcode(p)..p.name.."\x80"
		elim.announcementnum = P_RandomRange(1, #announcements)
	else
		CONS_Printf(p, "Invalid player or number")
	end
end, COM_ADMIN)

COM_AddCommand("elim_announcement", function(p, i)
	i = tonumber($)
	if i == nil then
		i = P_RandomRange(1, #announcements)
		print("#"..i)
	end
	if announcements[i] then
		elim.deathtime = leveltime
		elim.diedname = SG_Xcolorcode(p)..p.name.."\x80"
		elim.announcementnum = i
	end
end, COM_ADMIN)

addHook("ThinkFrame", function()
	if leveltime == 0 then return end

	-- pregame start
	if not elim.on then
		if elim.canpregamestart and el_pregamestart.value and leveltime < elim.startingtime
		and not (mapheaderinfo[gamemap].levelflags & LF_SECTIONRACE) then
			local pcount = 0
			for p in players.iterate do
				if p.laps > 0 or p.exiting then return end
				if not p.spectator then
					pcount = $ + 1
				end
			end

			if pcount >= el_minplayers.value then
				S_StartSound(nil, pregamesound)
				elimEnable(pcount)
			end
		end
		return
	end

	-- exit if sprint map was loaded
	if leveltime == 10 and mapheaderinfo[gamemap].levelflags & LF_SECTIONRACE then
		print("Non-looping tracks are not supported! Ending map immediately.")
		elimRestore()
		G_ExitLevel()
	end

	-- to avoid touching numlaps and basenumlaps and breaking replays and shit,
	-- we'll instead replace every finish line in the map with a bogus sector special
	-- in which we remove the code that makes the player finish the race
	-- but only after the first time someone crosses the real finish line,
	-- otherwise thwomps will never activate!
	if elim.replacedfinish then
		for p in players.iterate do
			if p.spectator then continue end
			if P_PlayerTouchingSectorSpecial(p, 4, 14) then
				if p.starpostnum >= (elim.numstarposts - (elim.numstarposts/2)) or p.exiting then
					p.kartstuff[k_starpostwp], p.kartstuff[k_waypoint] = 0, 0
				end

				if not p.exiting then
					if p.starpostnum >= (elim.numstarposts - (elim.numstarposts/2)) then // srb2kart: must have touched *enough* starposts (was originally "(player->starpostnum == numstarposts)")
						p.laps = $ + 1
						if p.laps == 0 then
							elim.giveup = max(1, $)
							COM_BufInsertText(server, "allowteamchange 0")
							S_StartSound(nil, sfx_s3k53)
						end

						-- lol why not
						if p.pflags & PF_NIGHTSMODE then
							p.drillmeter = $ + 48*20
						end

						p.starposttime = p.realtime
						p.starpostnum = 0

						// SRB2kart 200117
						// Reset starposts (checkpoints) info
						p.starpostangle, p.starpostx, p.starposty, p.starpostz, p.kartstuff[k_starpostflip] = 0, 0, 0, 0, 0

						S_StartSound(nil, sfx_s221, p)

						-- lua can't set this. that's why we have to run the real finish line first
						-- thwompsactive = true // Lap 2 effects
						p.grieftime = 0
					elseif p.starpostnum then
						// blatant reuse of a variable that's normally unused in circuit
						if not p.tossdelay then
							S_StartSound(p.mo, sfx_s26d)
							if netgame and CV_FindVar("antigrief").value then p.grieftime = $ + TICRATE end
						end
						p.tossdelay = 3
					end
				end
			end
		end
	elseif G_RaceGametype() then
		-- if there's only one lap, we kinda HAVE to replace the finish line early
		-- thwomps wouldn't activate anyway...
		-- oh btw, numlaps is a global variable and it's a shortcut to cv_numlaps.value. neat!
		if numlaps <= 1 then
			replaceFinishLine()
		else
			for p in players.iterate do
				if p.laps > 0 then
					p.kartstuff[k_lapanimation] = 0 -- no animation
					replaceFinishLine()
					break
				end
			end
		end
	end

	if elim.giveup > 0 then
		elim.giveup = $ + 1
		if elim.giveup == 5*TICRATE/2 then
			for p in players.iterate do
				if elim.on and p.elim.isplaying and not p.elim.iseliminated then eliminatePlayer(p) end
			end
			elim.gameover = true
		end
	end

	if not elim.gameover then
		-- elimination start
		if leveltime == elim.startingtime then elimStart() end

		if elim.started then elimThinker() else elimPregameThinker() end
	end

	-- if someone died this tic, announce dead players
	if #elim.deadnames > 0 then
		elim.deathtime = leveltime
		elim.announcementnum = P_RandomRange(1, #announcements)
		elim.diedname = ""
		for _, name in ipairs(elim.deadnames) do
			-- replace spaces with non-printing characters so name isn't
			-- linebroken in half. not just to make the name look good,
			-- but also because color codes aren't preserved across lines lol
			elim.diedname = $..(name:gsub(" ", "\x01") or name).." + "
		end
		-- remove the trailing +
		elim.diedname = $:sub(1, #$ - 3)
		elim.deadnames = {}

		if elim.curtime < 0 then
			S_StartSound(nil, overelim)
		else
			S_StartSound(nil, elimsound)
		end

		-- calculate new player counts and reset timer
		elimCountPlayers()
		elim.curtime = elim.nexttime
	end

	-- end game
	if elim.gameover then
		elim.wintimer = $ + 1
		if elim.wintimer == 1 then elimRoundEnd() end
		server.hmfinishtimer = max(2, 8*TICRATE - elim.wintimer)
	end
end)

-- exit game after thinkers have run, prevents stuff like
-- win sound playing a split second before intermission starts etc
addHook("PostThinkFrame", function()
	if elim.gameover and elim.wintimer > 8*TICRATE then
		elimExit()
	end
end)

-- blow up ragequitters
addHook("PlayerQuit", function(p)
	if elim.on and elim.started and not elim.gameover and p.elim.isplaying and not p.elim.iseliminated then
		eliminatePlayer(p, true)
	end
end)

-- don't blow up mid-game joiners
addHook("PlayerSpawn", function(p)
	if not p.elim then
		elimResetPlayer(p)
	end
end)

-- Some addons enable those back, so for now there's no better solution other than force disabling it each frame
-- otherwise it will just depend on load order
addHook("PostThinkFrame", function()
	if elim.on then
		hud.disable("gametypeinfo")
		hud.disable("time")
		hud.disable("freeplay")
	end
end)

-- sync data over netgames
addHook("NetVars", function(sync) elim = sync($) end)

local warncolors = { [0] = SKINCOLOR_GREY, [1] = SKINCOLOR_RED, [2] = SKINCOLOR_CRIMSON, [3] = SKINCOLOR_RED, }
local wincolors = { [0] = SKINCOLOR_GOLD, [1] = SKINCOLOR_TANGERINE, [2] = SKINCOLOR_YELLOW, [3] = SKINCOLOR_TANGERINE, }

local V_10TRANS = V_10TRANS
local V_HUDTRANS = V_HUDTRANS
local V_HUDTRANSHALF = V_HUDTRANSHALF
local V_REDMAP = V_REDMAP
local V_SNAPTOTOP = V_SNAPTOTOP
local V_SNAPTORIGHT = V_SNAPTORIGHT
local V_NOSCALESTART = V_NOSCALESTART
local V_NOSCALEPATCH = V_NOSCALEPATCH
local SKINCOLOR_GREY = SKINCOLOR_GREY
local SKINCOLOR_RED = SKINCOLOR_RED
local SKINCOLOR_KETCHUP = SKINCOLOR_KETCHUP
local SKINCOLOR_BROWN = SKINCOLOR_BROWN

-- not real, but will come in handy
local V_100TRANS = V_90TRANS + V_10TRANS

-- making this local so it doesn't conflict with the other global versions
local FONT_KART2

hud.add(function(v, p)
	if not FONT_KART2 then
		FONT_KART2 = {monospace = 6, height = 14}
		for i = 0, 255 do
			local patch = string.format("MKFT2%03d", i)
			if v.patchExists(patch) then
				FONT_KART2[i] = v.cachePatch(patch)
			end
		end
	end

	if p ~= displayplayers[splitscreen] or SG_MapReset() then return end
	local hudtrans = 10 - CV_FindVar("translucenthud").value

	if elim.on then
		local drawx, drawy = 270, 4

		local ttext, tcolor = "", SKINCOLOR_GREY
		local btext, bcolor = "", SKINCOLOR_GREY
		local flags = V_SNAPTOTOP | V_SNAPTORIGHT

		if elim.started then
			if elim.gameover then
				ttext = "FINISH"
				btext = "---"
				tcolor = wincolors[(leveltime/4) & 3]
				bcolor = wincolors[(leveltime/4)+1 & 3]
			elseif elim.curtime >= 0 then
				ttext = elim.liveplayers.." LEFT"
				btext = string.format("%02d", elim.curtime / TICRATE)
				if elim.curtime < 10*TICRATE then
					bcolor = warncolors[(leveltime/2) & 3]
				end
				-- draw scary pointy braces or whatever you call 'em
				if elim.curtime < 5*TICRATE  then
					for i = 0, 8, 8 do
						local arrowofs = (elim.curtime + i) % 16
						local trans = V_10TRANS * max(hudtrans, min(arrowofs, 9))
						SG_DrawString(drawx - 22 - arrowofs*2, drawy+16, ">", FONT_KART2, flags|trans, "left", bcolor)
						SG_DrawString(drawx + 22 + arrowofs*2, drawy+16, "<", FONT_KART2, flags|trans, "right", bcolor)
					end
				end
			else
				ttext = "OVERTIME"
				btext = (elim.curtime + el_overtime.value) / TICRATE
				tcolor = SKINCOLOR_RED
				bcolor = warncolors[leveltime & 3]
			end
			flags = $ | V_HUDTRANS
		else
			flags = $ | V_HUDTRANSHALF
			ttext = "PREGAME"
			btext = "- "..string.format("%02d", (elim.startingtime - leveltime)/TICRATE).." -"
		end

		-- timer
		local timestring = string.format("%i'%02i\"%02i",G_TicsToMinutes(p.realtime,true),G_TicsToSeconds(p.realtime),G_TicsToCentiseconds(p.realtime))
		v.drawString(drawx, drawy+31, timestring, flags, "center")

		-- top text
		SG_DrawString(drawx, drawy, ttext, FONT_KART2, flags, "center", tcolor)
		-- bottom text
		if elim.curtime >= 0 then
			SG_DrawString(drawx, drawy+16, btext, FONT_KART2, flags, "center", bcolor)
		else
			-- we want the number to "bounce" whenever it ticks down
			-- ANGLE_180 == INT32_MIN
			local bounce = sin((elim.curtime + el_overtime.value) * FixedDiv(ANGLE_180, (TICRATE*FRACUNIT)>>1))
			-- multiply scale by overtime for dramatic effect (and clamp to 1x)
			local scale = max(FRACUNIT, FRACUNIT + FixedMul(bounce, FixedDiv((-elim.curtime + TICRATE) * el_overbounce.value, el_overtime.value)))
			-- put the Y coordinate slightly off-center so the number doesn't hit the top of the screen as easily
			SG_DrawFixedString(drawx<<FRACBITS, ((drawy+22)<<FRACBITS) - scale*6, scale, btext, FONT_KART2, flags, "center", bcolor)
		end

		-- last man standing
		local lastmanflash = 0
		if p.elim.lastmanannounce > 0 then
			if p.elim.lastmanannounce % 35 > 12 then lastmanflash = V_HUDTRANSHALF end
			v.drawString(160, 50, "!! LAST MAN STANDING !!", lastmanflash|V_SNAPTOTOP|V_REDMAP, "center")
		end

		-- red flashing screen of doom
		for dp, splitindex in displayplayers.iterate do
			if dp.elim.inlast and not elim.gameover then
				local trans = max(el_flashintensity.value - elim.pingtime, 0)
				if trans == 0 then break end

				if splitscreen == 0 then
					v.fadeScreen(127, trans)
				else
					local vflags = V_NOSCALESTART | V_NOSCALEPATCH | V_100TRANS - V_10TRANS * trans
					local hw = (v.width()/2)*FRACUNIT
					local hh = (v.height()/2)*FRACUNIT

					if splitscreen < 2 then
						v.drawScaled(0, splitindex == 1 and hh or hh - hw, hw, v.cachePatch("REDSCR2P"), vflags)
					else
						v.drawScaled((splitindex & 1) and hw or 0, splitindex > 1 and hh or hh - hw, hw, v.cachePatch("REDSCR4P"), vflags)
					end
				end
			end
		end

		if elim.giveup > 0 and elim.giveup <= 5*TICRATE/2 then SG_DrawFixedString(160*FRACUNIT, (100-elim.giveup/2)*FRACUNIT, (elim.giveup*FRACUNIT)/16, "fuck", FONT_KART2, 0, "center", SKINCOLOR_WHITE) end
	end

	-- announcement
	if el_announcements.value == 1 then
		local timeSinceDeath = leveltime - elim.deathtime
		local trans = V_10TRANS * max(hudtrans, min((timeSinceDeath - TICRATE*2)/10, V_100TRANS))
		if trans < V_100TRANS then
			local y = 6*v.dupy() - (timeSinceDeath*v.dupy())/20
			local flags = V_SNAPTOTOP | V_NOSCALESTART | trans

			-- insert player name(s)
			-- can't use gsub because some weirdo might have percent signs in their name
			local text = string.format(announcements[elim.announcementnum], elim.diedname)
			-- linebreak string
			text = SG_Linebreak($, 21*12, SG_StringWidth, FONT_KART2, 0)
			-- print it
			SG_DrawString(v.width()>>1, y, text, FONT_KART2, flags, "center", SKINCOLOR_BROWN)
		end
	end
end)

rawset(_G, "Elimination", function() --lets other scripts tell if elimination is running
	return elim.on
end)

-- makes someone blow up in elimination
-- input: player_t player, boolean losesound (wheter to play character's lose sound)
rawset(_G, "elim_eliminatePlayer", eliminatePlayer)





-- dug up this heap of shit
-- thought it'd be a shame if this never saw the light of day
addHook("PlayerThink", function(p)
	if not p.toadlauncher or p.playerstate ~= PST_LIVE then return end

	if not p.toadlaunchercooldown and p.cmd.buttons & BT_CUSTOM1 then
		local toad = P_SpawnPlayerMissile(p.mo, MT_ARIDTOAD)
		P_InstaThrust(toad, p.mo.angle + P_SignedRandom()*2000000, FixedMul(FRACUNIT*64, p.mo.scale) + FixedMul(p.speed, FRACUNIT*3/2))
		p.toadlaunchercooldown = TICRATE/3
	end
	if p.toadlaunchercooldown then p.toadlaunchercooldown = $ - 1 end
end)

COM_AddCommand("toadlauncher", function(p, target)
	target = tonumber($)
	if not (target ~= nil and target >= 0 and target < #players and players[target]) then
		CONS_Printf(p, "Bad player number")
	else
		target = players[target]
		COM_BufInsertText(target, "cecho You unlocked the Toad Launcher!\\Press CUSTOM 1 to fire.")
		S_StartSound(nil, sfx_itrolk, target)
		target.toadlauncher = true
	end
end, COM_ADMIN)
