-- shut down the script when we die and reset things

Humanoid.Died:Connect(function()
	coroutine.close(ArmCoroutine)
	LeftShoulderClone:Destroy()
	RightShoulderClone:Destroy()
	Viewmodel:Destroy()
	if RightShoulder then
		RightShoulder.Enabled = true
	end
	if LeftShoulder then
		LeftShoulder.Enabled = true
	end
	LeftArm.Anchored = false
	RightArm.Anchored = false
	armTransparency = 0
	setArmVisibility(false)
end)

ArmCoroutine = coroutine.create(function()
	while true do
		SwaySize = script.WalkSwayMultiplier.Value
		-- checkFirstPerson() checks if camera is first person and enables/disables the Viewmodel accordingly
		checkFirstPerson()
		-- update loop
		if isFirstPerson == true then
			-- make arms visible
			setArmVisibility(true)
			-- update walk Sway if we are walking
			if checkPlayerRunning() then
				WalkSway = WalkSway:Lerp(CFrame.new((0.07*SwaySize) * math.sin(tick() * (2 * Humanoid.WalkSpeed/4)),(0.07*SwaySize) * math.cos(tick() * (4 * Humanoid.WalkSpeed/4)),0) * CFrame.Angles(0,0,(-.03*SwaySize) * math.sin(tick() * (2 * Humanoid.WalkSpeed/4))),0.2*Sensitivity)
			else
				WalkSway = WalkSway:Lerp(CFrame.new(), 0.05*Sensitivity)
			end
			--
			local delta = UserInputService:GetMouseDelta()
			--
			if IncludeCameraSway then
				Sway = Sway:Lerp(Vector3.new(delta.X,delta.Y,delta.X/2), 0.1*Sensitivity)
			end
			--
			if IncludeStrafe then
				StrafeSway = StrafeSway:Lerp(CFrame.Angles(0,0,-HumanoidRootPart.CFrame.rightVector:Dot(Humanoid.MoveDirection)/(20/SwaySize)), 0.1*Sensitivity)
			end
			--
			if IncludeJumpSway == true then
				JumpSway = JumpSwayGoal.Value
			end
			-- update animation transform for Viewmodel
			RightShoulderClone.Transform = RightShoulder.Transform
			LeftShoulderClone.Transform = LeftShoulder.Transform
			-- cframe the Viewmodel
			local SwayRotation = CFrame.Angles(math.rad(Sway.Y*SwaySize),math.rad(Sway.X*SwaySize)/10,math.rad(Sway.Z*SwaySize)/2)
			local OffsetVector3 = (Camera.CFrame.UpVector*(-1.7-(HeadOffset.Y+(AimOffset.Value.Y))))+(Camera.CFrame.LookVector*(HeadOffset.Z+(AimOffset.Value.Z)))+(Camera.CFrame.RightVector*(-HeadOffset.X-(AimOffset.Value.X)+(-(Sway.X*SwaySize)/75)))
			local SwayPosition = WalkSway*JumpSway*StrafeSway
			local OffsetCFrame = script.CFrameAimOffset.Value:Inverse()
			local FinalCFrame = ((Camera.CFrame * SwayPosition * SwayRotation) + OffsetVector3) * OffsetCFrame
			Viewmodel.PrimaryPart.CFrame = FinalCFrame
		end
		RunService.RenderStepped:Wait()
	end
end)

coroutine.resume(ArmCoroutine)

if (game.StarterPlayer.CameraMode == Enum.CameraMode.LockFirstPerson) or (game.StarterPlayer.CameraMaxZoomDistance <= 0.5) then
	toggleViewmodel(true)
end
