--Author: Owen - www.owensoft.net
--Description: code for reading and updating settings file

--system

require("global.lua")

ge['setting_none']=true  --if file is blank these are the defaults

filename = 'setting.txt'  --file in which to save settngs

function save_settings()
	--test file for writing
	f = io.open (filename, "a+");

	if( io.type (f)=="file" ) then
		f:close (f);

		ge['setting_none']=false

		if ge['setting_save_count'] == nil then
			ge['setting_save_count']=0
		end

		ge['setting_save_count']=ge['setting_save_count']+1;

		--write settings back to file
		f = io.open (filename, "w");
		for  k,v in pairs(ge) do
			f:write ( k, "=", tostring(v), ";\n\r" );
			f:flush ();
		end
		f:close (f);
	else
		print("failed to open or cannot create settings file, nothing saved. ", filename );
	end

end


function load_settings()
	--test file for writing
	f = io.open (filename, "a+");

	if( io.type (f)=="file" ) then
		f:close (f);

		t = {};

		--read and load settings into array
		for line in io.lines(filename) do
			--print(line)
			for k, v in string.gmatch(line, "([%w_]+)=([%w_]+);") do  --words including words with underscore
				   t[k] = v;
				   --print(k, v);
			end
		end

		--print out settings
		for  k,v in pairs(t) do
			if v == "" then
			else
				if v=='true' then v=true; end
				if v=='false' then v=false; end
				ge[k]=v;
			end
			print( k, v );
		end

	else
		print("failed to open or cannot create settings file, nothing saved. ", filename );
	end

end

function test_settings()
	load_settings();
	save_settings();
	print( ge['setting_save_count'] );
end

--test_settings();
