-- Kinda ripping off my own code again, but this time using envs instead of a wacky local metatable.
local function LoadProfOptsToEnv(pn, dir)
	Trace("(LoadProfOptsToEnv) Attempting to load options for " .. pn .. " from " .. dir)
	if FILEMAN:DoesFileExist(dir .. "eksd.ini") then
		local theFile = IniFile.ReadFile(dir .. "eksd.ini")
		--SM(theFile)
		
		if theFile and theFile["Options"] then
			for k,v in pairs(theFile["Options"]) do
				-- try and play this safe
				if type(getenv(k .. pn)) == type(v) then
					setenv(k .. pn, v)
				else
					Trace("Skipped invalid option '" .. k .. "' (expected " .. type(getenv(k .. pn)) .. ", got " .. type(v) .. ")")
				end
			end
			
			Trace(pn .. "'s eksd.ini loaded")
		else
			Trace("??? [Options] section in eksd.ini might not exist")
		end
	else
		Trace(pn .. "'s eksd.ini not found, sticking to default options")
	end
end

-- Loaded on SelectProfile's Off command, and on SelectMusic(etc) if a new player joins in with a profile.
function LoadProfileCustom(profile, dir)
	local pn
	
	for player in ivalues( GAMESTATE:GetHumanPlayers() ) do
		if profile == PROFILEMAN:GetProfile(player) then
			pn = ToEnumShortString(player)
			break
		end
	end

	if pn then
		LoadProfOptsToEnv(pn, dir)
		Trace("(LoadProfileCustom) " .. pn .. "'s profile loaded from " .. dir)
	end
end

-- Loaded on ProfileSave's Off command.
function SaveProfileCustom(profile, dir)
	for player in ivalues( GAMESTATE:GetHumanPlayers() ) do
		if profile == PROFILEMAN:GetProfile(player) then
			local pn = ToEnumShortString(player)
			local output = {}
			for i, op in ipairs(LoadModule("Options.Envs.lua")) do
				output[op[1]] = getenv(op[1] .. pn)
			end
			
			IniFile.WriteFile(dir .. "eksd.ini", {["Options"] = output} )
			
			Trace("(SaveProfileCustom) " .. pn .. "'s profile saved to " .. dir)
			break
		end
	end
end
