--===========================SAVING AND LOADING PAGE==============================
--Functions related to loading and saving.
--================================================================================

rawset(_G, "ProfileSamusSave", function(s, p, savenum, dosave, doload, checkonly) 
	--First, setup to make sure!
	if (doload or dosave) and (gametype != GT_COOP) --Cannot load or save in Matches!
	or not s or not p --Makes sure we exist first!
	or splitscreen and players[1] == p --Player 2 doesn't need a dedicated save.
		return false --
	end
	if not (gamemap)
		CONS_Printf(p, "\x87"+"No map to save!") return false --
	end

	--Save File! First, we set up a table to put all our data in, or I will literally go to hell.
	if dosave
	
		local s1 = {
		sam_bombs = (p.sam_bombs) and 1 or 0, --Main equipment
		samspbs = (p.samspbs) and 1 or 0,
		sambsbl = (p.sambsbl) and 1 or 0,
		sam_spiderball = (p.sam_spiderball) and 1 or 0,
		sam_gravitysuit = (p.sam_gravitysuit==1) and 1 or (p.sam_gravitysuit) and 2 or 0,
		sam_screwattack = (p.sam_screwattack) and 1 or 0,
		sam_highjump = (p.sam_highjump) and 1 or 0,
		sam_spacejump = (p.sam_spacejump) and 1 or 0,
		sam_spazerbeam = (p.sam_spazerbeam) and 1 or 0,
		sam_wavebeam = (p.sam_wavebeam) and 1 or 0,
		sam_icebeam = (p.sam_icebeam) and 1 or 0,
		sam_plasmabeam = (p.sam_plasmabeam) and 1 or 0,
		sam_powerbeamcombo = (p.sam_powerbeamcombo) and 1 or 0,
		sam_spazerbeamcombo = (p.sam_spazerbeamcombo) and 1 or 0,
		sam_wavebeamcombo = (p.sam_spazerbeamcombo) and 1 or 0,
		sam_icebeamcombo = (p.sam_icebeamcombo) and 1 or 0,
		sam_plasmabeamcombo = (p.sam_plasmabeamcombo) and 1 or 0,
		sam_hyperbeam = (p.sam_hyperbeam) and 1 or 0,
						
		sam_energy = (p.sam_energy) or 99, --Energy
		sam_energytanksmax = (p.sam_energytanksmax) or 0,

		sammissiles = 0, --Ammo
		sammissilesmax = 0,
		samsupermissiles = 0,
		samsupermissilesmax = 0,
		sampw = 0,
		sampwmax = 0,
		
		sam_scanvisor = (p.sam_scanvisor) and 1 or 0, --Bonus
		sam_ammodigitizer = (p.sam_ammodigitizer == 3) and 3 or 1,
		sam_autotank = (p.sam_autotank) and 99 or 0,
		crystalflashchance = 0,
		sam_emeraldflags = 0,
		
		sam_fullypoweredsuit = 0, --Achievements
		sam_gamemap = (gamemap) or 1,
		sam_achievement1 = 0,
		sam_achievement2 = 0,
		sam_achievement3 = 0,
		sam_achievementlock = 0,
		sam_saveddifficulty = 1,
		sam_diffusionmissiles = 0,
		sam_power_grip = 0,
		sam_chargebeam = 0,
		sam_hyperbeamammo = 0,
		sams_itemcompletion = 0
		}
		
		--Now that the table is set, let's decide what else needs to be saved!		
		
		--Ammo
		s1.sammissiles = p.sammissiles
		s1.sammissilesmax = p.sammissilesmax
		s1.samsupermissiles = p.samsupermissiles
		s1.samsupermissilesmax = p.samsupermissilesmax
		s1.sampw = p.sampw
		s1.sampwmax = p.sampwmax
		if p.crystalflashchance
			s1.crystalflashchance = min(999, p.crystalflashchance) 
		end
		
		--Which emeralds did we get?
		local MYEMERALDS = p.personalemeralds or 0
		local CHAOSEMERALDS = tonumber(emeralds) or 0
		if (MYEMERALDS > CHAOSEMERALDS)
			s1.sam_emeraldflags = (MYEMERALDS) or 0
		else
			s1.sam_emeraldflags = (CHAOSEMERALDS) or 0		
		end
		s1.sam_fullypoweredsuit = (p.sam_fullypoweredsuit) and 1 or 0
		
		s1.sam_gamemap = (gamemap) or 1
		
		if p.sam_achievement1 s1.sam_achievement1 = p.sam_achievement1 end
		if p.sam_achievement2 s1.sam_achievement2 = p.sam_achievement2 end
		if p.sam_achievement3 s1.sam_achievement3 = p.sam_achievement3 end
		
		if p.sam_achievementlock s1.sam_achievementlock = 1 end
		
		if SAMUSDIFFICULTY == 2
			s1.sam_saveddifficulty = 2
		elseif SAMUSDIFFICULTY != 0
			s1.sam_saveddifficulty = 1
		else
			s1.sam_saveddifficulty = 0
		end
			
		if p.sam_diffusionmissiles s1.sam_diffusionmissiles = 1 end
		
		if p.sam_power_grip s1.sam_power_grip = 1 end
		if p.sam_chargebeam s1.sam_chargebeam = 1 end	--Amazing, I forgot the CHARGE BEAM of all things.
		if p.sam_hyperbeamammo s1.sam_hyperbeamammo = p.sam_hyperbeamammo end
		if p.sams_itemcompletion s1.sams_itemcompletion = p.sams_itemcompletion end
		
		p.samussave = s1 --Okay! Table saved!
	end
	
	--Okay, so what are we actually DOING with this info? Are we loading? Saving it to a savefile?
	if p.samussave or doload --The table is here!
		local s1 = p.samussave
		savenum = (tonumber(savenum)) or 0
		if doload --We're loading!
			if savenum == 0 or (savenum > 99) --No save slot given? Then load whatever's in the table right now!
				if savenum == 9001 --Is it 9001? Then start at the load screen. Otherwise do nothing.
					p.sam_initmenu = true
					p.newsamfile = true
				//	if p == consoleplayer
				//		SAM_COM_BufInsertText(p, "gr_shaders 1")
				//	end
				end
			else  --Okay, load from the designated save slot! Open Locally, then use BufInsertText to force it to re-sync
				local file = io.openlocal("client/MetroidVanguard/sav"+tostring(savenum)+".dat")
				if file 
				local code = file:read("*a")
					if code ~= nil and not (string.find(code, ";"))
					and (string.find(code, "21473647"))
						SAM_COM_BufInsertText(p, tostring(code))
						p.newsamfile = false
						if not checkonly
							CONS_Printf(p, "\x83"+"Successfully loaded from saveslot\x80 "+savenum)
						end
					else
						p.newsamfile = true
						SAM_COM_BufInsertText(p, "SamusLoad 21473647")
					end
					file:close()
					return true --
				else
					SAM_COM_BufInsertText(p, "SamusLoad 21473647")
					p.newsamfile = true
					return true --
				end
			end
			
		elseif dosave --We're saving!
			if savenum == 0 or (savenum > 99) --No save slot? Well, we just updated the table, so our job here's done!
				return --
			else --Save it to a specific io slot as some kinda console command.	
				if io and p == consoleplayer
					local file = io.openlocal("client/MetroidVanguard/sav"+tostring(savenum)+".dat", "w+")

					file:write("SAMUSLOAD "+tostring(21473647)+" "+tostring(savenum)+" "+s1.sam_bombs+" "
					+s1.samspbs+" "+s1.sambsbl+" "+s1.sam_spiderball+" "+s1.sam_gravitysuit+" "
					+s1.sam_screwattack+" "+s1.sam_highjump+" "+s1.sam_spacejump+" "+s1.sam_spazerbeam+" "
					+s1.sam_wavebeam+" "+s1.sam_icebeam+" "+s1.sam_plasmabeam+" "
					+s1.sam_powerbeamcombo+" "+s1.sam_spazerbeamcombo+" "+s1.sam_wavebeamcombo+" "
					+s1.sam_icebeamcombo+" "+s1.sam_plasmabeamcombo+" "+s1.sam_hyperbeam+" "
					+s1.sam_energy+" "+s1.sam_energytanksmax+" "+s1.sammissiles+" "
					+s1.sammissilesmax+" "+s1.samsupermissiles+" "+s1.samsupermissilesmax+" "
					+s1.sampw+" "+s1.sampwmax+" "+s1.sam_scanvisor+" "
					+s1.sam_ammodigitizer+" "+s1.sam_autotank+" "+s1.crystalflashchance+" "
					+s1.sam_emeraldflags+" "+s1.sam_fullypoweredsuit+" "+s1.sam_gamemap+" "
					+s1.sam_achievement1+" "+s1.sam_achievement2+" "+s1.sam_achievement3+" "
					+s1.sam_achievementlock+" "+s1.sam_saveddifficulty+" "+s1.sam_diffusionmissiles+" "
					+s1.sam_power_grip+" "+s1.sam_chargebeam+" "+s1.sam_hyperbeamammo+" "
					+s1.sams_itemcompletion)

					file:close()
					CONS_Printf(p, "\x86"+"Game has been saved to slot "+savenum+"\x86"+"!")
				end
			end
		end
	end
end)

//Ridiculously long command for autoloading. Practically requires copy&paste.
COM_AddCommand("SAMUSLOAD", function(p, ...)
	local args = {...} args[1] = tonumber($) --Go ahead and turn the first argument into a number.
	
	if (args[1] != nil and (args[1] == 21473647) and not args[2])
	and p.sam_saveselect
		p.newsamfile = true --Looks like a new save, so go stop the function here.
		return --
	elseif args[1] == nil or ((args[1] != 21473647) and (args[1] != -21473648)) or not p.sam_saveselect
		return --Looks like we got to something completely invalid.
	end
	if (gametype != GT_COOP) or not p.mo
		return --
	end
	if splitscreen and (p ~= players[0]) --Splitscreen unfortunately is barely supported with these HUD elements.
		return false  --I don't want it to completely break, though...
	end
	for i = 2,45 --Turn all these string variables into numbers. Allow 45 at max.
		args[i] = tonumber($) --We already did 1, so start with 2.
	end	
	
	local s = p.mo --s to save me headaches.
	p.newsamfile = false --If we got this far, this is not a new save.
	
	 --Which save is it we're loading here??
	p.samussavenum = args[2] or 0
	p.sam_bombs = (args[3]==1)
	p.samspbs = (args[4]==1)
	p.sambsbl = (args[5]==1)
	p.sam_spiderball = (args[6]==1)
	p.sam_gravitysuit = (args[7]==1) and 1 or (args[7]) and 2 or 0
	p.sam_screwattack = (args[8]==1)
	p.sam_highjump = (args[9]==1)
	p.sam_spacejump = (args[10]==1)
	p.sam_spazerbeam = (args[11]==1)
	p.sam_wavebeam = (args[12]==1)
	p.sam_icebeam = (args[13]==1)
	p.sam_plasmabeam = (args[14]==1)
	p.sam_powerbeamcombo = (args[15]==1)
	p.sam_spazerbeamcombo = (args[16]==1)
	p.sam_wavebeamcombo = (args[17]==1)
	p.sam_icebeamcombo = (args[18]==1)
	p.sam_plasmabeamcombo = (args[19]==1)
	
	if args[20]==1
		if ( (netgame and (IsPlayerAdmin(p) or (p == server)) ) or not netgame )
		or (players[0] and (players[0] == server) and players[0].sam_hyperbeam) --If they get it, so should you.
			p.sam_hyperbeam = true
		end
	else
		p.sam_hyperbeam = false
	end
	
	--Our last energy amount?
	if p.sam_dontupdateenergy
		if args[21] and (args[21] < p.sam_energy) --You can lower energy in this case.
			p.sam_energy = max(1, args[21])
		end
		p.sam_dontupdateenergy = false
	else
		p.sam_energy = (args[21]) and max(99, args[21]) or 99
	end
	
	p.sam_energytanksmax = (args[22]) and min(12,args[22]) or 0
	
	p.sammissiles = (args[23]) and max(0, args[23]) or 0
	p.sammissilesmax  = (args[24]) and max(0, args[24]) or 0 
	
	p.samsupermissiles  = (args[25]) and max(0, args[25]) or 0
	p.samsupermissilesmax = (args[26]) and max(0, args[26]) or 0
	
	p.sampw = (args[28]) and max(0, args[28]) or 0
	p.sampwmax = (args[28]) and max(0, args[28]) or 0

	--Bonus items.
	p.sam_scanvisor = (args[29]==1)
	p.sam_ammodigitizer = (args[30]==3) and 3 or 1
	p.sam_autotank = (args[31]==99) and 99 or 0
	
	p.crystalflashchance = (args[32]) and max(0, args[32]) or 0	--Yes, we save even this.
	
	--Which Chaos Emeralds we've collected.
	if args[33]
		if not netgame
		or netgame and (IsPlayerAdmin(p) or (p == server)) 
			p.sam_emeraldflags = max(0, args[33])
		else
			p.personalemeralds = max(0, args[33])
		end
	end
	
	--Fully Powered Suit status
	if args[34] == 1
		p.sam_fullypoweredsuit = true
		if not netgame
		or netgame and (IsPlayerAdmin(p) or (p == server))
			p.sam_hyperbeam = true
			p.sam_emeraldflags = 127
		end
		p.sam_fpsmsg = 0 --Just incase.
	else
		p.sam_fullypoweredsuit = false
	end	
	
	--Map and achievement saves.
	p.sam_savedgamemap = args[35] or 1 --Let players choose to go back to this map and continue!
	
	--Achievements! Achievement1 is any%, Achievement2 is 100% clear, Achievement3 is under 8% clear!
	p.sam_achievement1 = (args[36]) and min(3, args[36]) or 0 --1 is bronze(normal), 2 is silver(hard), 3 is gold(fusion) 
	p.sam_achievement2 = (args[37]) and min(3, args[37]) or 0
	p.sam_achievement3 = (args[38]) and min(3, args[38]) or 0
	
	--Achievement lock.
	p.sam_achievementlock = (args[39])
	
	if args[40] --Difficulty
		p.sam_saveddifficulty = max(0, min(2, args[40]) )
		if not netgame or netgame and (IsPlayerAdmin(p) or (p == server))
			if args[40] == 1
				SAMUSDIFFICULTY = 1
			elseif args[40] == 2
				SAMUSDIFFICULTY = 2
			end
		end
	else
		p.sam_saveddifficulty = 0
		if not netgame
		or netgame and (IsPlayerAdmin(p) or (p == server))
			SAMUSDIFFICULTY = 0
		end			
	end
	
	p.sam_diffusionmissiles = (args[41]) --?!?!?
	p.sam_power_grip = (args[42])
	p.sam_chargebeam = (args[43])  --Charge Beam
	p.sam_hyperbeamammo = (args[44]) and max(0,args[44]) or 0 --Hyper Beam ammo
	
	--Your save's item Completion
	p.sams_realitemcompletion = (args[45]) and max(0, args[45]) or 0
	
	SetSamusColor(s, p) 
end)

COM_AddCommand("SAMUSLOADCONFIG", function(p, ...)
	if splitscreen and p==players[1] return false end --
	
	local args = {...} 
	args[1] = tonumber($) --Only turn the first number initially.
	
	if not (args[1])
		return false --
	elseif args[1] == 21473636 -- Welcome back.
		p.samusfirstsetupdone = true return false --
	elseif args[1] == 21473632 -- First time, boys?
		p.samusfirstsetupdone = false return false --
	end

	if args[1]==21473637 --Personal version

		if not p.customsuitc1 p.customsuitc1 = false end --Only set these to false if they're not something valid already.
		if not p.customsuitc2 p.customsuitc2 = false end
		if not p.customsuitc3 p.customsuitc3 = false end
		if not p.samvisorcolor p.samvisorcolor = SKINCOLOR_SKY end

		local MAXCOLORS = #skincolors-1
		for i = 2,8 
			if (i>4) and (i<8) i=7 
			or not args[i]
				continue --Skip!
			end
			
			local COLOR = args[i]	
			if type(COLOR) == "string" --Very likely starts off as a string.
				COLOR = string.gsub(COLOR, "blurwhyPLZ", " ")  --Filter this string first off spaces.
				COLOR = R_GetColorByName(COLOR) --Then...! convert to a number.
			end
			if COLOR
				if type(COLOR) != "number" --It's a number then? Old save version or a supercolor, probably.
					COLOR = tonumber(COLOR)
				end
				if COLOR and type(COLOR)=="number" and not (COLOR > MAXCOLORS) --Is it all valid, then let's go!
					if i == 2	p.customsuitc1 = COLOR
					elseif i==3	p.customsuitc2 = COLOR
					elseif i==4	p.customsuitc3 = COLOR
					elseif i==8 p.samvisorcolor = COLOR
					end
				end
			end
		end

		for i = 5,#args args[i] = tonumber($) end --The rest of you become numbers.
		
		p.autospeedbooster = args[5] and 1 or 0	
		p.swapfire = args[6] and true or false
		p.nosamustutorials = args[7] and true or false
		--We did args[8] earlier in the "for" loop.
		p.sam_scrollswap = args[9] and true or false
		p.sam_visorhidden = args[10] and true or false
		
		if args[11]
			p.sam_lockonpower = (args[11]==1) and 1 or 2
		else
			p.sam_lockonpower = 0
			if p.mo
				SamusTutorial(p.mo, "lockon", true)
			end
		end
		p.sam_lockontoggle = args[12] and true or false
		p.sam_lockonnomon = args[13] and true or false
		if args[14]
			p.sam_noautoscan = (args[14] == 1) and 1 or 2
		else
			p.sam_noautoscan = 0
		end
		if args[15]
			if not p.samusmusicadd2
				p.samusmusicadd2 = 3 --wait 3 tics.
			end
		else
			p.sam_autoaddmusic = false
		end
		if args[16] --Screen Tilt option
			p.sam_noscreentilt = (args[16] == 1) and 1 or 2
		else
			p.sam_noscreentilt = 0
		end
		
		if p.mo
			SetSamusColor(p.mo, p)
		end
			
	elseif args[1]==21473539
	
		local ADMIN = ((p == server) or (IsPlayerAdmin(p))) --Run the Admin version
		if ADMIN != true and (isdedicatedserver)
			local TOTAL = 0
			for z in players.iterate
				if z.valid TOTAL = $+1
					if (z == server) or (IsPlayerAdmin(z))
						TOTAL = 99 break --
					end 
				end
			end if (TOTAL<2) ADMIN = true end
		end

		if ADMIN == true
		
			for i = 2,#args args[i] = tonumber($) end --Turn into numbers!
			
			local CALLVISUALS = false
			for z in players.iterate
				z.samusmatch = (args[2]) and args[2] or 0 
				z.sam_netsaves = (args[3]==0 or args[3]==false) and false or true --Are joiners allowed to load any of their savefiles in COOP?
				z.sam_energytanksstart = (args[4]) and args[4] or 0 --How many energy tanks to start with in Match?
				z.sammatchchars = (args[5]) and args[5] or 0 --Is Samus allowed in standard ringslinger or not?		
				z.sammatchmonitors = (args[6]) and true or false --Spawn monitors in Match with Samus' balance in mind, or with SRB2's standard algorithm?
				z.coopboxrespawn = (args[7]) and args[7] or 0 --Respawn per Player, per timer, or not at all?
--				if args[8] --Metroid style skins for objects like rings and starposts?
--					z.metroidvisuals = true --Otherwise leave as is.
--				end
				z.morphcoop = (args[9]) and true or false --Can you toss players with morph ball?
				z.nosuperpowert = (args[10]) and true or false  --Are powerbombs and Super Missiles available in match modes?
				z.hypernetgo = (args[11]) and true or false --Can the Hyper Beam be used in netgames?
				z.sam_beamcombosrestrict = (args[12]) and true or false -- Can players use beam combos in match modes?
--				z.samworldevents = (args[13]) and true or false --Metroid Vanguard story mode active, or are we playing the unaltered campaign?
				z.tokensrb2style = (args[14]) and args[14] or 0 --No Damage Challenge for emeralds or SRB2 vanilla behaviour?
				if (tonumber(args[15])) --How long until boxes respawn in match? Never make this one 0.
					z.sam_respawnboxer = tonumber(args[15])
				else
					z.sam_respawnboxer = 30
				end
				z.nogunshipspawn = (args[16]) and true or false  --Spawn gunship?
				
				CALLVISUALS = true
				if not (netgame) and (gametype == GT_COOP)
					if p.samuschosefile == nil or p.sam_saveselect
						if p.mo and YouAreSamus(p.mo)
							CALLVISUALS = false
						end
					end
				end
			end
			if CALLVISUALS != false
				SetMetroidVisuals(nil) --Call this at the end.
			end
		end
	end
end)

local function LoadSamusStage(p, mapnum)
	if not (p == server) and not netgame
	or splitscreen and players[1] == p
		return false --
	end	
	p.sam_dontsave = true --Don't immediately save upon loading.
	if netgame
		if not (IsPlayerAdmin(p) or (p == server))
			p.pflags = $ & ~(PF_INVIS|PF_GODMODE|PF_FORCESTRAFE)
			if p.mo
				p.mo.flags = $|MF_SHOOTABLE & ~(MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY)
				p.mo.flags2 = $ & ~(MF2_DONTDRAW|MF2_SHADOW)
			end
			return --
		end
	end
	S_StopMusic(p)
	local TITLE = mapheaderinfo[mapnum].lvlttl
	if not TITLE or TITLE == ""
		local SKY = mapheaderinfo[mapnum].skynum
		if not SKY or SKY == 1
			if not (mapheaderinfo[mapnum].typeoflevel)
				p.sam_wrongmap = true --Okay, we can say fairly certainly this map doesn't exist.
				return false --Or at least, the creator didn't bother with some VERY crucial mapheader info....
			end
		end
	end	
	for z in players.iterate
		z.score = 0
	end
	p.pflags = $ & ~(PF_INVIS|PF_GODMODE|PF_FORCESTRAFE)
	if p.mo
		p.mo.flags = $|MF_SHOOTABLE & ~(MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY)
		p.mo.flags2 = $ & ~(MF2_DONTDRAW|MF2_SHADOW)
	end
	G_SetCustomExitVars(mapnum, 1)		
	G_ExitLevel()
end
rawset(_G, "FinishSamusSaveSelect", function(p, currentstage, truereset)
	if not p.sam_saveselect return false end --
	local samestage = true
	
	--Reload the stage, or move to the last stage you were at.
	samestage = false
	if truereset
		LoadSamusStage(p, 1)
		if p.sam_achievementlock
			p.sam_setachievementlock = true
			p.sam_achievementlock = false
		end
		CollectSamusTax(p, true)
	elseif currentstage
		LoadSamusStage(p, SAM_map(nil))
	else
		LoadSamusStage(p, (p.sam_saveselect.chosenstage))
	end
	
	if p.sam_wrongmap --This map didn't exist, it seems.
		p.sam_wrongmap = false
		P_FlashPal(p, PAL_NUKE, 5)
		S_StartSound(nil, sfx_sdenid, p)
		CONS_Printf(p, "\x85"+"This map does not exist!")
		p.sam_saveselect.menuvertical = 2
		p.sam_saveselect.submenu = 1
		SAM_COM_BufInsertText(p, "tunes SAMMU1")
	--	S_ChangeMusic("SAMMU1", true, p, 0, 0, 699, 699)
		if p.sam_setachievementlock
			p.sam_achievementlock = true
		end
		p.sam_setachievementlock = false
		return false --
	end
	
	--Reset flags incase of netgame or some weird failure.
	p.pflags = $ & ~(PF_INVIS|PF_GODMODE|PF_FORCESTRAFE)
	if p.mo
		p.mo.flags = $|MF_SHOOTABLE & ~(MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY)
		p.mo.flags2 = $ & ~(MF2_DONTDRAW|MF2_SHADOW)
		if YouAreSamus(p.mo) and SAM_displayplayer(p)
			camera.chase = false
		end
	end
	p.sam_prevcam = nil
	p.sam_firstperson = true
	p.visorclosein = 15
	p.samtoken = nil
	
	p.sam_saveselect = nil
	if not p.sam_powerbeamequip --Fix beam bug.
		p.sam_wantstoswitch = 1 A_SAMBEAMSWITCH(p)
	end
	P_FlashPal(p, PAL_RECYCLE, 5)
	S_StartSound(nil, sfx_samtm7, p)
	S_StartSound(nil, sfx_samjin, p)
	if (IsPlayerAdmin(p) or (p == server))
		emeralds = (p.sam_emeraldflags) or 0
	elseif p.sam_emeraldflags
		p.personalemeralds = p.sam_emeraldflags
	end
	
	if samestage or (p != server)
		SAM_COM_BufInsertText(p, "tunes -default")
		S_FadeMusic(0, 1, p)
		S_FadeMusic(100, 999, p)
	end
	return true --
end)

--Careful. Starting this immediately ditches previous data. It's only meant for the start of new games!
rawset(_G, "StartSamusSaveSelect", function(p)
	if gametype != GT_COOP return end
	if splitscreen and players[1] == p
		return false --
	end
	if io and p == consoleplayer
		local file = io.openlocal("client/MetroidVanguard/firstsetup.dat")
		if file			
			local code = file:read("*a")	
			if code ~= nil and (string.find(code, "21473636")) and not (string.find(code, "RESET"))
				SAM_COM_BufInsertText(p, "SAMUSLOADCONFIG 21473636")
				--Set first time menu to done. 'cause you've got this already.
			else
				SAM_COM_BufInsertText(p, "SAMUSLOADCONFIG 21473632")
			end		
			file:close()
		else
			SAM_COM_BufInsertText(p, "SAMUSLOADCONFIG 21473632")
		end
	end
	if p.samusfirstsetupdone == nil --You didn't get an answer....
		p.samuschosefile = nil
		p.sam_saveselect = nil return --
	end
	p.samuschosefile = true
	
	p.sam_saveselect = { --Menu table.
	fadein = 20<<16,
	transfadebg = FF_TRANS90,
	transfadebuttons = FF_TRANS90,
	transfadebuttons2 = FF_TRANS90,
	begintrans = 3,
	textbgfade = FF_TRANS90,
	scale = 65356,
	menuvertical = 2,
	menuhorizontal = 1,
	submenu = 1,
	backgroundx = 0,
	backgroundy = 0,
	randomsparkx = 0,
	randomsparky = 0,
	randomsparkt = 0,
	randomsparkscale = 0,
	left = 5,
	right = 5,
	up = 0, 
	down = 0,
	jump = 5,
	spin = 5,
	custom1 = 0,
	arrowanim = 0,
	cursoranim = "SAMSAVS3",
	tempsavenum = 1,
	chosenstage = 1,
	firsttrans1 = FF_TRANS90,
	firsttrans2 = FF_TRANS90,
	firsttrans3 = FF_TRANS90,
	runanim = A,
	runanim2 = A,
	huddash1 = 0,
	huddash2 = 0,
	huddash3 = 0,
	noloadsave = 0,
	delaycrash = 150
	}
	S_StartSound(nil, sfx_sscan2, p)
	
	if p.samusfirstsetupdone == false
		p.sam_saveselect.submenu = 10
		p.samuschosefile = true
		if p.samusmusicadded
			SAM_COM_BufInsertText(p, "tunes SAMUSG")
			S_ChangeMusic("SAMUSG", true, p)
		else
			SAM_COM_BufInsertText(p, "tunes SAMMU1")
			S_ChangeMusic("SAMMU1", true, p)
		end	
		S_StartSound(nil, sfx_samtm6, p)
	elseif p.samusfirstsetupdone == true
		SAM_COM_BufInsertText(p, "tunes SAMMU1")
		S_ChangeMusic("SAMMU1", true, p, 0, 0, 699, 699)
	end
end)

--Config version of Samus' save. Loads automatically.
rawset(_G, "ConfigSamusSave", function(s, p, dosave, doload) 
	if not (s and p and p.valid)
	or not (p == consoleplayer or p == displayplayer)
	or not (doload or dosave) --Input something, darn you!
	or splitscreen and players[1] == p
		return false --
	end
	if dosave
		local s1 = {
		customsuitc1 = "SKINCOLOR_POWERSUIT",
		customsuitc2 = "SKINCOLOR_VARIASUIT",
		customsuitc3 = "SKINCOLOR_GRAVITYSUIT",
		autospeedbooster = 0,
		swapfire = 0,
		nosamustutorials = 0,
		samvisorcolor = "SKINCOLOR_SKY",
	/*	sam_scrollswap = 0, --These are the defaults!
		sam_visorhidden = 0,
		sam_lockonpower = 0,
		sam_lockontoggle = 0,
		sam_lockonnomon = 0,
		sam_noautoscan = 0,
		sam_autoaddmusic = 1,
		sam_noscreentilt = 0, */
		}	
		for i = 1,4
			local COLOR = i==1 and p.customsuitc1 or i==2 and p.customsuitc2 or i==3 and p.customsuitc3 or i==4 and p.samvisorcolor
			if type(COLOR)=="number" COLOR = R_GetNameByColor(COLOR) end --Convert to a name string!
			if COLOR
				if i == 1	s1.customsuitc1 = COLOR
				elseif i==2	s1.customsuitc2 = COLOR
				elseif i==3	s1.customsuitc3 = COLOR
				elseif i==4 s1.samvisorcolor = COLOR
				end
			end
		end
		
		s1.autospeedbooster = (p.autospeedbooster) and 1 or 0
		s1.swapfire = (p.swapfire) and 1 or 0
		s1.nosamustutorials = (p.nosamustutorials) and 1 or 0 	
		s1.sam_scrollswap = (p.sam_scrollswap) and 1 or 0
		s1.sam_visorhidden = (p.sam_visorhidden) and 1 or 0
		
		s1.sam_lockonpower = (p.sam_lockonpower==1) and 1 or (p.sam_lockonpower) and 2 or 0
		s1.sam_lockontoggle = (p.sam_lockontoggle) and 1 or 0
		s1.sam_lockonnomon = (p.sam_lockonnomon) and 1 or 0	
		s1.sam_noautoscan = (p.sam_noautoscan==1) and 1 or (p.sam_noautoscan) and 2 or 0
		s1.sam_autoaddmusic = (p.sam_autoaddmusic) and 1 or 0
		s1.sam_noscreentilt = (p.sam_noscreentilt) and 1 or 0
			
		p.samuspersonalsettings = s1 --Okay! Table saved!
	end
	
	--Okay, so what are we actually DOING with this info? Are we loading? Saving it to a savefile?

	if p.samuspersonalsettings or doload --The table is here!
		local s1 = p.samuspersonalsettings
	
		if doload and not p.samuspsettingload --We're loading!		
		
			local file = io.openlocal("client/MetroidVanguard/samuspersonalsettings.dat")
			if file 
				local code = file:read("*a")
				if code ~= nil and not (string.find(code, ";")) and (string.find(code, "21473637"))
					SAM_COM_BufInsertText(p, tostring(code))
					CONS_Printf(p, "\x86"+"Loaded Metroid Vanguard personal settings.")
				end
				file:close()
			end
			p.samuspsettingload = true --Only ONCE!
			p.samuspersonalsettings = nil
			
		elseif dosave --We're saving!
		
			if io and p == consoleplayer
				local file = io.openlocal("client/MetroidVanguard/samuspersonalsettings.dat", "w+")
				file:write("SAMUSLOADCONFIG "+tostring(21473637)+" "+s1.customsuitc1+" "
				+s1.customsuitc2+" "+s1.customsuitc3+" "+s1.autospeedbooster+" "+s1.swapfire+" "
				+s1.nosamustutorials+" "+s1.samvisorcolor+" "+s1.sam_scrollswap+" "
				+s1.sam_visorhidden+" "+s1.sam_lockonpower+" "+s1.sam_lockontoggle+" "
				+s1.sam_lockonnomon+" "+s1.sam_noautoscan+" "+s1.sam_autoaddmusic+" "
				+s1.sam_noscreentilt)
				file:close()
				CONS_Printf(p, "\x86"+"Saved Metroid Vanguard personal settings!")
			end
			p.samuspersonalsettings = nil		
		end
	end	
end)


--Saves ADMIN-only features.
rawset(_G, "AdminSamusSave", function(p, dosave, doload) 
	if not (p.valid and p == server) --Server only
	and (p == consoleplayer or p == displayplayer)
	or not (doload or dosave) --Input something, darn you.
		return false
	end
	if dosave
		local s1 = {
		nogunshipspawn = 0,
		sam_respawnboxer = 30,
		tokensrb2style = 0,
		samworldevents = (SAMUSCAMPAIGN != false) and 1 or 0,
		sam_beamcombosrestrict = 0,
		hypernetgo = 0,
		nosuperpowert = 0,
		morphcoop = 0,
		metroidvisuals = 0,
		coopboxrespawn = 2,
		boxammospawns = 0,
		sammatchmonitors = 0,
		sammatchchars = 0,
		sam_energytanksstart = 2,
		sam_netsaves = 1,
		samusmatch = 0
		}
		if p.samusmatch				s1.samusmatch = p.samusmatch end
		if not p.sam_netsaves		s1.sam_netsaves = 0 end
		if p.sam_energytanksstart	s1.sam_energytanksstart = p.sam_energytanksstart end
		if p.sammatchchars			s1.sammatchchars = p.sammatchchars end
		if p.sammatchmonitors 		s1.sammatchmonitors = 1 end
		if p.coopboxrespawn 		s1.coopboxrespawn = p.coopboxrespawn end
		if (METROIDSKINS == true)	s1.metroidvisuals = 1 end
		if p.morphcoop 				s1.morphcoop = 1 end
		if p.nosuperpowert 			s1.nosuperpowert = 1 end
		if p.hypernetgo 			s1.hypernetgo = 1 end
		if p.sam_beamcombosrestrict s1.sam_beamcombosrestrict = 1 end
		if p.tokensrb2style 		s1.tokensrb2style = p.tokensrb2style end
		if p.sam_respawnboxer 		s1.sam_respawnboxer = p.sam_respawnboxer end
		if p.nogunshipspawn 		s1.nogunshipspawn = 1 end		
						
		p.samusadminsettings = s1
	end
	
--Are we loading? Or saving?

	if p.samusadminsettings or doload --The table is here!
		local s1 = p.samusadminsettings
	
		if doload and not p.samusasettingload --We're loading!			
			local file = io.openlocal("client/MetroidVanguard/samusadminsettings.dat")
			if file 
			local code = file:read("*a")
				if code ~= nil and not (string.find(code, ";"))
				and (string.find(code, "21473539"))
					SAM_COM_BufInsertText(p, tostring(code))
					CONS_Printf(p, "\x86"+"Loaded Metroid Vanguard admin settings.")
				end		
				file:close()
			end
			p.samusasettingload = true --Only ONCE!
			p.samusadminsettings = nil
			
		elseif dosave --We're saving!	
			if io and p == consoleplayer
				local file = io.openlocal("client/MetroidVanguard/samusadminsettings.dat", "w+")

				file:write("SAMUSLOADCONFIG "+tostring(21473539)+" "+s1.samusmatch+" "
				+s1.sam_netsaves+" "+s1.sam_energytanksstart+" "+s1.sammatchchars+" "+s1.sammatchmonitors+" "
				+s1.coopboxrespawn+" "+s1.metroidvisuals+" "+s1.morphcoop+" "+s1.nosuperpowert+" "
				+s1.hypernetgo+" "+s1.sam_beamcombosrestrict+" "+s1.samworldevents+" "
				+s1.tokensrb2style+" "+s1.sam_respawnboxer+" "+nogunshipspawn)
				
				file:close()
				CONS_Printf(p, "\x86"+"Saved Metroid Vanguard admin settings!")
			end
			p.samusadminsettings = nil	
		end
	end
end)

--Legacy method of setting match settings, but has some hidden variables too.
COM_AddCommand("samusmatch", function(p, var1, var2) if (gamestate!=GS_LEVEL) or not p.valid return end

	var1 = (var1) and tostring(var1) and string.lower(tostring(var1)) or nil
	var2 = (var2) and tostring(var2) and string.lower(tostring(var2)) or nil
	
	if var1 == "hidegore"
		if p.sam_hidegore
			CONS_Printf(p, "\x87"+"Corpse Scene in stage is already hidden! Restart game to reset setting.")
			if p.mo
				S_StartSound(p.mo, sfx_sdenid)
			end
		else
			CONS_Printf(p, "\x82"+"Corpse Scene in stage is now hidden.")
			p.sam_hidegore = true
			for m in mobjs.iterate(mobjs)
				if (m.type == MT_DARKPZREMAINS) 
					if (consoleplayer and p and p == consoleplayer)
						m.flags2 = MF2_DONTDRAW
					end
				end
			end
			if p.mo
				S_StartSound(p.mo, sfx_samtm7)
			end
		end
		return --
	end
	
	if not (IsPlayerAdmin(p) or (p == server))
		CONS_Printf(p, "Command is for an admin only.") return --
	end
	
	p.shotbeambefore = true --Anyone using this already knows how to use Samus.
	if var1
		if var1 == "0"
			print("Samus starts fresh on powerups each match!")
			S_StartSound(nil, sfx_mpku)
			for z in players.iterate
				z.samusmatch = 0
			end
		
		elseif var1 == "1"
			print("Samus now keeps every powerup she gets between matches!")
			S_StartSound(nil, sfx_mtnk)
			for z in players.iterate
				z.samusmatch = 1
			end
		
		elseif var1 == "2"
			print("Samus now starts with every powerup in a match!")
			S_StartSound(nil, sfx_spwup)
			for z in players.iterate
				z.samusmatch = 2
			end
		elseif var1 == "justinbailey"
			local ETANKSTOO = (not (gametyperules & GTR_RINGSLINGER) and not G_GametypeHasSpectators())
			for z in players.iterate
				z.sammissilesmax = max(z.sammissilesmax or 0, 100)
				z.sammissiles = max(z.sammissiles or 0, 100)
				z.samsupermissilesmax = max(z.samsupermissilesmax or 0, 10)
				z.samsupermissiles = max(z.samsupermissiles or 0, 10)
				z.sampwmax = max(z.sampwmax or 0, 5)
				z.sampw = max(z.sampw or 0, 5)
				
				z.samspbs = true
				z.sambsbl = true
				z.sam_spiderball = true
				z.sam_bombs = true
				z.sam_highjump = true
				z.sam_spacejump = true
				z.sam_chargebeam = true
				z.sam_spazerbeam = true
				z.sam_wavebeam = true
				z.sam_icebeam = true
				z.sam_plasmabeam = true
				z.sam_screwattack = true
				z.sam_powerbeamcombo = true
				z.sam_spazerbeamcombo = true
				z.sam_wavebeamcombo = true
				z.sam_icebeamcombo = true
				z.sam_plasmabeamcombo = true
				z.sam_power_grip = true
				if ETANKSTOO
					z.sam_energytanksmax = 12
				--	z.sam_energy = 99+(z.sam_energytanksmax*50)
				end
				if not z.sam_gravitysuit or z.sam_gravitysuit == 1
					z.sam_gravitysuit = 2
				end
				if not modeattacking --Not in record attack.
					P_SamFP(z, PAL_MIXUP, 9)
					S_StartSound(nil, sfx_spwup)
				end
			end
		elseif var1 == "engageridleymotherfucker" or var1 == "engage"
		
			emeralds = 0 --Remove emeralds now too.
			
			for z in players.iterate
				z.powers[pw_emeralds] = 0 --Remove Match Emeralds too.
				z.sammissilesmax = (G_GametypeHasSpectators() and (gametyperules & GTR_RINGSLINGER)) and 5 or 0
				z.samsupermissilesmax = 0
				z.sampwmax = 0
				z.sam_spiderball = false
				z.samspbs = false
				z.sambsbl = false
				z.sam_bombs = false
				z.sam_highjump = false
				z.sam_spacejump = false
				z.sam_chargebeam = false
				z.sam_spazerbeam = false
				z.sam_wavebeam = false
				z.sam_icebeam = false
				z.sam_plasmabeam = false
				z.sam_hyperbeam = false
				z.sam_powerbeamcombo = false
				z.sam_spazerbeamcombo = false
				z.sam_wavebeamcombo = false
				z.sam_icebeamcombo = false
				z.sam_plasmabeamcombo = false
				z.sam_screwattack = false
				z.sam_fullypoweredsuit = false
				z.sam_power_grip = false
				SamResetBeam(z)
				z.sams_itemcompletion = 0
				z.sam_energytanksmax = 0
				z.sam_gravitysuitjustgot = 0
				z.sam_autotank = nil
				z.sam_ammodigitizer = 1
	
				if z.sam_gravitysuit
					z.sam_gravitysuit = 0
					SetSamusColor(z.mo, z) 
				end
	
				if not var2 == "7"
					P_SamFP(z, PAL_NUKE, 9)
					P_DoPlayerPain(z, nil, nil)
					CONS_Printf(z, "\x85"+"You got hit by a plot device! There goes all your gear...again")
					S_StartSound(nil, sfx_mario2)
				end
			end
		elseif var1 == "ragdolls"
			if p.samusragdolls
				print("\x85"+"Nothing but serious business here, sir.")
				for z in players.iterate
					z.samusragdolls = false
				end			
			else
				print("\x82"+"The funnies have been activated.")
				for z in players.iterate
					z.samusragdolls = true
				end
			end
		end
	else
		CONS_Printf(p, "\x82SamusMatch - 0: Start fresh each Match. 1: Keep items between Matches. 2: Start with all powerups. 3: No Samus")
		CONS_Printf(p, "The default setting is 0.")
	end
end)

--Legacy setting for setting energy tanks.
COM_AddCommand("energytanks", function(p, var1) if (gamestate!=GS_LEVEL) or not p.valid return end
	if not ( IsPlayerAdmin(p) or (p == server) )
		CONS_Printf(p, "Command is for an admin only.") return --
	end
	if var != nil
		var1 = (tonumber(var1)) or 0
		if (var1 >= 0) and (var1 <= 12)
			for z in players.iterate
				z.sam_energytanksstart = tonumber(var1)
			end
			CONS_Printf(p, "New energy tank start-amount for matches set!")
		else
			CONS_Printf(p, "Start amount must be set between 0 and 12.")
		end
	else
		CONS_Printf(p, "\x82"+"Start amount for match. 1 tank increases energy by 50. Max is 12 tanks.")
	end
end)

--Legacy method for setting autospeedbooster.
COM_AddCommand("AutoSpeedBooster", function(p, var1) if (gamestate!=GS_LEVEL) or not p.valid return end
	var1 = (var1) and (tostring(var1)) and string.lower(tostring(var1)) or nil	
	if var1 == "1" or var1 == "on" or var1 == "yes"
	or var1 == "0" or var1 == "off" or var1 == "no"
		if var1 == "1" or var1 == "on" or var1 == "yes"	
			CONS_Printf(p, "\x82"+"AutoSpeedBooster toggled\x83 on")
			p.autospeedbooster = 1
		else--if var1 == "0" or var1 == "off" or var1 == "no"
			CONS_Printf(p, "\x82"+"AutoSpeedBooster toggled\x85 off")
			p.autospeedbooster = 0
		end
		p.shotbeambefore = true
	else
		CONS_Printf(p, "\x8a"+"If set to ON, the speedbooster will automatically be active without pressing\x82 CUSTOM 1")
	end
end)

COM_AddCommand("LockOnType", function(p, var1) if (gamestate!=GS_LEVEL) or not p.valid return end
	var1 = (var1) and (tostring(var1)) and string.lower(tostring(var1)) or nil		
	if var1
		if var1 == "1" or var1 == "toggle"
			CONS_Printf(p, "\x82"+"Lock On style set to toggle")
			p.sam_lockontoggle = true
		elseif var1 == "0" or var1 == "hold"
			CONS_Printf(p, "\x82"+"Lock On style set to hold")
			p.sam_lockontoggle = false
		else
			if p.sam_lockontoggle
				CONS_Printf(p, "\x82"+"Lock On style set to hold")
				p.sam_lockontoggle = false				
			else
				CONS_Printf(p, "\x82"+"Lock On style set to toggle")
				p.sam_lockontoggle = true			
			end
		end
		p.shotbeambefore = true
	else
		CONS_Printf(p, "\x82"+"Set your lock on to either toggle or hold.")
	end
end)
COM_AddCommand("SwapFire", function(p, var1) if (gamestate!=GS_LEVEL) or not p.valid return end
	var1 = (var1) and (tostring(var1)) and string.lower(tostring(var1)) or nil	
	if var1
		if var1 == "1" or var1 == "on" 
			CONS_Printf(p, "\x82"+"Fire buttons swapped! Fire missiles with NORMALFIRE, shoot beams with FIRE!")
			p.swapfire = 1
		elseif var1 == "0" or var1 == "off"
			CONS_Printf(p, "\x82"+"Fire buttons reverted to normal! Fire missiles with FIRE, shoot beams with NORMALFIRE!")
			p.swapfire = 0
		end
		p.shotbeambefore = true
	else
		CONS_Printf(p, "\x82"+"If set to ON, NORMALFIRE will fire missiles, and beams will be shot with FIRE.")
	end
end)
COM_AddCommand("ToggleSamusCustomButtons", function(p) if (gamestate!=GS_LEVEL) or not p.valid return end
	if not p.c1c2disable
		CONS_Printf(p, "\x81"+"Custom 1 and Custom 2 are now disabled as useable buttons for Samus' actions. Autospeedbooster is highly recommended.")
		p.c1c2disable = true
	else
		CONS_Printf(p, "\x83"+"Custom 1 and Custom 2 are now enabled again as useable buttons for Samus' actions.")
		p.c1c2disable = nil
	end
end)
COM_AddCommand("SpawnGunShip", function(p) if (gamestate!=GS_LEVEL) or not (p.valid) return end
	if p.nogunshipspawn
		print("\x82"+"Samus' gunship\x80 will now appear again upon player spawn!")
	end
	for z in players.iterate
		z.nogunshipspawn = nil
	end
	for m in mobjs.iterate(mobjs)
		if m.valid and (m.type == MT_SAMUSSHIP)
			for z in players.iterate
				z.shipexists = m --Hey, we found it!
			end
			break --Cool! Now stop.
		end
	end
	local s = p.mo
	if not p.shipexists and s and s.valid
		local ghs = P_SpawnMobj(s.x, s.y, s.z, MT_SAMUSSHIP)
		if ghs and ghs.valid
			for z in players.iterate
				z.shipexists = m
			end
			ghs.eflags = s.eflags
			P_TryMove(ghs, 
			s.x+FixedMul(-s.scale,cos(s.angle)), 
			s.y+FixedMul(-s.scale,sin(s.angle)), true) --Don't get this thing right into your vision, tho'!
		end
	end
	p.shipexists = nil
end, COM_ADMIN)

COM_AddCommand("GravityLights", function(p, var1) if (gamestate!=GS_LEVEL) or not p.valid return end
	if var1 != nil and (tonumber(var1) != nil)
		var1 = tonumber(var1)
		local MAXCOLOR = #skincolors
		if (var1>0) and (var1<MAXCOLOR) and var1 != SKINCOLOR_EMERALD
			p.samvisorcolor = var1
			CONS_Printf(p, "\x83"+"New visor and light colors set!")
		else
			CONS_Printf(p, "Color must actually exist, and cannot be emerald.(the default color)")
		end
		p.shotbeambefore = true
	else
		CONS_Printf(p, "\x82"+"Choose any color for the gravity suit lights between \x83"+"1 and 40"+"\x82, except for\x85 20!")
	end
end)

--Old ass command!
COM_AddCommand("CustomSuits", function(p, var1, var2, var3) 
	if (gamestate!=GS_LEVEL) or not p.valid
		return --
	end
	if G_GametypeHasTeams()
		CONS_Printf(p, "Cannot change this within team games.") return --
	end
	local s = p.mo
	if not (s and s.valid and YouAreSamus(s) )
		CONS_Printf(p, "Player character must exist, be alive, and be Samus!") return --
	end
	if var1
		if var1 == "steady" or var1 == "Steady" or var1 == "STEADY"
			p.customsuitc1,p.customsuitc2,p.customsuitc3 = 0,0,0
			CONS_Printf(p, "Suit colors set to\x82"+"STEADY!\x80 You'll remain whichever color you pick regardless of your obtained suit.") 
			return --
		elseif var2 and var3
			var1 = tonumber(var1) var2 = tonumber(var2) var3 = tonumber(var3)		
			if type(var1) == "number" and type(var2) == "number" and type(var3) == "number"
				local MAXCOLORS = #skincolors-1
				if var1 and (var1 <= MAXCOLORS)
				and var2 and (var2 <= MAXCOLORS)
				and var3 and (var3 <= MAXCOLORS)
					p.customsuitc1,p.customsuitc2,p.customsuitc3 = var1,var2,var3
					CONS_Printf(p, "\x83"+"New custom suit colors set!")
					SetSamusColor(p.mo, p) 
					p.shotbeambefore = true return --
				end
			end
		end
	end
	CONS_Printf(p, "Set 3 color numbers for each suit upgrade in order of power>varia>gravity. Example:\x82 CustomSuits 25 14 12")
end)

local function SPDMsg(p)
	CONS_Printf(p, "Choose a number from this list! You can also set another player's node number at the end to spawn it in front of them!")
	CONS_Printf(p, "\x85"+"0:Bombs 1:Charge 2:Spazer 3:Wave 4:Ice 5:Plasma\x82 6:Hi-Jump 7:SpaceJump 8:SpeedBooster 9:BallUpgrade")
	CONS_Printf(p, "\x82"+"10:SuitUpgrade 11:ScrewAttack\x83 12:MissileTank 13:SuperMTank 14:PBOMB tank 15:EnergyTank")
end
COM_AddCommand("AntiSeizureMode", function(p) if (gamestate!=GS_LEVEL) or not p.valid return end
	if p.sam_sensitive
		CONS_Printf(p, "\x84"+"Viewrolling, quakes, and flashes from Samus are back.")
		p.sam_sensitive	= false
	else
		CONS_Printf(p, "\x83"+"Most viewrolls, quakes, and flashes from Samus are now turned off for you.")
		p.sam_sensitive	= true
	end
end)

local PowerDropList = {
[0] = {TEXT = "\x82 spawned Morph Ball Bombs for \x80", i = MT_MHBM},
[1] = {TEXT = "\x82 spawned the Charge Beam for \x80", i = MT_CHBM},
[2] = {TEXT = "\x82 spawned the Spazer Beam for \x80", i = MT_SPBM},
[3] = {TEXT = "\x82 spawned the Wave Beam for \x80", i = MT_WVBM},
[4] = {TEXT = "\x82 spawned the Ice Beam for \x80", i = MT_ICBM},
[5] = {TEXT = "\x82 spawned the Plasma Beam for \x80", i = MT_PLBM},
[6] = {TEXT = "\x82 spawned the High Jump/Spring Ball for \x80", i = MT_SPBL},
[7] = {TEXT = "\x82 spawned the Space Jump boots for \x80", i = MT_SJMP},
[8] = {TEXT = "\x82 spawned the Speed Booster for \x80", i = MT_SPBS},
[9] = {TEXT = "\x82 spawned the Boost Ball for \x80", i = MT_BSBL},
[10] = {TEXT = "\x82 spawned the Varia Suit for \x80", i = MT_VRST},
[11] = {TEXT = "\x82 spawned the Screw Attack for \x80", i = MT_SATK},
[12] = {TEXT = "\x82 spawned a Missile Tank for \x80", i = MT_MTNK},
[13] = {TEXT = "\x82 spawned a Super Missile Tank for \x80", i = MT_STNK},
[14] = {TEXT = "\x82 spawned a Powerbomb Tank for \x80", i = MT_PTNK},
[15] = {TEXT = "\x82 spawned an Energy Tank for \x80", i = MT_ENGTNK},
[16] = {TEXT = "\x82 spawned the Auto Tank for \x80", i = MT_AUTOTANK},
[17] = {TEXT = "\x82 spawned the Ammo Digitizer for \x80", i = MT_AMMODIGITIZER},
[18] = {TEXT = "\x82 spawned the Scan Visor for \x80", i = MT_SCANVISOR},
[19] = {TEXT = "\x82 spawned the Power Grip for \x80", i = MT_PWGRP},
}
COM_AddCommand("SamusPowerDrop", function(p, var1, wt) if (gamestate!=GS_LEVEL) or not p.valid return end

	local OGP = p local s = p.mo
	
	if wt == nil
		wt = p
	elseif tonumber(wt) != nil and not (tonumber(wt) > 31)
		for z in players.iterate
			if z.valid and z.mo and z == players[tonumber(wt)]
				wt = z
			end
		end
		if type(wt) != "userdata"
			CONS_Printf(p, "\x85"+"Invalid player!") return --
		end
	else
		CONS_Printf(p, "\x85"+"Invalid playernum.")
		SPDMsg(p) return --	
	end
	local NUMVAR = tonumber(var1) --What number did you pick?
	
    if NUMVAR != nil and (NUMVAR < 20)
		local i,TEXT --item type and accompanying text.
		var1 = NUMVAR
		local POWERUP = PowerDropList[var1]
		
		--Some special cases that check what power you have and can then drop something else.
		if var1==9 and wt.sambsbl 
			i = MT_SPDRBL
			TEXT = p.name+"\x82 spawned the Spider Ball for \x80"+wt.name
		elseif var1==10 and wt.sam_gravitysuit
			TEXT = p.name+"\x82 spawned the Gravity Suit for \x80"+wt.name
			i = MT_GVST
		elseif POWERUP
			TEXT = POWERUP.TEXT
			i = POWERUP.i
		end	
		if i
			local DIST = max(wt.mo.radius*2, 210<<16)
			local ANG = (wt.mo.angle) or 0
			for d = 0,15
				local ghs = P_SpawnMobj(
				wt.mo.x+FixedMul(DIST, cos(ANG+(ANGLE_22h*d))), 
				wt.mo.y+FixedMul(DIST, sin(ANG+(ANGLE_22h*d))), wt.mo.z, i)
				if ghs and ghs.valid
					local ths = P_SpawnMobjFromMobj(ghs,0,0,0,MT_EXPLODE)
					ths.dispoffset = 99
					S_StartSoundAtVolume(ghs, sfx_sballf,100)
					if TEXT print(p.name+TEXT+wt.name) end break --
				elseif d==15 and OGP
					CONS_Printf(OGP, "\x85"+"Error spawning item. Try changing location.")
				end
			end
		else
			SPDMsg(p)
		end
    else
		SPDMsg(p)
		CONS_Printf(p, "Choose who you want to receive the item, putting their nodenumber behind the item number.")
		SAM_COM_BufInsertText(p, "nodes")	     
     end
	 p.shotbeambefore = true
end, COM_ADMIN)