local E={}local Z=tycoons[1].Buttons:GetChildren()local w=RebirthSettings.unlockPurchases function addDependencies(E,w)local c={}for n=1,#Z,1 do local X=Z[n]:FindFirstChild("\079\098\106\101\099\116")local e=Z[n]:FindFirstChild("\068\101\112\101\110\100\101\110\099\121")if X~=nil and e~=nil then if e.Value==w then table.insert(E,X.Value)table.insert(c,X.Value)end end end for Z=1,#c,1 do addDependencies(E,c[Z])end end for Z=1,#w,1 do E[Z]={rebirthCount=w[Z].rebirthCount}table.insert(E[Z],w[Z].unlock)addDependencies(E[Z],w[Z].unlock)end function hideBillboadAndText(E,Z)if E then E.Enabled=false if Z then Z.TextTransparency=1 end end end function showBillboadAndText(E,Z)if E then E.Enabled=true if Z then Z.TextTransparency=0 end end end function hideButton(E,Z)local w=Z:GetChildren()local c=nil for Z=1,#w,1 do local n=w[Z]:FindFirstChild("\079\098\106\101\099\116")if n and(n:IsA("\083\116\114\105\110\103\086\097\108\117\101")and w[Z].Object.Value==E)then c=w[Z]break end end if c~=nil then local E=c:FindFirstChild("\072\101\097\100")if E~=nil then local Z=E:FindFirstChild("\066\105\108\108\098\111\097\114\100\071\117\105")local w if Z then w=Z:FindFirstChild("\084\101\120\116\076\097\098\101\108")end if TycoonSettings.ButtonsFadeOut then E.CanCollide=false coroutine.resume(coroutine.create(function()for Z=1,20,1 do wait(TycoonSettings.FadeOutTime/20)E.Transparency=E.Transparency+.05 if w then w.TextTransparency=w.TextTransparency+.05 end end hideBillboadAndText(Z,w)end))else E.CanCollide=false E.Transparency=1 hideBillboadAndText(Z,w)end end end end local function c(E)local Z=E.Entrance:GetChildren()local w=nil for E=1,#Z,1 do local c=Z[E]:FindFirstChild("\071\097\116\101\067\111\110\116\114\111\108")if c~=nil then w=Z[E]c:Destroy()break end end if w==nil then error("\090\101\100\'\115 \116\121\099\111\111\110 \083\097\118\101 \115\099\114\105\112\116\115 \109\097\107\101 \115\117\114\101 \121\111\117 \104\097\118\101 \097 \115\099\114\105\112\116 \099\097\108\108\101\100 \'\071\097\116\101\067\111\110\116\114\111\108\' \105\110 \101\097\099\104 \116\121\099\111\111\110\115 \069\110\116\114\097\110\099\101\047\084\111\117\099\104 \116\111 \099\108\097\105\109\033")end return w end function loadPurchedObjectFromDatabaseIfPlayerTouchToClaim(E,Z,w,c)local n=c:WaitForChild("\080\117\114\099\104\097\115\101\115")while true do wait(.1)if#n:GetChildren()<10 then break end end local X=true E.Touched:Connect(function(n)local e=n.Parent:FindFirstChild("\072\117\109\097\110\111\105\100")if e~=nil and(e.Health>0 and X)then local n,Q=pcall(function()local n=playerMoney:FindFirstChild(e.Parent.Name)local Q=nil if n~=nil then Q=n:FindFirstChild("\079\119\110\115\084\121\099\111\111\110")end if Q~=nil and(Q.Value==nil and not c.Owner.Value)then local n=game.Players:FindFirstChild(e.Parent.Name)print("\066\101\102\111\114\101 \108\111\097\100\105\110\103 \111\098\106\101\099\116\115 \105\110 \116\121\099\111\111\110 \102\111\114 \112\108\097\121\101\114 ",n.Name)print("------------------------------")if n~=nil then X=false c.CurrencyToCollect.Value=0 E.Transparency=1 c.Owner.Value=n Q.Value=c E.Parent.Name=n.Name.."\'\115 \084\121\099\111\111\110"E.Transparency=.6 E.CanCollide=false n.TeamColor=c.TeamColor.Value local e=(PlayerStatManager:getPlayerData(n)).TycoonPurchases for E,w in pairs(w)do print("\065\100\100\105\110\103 ",E)if e[E]==true then w.Parent=Z end end wait(2.5)for E,Z in pairs(w)do if e[E]==true then local Z=E local w=c.Buttons hideButton(Z,w)end end if RebirthSettings.enabled==true then giveRebirthGuiIfTycoonFinished(w,n)end else print(" \108\111\097\100\080\117\114\099\104\101\100\079\098\106\101\099\116\070\114\111\109\068\097\116\097\098\097\115\101\073\102\080\108\097\121\101\114\084\111\117\099\104\084\111\067\108\097\105\109 \080\108\097\121\101\114 \061\061 \110\105\108")end else print("\111\119\110\115\084\121\099\111\111\110\046\086\097\108\117\101 ~\061 \110\105\108 \111\114 \111\119\110\115\084\121\099\111\111\110 \061\061 \110\105\108 ")end end)if n==false then print(Q)end end end)end function isTycoonFinished(Z,w)local c=(PlayerStatManager:getPlayerData(w)).TycoonPurchases local n=PlayerStatManager:getStat(w,"\082\101\098\105\114\116\104\067\111\117\110\116")local X=false for Z,w in pairs(Z)do local e=RebirthSettings.ignorePurchases local Q=true for E=1,#e,1 do if e[E]==Z then Q=false break end end for w=1,#E,1 do if n<E[w].rebirthCount then for c=1,#E[w],1 do if E[w][c]==Z then Q=false break end end end if Q==false then break end end if Q then X=false for E,w in pairs(c)do if w==true and Z==E then X=true break end end if X==false then return false end end end return true end function giveRebirthGuiIfTycoonFinished(E,Z)local w=isTycoonFinished(E,Z)if w==true then local E=Z:FindFirstChild("\067\097\110\082\101\098\105\114\116\104")if E~=nil then E.Value=true end giveRebirthGui(Z)end end function giveRebirthGui(E)local Z,w=pcall(function()local Z=rebirthGui:Clone()local w=E:FindFirstChild("\080\108\097\121\101\114\071\117\105")if w~=nil then wait(3)local E=w:FindFirstChild("\082\101\098\105\114\116\104\071\117\105 \040\068\111\110\'\116 \077\111\118\101\041")if E==nil then Z.Parent=w end else print("\112\108\097\121\101\114\071\117\105 \061\061 \110\105\108")end end)if Z==false then print(w)end end function savePurchasesObjectsInDatabase(E,Z,w)local c,n=pcall(function()local c=E.Value if c~=nil then local E=PlayerStatManager:getStatInTycoonPurchases(c,Z.Name)local n=PlayerStatManager:getStat(c,"\077\111\110\101\121")if c~=nil and not E then PlayerStatManager:ChangeStatInTycoonPurchases(c,Z.Name,true)if RebirthSettings.enabled==true then giveRebirthGuiIfTycoonFinished(w,c)end end end end)if c==false then print(n)end end function playerJoinedCallFunction(E)local Z=PlayerStatManager:getStat(E,"\082\101\098\105\114\116\104\067\111\117\110\116")local w=RebirthSettings.playerRespawned for c=1,#w,1 do if Z and Z>=w[c].rebirthCount then w[c][1](E)end end end game.Players.PlayerAdded:Connect(function(E)E.CharacterAdded:Connect(function(Z)if RebirthSettings.enabled==true then local Z=E:FindFirstChild("\067\097\110\082\101\098\105\114\116\104")if Z and Z.Value==true then giveRebirthGui(E)end playerJoinedCallFunction(E)end end)end)for E=1,#tycoons,1 do local Z=c(tycoons[E]);(purchaseHandlerNew:Clone()).Parent=tycoons[E]local w=tycoons[E]:FindFirstChild("\080\117\114\099\104\097\115\101\100\079\098\106\101\099\116\115")local n=tycoons[E]:FindFirstChild("\079\119\110\101\114")local X=tycoons[E].Entrance local e=Z.Head allObjects[E]=require(tycoons[E].PurchaseHandlerNew)loadPurchedObjectFromDatabaseIfPlayerTouchToClaim(e,w,allObjects[E],tycoons[E])if w~=nil and n~=nil then w.ChildAdded:Connect(function(Z)savePurchasesObjectsInDatabase(n,Z,allObjects[E])end)else error("\083\097\118\101\084\114\105\103\103\101\114 \115\099\114\105\112\116 \119\111\110\'\116 \115\097\118\101 \100\097\116\097 \098\101\099\097\117\115\101 \101\105\116\104\101\114 \112\117\114\099\104\097\115\101\100\079\098\106\101\099\116\115 \111\114 \111\119\110\101\114 \105\115 \078\073\076")end end tycoonsFolder.ChildAdded:Connect(function(E)(purchaseHandlerNew:Clone()).Parent=E local Z=E:FindFirstChild("\080\117\114\099\104\097\115\101\100\079\098\106\101\099\116\115")local w=E:FindFirstChild("\079\119\110\101\114")local n=c(E)local X=n.Head local e=require(E.PurchaseHandlerNew)loadPurchedObjectFromDatabaseIfPlayerTouchToClaim(X,Z,e,E)if Z~=nil and w~=nil then Z.ChildAdded:Connect(function(E)savePurchasesObjectsInDatabase(w,E,e)end)else error("\083\097\118\101\084\114\105\103\103\101\114 \115\099\114\105\112\116 \119\111\110\'\116 \115\097\118\101 \100\097\116\097 \098\101\099\097\117\115\101 \101\105\116\104\101\114 \112\117\114\099\104\097\115\101\100\079\098\106\101\099\116\115 \111\114 \111\119\110\101\114 \105\115 \078\073\076")end end)function getTycoonByPlayerName(E)local Z=tycoonsFolder:GetChildren()for w=1,#Z,1 do local c=Z[w]:FindFirstChild("\079\119\110\101\114")if c~=nil and Z[w]:IsA("\077\111\100\101\108")then if c.Value~=nil and c.Value.Name==E then return Z[w]end else print("\077\065\075\069 \083\085\082\069 \069\065\067\072 \084\089\067\079\079\078 \072\065\083 \079\087\078\069\082 \086\065\076\085\069")end end return nil end function removeTycoonAndAddOriginal(E,Z)local w=game.ServerStorage.PlayerMoney:FindFirstChild(Z)if w~=nil then w.OwnsTycoon.Value=nil end if E then local Z=AllTycoons[E.Name]:Clone()E:Destroy()wait()local w=Z:FindFirstChild("\067\117\114\114\101\110\099\121\084\111\067\111\108\108\101\099\116")if w~=nil then w.Value=0 else print("\099\117\114\114\101\110\099\121\084\111\067\111\108\108\101\099\116 \061\061 \110\105\108 -----------------------\062")end Z.Parent=script.Parent.Tycoons end end function teleportCharacterToSuppliedPart(E,Z)local w=RebirthSettings.teleportToo local c=Z:FindFirstChild(w)if c and c:IsA("\066\097\115\101\080\097\114\116")then local Z=E.Character if Z then Z:SetPrimaryPartCFrame(c.CFrame)end end end function callFunctionsIfRebirthIsReached(E,Z)local w=RebirthSettings.playerReachedRebirthCount for c=1,#w,1 do if w[c].rebirthCount==E then w[c][1](Z)break end end end local function n(E,Z)for E,w in pairs(E)do if w.rebirthCount==Z then return w.cashAmount end end end rebirthEvent.OnServerEvent:Connect(function(E)local Z=PlayerStatManager:getStat(E,"\082\101\098\105\114\116\104\067\111\117\110\116")if Z==nil then return end local c=RebirthSettings.cashNeededForRebirth local X=n(c,Z+1)local e=game.ServerStorage.PlayerMoney:FindFirstChild(E.Name)if not X then X=RebirthSettings.defaultCashNeededForRebirth end if RebirthSettings.enabled==true then if(e.Value>=X)==false then rebirthEvent:FireClient(E,X)return end local c,n=pcall(function()local c=e:FindFirstChild("\079\119\110\115\084\121\099\111\111\110")if c~=nil and c.Value~=nil then local c=getTycoonByPlayerName(E.Name)if c~=nil then local n=require(c.PurchaseHandlerNew)local X=isTycoonFinished(n,E)if X==true then PlayerStatManager:setAllTycoonPurchasesToNil(E)if Z==nil then PlayerStatManager:saveStat(E,"\082\101\098\105\114\116\104\067\111\117\110\116",0)end if RebirthSettings.resetCash then PlayerStatManager:saveStat(E,"\077\111\110\101\121",0)end PlayerStatManager:IncrementStat(E,"\082\101\098\105\114\116\104\067\111\117\110\116",1)Z=PlayerStatManager:getStat(E,"\082\101\098\105\114\116\104\067\111\117\110\116")for c=1,#w,1 do if Z>=w[c].rebirthCount then PlayerStatManager:ChangeStatInTycoonPurchases(E,w[c].unlock,true)end end callFunctionsIfRebirthIsReached(Z,E)local n=E:FindFirstChild("\108\101\097\100\101\114\115\116\097\116\115")if n~=nil then local E=n:FindFirstChild("\082\101\098\105\114\116\104\115")local w=n:FindFirstChild("\077\111\110\101\121")if E~=nil and Z~=nil then E.Value=Z end if w~=nil and RebirthSettings.resetCash then w.Value=0 end end local X=game.ServerStorage.PlayerMoney:FindFirstChild(E.Name)if RebirthSettings.resetCash then X.Value=0 end teleportCharacterToSuppliedPart(E,c)removeTycoonAndAddOriginal(c,E.Name)local e=E:FindFirstChild("\067\097\110\082\101\098\105\114\116\104")if e~=nil then e.Value=false end local Q=E:FindFirstChild("\080\108\097\121\101\114\071\117\105")if Q~=nil then local E=Q:FindFirstChild("\082\101\098\105\114\116\104\071\117\105 \040\068\111\110\'\116 \077\111\118\101\041")if E~=nil then E:Destroy()end end end else print("\084\121\099\111\111\110 \105\115 \110\105\108 \103\101\116\084\121\099\111\111\110\066\121\080\108\097\121\101\114\078\097\109\101\040"..(E.Name.."\041"))end end end)if c==false then print(n)end end end)if runService:IsStudio()or TestSettings.showTouchTycoonButtonsGuiOutsideStudio then local E=false touchAllTycoonButtons.OnServerEvent:Connect(function(Z,w)E=w if E then local w=Z.Character local c=getTycoonByPlayerName(Z.Name)if not c then return end while E do local Z=c.Buttons:GetChildren()local n=false for c=1,#Z,1 do local X=Z[c]:FindFirstChild("\072\101\097\100")if not E then return end if X and X.Transparency==0 then local E=X.Position local Z=Vector3.new(E.X,E.Y+1.2,E.Z)w:MoveTo(Z)wait(.5)n=true end end if n==false then break end end end end)giveCashEvent.OnServerEvent:Connect(function(E,Z)local w=playerMoney:FindFirstChild(E.Name)if w then w.Value=w.Value+Z end end)end

local unlock = {}
local allButtons = tycoons[1].Buttons:GetChildren()
local unlockPurchases = RebirthSettings.unlockPurchases

function addDependencies(ignoreInner,obj)
	local queue = {}
	for t = 1,#allButtons,1 do
		local object = allButtons[t]:FindFirstChild("Object")
		local dependency = allButtons[t]:FindFirstChild("Dependency")
		if object ~= nil and dependency ~= nil then
			if dependency.Value == obj then
				table.insert(ignoreInner,object.Value)
				table.insert(queue,object.Value)
			end
		end
	end
	for d = 1,#queue,1 do
		addDependencies(ignoreInner,queue[d])
	end
end

for u = 1,#unlockPurchases,1 do
	unlock[u] = {rebirthCount = unlockPurchases[u].rebirthCount}
	table.insert(unlock[u],unlockPurchases[u].unlock)
	addDependencies(unlock[u],unlockPurchases[u].unlock)
end

function hideBillboadAndText(billboardGui, textLabel)
	if billboardGui then
		billboardGui.Enabled = false
		if textLabel then
			textLabel.TextTransparency = 1
		end
	end
end

function showBillboadAndText(billboardGui, textLabel)
	if billboardGui then
		billboardGui.Enabled = true
		if textLabel then
			textLabel.TextTransparency = 0
		end
	end
end

function hideButton(name,buttons)
	local allButtons = buttons:GetChildren()
	local item = nil
	for i = 1,#allButtons,1 do
		local hasObject = allButtons[i]:FindFirstChild("Object")
		if hasObject and hasObject:IsA("StringValue") and 
		   allButtons[i].Object.Value == name then
			item = allButtons[i]
			break
		end
	end
	if item ~= nil then
		local head = item:FindFirstChild("Head")
		if head ~= nil then
			local billboardGui = head:FindFirstChild("BillboardGui")
			local textLabel
			if billboardGui then
				textLabel = billboardGui:FindFirstChild("TextLabel")
			end
			if TycoonSettings['ButtonsFadeOut'] then
				head.CanCollide = false
				coroutine.resume(coroutine.create(function()
					for i=1,20 do
						wait(TycoonSettings['FadeOutTime']/20)
						head.Transparency = head.Transparency + 0.05
						if textLabel then
							textLabel.TextTransparency = textLabel.TextTransparency + 0.05
						end
					end
					
					hideBillboadAndText(billboardGui, textLabel)
				end))
			else
				head.CanCollide = false
				head.Transparency = 1
				hideBillboadAndText(billboardGui, textLabel)
			end
		end
	end
end

local function getTouchToClaimAndDeleteGateControl(nextTycoon)
	local gate = nextTycoon.Entrance:GetChildren()
	local touchToClaim = nil
	for i = 1,#gate, 1 do
		local gateControl = gate[i]:FindFirstChild("GateControl")
		if gateControl ~= nil then
			touchToClaim = gate[i]
			gateControl:Destroy()
			break
		end
	end
	if touchToClaim == nil then
		error("Zed's tycoon Save scripts make sure you have a script called 'GateControl' in each tycoons Entrance/Touch to claim!")
	end
	return touchToClaim
end

function loadPurchedObjectFromDatabaseIfPlayerTouchToClaim(touchToClaimHead,
															purchasedObjects,
															PurchaseHandlerNew,
															tycoon)
	--TODO all purhcases must have a button
	local purchases = tycoon:WaitForChild("Purchases")
	while true do
		wait(0.1)
		if #purchases:GetChildren() < 10 then break end
	end
	local debounce = true
	touchToClaimHead.Touched:Connect(function(hit)
		local humanoid = hit.Parent:FindFirstChild("Humanoid")
		if humanoid ~= nil and humanoid.Health > 0 and debounce then
			local success,err = pcall(function() 
				local playerInPlayerMoney = playerMoney:FindFirstChild(humanoid.Parent.Name)
				local ownsTycoon = nil
				if playerInPlayerMoney ~= nil then
			   		 ownsTycoon = playerInPlayerMoney:FindFirstChild("OwnsTycoon")
				end
				if ownsTycoon ~= nil and ownsTycoon.Value == nil and not tycoon.Owner.Value then
					
					local player = game.Players:FindFirstChild(humanoid.Parent.Name)
					print("Before loading objects in tycoon for player ",player.Name)
					print("------------------------------")

					if player ~= nil then
						debounce = false
						tycoon.CurrencyToCollect.Value = 0
						touchToClaimHead.Transparency = 1
						tycoon.Owner.Value = player
						ownsTycoon.Value = tycoon
						touchToClaimHead.Parent.Name = player.Name.."'s Tycoon"
						touchToClaimHead.Transparency = 0.6
						
						touchToClaimHead.CanCollide = false
						player.TeamColor = tycoon.TeamColor.Value
						local data = PlayerStatManager:getPlayerData(player)["TycoonPurchases"]

						for key,value in pairs(PurchaseHandlerNew) do	
							print("Adding ",key)
							if data[key] == true then
								value.Parent = purchasedObjects
							end
						end	
						wait(2.5)
						for k,v in pairs(PurchaseHandlerNew) do
							if data[k] == true then
								local buttonName = k
								local buttons = tycoon.Buttons
								hideButton(buttonName,buttons)
							end
						end	
						if RebirthSettings.enabled == true then
							giveRebirthGuiIfTycoonFinished(PurchaseHandlerNew,player)
						end
					else
						print(" loadPurchedObjectFromDatabaseIfPlayerTouchToClaim Player == nil")	
					end
				else
					print("ownsTycoon.Value ~= nil or ownsTycoon == nil ")	
				end
				
			end)
			if success == false then
				print(err)
			end		
		end
		
	end)
end

function isTycoonFinished(PurchaseHandlerNew,player)
	local purchases = PlayerStatManager:getPlayerData(player)["TycoonPurchases"]
	local rebirthCountStat = PlayerStatManager:getStat(player,"RebirthCount")
	local playerHasTycoonObject = false
	--Checking what object should be ignored
	for key1,value1 in pairs(PurchaseHandlerNew) do
		local ignorePurchases = RebirthSettings.ignorePurchases
		local canContinue = true
		for i = 1,#ignorePurchases,1 do
			if ignorePurchases[i] == key1 then
				canContinue = false
				break
			end
		end
		--Check if it should ignore unlock purchases
		for u = 1,#unlock,1 do
			if rebirthCountStat < unlock[u].rebirthCount then
				for a = 1,#unlock[u],1 do
					if unlock[u][a] == key1 then
						canContinue = false
						break
					end
				end
			end
			if canContinue == false then
				break
			end
		end
	
		if canContinue then
			playerHasTycoonObject =  false
			for key2,value2 in pairs(purchases) do
				if value2 == true and key1 == key2 then
					playerHasTycoonObject = true
					break
				end
			end
			if playerHasTycoonObject == false then
				return false
			end
		end
	end
	return true
end

function giveRebirthGuiIfTycoonFinished(PurchaseHandlerNew,player)
	local hasFinishedTycoon = isTycoonFinished(PurchaseHandlerNew,player)
	if hasFinishedTycoon == true then
		local canRebirth = player:FindFirstChild("CanRebirth")
		if canRebirth ~= nil then
			canRebirth.Value = true
		end
		giveRebirthGui(player)
		
	end
end

function giveRebirthGui(player)
	local success,err = pcall(function() 
		local rebirthGuiClone = rebirthGui:Clone()
		local playerGui = player:FindFirstChild("PlayerGui")

		if playerGui ~= nil then
			--Added wait because after player died and their character is added
			--the gui does not get cloned only after I add wait
			wait(3)
			local hasRebirthGui = playerGui:FindFirstChild("RebirthGui (Don't Move)")
			if hasRebirthGui == nil then
				rebirthGuiClone.Parent = playerGui
			end
		else
			print("playerGui == nil")	
		end
	end)
	if success == false then
		print(err)
	end
end

function savePurchasesObjectsInDatabase(owner,instance,PurchaseHandlerNew)
	
	local status,err = pcall(function() 
		local player = owner.Value
		if player ~= nil then
			--local stat = PlayerStatManager:getStat(player,instance.Name)
			local stat = PlayerStatManager:getStatInTycoonPurchases(player,instance.Name)
			local statMoney = PlayerStatManager:getStat(player,"Money")

			if player ~= nil and not stat then
				PlayerStatManager:ChangeStatInTycoonPurchases(player, instance.Name, true)
				if RebirthSettings.enabled == true then
					giveRebirthGuiIfTycoonFinished(PurchaseHandlerNew,player)
				end
			end
		end
	end)
	if status == false then
		print(err)
	end
end

function playerJoinedCallFunction(player)
	local rebirthCountStat = PlayerStatManager:getStat(player,"RebirthCount")
	local plrJoinedOrDied = RebirthSettings.playerRespawned
	for i = 1,#plrJoinedOrDied,1 do
		if rebirthCountStat and rebirthCountStat >= plrJoinedOrDied[i].rebirthCount then
			plrJoinedOrDied[i][1](player)
		end
	end
end

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		if RebirthSettings.enabled == true then
			local canRebirth = player:FindFirstChild("CanRebirth")
			
			if canRebirth and canRebirth.Value == true then
				giveRebirthGui(player)
			end
			playerJoinedCallFunction(player)			
		end
	end)
end)

for i = 1,#tycoons,1 do
    --getTouchToClaimAndDeleteGateControl also destroys the gate
	local touchToClaim = getTouchToClaimAndDeleteGateControl(tycoons[i])
	
	purchaseHandlerNew:Clone().Parent = tycoons[i]

	local purchasedObjects = tycoons[i]:FindFirstChild("PurchasedObjects")
	local owner = tycoons[i]:FindFirstChild("Owner")
	local entrance = tycoons[i].Entrance
	local touchToClaimHead = touchToClaim.Head
	
	--Is PurchaseHandlerNew
	allObjects[i] = require(tycoons[i].PurchaseHandlerNew)
	
	--Load data
	--Check old code below long load data
	loadPurchedObjectFromDatabaseIfPlayerTouchToClaim(touchToClaimHead,
														purchasedObjects,
														allObjects[i],
														tycoons[i])
	
	--Save data
	if purchasedObjects ~= nil and owner ~= nil then
		purchasedObjects.ChildAdded:Connect(function(instance)
			--Check old code below long save data
			savePurchasesObjectsInDatabase(owner,instance,allObjects[i])
		end)
	else
		error("SaveTrigger script won't save data because either purchasedObjects or owner is NIL")
	end
end

tycoonsFolder.ChildAdded:Connect(function(tycoon)

	purchaseHandlerNew:Clone().Parent = tycoon
	local purchasedObjects = tycoon:FindFirstChild("PurchasedObjects")
	local owner = tycoon:FindFirstChild("Owner")
	
	local touchToClaim = getTouchToClaimAndDeleteGateControl(tycoon)
	
	local touchToClaimHead = touchToClaim.Head
	
	local PurchaseHandlerNew = require(tycoon.PurchaseHandlerNew)
	
	--Load data
	--Check old code below long load data
	loadPurchedObjectFromDatabaseIfPlayerTouchToClaim(touchToClaimHead,
													  purchasedObjects,
													  PurchaseHandlerNew,
													  tycoon)
	
	--Save data
	if purchasedObjects ~= nil and owner ~= nil then
		purchasedObjects.ChildAdded:Connect(function(instance)
			--Check old code below long save data
			savePurchasesObjectsInDatabase(owner,instance,PurchaseHandlerNew)
		end)
	else
		error("SaveTrigger script won't save data because either purchasedObjects or owner is NIL")
	end
end)

function getTycoonByPlayerName(playerName)
	local allTycoons = tycoonsFolder:GetChildren()
	for i = 1,#allTycoons,1 do
		local owner = allTycoons[i]:FindFirstChild("Owner")
		if owner ~= nil and allTycoons[i]:IsA("Model") then
			if owner.Value ~= nil and owner.Value.Name == playerName then
				return allTycoons[i]
			end
		else
			print("MAKE SURE EACH TYCOON HAS OWNER VALUE")	
		end
	end
	return nil
end

function removeTycoonAndAddOriginal(tycoon,playerName)
	local plrStats = game.ServerStorage.PlayerMoney:FindFirstChild(playerName)
	if plrStats ~= nil then
		plrStats.OwnsTycoon.Value = nil
	end
	if tycoon then

        --Holds the original tycoons
		local backup = AllTycoons[tycoon.Name]:Clone()
		tycoon:Destroy()
		wait()
		local currencyToCollect = backup:FindFirstChild("CurrencyToCollect")
		if currencyToCollect ~= nil then
			currencyToCollect.Value = 0
		else 
			print("currencyToCollect == nil ----------------------->")
		end
		backup.Parent=script.Parent.Tycoons
		
	end
end

function teleportCharacterToSuppliedPart(player,tycoon)
	local partName = RebirthSettings.teleportToo
	local part = tycoon:FindFirstChild(partName)

	if part and part:IsA("BasePart") then
		local character = player.Character
		if character then
			character:SetPrimaryPartCFrame(part.CFrame)
		end
	end
end

function callFunctionsIfRebirthIsReached(rebirthCountStat,player)
	local playerReachedRebirthCount = RebirthSettings.playerReachedRebirthCount

	for i = 1,#playerReachedRebirthCount do
		if playerReachedRebirthCount[i].rebirthCount == rebirthCountStat then
			playerReachedRebirthCount[i][1](player)
			break
		end
	end
end

local function getCashAmountByRebirthCount(array,rebirthCount)
	for key,value in pairs(array) do
		if value.rebirthCount == rebirthCount then
			return value.cashAmount
		end
	end
end

rebirthEvent.OnServerEvent:Connect(function(player)
	
	local rebirthCountStat = PlayerStatManager:getStat(player,"RebirthCount")
	--TODO real investigate if rebirth count can be nil
	if rebirthCountStat == nil then return end
	local array = RebirthSettings.cashNeededForRebirth 
	local cashNeeded = getCashAmountByRebirthCount(array,rebirthCountStat+1)
	local playerStats = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
	
	if not cashNeeded then cashNeeded = RebirthSettings.defaultCashNeededForRebirth end
	
	if RebirthSettings.enabled == true then 
		if (playerStats.Value >= cashNeeded) == false then
			rebirthEvent:FireClient(player,cashNeeded)
			return
		end
		
		local success,err = pcall(function() 
			local ownsTycoon = playerStats:FindFirstChild("OwnsTycoon")
		
			if ownsTycoon ~= nil and ownsTycoon.Value ~= nil then
			
				local tycoon = getTycoonByPlayerName(player.Name);
				if tycoon ~= nil then
					local PurchaseHandlerNew = require(tycoon.PurchaseHandlerNew)
					local hasFinishedTycoon = isTycoonFinished(PurchaseHandlerNew,player)
					if hasFinishedTycoon == true then
					
						PlayerStatManager:setAllTycoonPurchasesToNil(player)
						
						if rebirthCountStat == nil then
							PlayerStatManager:saveStat(player,"RebirthCount",0)
						end
						if RebirthSettings.resetCash then
							PlayerStatManager:saveStat(player,"Money",0)
						end
						
						PlayerStatManager:IncrementStat(player,"RebirthCount",1)
						rebirthCountStat = PlayerStatManager:getStat(player,"RebirthCount")
						for u = 1,#unlockPurchases,1 do
							if rebirthCountStat >= unlockPurchases[u].rebirthCount then
								--TODO check if there is bugs
								PlayerStatManager:ChangeStatInTycoonPurchases(player, unlockPurchases[u].unlock, true)
							end
						end
						callFunctionsIfRebirthIsReached(rebirthCountStat,player)
						
						local leaderstats = player:FindFirstChild("leaderstats")
						if leaderstats ~= nil then
							local rebirths = leaderstats:FindFirstChild("Rebirths")
							local moneyStat = leaderstats:FindFirstChild("Money")
							if rebirths ~= nil and rebirthCountStat ~= nil then
								rebirths.Value = rebirthCountStat
							end
							if moneyStat ~= nil and RebirthSettings.resetCash then
								moneyStat.Value = 0
							end
						end
						
						local playerStats = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
						if RebirthSettings.resetCash then
							playerStats.Value = 0
						end
						teleportCharacterToSuppliedPart(player,tycoon)
						removeTycoonAndAddOriginal(tycoon,player.Name)
						local canRebirth = player:FindFirstChild("CanRebirth")
						if canRebirth ~= nil then
							canRebirth.Value = false
						end
						local playerGui = player:FindFirstChild("PlayerGui")
						if playerGui ~= nil then
							local rebirthGui = playerGui:FindFirstChild("RebirthGui (Don't Move)")
							if rebirthGui ~= nil then
								rebirthGui:Destroy()
							end
						end
						
					end
				else
					print("Tycoon is nil getTycoonByPlayerName("..player.Name..")")	
				end
			end
		end)
		if success == false then
			print(err)
		end
	end
end)


if runService:IsStudio() or TestSettings.showTouchTycoonButtonsGuiOutsideStudio then
	local canContinueTouchingButtons = false
	
	touchAllTycoonButtons.OnServerEvent:Connect(function(player,start)
		canContinueTouchingButtons = start
		if canContinueTouchingButtons then
			local character = player.Character
			local tycoon = getTycoonByPlayerName(player.Name);
			if not tycoon then return end
			while canContinueTouchingButtons do 
				local allTheButtons = tycoon.Buttons:GetChildren();
				local notOpen = false
				for i = 1,#allTheButtons,1 do
					local head = allTheButtons[i]:FindFirstChild("Head")
					if not canContinueTouchingButtons then return end
					if head and head.Transparency == 0 then
						local headPos = head.Position
						local newPos = Vector3.new(headPos.X,headPos.Y+1.2,headPos.Z)
						character:MoveTo(newPos)
						wait(0.5)
						notOpen = true
					end
				end
				if notOpen == false then
					break
				end
			end
		end
	end)
	
	giveCashEvent.OnServerEvent:Connect(function(player,cashAmount)
		local plrCash = playerMoney:FindFirstChild(player.Name)
		if plrCash then
			plrCash.Value = plrCash.Value + cashAmount
		end
	end)
end
