--Humanoid:SetStateEnabled(Enum.HumanoidStateType.Dead, false)


Rig.Character = Character
Rig.CreateFolders()
Rig.FindParts()
Rig.CreateAltRootMotor()
Rig.ScaleAltRootMotorOffset()
Rig.CreateConstraints()
Rig.BuildConstraintRig()
if Settings.CreateAccessoryConstraints == true then Rig.CreateAccessoryConstraints() end
Rig.CreateNoClipCollisionGroup()
Rig.TakeCareOfRootPartAndHead()
Rig.CreateCustomHeadCollisionBox()
Rig.CreateNoCollisionConstraints()

local Debris = game:GetService("Debris")
local IsRagdollNow = false

local CurrentCooldown = 0

function ragdoll(Mode,Velocity)
	if Mode == true then
		if IsRagdollNow then spawn(function() if Velocity then Functions_RemoteVelocity:InvokeClient(Player,Velocity) end end) return end
		IsRagdollNow = true
		CurrentCooldown = time()+Settings.UnRagdollCooldown
		Variables_Ragdoll.Value = true
		Rig.ToggleRagdollRig(true)
		Functions_RemoteRagdoll:InvokeClient(Player,true,Velocity)
	elseif Mode == "dead" then
		if Settings.CloneCharacterOnDeath then
			Player.CharacterRemoving:Connect(function()
				Character.Archivable = true
				Humanoid.AutomaticScalingEnabled = false
				local CharClone = Character:Clone()
				CharClone.Name = Player.Name.."'s Ragdoll"
				for _,v in pairs(CharClone:GetDescendants()) do
					if v:IsA("BaseScript") or v:IsA("Sound") then
						v:Destroy()
					end
				end
				Character:Destroy()
				CharClone.Parent = workspace
				Addons.KillHumanoid(CharClone.Humanoid)
				if Settings.AutoCleanup and Settings.AutoCleanupTime then
					Debris:AddItem(CharClone, Settings.AutoCleanupTime)
				end
				pcall(function()
					for _,v in pairs(CharClone:GetDescendants()) do
						if v:IsA("BasePart") then
							v:SetNetworkOwnershipAuto()
						end
					end
				end)
			end)
		end
	else
		if not IsRagdollNow then return end
		IsRagdollNow = false
		Variables_Ragdoll.Value = false
		Rig.ToggleRagdollRig(false)
		Functions_RemoteRagdoll:InvokeClient(Player,false)
	end
end

local HealthConnection
HealthConnection = Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
	if Humanoid.Health <= 0 then
		
		HealthConnection:Disconnect()												--Preparing for death sequence
		pcall(function() Character.Health:Destroy() end)
		
		-- PLACE FOR CODE MEANT TO HAPPEN BEFORE ACTUALLY KILLING					--Executing code that needs to run before death to avoid bugs
		
		--Humanoid:SetStateEnabled(Enum.HumanoidStateType.Dead, true)				--Killing
		Addons.KillHumanoid(Humanoid)
		
		ragdoll(true)																--Ragdolling
		
		if Settings.BreakJointsOnDeath then Addons.DestroyMotors(Rig.Motors) end	--Breaking joints after ragdolling to ensure consistency with ragdolling normally
		
		ragdoll("dead")																--Executing post-mortem events
		
	end
end)

Variables_Ragdoll:GetPropertyChangedSignal("Value"):Connect(function()
	if Humanoid.Health > 0 then
		ragdoll(Variables_Ragdoll.Value)
	end
end)
