local f={DEBUG=false}function f.debugPrint(e)if f.DEBUG then print("\091\068\065\084\065\093 "..e)end end local e=600 local t=60 local I=5 local S={}local b={}local a="\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\095\080\108\097\121\101\114\068\097\116\097\095\082\069\076\069\065\083\069\048\048"local w=true local p=false if game.Players.LocalPlayer then error("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101 \114\101\113\117\101\115\116\101\100 \111\110 \116\104\101 \099\108\105\101\110\116\044 \105\115 \097 \115\101\114\118\101\114-\111\110\108\121 \109\111\100\117\108\101\046",2)end local function Q(f)if type(f)=="\116\097\098\108\101"then local e={}for f,t in pairs(f)do e[f]=Q(t)end return e else return f end end local function P(f)local e=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")e.Event:connect(f)e:Fire()end local m={}function m.new(e,t)local I={}I.userId=t I.lastSaved=0 I.locked=false I.unlocked=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")I.dataSet=nil I.dirtyKeySet={}I.ownedKeySet={}local function S(f)I.ownedKeySet[f]=true end local function a(f)I.dirtyKeySet[f]=true end local function w(f)S(f)e:markAsTouched(I)end local function Q(f)S(f)a(f)e:markAsDirty(I)end function I.makeReady(t,f)I.dataSet=f I.lastSaved=tick()e:markAsTouched(I)end function I.waitForUnlocked(f)while I.locked do I.unlocked.Event:wait()end end function I.lock(f)I.locked=true end function I.unlock(f)I.locked=false I.unlocked:Fire()end function I.Get(t,e)f.debugPrint("\040"..(I.userId..("\041 \071\069\084\084\073\078\071 "..tostring(e))))if type(e)~="\115\116\114\105\110\103"then error("\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \083\097\118\101\068\097\116\097\058\058\071\101\116\040\041 \040\115\116\114\105\110\103 \101\120\112\101\099\116\101\100\041",2)end if p then print("\083\097\118\101\068\097\116\097\060"..(I.userId..("\062\058\058\071\101\116\040"..(e.."\041"))))end w(e)local S=I.dataSet[e]if S==nil and b[e]then local f=b[e](nil)I.dataSet[e]=f return f else return S end end function I.Set(b,e,t,S)f.debugPrint("\040"..(I.userId..("\041 \083\069\084\084\073\078\071 "..(tostring(e)..(" \084\079 "..tostring(t))))))if type(e)~="\115\116\114\105\110\103"then error("\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \083\097\118\101\068\097\116\097\058\058\083\101\116\040\041 \040\115\116\114\105\110\103 \101\120\112\101\099\116\101\100\041",2)end if t==nil and not S then error("\065\116\116\101\109\112\116 \116\111 \083\097\118\101\068\097\116\097\058\058\083\101\116\040\'"..(e.."\'\044 \110\105\108\041 \119\105\116\104\111\117\116 \097\108\108\111\119\069\114\097\115\101 \061 \116\114\117\101"),2)end if p then print("\083\097\118\101\068\097\116\097\060"..(I.userId..("\062\058\058\083\101\116\040"..(e..("\044 "..(tostring(t).."\041"))))))end Q(e)I.dataSet[e]=t end function I.Update(S,f,t)if type(f)~="\116\097\098\108\101"then error("\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \083\097\118\101\068\097\116\097\058\058\085\112\100\097\116\101\040\041 \040\116\097\098\108\101 \111\102 \107\101\121\115 \101\120\112\101\099\116\101\100\041",2)end if type(t)~="\102\117\110\099\116\105\111\110"then error("\066\097\100 \097\114\103\117\109\101\110\116 \035\050 \116\111 \083\097\118\101\068\097\116\097\058\058\085\112\100\097\116\101\040\041 \040\102\117\110\099\116\105\111\110 \101\120\112\101\099\116\101\100\041",2)end if p then print("\083\097\118\101\068\097\116\097\060"..(I.userId..("\062\058\058\085\112\100\097\116\101\040"..(table.concat(f,"\044 ")..("\044 "..(tostring(t).."\041"))))))end e:doUpdate(I,f,t)end function I.Flush(f)if p then print("\083\097\118\101\068\097\116\097\060"..(I.userId.."\062\058\058\070\108\117\115\104\040\041"))end e:doSave(I)end return I end local D={}function D.new()local f={}local D=game:GetService("\068\097\116\097\083\116\111\114\101\083\101\114\118\105\099\101")local u=D:GetDataStore(a)local W=setmetatable({},{__mode="\118"})local l={}local s={}local R={}local J={}local y=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")local V=0 local function r(f)return"\080\064"..f end function f.markAsTouched(e,f)if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\109\097\114\107\065\115\084\111\117\099\104\101\100\040"..(f.userId.."\041"))end l[f]=true f.lastTouched=tick()W[f.userId]=f end function f.markAsDirty(t,e)if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\109\097\114\107\065\115\068\105\114\116\121\040"..(e.userId.."\041"))end f:markAsTouched(e)R[e]=true W[e.userId]=e end local function G(f)return{}end local function z(f)local e={}local t={}for I,b in pairs(f.dirtyKeySet)do local a=f.dataSet[I]if a~=nil then if S[I]then e[I]=S[I](a)else e[I]=Q(a)end else table.insert(t,I)end f.dirtyKeySet[I]=nil end return e,t end function f.doSave(e,f)if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\100\111\083\097\118\101\040"..(f.userId.."\041 \123"))end f.lastSaved=tick()R[f]=nil if next(f.dirtyKeySet)then local e,t=z(f)f:waitForUnlocked()f:lock()V=V+1 u:UpdateAsync(r(f.userId),function(I)if not I then I=G(f.userId)end if p then print("\t\097\116\116\101\109\112\116\105\110\103 \115\097\118\101\058")end for f,e in pairs(e)do if p then print("\t\t\115\097\118\105\110\103 \096"..(f..("\096 \061 "..tostring(e))))end I[f]=e end for f,e in pairs(t)do if p then print("\t\t\115\097\118\105\110\103 \096"..(e.."\096 \061 \110\105\108 \091\069\082\065\083\073\078\071\093\041"))end I[e]=nil end return I end)if p then print("\t \115\097\118\101\100\046")end V=V-1 f:unlock()elseif p then print("\t\110\111\116\104\105\110\103 \116\111 \115\097\118\101")end if p then print("\125")end end function f.doUpdate(I,f,e,t)if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\100\111\085\112\100\097\116\101\040"..(f.userId..("\044 \123"..(table.concat(e,"\044 ")..("\125\044 "..(tostring(t).."\041 \123"))))))end f:waitForUnlocked()f:lock()V=V+1 f.lastSaved=tick()R[f]=nil local a={}for e,t in pairs(e)do f.ownedKeySet[t]=true a[t]=true end local w,Q=z(f)u:UpdateAsync(r(f.userId),function(I)if p then print("\t\116\114\121\105\110\103 \117\112\100\097\116\101\058")end if not I then I=G(f.userId)end local P={}for e,t in pairs(e)do local I=f.dataSet[t]if I==nil and b[t]then P[e]=b[t](nil)else P[e]=I end end local m={t(unpack(P,1,#e))}for t,b in pairs(m)do local a=e[t]if S[a]then local f=S[a](b)if p then print("\t\t\115\097\118\105\110\103 \114\101\115\117\108\116\058 \096"..(a..("\096 \061 "..(tostring(f).." \091\083\069\082\073\065\076\073\090\069\068\093"))))end I[a]=f else if p then print("\t\t\115\097\118\105\110\103 \114\101\115\117\108\116\058 \096"..(a..("\096 \061 "..tostring(b))))end I[a]=b end f.dataSet[a]=b end for f,e in pairs(w)do if not a[f]then if p then print("\t\t\115\097\118\105\110\103 \117\110\115\097\118\101\100 \118\097\108\117\101\058 \096"..(f..("\096 \061 "..tostring(e))))end I[f]=e end end for f,e in pairs(Q)do if not a[e]then if p then print("\t\t\115\097\118\105\110\103 \117\110\115\097\118\101\100 \118\097\108\117\101\058 \096"..(e.."\096 \061 \110\105\108 \091\069\082\065\083\073\078\071\093"))end I[e]=nil end end return I end)V=V-1 f:unlock()if p then print("\125")end end local function H(e)if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\100\111\076\111\097\100\040"..(e.."\041 \123"))end local t t=W[e]if t then if p then print("\t\082\101\099\111\114\100 \119\097\115 \097\108\114\101\097\100\121 \105\110 \099\097\099\104\101")end f:markAsTouched(t)if p then print("\125")end return t end if J[e]then if p then print("\t\082\101\099\111\114\100 \097\108\114\101\097\100\121 \114\101\113\117\101\115\116\101\100\044 \119\097\105\116 \102\111\114 \105\116\046\046\046")end while true do t=(y.Event:wait())()if t.userId==e then f:markAsTouched(t)if p then print("\t\082\101\099\111\114\100 \115\117\099\099\101\115\115\102\117\108\108\121 \114\101\116\114\105\101\118\101\100 \098\121 \097\110\111\116\104\101\114 \116\104\114\101\097\100")print("\125")end return t end end else if p then print("\t\082\101\113\117\101\115\116 \114\101\099\111\114\100\046\046\046")end J[e]=true local I=nil local S=pcall(function()I=u:GetAsync(r(e))or{}end)if not S then local function f()pcall(function()I=u:GetAsync(r(e))or{}end)end repeat print("\091\068\065\084\065\093 \033\033\033 \082\079\066\076\079\088 \083\069\082\086\069\082\083 \070\065\073\076\069\068 \070\079\082 "..(e.."\046 \084\082\089\073\078\071 \065\071\065\073\078 \073\078 \053 \083\069\067\079\078\068\083 \033\033"))wait(5)f()until I~=nil end for f,e in pairs(I)do if b[f]then I[f]=b[f](e)end end t=m.new(f,e)t:makeReady(I)f:markAsTouched(t)J[e]=nil y:Fire(function()return t end)if p then print("\t\082\101\099\111\114\100 \115\117\099\099\101\115\115\102\117\108\108\121 \114\101\116\114\105\101\118\101\100 \102\114\111\109 \100\097\116\097 \115\116\111\114\101")print("\125")end return t end end local function h(f)if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\062 \080\108\097\121\101\114 "..(f.userId.." \069\110\116\101\114\101\100 \062 \076\111\097\100 \068\097\116\097"))end local e=H(f.userId)if f.Parent then s[f]=e end end game.Players.PlayerAdded:connect(h)for f,e in pairs(Game.Players:GetChildren())do if e:IsA("\080\108\097\121\101\114")then h(e)end end game.Players.PlayerRemoving:connect(function(e)local t=s[e]s[e]=nil if w and t then if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\062 \080\108\097\121\101\114 "..(e.userId.." \076\101\102\116 \119\105\116\104 \100\097\116\097 \116\111 \115\097\118\101 \062 \083\097\118\101 \068\097\116\097"))end f:doSave(t)end end)game.OnClose=function()if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\062 \079\110\067\108\111\115\101 \083\104\117\116\100\111\119\110\n\t\070\108\117\115\104\105\110\103\046\046\046")end f:FlushAll()if p then print("\t\070\108\117\115\104\101\100\044 \097\100\100\105\116\105\111\110\097\108 \119\097\105\116\046\046\046")end while V>0 do wait()end if p then print("\t\083\104\117\116\100\111\119\110 \099\111\109\112\108\101\116\101\100 \110\111\114\109\097\108\108\121\046")end end local function C()local t=tick()for I,S in pairs(l)do if t-I.lastTouched>e then if R[I]then if p then print("\062\062 \067\097\099\104\101 \101\120\112\105\114\101\100 \102\111\114\058 "..(I.userId.."\044 \104\097\115 \117\110\115\097\118\101\100 \099\104\097\110\103\101\115\044 \119\097\105\116\046"))end P(function()f:doSave(I)end)else if p then print("\062\062 \067\097\099\104\101 \101\120\112\105\114\101\100 \102\111\114\058 "..(I.userId.."\044 \114\101\109\111\118\105\110\103\046"))end l[I]=nil end end end end local function v()local e=tick()for I,S in pairs(R)do if e-I.lastSaved>t then if p then print("\080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\062\062 \080\097\115\115\105\118\101 \115\097\118\101 \102\111\114\058 "..I.userId)end P(function()f:doSave(I)end)end end end spawn(function()while true do C()v()wait(I)end end)function f.GetSaveData(e,f)if not f or not f:IsA("\080\108\097\121\101\114")then error("\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\071\101\116\083\097\118\101\068\097\116\097\040\041\044 \080\108\097\121\101\114 \101\120\112\101\099\116\101\100",2)end return H(f.userId)end function f.GetSaveDataById(e,f)if type(f)~="\110\117\109\098\101\114"then error("\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \080\108\097\121\101\114\068\097\116\097\083\116\111\114\101\058\058\071\101\116\083\097\118\101\068\097\116\097\066\121\073\100\040\041\044 \117\115\101\114\073\100 \101\120\112\101\099\116\101\100",2)end return H(f)end function f.FlushAll(e)local t=0 local I=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")for e,S in pairs(R)do P(function()t=t+1 f:doSave(e)t=t-1 if t<=0 then I:Fire()end end)end if t>0 then I.Event:wait()end end return f end return D.new()
--===============================================--
--==                    API                    ==--
--===============================================--

local me = {
	DEBUG = false,
};
function me.debugPrint(msg)
	if (me.DEBUG) then
		print("[DATA] " .. msg);
	end
end

--[[

The module returns an object 'PlayerDataStore'
with the following methods:

PlayerDataStore:GetSaveData(Player player) -> returns SaveData
	Returns the SaveData structure for a given
	player who is currently in the server.
	Will yield until the player's data is actually
	ready before returning.

PlayerDataStore:GetSaveDataById(integer userId) -> returns SaveData
	Returns the SaveData structure for a player
	with a given userId, who may or may not
	currently be in the server.
	Will yield until the user's data is actually
	ready before returning.

PlayerDataStore:FlushAll()
	Saves all unsaved changes in all SaveData
	structures in the place at the time of calling.
	Will yield until all of the save calls have
	completed.

The SaveData structures have the following methods:

SaveData:Get(string key) -> returns stored value
	Gets the value associated with |key| in this
	player's stored data. The cached value for this
	server will be returned, so this call will always
	return immediately.

SaveData:Set(string key, variant value)
	Sets the cached value associated with |key| on
	this server. This cached value will be saved to
	the DataStore at some point in the future: either
	when the passive save runs, when the player leaves
	the server, or when you call Flush() on he SaveData,
	whichever happens first.
	The call returns immediately.

SaveData:Update((array of strings) keys, function updateFunction)
	Atomically update multiple keys of a SaveData
	at once, and update the results in the data store,
	ensuring that no data is lost. Will yield until the
	save to the data store has actually completed.
	EG, for an important developer product purchase:
	saveData:Update({'PurchaseCount', 'Money'}, function(oldPurchaseCount, oldMoney)
		if not oldPurchaseCount then oldPurchaseCount = 0 end
		if not oldMoney then oldMoney = 0 end
		oldMoney = oldMoney + developerProductAmount
		oldPurchaseCount = oldPurchaseCount + 1
		return oldPurchaseCount, oldMoney
	end)
	In general you should only be using this function to
	handle developer product purchases, as the data store
	throttling limit is quite low, and you will run into
	it if your users are hitting part of your functionality
	that uses this with a lot of requests.

]]--


--===============================================--
--==          Global Module Settings           ==--
--===============================================--

-- How long to keep cached data for a given player
-- before letting it be thrown away if there are
-- no other references to it in your code.
-- Note1: Even after the expiry time, as long as
-- there is Lua code in your project somewhere
-- holding onto a reference to the SaveData object
-- for a player, the cached data for that player
-- will be kept.
-- Note2: Data for a given play will be cached for
-- as long as that player is in the server whether
-- or not you actually have a reference to it. The
-- expiry time is only relevant for the data of
-- players who are not in the server.
local CACHE_EXPIRY_TIME = 60*10 --10 minutes

-- How often to save unsaved changes to a player's 
-- data store if it has not been manually Flush'd 
-- by calling the Flush method on their SaveData,
-- or Flush'd via the player leaving the place.
local PASSIVE_SAVE_FREQUENCY = 60*1 -- once every 1 minute

-- How accurately to clear cache entries / do passive
-- saves. That is, how often to check if those things
-- need to be done.
local PASSIVE_GRANULARITY = 5 -- check once every 5 seconds

-- Optional key serialization. This specifies how
-- a given key should be saved to or loaded from
-- the actual data store. If not specified in the
-- tables then the key will just be directly 
-- passed to the DataStore:Get/Set/UpdateAsync
-- methods.
local SERIALIZE = {}
local DESERIALIZE = {}
-- Put your entries here --
         --vvvvv--

         --^^^^^--
----------------------------
-- EG:
-- SERIALIZE.ScoreObject = function(scoreObject)
--     return scoreObject.Value
-- end
-- DESERIALIZE.ScoreObject = function(value)
--     local object = Instance.new('IntValue')
--     object.Name = 'ScoreIntValue'
--     object.Value = value
--     return object
-- end
-- ...usage (Note, you would never actually want to do this with an 
--           IntValue object as shown, you could just be storing a straight 
--           number instead, and it wouldn't work very well because
--           if you just set the IntValue's value the PlayerDataStore
--           would not know that it had changed, and would not save the
--           change. You'd actually have to call Set(...) to make the
--           change save):
-- local PlayerDataStore = require(game.ServerStorage.PlayerDataStore)
-- local saveData = PlayerDataStore:GetSaveData(player)
-- local valueObject = saveData:Get('ScoreObject')
-- print(valueObject.Name, valueObject.Value) -> ScoreIntValue <value>
-- local newScoreObject = Instance.new('IntValue')
-- newScoreObject.Value = 4
-- -- Even though normally you cannot save objects to the data 
-- -- store, the custom serialize you provided handles it
-- saveData:Set('ScoreObject', newScoreObject)
-- saveData:Flush()


-- The name of the data store to use to store the 
-- player data.
local DATASTORE_NAME = 'PlayerDataStore_PlayerData_RELEASE00'

-- Guarantee a save ASAP when a player leaves a server.
-- This ensures that if they go to another server of the 
-- same place the save will almost certainly have already
-- completed when they enter the new place. You can leave
-- this off to be lighter on the save quota if you are
-- not possibly storing very important stuff in the data
-- store right before a player leaves.
local SAVE_ON_LEAVE = true

-- Debug flag, for internal debugging
local DEBUG = false

-- Check that we are on the server, as this is a server
-- only module.
if game.Players.LocalPlayer then
	error("PlayerDataStore requested on the client, is a server-only module.", 2)
end

--===============================================--
--==             Utility Functions             ==--
--===============================================--
-- Deep copy a table without circular references
local function DeepCopy(tb)
	if type(tb) == 'table' then
		local new = {}
		for k, v in pairs(tb) do
			new[k] = DeepCopy(v)
		end
		return new
	else
		return tb
	end
end

-- Spawn a new thread and run it immedately up to
-- the first yield before returning
local function SpawnNow(func)
	local ev = Instance.new('BindableEvent')
	ev.Event:connect(func)
	ev:Fire()
end

--===============================================--
--==              SaveData Class               ==--
--===============================================--
-- Holds the cached saved data for a given player.
local SaveData = {}
function SaveData.new(playerDataStore, userId)
	local this = {}

	--===============================================--
	--==               Private Data                ==--
	--===============================================--	
	this.userId = userId
	this.lastSaved = 0

	-- Locked status, so that saves and updates cannot
	-- end up fighting over the same data
	this.locked = false
	this.unlocked = Instance.new('BindableEvent')

	-- The actual data for this SaveData structure 
	this.dataSet = nil

	-- Keys that have unsaved changes
	this.dirtyKeySet = {}

	-- keys that we "own", that is, ones we have
	-- written to or read from on this SaveData.
	this.ownedKeySet = {}

	--===============================================--
	--==          Private Implementation           ==--
	--===============================================--
	local function ownKey(key)
		this.ownedKeySet[key] = true
	end
	local function dirtyKey(key)
		this.dirtyKeySet[key] = true
	end
	local function markAsTouched(key)
		ownKey(key)
		playerDataStore:markAsTouched(this)
	end
	local function markAsDirty(key)
		ownKey(key)
		dirtyKey(key)
		playerDataStore:markAsDirty(this)
	end

	-- Load in the data for the struct
	function this:makeReady(data)
		this.dataSet = data
		this.lastSaved = tick()
		playerDataStore:markAsTouched(this)
	end

	function this:waitForUnlocked()
		while this.locked do
			this.unlocked.Event:wait()
		end
	end
	function this:lock()
		this.locked = true
	end
	function this:unlock()
		this.locked = false
		this.unlocked:Fire()
	end

	--===============================================--
	--==                Public API                 ==--
	--===============================================--
	-- Getter and setter function to manipulate keys 
	-- for this player.
	function this:Get(key)
		me.debugPrint("(".. this.userId .. ") GETTING " .. tostring(key));
		if type(key) ~= 'string' then
			error("Bad argument #1 to SaveData::Get() (string expected)", 2)
		end
		if DEBUG then
			print("SaveData<"..this.userId..">::Get("..key..")")
		end
		markAsTouched(key)
		local value = this.dataSet[key]
		if value == nil and DESERIALIZE[key] then
			-- If there's no current value, and the key
			-- has serialization, then we should get the
			-- null deserialized state. 
			local v = DESERIALIZE[key](nil)
			-- Note: we don't markAsDirty here, that's 
			-- intentional, as we don't want to save
			-- if we don't have to, and we don't need
			-- to here, as Deserialize(key, nil) should
			-- return back the same thing every time.
			-- However, we still need cache the value,
			-- because deserialize(key, nil) might still
			-- be expensive or the caller might expect
			-- the same reference back each time. 
			this.dataSet[key] = v
			return v
		else
			return value
		end
	end
	-- Set(key, value, allowErase)
	-- Note: If allowErase is not set to true, then 
	-- the call will error on value = nil, this is
	-- to prevent you accidentally erasing data when
	-- you don't mean to. If you do want to erase,
	-- then call with allowErase = true
	function this:Set(key, value, allowErase)
		me.debugPrint("(".. this.userId .. ") SETTING " .. tostring(key) .. " TO " .. tostring(value));
		if type(key) ~= 'string' then
			error("Bad argument #1 to SaveData::Set() (string expected)", 2)
		end
		if value == nil and not allowErase then
			error("Attempt to SaveData::Set('"..key.."', nil) without allowErase = true", 2)
		end
		if DEBUG then
			print("SaveData<"..this.userId..">::Set("..key..", "..tostring(value)..")")
		end
		markAsDirty(key)
		this.dataSet[key] = value
	end

	-- For important atomic transactions, update data 
	-- store. For example, for any Developer Product
	-- based purchases you should use this to ensure
	-- that the changes are saved right away, and
	-- correctly.
	-- Note: Update() will automatically Flush any
	-- unsaved changes while doing the update.
	function this:Update(keyList, func)
		if type(keyList) ~= 'table' then
			error("Bad argument #1 to SaveData::Update() (table of keys expected)", 2)
		end
		if type(func) ~= 'function' then
			error("Bad argument #2 to SaveData::Update() (function expected)", 2)
		end
		if DEBUG then
			print("SaveData<"..this.userId..">::Update("..table.concat(keyList, ", ")..", "..tostring(func)..")")
		end
		playerDataStore:doUpdate(this, keyList, func)
	end

	-- Flush all unsaved changes out to the data 
	-- store for this player.
	-- Note: This call will yield and not return
	-- until the data has actually been saved if
	-- there were any unsaved changes.
	function this:Flush()
		if DEBUG then
			print("SaveData<"..this.userId..">::Flush()")
		end
		playerDataStore:doSave(this)
	end

	return this
end


--===============================================--
--==           PlayerDataStore Class           ==--
--===============================================--
-- A singleton that manages all of the player data
-- saving and loading in a place.
local PlayerDataStore = {}
function PlayerDataStore.new()
	local this = {}

	--===============================================--
	--==               Private Data                ==--
	--===============================================--

	-- The actual data store we are writing to
	local DataStoreService = game:GetService('DataStoreService')
	local mDataStore = DataStoreService:GetDataStore(DATASTORE_NAME)

	-- The weak-reference to each player's data, so
	-- that as long as the place owner keeps a ref
	-- to the data we will have it in this cache, and
	-- won't reload a second copy.
	local mUserIdSaveDataCache = setmetatable({}, {__mode = 'v'}) -- {UserId -> SaveData}

	-- Strong-reference to recently touched data, to
	-- implement the cache expiry time.
	local mTouchedSaveDataCacheSet = {} -- {SaveData}

	-- Strong-reference to the data of players who are
	-- online, we always want to keep a reference to
	-- their data.
	local mOnlinePlayerSaveDataMap = {} -- {Player -> SaveData}

	-- Dirty save datas, that is, ones that have
	-- unsaved changes.
	local mDirtySaveDataSet = {} -- {SaveData}

	-- Players whose data is currently being requested
	local mOnRequestUserIdSet = {} -- {UserId}
	local mRequestCompleted = Instance.new('BindableEvent')

	-- Number of save functions still running
	-- used on server shutdown to know how long to keep the
	-- server alive for after the last player has left.
	local mSavingCount = 0

	--===============================================--
	--==          Private Implementation           ==--
	--===============================================--
	-- transform a userId into a data store key
	local function userIdToKey(userId)
		return 'P@'..userId
	end

	function this:markAsTouched(saveData)
		if DEBUG then print("PlayerDataStore::markAsTouched("..saveData.userId..")") end
		mTouchedSaveDataCacheSet[saveData] = true
		saveData.lastTouched = tick()
		mUserIdSaveDataCache[saveData.userId] = saveData
	end
	function this:markAsDirty(saveData)
		if DEBUG then print("PlayerDataStore::markAsDirty("..saveData.userId..")") end
		this:markAsTouched(saveData)
		mDirtySaveDataSet[saveData] = true
		mUserIdSaveDataCache[saveData.userId] = saveData
	end

	-- the initial data to record for a given userId
	local function initialData(userId)
		return {}
	end

	-- collect and clear out the dirty key set of a save data
	local function collectDataToSave(saveData)
		local toSave = {}
		local toErase = {}
		for key, _ in pairs(saveData.dirtyKeySet) do
			local value = saveData.dataSet[key]
			if value ~= nil then
				-- Get the value to be saved
				if SERIALIZE[key] then
					-- If there is a seralization function provided, then use
					-- that to serialize out the value into the data to be
					-- stored.
					toSave[key] = SERIALIZE[key](value)
				else
					-- If no serialiation is provided, still do at least a deep
					-- copy of the value, so that further changes to the SaveData
					-- after the save call will not interfear with the call if
					-- it takes multiple tries to update the DataStore data.
					toSave[key] = DeepCopy(value)				
				end
			else
				-- no value, add to the list of keys to erase
				table.insert(toErase, key)
			end
			-- Turn off the dirty flag for the key, we are working on saving it
			saveData.dirtyKeySet[key] = nil
		end	
		return toSave, toErase
	end

	-- Main saving functions that push out unsaved
	-- changes to the actual data store
	function this:doSave(saveData)
		if DEBUG then print("PlayerDataStore::doSave("..saveData.userId..") {") end
		-- update save time and dirty status in my
		-- listing even if there arn't any changes 
		-- to save.
		saveData.lastSaved = tick()
		mDirtySaveDataSet[saveData] = nil	

		-- are there any dirty keys?
		if next(saveData.dirtyKeySet) then
			-- cache the data to save
			local toSave, toErase = collectDataToSave(saveData)

			-- update the data with all the dirty keys
			saveData:waitForUnlocked()
			saveData:lock()
			mSavingCount = mSavingCount + 1
			mDataStore:UpdateAsync(userIdToKey(saveData.userId), function(oldData)
				-- Init the data if there is none yet
				if not oldData then
					oldData = initialData(saveData.userId)
				end
				if DEBUG then print("\tattempting save:") end

				-- For each dirty key to be saved, update it
				for key, data in pairs(toSave) do
					if DEBUG then print("\t\tsaving `"..key.."` = "..tostring(data)) end
					oldData[key] = data
				end

				-- For each key to erase, erase it
				for _, key in pairs(toErase) do
					if DEBUG then print("\t\tsaving `"..key.."` = nil [ERASING])") end
					oldData[key] = nil
				end

				-- Return back the updated data
				return oldData
			end)
			if DEBUG then print("\t saved.") end
			mSavingCount = mSavingCount - 1
			saveData:unlock()
		elseif DEBUG then
			print("\tnothing to save")
		end
		if DEBUG then print("}") end
	end
	function this:doUpdate(saveData, keyList, updaterFunc)
		if DEBUG then print("PlayerDataStore::doUpdate("..saveData.userId..", {"..table.concat(keyList, ", ").."}, "..tostring(updaterFunc)..") {") end
		-- updates happen all at once, lock right away
		saveData:waitForUnlocked()
		saveData:lock()
		mSavingCount = mSavingCount + 1

		-- Unflag this SaveData as dirty
		saveData.lastSaved = tick()
		mDirtySaveDataSet[saveData] = nil

		-- turn the keyList into a key set as well
		-- also own all of the keys in it.
		local updateKeySet = {}
		for _, key in pairs(keyList) do
			saveData.ownedKeySet[key] = true
			updateKeySet[key] = true
		end

		-- gather the data to save currently in the saveData. There
		-- may be some or none.
		local toSave, toErase = collectDataToSave(saveData)

		-- do the actual update
		mDataStore:UpdateAsync(userIdToKey(saveData.userId), function(oldData)
			if DEBUG then print("\ttrying update:") end
			-- Init the data if there is none yet
			if not oldData then
				oldData = initialData(saveData.userId)
			end

			-- gather current values to pass to the the updater func
			local valueList = {}
			for i, key in pairs(keyList) do
				local value = saveData.dataSet[key]
				if value == nil and DESERIALIZE[key] then
					valueList[i] = DESERIALIZE[key](nil)
				else
					valueList[i] = value
				end
			end

			-- call the updaterFunc and get the results back
			local results = {updaterFunc(unpack(valueList, 1, #keyList))}

			-- Save the results to the data store and SaveData cache
			for i, result in pairs(results) do			
				local key = keyList[i]
				-- Serialize if needed, and save to the result for the data store
				if SERIALIZE[key] then
					local serialized = SERIALIZE[key](result)
					if DEBUG then print("\t\tsaving result: `"..key.."` = "..tostring(serialized).." [SERIALIZED]") end	
					oldData[key] = serialized
				else
					if DEBUG then print("\t\tsaving result: `"..key.."` = "..tostring(result)) end	
					oldData[key] = result
				end
				-- also save the result to the SaveData cache:
				saveData.dataSet[key] = result
			end

			-- Also while we're at it, save the dirty values to the data store
			-- but only if they weren't in the set that we just updated.
			for key, value in pairs(toSave) do
				-- Serialize if needed. 
				if not updateKeySet[key] then
					if DEBUG then print("\t\tsaving unsaved value: `"..key.."` = "..tostring(value)) end
					oldData[key] = value --(note, value is already serialized)
				end
			end
			for _, key in pairs(toErase) do
				if not updateKeySet[key] then
					if DEBUG then print("\t\tsaving unsaved value: `"..key.."` = nil [ERASING]") end
					oldData[key] = nil
				end
			end

			-- return the finalized result
			return oldData
		end)


		-- finish the save
		mSavingCount = mSavingCount - 1
		saveData:unlock()

		if DEBUG then print("}") end
	end

	-- Main method for loading in the data of a user
	-- or grabbing it from the cache if it is still
	-- "hot" (in the UserIdSaveDataCache but nowhere
	-- else)
	local function doLoad(userId)
		if DEBUG then print("PlayerDataStore::doLoad("..userId..") {") end
		local saveData;
		-- First see if it is in the cache
		saveData = mUserIdSaveDataCache[userId]
		if saveData then
			if DEBUG then print("\tRecord was already in cache") end
			-- touch it and return it
			this:markAsTouched(saveData)
			if DEBUG then print("}") end
			return saveData
		end
		-- Not on file, we need to load it in, are
		-- we already loading it though?
		if mOnRequestUserIdSet[userId] then
			if DEBUG then print("\tRecord already requested, wait for it...") end
			-- wait for the existing request to complete
			while true do
				saveData = mRequestCompleted.Event:wait()()
				if saveData.userId == userId then
					-- this IS the request we're looking for
					this:markAsTouched(saveData)
					if DEBUG then 
						print("\tRecord successfully retrieved by another thread")
						print("}") 
					end
					return saveData
				end
			end
		else
			if DEBUG then print("\tRequest record...") end
			-- Not on request, we need to do the load
			mOnRequestUserIdSet[userId] = true
			-- load the data
			local data = nil;
			local dataRequest = pcall(function()
				data = mDataStore:GetAsync(userIdToKey(userId)) or {}
			end);
			if not dataRequest then
				-- we need to constantly wait for roblox servers to respond.
				local function retry()
					pcall(function()
						data = mDataStore:GetAsync(userIdToKey(userId)) or {}
					end);
				end
				repeat print("[DATA] !!! ROBLOX SERVERS FAILED FOR ".. userId ..". TRYING AGAIN IN 5 SECONDS !!"); wait(5) retry() until data ~= nil;
			end
			-- deserialize any data that needs to be deserialized
			for key, value in pairs(data) do
				if DESERIALIZE[key] then
					data[key] = DESERIALIZE[key](value)
				end
			end
			-- create te SaveData structure and initialize it
			saveData = SaveData.new(this, userId)
			saveData:makeReady(data)
			this:markAsTouched(saveData)
			-- unmark as loading
			mOnRequestUserIdSet[userId] = nil
			-- Pass to other waiters
			mRequestCompleted:Fire(function() return saveData end)
			if DEBUG then 
				print("\tRecord successfully retrieved from data store")
				print("}") 
			end
			return saveData
		end
	end

	-- Handle adding and removing strong-references to a player's
	-- data while they are in the server.
	local function HandlePlayer(player)
		if DEBUG then print("PlayerDataStore> Player "..player.userId.." Entered > Load Data") end
		local saveData = doLoad(player.userId)
		-- are the still in the game? If they are then
		-- add the strong-reference to the SaveData
		if player.Parent then
			mOnlinePlayerSaveDataMap[player] = saveData
		end 
	end
	game.Players.PlayerAdded:connect(HandlePlayer)
	for _, player in pairs(Game.Players:GetChildren()) do
		if player:IsA('Player') then
			HandlePlayer(player)
		end
	end
	game.Players.PlayerRemoving:connect(function(player)
		-- remove the strong-reference when they leave.
		local oldSaveData = mOnlinePlayerSaveDataMap[player]
		mOnlinePlayerSaveDataMap[player] = nil

		-- Do a save too if the flag is on
		if SAVE_ON_LEAVE and oldSaveData then 
			-- Note: We only need to do a save if the initial 
			-- load for that player actually completed yet. Cached
			-- versions from before the player entered are not a concern
			-- here as if there were a cache version the oldSaveData
			-- would exist, as the doLoad on player entered would
			-- have completed immediately.
			if DEBUG then print("PlayerDataStore> Player "..player.userId.." Left with data to save > Save Data") end
			this:doSave(oldSaveData)
		end
	end)

	-- when the game shuts down, save all data
	game.OnClose = function()
		if DEBUG then print("PlayerDataStore> OnClose Shutdown\n\tFlushing...") end

		-- First, flush all unsaved changes at the point of shutdown
		this:FlushAll()

		if DEBUG then print("\tFlushed, additional wait...") end

		-- Then wait for random saves that might still be running
		-- for some reason to complete as well
		while mSavingCount > 0 do
			wait()
		end

		if DEBUG then print("\tShutdown completed normally.") end
	end

	-- Cleanup of cache entries that have timed out (not been touched
	-- in any way for more than CACHE_EXPIRY_TIME)
	local function removeTimedOutCacheEntries()
		local now = tick()
		for saveData, _ in pairs(mTouchedSaveDataCacheSet) do
			if (now - saveData.lastTouched) > CACHE_EXPIRY_TIME then
				-- does it have unsaved changes still somehow?
				if mDirtySaveDataSet[saveData] then
					if DEBUG then print(">> Cache expired for: "..saveData.userId..", has unsaved changes, wait.") end
					-- Spawn off a save and don't remove it, it needs to save
					SpawnNow(function() this:doSave(saveData) end)
				else
					if DEBUG then print(">> Cache expired for: "..saveData.userId..", removing.") end
					-- It is not needed, uncache it
					mTouchedSaveDataCacheSet[saveData] = nil
				end
			end 
		end
	end

	-- Passive saving task, save entries with unsaved changes that have
	-- not been saved for more than PASSIVE_SAVE_FREQUENCY.
	local function passiveSaveUnsavedChanges()
		local now = tick()
		for saveData, _ in pairs(mDirtySaveDataSet) do
			if (now - saveData.lastSaved) > PASSIVE_SAVE_FREQUENCY then
				if DEBUG then print("PlayerDataStore>> Passive save for: "..saveData.userId) end
				SpawnNow(function()
					this:doSave(saveData)
				end)
			end
		end
	end

	-- Main save / cache handling daemon
	spawn(function()
		while true do
			removeTimedOutCacheEntries()
			passiveSaveUnsavedChanges()
			wait(PASSIVE_GRANULARITY)
		end
	end)

	--===============================================--
	--==                Public API                 ==--
	--===============================================--

	-- Get the data for a player online in the place
	function this:GetSaveData(player)
		if not player or not player:IsA('Player') then
			error("Bad argument #1 to PlayerDataStore::GetSaveData(), Player expected", 2)
		end
		return doLoad(player.userId)
	end

	-- Get the data for a player by userId, they may
	-- or may not be currently online in the place.
	function this:GetSaveDataById(userId)
		if type(userId) ~= 'number' then
			error("Bad argument #1 to PlayerDataStore::GetSaveDataById(), userId expected", 2)
		end
		return doLoad(userId)
	end

	-- Save out all unsaved changes at the time of 
	-- calling.
	-- Note: This call yields until all the unsaved 
	-- changes have been saved out.
	function this:FlushAll()
		local savesRunning = 0
		local complete = Instance.new('BindableEvent')
		-- Call save on all of the dirty entries
		for saveData, _ in pairs(mDirtySaveDataSet) do
			SpawnNow(function()
				savesRunning = savesRunning + 1
				this:doSave(saveData)
				savesRunning = savesRunning - 1
				if savesRunning <= 0 then
					complete:Fire()
				end
			end)
		end
		-- wait for completion
		if savesRunning > 0 then
			complete.Event:wait()
		end
	end

	return this
end

return PlayerDataStore.new()