config = {}

config.loaded = {}

function config.load(filename, defaultTable, targetTable)
	local path = daisy.getUserFolderPath("/")
	local newTable = table.load(path .. filename..(EXTENSIONS.config or ".cfg")) or {}
	
	if defaultTable then
		for index, setting in pairs(defaultTable) do
			if newTable[index] ~= nil then
				targetTable[index] = newTable[index]
			elseif setting ~= "NIL" then
				targetTable[index] = setting
			end
		end
	else
		for index, val in pairs(newTable) do
			targetTable[index] = val
		end
	end
	
	local found = false
	
	for index, con in pairs(config.loaded) do
		if con.targetTable == targetTable then
			found = true
			break
		end
	end
	
	if not found then
		table.insert(config.loaded, {filename = filename..(EXTENSIONS.config or ".cfg"), targetTable = targetTable, defaultTable = defaultTable})
	end
end

function config.saveAll()
	local path = daisy.getUserFolderPath("/")
		
	for index, con in pairs(config.loaded) do
		if con.defaultTable then
			local tmpT = {}
			for key, v in pairs(con.defaultTable) do
				tmpT[key] = con.targetTable[key]
			end
			table.save(tmpT, path .. con.filename)
		else
			table.save(con.targetTable, path .. con.filename)
		end
		
	end
end
