--------------------------------------------------------------------------------------
--------------------[ TOOL SELECTION AND DESELECTION ]--------------------------------
--------------------------------------------------------------------------------------


function onEquipped()
	wait()
	if Humanoid.Health ~= 0 and (not Selected) and Gun.Parent == Char then
		Selected = true
		breakReload = false
		equipAnimPlaying = true
		
		math.randomseed(tick()) --This sets a new seed for the random function each time you select the gun
		
		--------------------[ FAILSAFE RESETING ]-------------------------------------
		
		for _, GM in pairs(ignoreModel:GetChildren()) do
			if GM.Name == "gunIgnore_"..Player.Name then
				GM:Destroy()
			end
		end
		
		for _, c in pairs(Connections) do
			c:disconnect()
		end
		
		Connections = {}
		
		--------------------[ REMOTE GUN SETUP ]--------------------------------------
		
		--[[local Vars = {
			ignoreModel = ignoreModel;
			Humanoid = Humanoid;
			Shoulders = Shoulders;
			Torso = Torso;
			Head = Head;
			armC0 = armC0;
			leftArmC1 = S.equipSettings.leftArmC1;
			rightArmC1 = S.equipSettings.rightArmC1;
			LArm = LArm;
			RArm = RArm;
			gunParts = gunParts;
			Handle = Handle;
		}
		gunIgnore, playerFolder, headWeld, headWeld2, animWeld, ABWeld, LWeld, RWeld, LWeld2, RWeld2, LLegWeld, RLegWeld, gunParts2 = gunSetup:InvokeServer(Vars)]]
		
		--------------------[ CREATING IGNORE MODELS ]--------------------------------
		
		gunIgnore = Instance.new("Model")
		gunIgnore.Name = "gunIgnore_"..Player.Name
		gunIgnore.Parent = ignoreModel
		
		--------------------[ MODIFYING THE PLAYER ]----------------------------------
		
		Player.CameraMode = Enum.CameraMode.LockFirstPerson
		Cam.CameraType = Enum.CameraType.Scriptable
		Cam.FieldOfView = 80
		UIS.MouseBehavior = Enum.MouseBehavior.LockCenter
		UIS.MouseIconEnabled = false
		
		local initialX, initialY = getYawPitch(Cam.CoordinateFrame)
		camAng = -VEC2(initialX, initialY)
		
		mainGUI.Parent = Player.PlayerGui
		
		setUpGUI()
		updateHealth()
		
		if S.selectFire then
			local currentMode = Modes[((rawFireMode - 1) % numModes) + 1]
			if currentMode == "AUTO" then
				fireFunction = autoFire
			elseif currentMode == "BURST" then
				fireFunction = burstFire
			elseif currentMode == "SEMI" then
				fireFunction = semiFire
			else
				fireFunction = nil
			end
		else
			if S.gunType.Semi then
				fireFunction = semiFire
			elseif S.gunType.Auto then
				fireFunction = autoFire
			elseif S.gunType.Burst then
				fireFunction = burstFire
			else
				fireFunction = nil
			end
		end
		
		changePlayerTrans(Char, 1)
		
		Humanoid.AutoRotate = false
		
		Shoulders.Right.Part1 = nil
		Shoulders.Left.Part1 = nil

		playerFolder = Instance.new("Model")
		playerFolder.Name = "playerFolder"
		playerFolder.Parent = gunIgnore
		
		local headBase = Instance.new("Part")
		headBase.Transparency = 1
		headBase.Name = "headBase"
		headBase.CanCollide = false
		headBase.FormFactor = Enum.FormFactor.Custom
		headBase.Size = V3(0.2, 0.2, 0.2)
		headBase.BottomSurface = Enum.SurfaceType.Smooth
		headBase.TopSurface = Enum.SurfaceType.Smooth
		headBase.Parent = playerFolder
		
		headWeld = Instance.new("Weld")
		headWeld.Part0 = Torso
		headWeld.Part1 = headBase
		headWeld.C0 = CF(0, 1.5, 0)
		headWeld.Parent = Torso
		
		headWeld2 = Instance.new("Weld")
		headWeld2.Part0 = headBase
		headWeld2.Part1 = Head
		headWeld2.Parent = headBase
		
		neckClone = Neck:Clone()
		
		--[[local stanceBase = Instance.new("Part")
		stanceBase.Transparency = 1
		stanceBase.Name = "stanceBase"
		stanceBase.CanCollide = false
		stanceBase.FormFactor = Enum.FormFactor.Custom
		stanceBase.Size = V3(0.2, 0.2, 0.2)
		stanceBase.BottomSurface = Enum.SurfaceType.Smooth
		stanceBase.TopSurface = Enum.SurfaceType.Smooth
		stanceBase.Parent = playerFolder
		
		stanceWeld = Instance.new("Weld")
		stanceWeld.Part0 = stanceBase
		stanceWeld.Part1 = Torso
		stanceWeld.Parent = stanceBase]]
		
		local animBase = Instance.new("Part")
		animBase.Transparency = 1
		animBase.Name = "animBase"
		animBase.CanCollide = false
		animBase.FormFactor = Enum.FormFactor.Custom
		animBase.Size = V3(0.2, 0.2, 0.2)
		animBase.BottomSurface = Enum.SurfaceType.Smooth
		animBase.TopSurface = Enum.SurfaceType.Smooth
		animBase.Parent = playerFolder
		
		animWeld = Instance.new("Weld")
		animWeld.Part0 = animBase
		animWeld.Part1 = headBase
		animWeld.Parent = animBase
		
		local ArmBase = Instance.new("Part")
		ArmBase.Transparency = 1
		ArmBase.Name = "ArmBase"
		ArmBase.CanCollide = false
		ArmBase.FormFactor = Enum.FormFactor.Custom
		ArmBase.Size = V3(0.2, 0.2, 0.2)
		ArmBase.BottomSurface = Enum.SurfaceType.Smooth
		ArmBase.TopSurface = Enum.SurfaceType.Smooth
		ArmBase.Parent = playerFolder
		
		ABWeld = Instance.new("Weld")
		ABWeld.Part0 = ArmBase
		ABWeld.Part1 = animBase
		ABWeld.Parent = ArmBase
		
		local LArmBase = Instance.new("Part")
		LArmBase.Transparency = 1
		LArmBase.Name = "LArmBase"
		LArmBase.CanCollide = false
		LArmBase.FormFactor = Enum.FormFactor.Custom
		LArmBase.Size = V3(0.2, 0.2, 0.2)
		LArmBase.BottomSurface = Enum.SurfaceType.Smooth
		LArmBase.TopSurface = Enum.SurfaceType.Smooth
		LArmBase.Parent = playerFolder
		
		local RArmBase = Instance.new("Part")
		RArmBase.Transparency = 1
		RArmBase.Name = "RArmBase"
		RArmBase.CanCollide = false
		RArmBase.FormFactor = Enum.FormFactor.Custom
		RArmBase.Size = V3(0.2, 0.2, 0.2)
		RArmBase.BottomSurface = Enum.SurfaceType.Smooth
		RArmBase.TopSurface = Enum.SurfaceType.Smooth
		RArmBase.Parent = playerFolder
		
		LWeld = Instance.new("Weld")
		LWeld.Name = "LWeld"
		LWeld.Part0 = ArmBase
		LWeld.Part1 = LArmBase
		LWeld.C0 = armC0[1]
		LWeld.C1 = S.equipSettings.leftArmC1
		LWeld.Parent = ArmBase
		
		RWeld = Instance.new("Weld")
		RWeld.Name = "RWeld"
		RWeld.Part0 = ArmBase
		RWeld.Part1 = RArmBase
		RWeld.C0 = armC0[2]
		RWeld.C1 = S.equipSettings.rightArmC1
		RWeld.Parent = ArmBase
		
		LWeld2 = Instance.new("Weld")
		LWeld2.Name = "LWeld"
		LWeld2.Part0 = LArmBase
		LWeld2.Part1 = LArm
		LWeld2.Parent = LArmBase
		
		RWeld2 = Instance.new("Weld")
		RWeld2.Name = "RWeld"
		RWeld2.Part0 = RArmBase
		RWeld2.Part1 = RArm
		RWeld2.Parent = RArmBase
		
		LLegWeld = Instance.new("Weld")
		LLegWeld.Name = "LLegWeld"
		LLegWeld.Part0 = Torso
		LLegWeld.Part1 = nil
		LLegWeld.C0 = CF(-0.5, -2, 0)
		LLegWeld.Parent = Torso
		
		RLegWeld = Instance.new("Weld")
		RLegWeld.Name = "RLegWeld"
		RLegWeld.Part0 = Torso
		RLegWeld.Part1 = nil
		RLegWeld.C0 = CF(0.5, -2, 0)
		RLegWeld.Parent = Torso
		
		if S.playerArms then
			armModel = Instance.new("Model", workspace.FilteringEnabled and playerFolder or Cam)
			
			fakeLArm = LArm:Clone()
			fakeLArm.Parent = armModel
			fakeLArm.Transparency = S.fakeArmSettings.Transparency
			fakeLArm.CanCollide = false
			fakeLArm.Size = S.fakeArmSettings.armSize
			fakeLArm:BreakJoints()
			
			--LArm.Transparency = 1
			
			local fakeLWeld = Instance.new("Weld")
			fakeLWeld.Part0 = fakeLArm
			fakeLWeld.Part1 = LArm
			fakeLWeld.Parent = fakeLArm
			
			fakeRArm = RArm:Clone()
			fakeRArm.Parent = armModel
			fakeRArm.Transparency = S.fakeArmSettings.Transparency
			fakeRArm.CanCollide = false
			fakeRArm.Size = S.fakeArmSettings.armSize
			fakeRArm:BreakJoints()
			
			--RArm.Transparency = 1
			
			local fakeRWeld = Instance.new("Weld")
			fakeRWeld.Part0 = fakeRArm
			fakeRWeld.Part1 = RArm
			fakeRWeld.Parent = fakeRArm
			
			Instance.new("Humanoid", armModel)
			
			if S.fakeArmSettings.characterMeshes then
				for _,Obj in pairs(Char:GetChildren()) do
					if Obj:IsA("CharacterMesh") then
						Obj:Clone().Parent = armModel
					end
				end
			end
			for _,Obj in pairs(Char:GetChildren()) do
				if Obj:IsA("Shirt") then
					Obj:Clone().Parent = armModel
				end
			end
		else
			armTable = createArms()
			if workspace.FilteringEnabled then
				armTable[1].Model.Parent = playerFolder
				armTable[2].Model.Parent = playerFolder
			else
				armTable[1].Model.Parent = Cam--playerFolder
				armTable[2].Model.Parent = Cam--playerFolder
			end
			
			fakeLArm = armTable[1].armPart
			
			--LArm.Transparency = 1
			
			local fakeLWeld = Instance.new("Weld")
			fakeLWeld.Part0 = fakeLArm
			fakeLWeld.Part1 = LArm
			fakeLWeld.Parent = fakeLArm
			
			fakeRArm = armTable[2].armPart
			
			--RArm.Transparency = 1
			
			local fakeRWeld = Instance.new("Weld")
			fakeRWeld.Part0 = fakeRArm
			fakeRWeld.Part1 = RArm
			fakeRWeld.Parent = fakeRArm
		end
		
		--------------------[ MODIFYING THE GUN ]-------------------------------------
		
		for _, Tab in pairs(gunParts) do
			local Weld = Instance.new("Weld")
			Weld.Name = "MainWeld"
			Weld.Part0 = Handle
			Weld.Part1 = Tab.Obj
			Weld.C0 = Tab.Obj.weldCF.Value
			Weld.Parent = Handle
			Tab.Weld = Weld
		end
		
		Grip = RArm:WaitForChild("RightGrip")
		
		local handleCF = Torso.CFrame * CF(0, 0.5, 0) * armC0[2] * S.aimedC1.rightArm:inverse() * Grip.C0
		local handleOffset = AimPart.CFrame:toObjectSpace(Handle.CFrame)
		aimedGripCF = ((Torso.CFrame * CF(headOffset.X, headOffset.Y, 0)) * handleOffset):toObjectSpace(handleCF)
		
		Grip.C1 = S.equipSettings.GripC1
		
		--------------------[ RUNNING PLUGINS ]---------------------------------------
		
		for _, Plugin in pairs(Plugins.OnEquipped) do
			spawn(function()
				Plugin()
			end)
		end
		
		--------------------[ GETTING PLAYER MASS ]-----------------------------------
		
		local connectedParts = HRP:GetConnectedParts(true)
		for _, v in pairs(connectedParts) do
			if v:IsA("BasePart") then
				playerMass = playerMass + v:GetMass()
			end
		end
		
		--------------------[ CONNECTIONS ]-------------------------------------------
		
		INSERT(Connections, Humanoid.Died:connect(function()
			onUnequipped(true)
		end))
		
		INSERT(Connections, Humanoid.Jumping:connect(function()
			if Stance ~= 0 then
				Stand()
			end
		end))
		
		INSERT(Connections, Humanoid.StateChanged:connect(onHumanoidStateChanged))
		
		INSERT(Connections, Humanoid.HealthChanged:connect(updateHealth))
		
		INSERT(Connections, M2.Button1Down:connect(onMB1Down))
		
		INSERT(Connections, M2.Button1Up:connect(onMB1Up))
		
		INSERT(Connections, M2.Button2Down:connect(onMB2Down))
		
		INSERT(Connections, M2.Button2Up:connect(onMB2Up))
		
		INSERT(Connections, M2.KeyDown:connect(keyDown))
		
		INSERT(Connections, M2.KeyUp:connect(keyUp))
		
		if S.sensitivitySettings.scrollToChange then
			INSERT(Connections, M2.WheelForward:connect(onScrollUp))
			INSERT(Connections, M2.WheelBackward:connect(onScrollDown))
		end
		
		if S.AutoKnife then
			INSERT(Connections, RS.Stepped:connect(function()
				local H, P = AdvRayCast(Head.CFrame.p, Head.CFrame.lookVector, S.AutoKnifeDist, nil)
				if H then
					local HitHuman = findFirstClass(H.Parent, "Humanoid")
					if HitHuman and isEnemy(HitHuman) and HitHuman.Health ~= 0 then
						Knife()
					end
				end
			end))
		end
		
		INSERT(Connections, UIS.InputChanged:connect(function(inputObj)
			if inputObj.UserInputType == Enum.UserInputType.MouseMovement then
				local rawCamAng = camAng - (VEC2(RAD(inputObj.Delta.x), RAD(inputObj.Delta.y)) * mouseSensitivity * 0.25)
				camAng = VEC2(rawCamAng.x, (rawCamAng.y > RAD(80) and RAD(80) or rawCamAng.y < RAD(-80) and RAD(-80) or rawCamAng.y))
				
				desiredXOffset = math.min(math.max(inputObj.Delta.x, -S.momentumSettings.maxInput), S.momentumSettings.maxInput)
				desiredYOffset = math.min(math.max(inputObj.Delta.y, -S.momentumSettings.maxInput), S.momentumSettings.maxInput)
			end
		end))
		
		INSERT(Connections, M2.Idle:connect(function(inputObj)
			desiredXOffset = 0
			desiredYOffset = 0
		end))
		
		INSERT(Connections, RS.Stepped:connect(function()
			if tick() - lastBeat > (Humanoid.Health / 75) then
				lastBeat = tick()
				HUD.Health.Tray.Beat:TweenPosition(
					UDim2.new(0, -21, 0, 0),
					Enum.EasingDirection.Out,
					Enum.EasingStyle.Linear,
					0.7 - ((100 - Humanoid.Health) / 400),
					false,
					function()
						HUD.Health.Tray.Beat.Position = UDim2.new(1, 0, 0, 0)
					end
				)
			end
		end))
		
		INSERT(Connections, RS.RenderStepped:connect(function()
			--Main animation
			local animC0, animC1 = getAnimCF()
			animWeld.C0 = animC0
			animWeld.C1 = animC1
			
			--Camera updating
			renderCamera()
		end))
		
		--------------------[ ANIMATE GUN ]-------------------------------------------
		
		tweenJoint(LWeld, nil, S.unAimedC1.leftArm, Sine, S.equipSettings.Time)
		tweenJoint(RWeld, nil, S.unAimedC1.rightArm, Sine, S.equipSettings.Time)
		tweenJoint(Grip, nil, S.unAimedC1.Grip, Sine, S.equipSettings.Time)
		spawn(function()
			local T = tick()
			while true do
				if tick() - T > S.equipSettings.Time then break end
				if (not Selected) then break end
				wait()
			end
			equipAnimPlaying = false
		end)
		
		Animate()
	end
end

function onUnequipped(deleteTool)
	if Selected then
		Selected = false
		
		breakReload = true
		
		--------------------[ RUNNING PLUGINS ]---------------------------------------
		
		for _, Plugin in pairs(Plugins.OnUnEquipped) do
			spawn(function()
				Plugin()
			end)
		end
		
		--------------------[ MODIFYING THE PLAYER ]----------------------------------
		
		Cam.FieldOfView = 70
		Cam.CameraType = Enum.CameraType.Custom
		
		UIS.MouseBehavior = Enum.MouseBehavior.Default
		UIS.MouseIconEnabled = true
		
		Player.CameraMode = Enum.CameraMode.Classic
		
		if armTable then
			armTable[1].Model:Destroy()
			armTable[2].Model:Destroy()
		elseif armModel then
			armModel:Destroy()
		end
		
		LLegWeld:Destroy()
		RLegWeld:Destroy()
		
		changePlayerTrans(Char, 0)
		
		mainGUI.Parent = script
		
		Shoulders.Right.Part1 = RArm
		Shoulders.Left.Part1 = LArm
		
		neckClone.Parent = Torso
		headWeld:Destroy()
		
		Humanoid.WalkSpeed = 16
		Humanoid.AutoRotate = true
		
		--------------------[ RESETING THE TOOL ]-------------------------------------
		
		gunIgnore:Destroy()
		
		mouseSensitivity = S.sensitivitySettings.Default
		
		MB1Down = false
		
		playerMass = 0
		
		Aimed = false
		
		camOffsets = {
			guiScope = {
				Rot = V3();
			};
			Reload = {
				Rot = V3();
				Code = nil;
			};
			Recoil = {
				Rot = V3();
				Code = nil;
			};
		}
		
		recoilAnim = {
			Pos = V3();
			Rot = V3();
			Code = nil;
		}

		--Setting the aim variables to unaimed
		spreadZoom = "unAimed"
		scopeMain.Visible = false
		scopeSteady.Visible = false
		aimAlpha = 0
		aimHeadOffset = 0
		jumpAnimMultiplier = 1
		translationDivisor = 7
		rotationMultiplier = S.momentumSettings.Amplitude.unAimed
		armTiltMultiplier = 1
		Scope.BackgroundTransparency = 1
		if S.guiScope then
			spawn(function()
				for _, Obj in pairs(Gun:GetChildren()) do
					if Obj:IsA("BasePart") then
						Obj.LocalTransparencyModifier = 0
					end
				end
			end)
		end
		
		onGround = true
		
		for _, Tab in pairs(gunParts) do
			Tab.Weld:Destroy()
			Tab.Weld = nil
		end
		
		for _,c in pairs(Connections) do
			c:disconnect()
		end
		
		Connections = {}
		
		if deleteTool then
			Cam:ClearAllChildren()
			Gun:Destroy()
		end
		
		wait() --This is here in case you dolphin dived and deselected the tool instantly
		
		if S.stanceSettings.standOnDeselect and Stance ~= 0 then
			crawlCamRot = 0
			isCrawling = false
			stanceSway = 1
			spreadStance = "Stand"
			Stand(true)
		end
		baseSpread = S.spreadSettings[spreadZoom][spreadStance][spreadMotion]
	end
end

Gun.Equipped:connect(onEquipped)
Gun.Unequipped:connect(function() onUnequipped(false) end)
