DataRegistry = {}
DataRegistry.savepath = "datareg/"
function DataRegistry.makepath (path)
	path = path:gsub("[^/\\]*$","")
	local d = ""
	for dd in path:gmatch("[^/\\]+") do
		d = d..dd.."/"
		if not lfs.attributes(d) then
			lfs.mkdir(d)
		end
	end
end

function DataRegistry.getpath(projectkey,file)
	return (DataRegistry.savepath.."/"..projectkey..(file and "/"..file or "/")):gsub("/+","/")
end

function DataRegistry.save(projectkey,file,data)
	DataRegistry.makepath(DataRegistry.getpath(projectkey,file))
	local fp = assert(io.open(DataRegistry.getpath(projectkey,file),"w"))
	fp:write(data)
	fp:close()
end

function DataRegistry.load(projectkey,file,defdata)
	if not lfs.attributes(DataRegistry.savepath..projectkey) then
		return defdata
	end
	return io.open(DataRegistry.getpath(projectkey,file)):read("*a")
end


function DataRegistry.loadtable(projectkey,file,deftab)
	if not lfs.attributes(DataRegistry.savepath..projectkey) then
		return deftab
	end
	return dofile(DataRegistry.getpath(projectkey,file))
end

function DataRegistry.savetable(projectkey,file,tab)
	local ser = UtilFunctions.serialize (tab)
	DataRegistry.makepath(DataRegistry.getpath(projectkey,file))
	local fp = assert(io.open(DataRegistry.getpath(projectkey,file),"w"))
	fp:write(ser)
	fp:close()
end


function DataRegistry.open(projectkey,file,mode)
	DataRegistry.makepath(DataRegistry.getpath(projectkey))
	return io.open(DataRegistry.getpath(projectkey,file),mode)
end

function DataRegistry.delete(projectkey,file)
	return os.remove(DataRegistry.getpath(projectkey,file))
end

function DataRegistry.deleteAll(projectkey,file)
	local function clear(dir)
		--print("clearing",dir)
		for name in lfs.dir(dir) do
			if name ~="." and name~=".." then
				if lfs.attributes(dir.."/"..name,"mode")=="directory" then
					clear(dir.."/"..name)
					--print("remove",dir.."/"..name)
				end
				print("remove",dir.."/"..name)
				print(os.remove(dir.."/"..name))
			end
		end
	end
	if #projectkey==0 or projectkey=="." or projectkey==".." then return end
	clear(DataRegistry.getpath(projectkey,file))
	os.remove(DataRegistry.getpath(projectkey))
end

function DataRegistry.dir(projectkey,file)
	return lfs.dir(DataRegistry.getpath(projectkey,file))
end
