local workspace		= game:GetService("Workspace")
local storage		= game:GetService("ReplicatedStorage")
local runService	= game:GetService("RunService")
local players = game:GetService("Players")


local character        = script:FindFirstAncestorWhichIsA("Model")
local player           = players:GetPlayerFromCharacter(character)
local part = script.Parent:WaitForChild("Part")
local goalPart		= part
local character		= script.Parent.Parent
local Torso = character:WaitForChild("Torso")
local RightArm = character:WaitForChild("Right Arm")
local LeftArm = character:WaitForChild("Left Arm")

local rightShoulder = Torso:WaitForChild("Right Shoulder")
local leftShoulder = Torso:WaitForChild("Left Shoulder")
local solveModule	= storage:WaitForChild("SolveIK")
local solveIK		= require(solveModule)

local rightclone = RightArm:Clone()
rightclone.Parent = character
rightclone.Name = "RClone"
rightclone.Transparency = 1
rightclone.Color = RightArm.Color
motor6_right = rightShoulder:Clone()
motor6_right.Part0 = Torso
motor6_right.Part1 = rightclone
motor6_right.C0 = motor6_right.C0
motor6_right.Parent = Torso
-----------------------------
local leftclone = LeftArm:Clone()
leftclone.Transparency = 1
leftclone.Color = LeftArm.Color
leftclone.Parent = character
leftclone.Name = "LClone"
motor6_left = leftShoulder:Clone()
motor6_left.Part0 = Torso
motor6_left.Part1 = leftclone
motor6_left.C0 = motor6_left.C0
motor6_left.Parent = Torso


local function cleanRotation(joint)
	joint.C0 = CFrame.new(joint.C0.p)
	joint.C1 = CFrame.new(joint.C1.p)
end

	
cleanRotation(motor6_left)
cleanRotation(motor6_right)


local SHOULDER_C0_CACHE		= motor6_right.C0
local ARM_LENGTH			= RightArm.Size.Y - 0.5
----------------------------------------------------
local SHOULDER_C0_CACHE2	= motor6_left.C0
local ARM_LENGTH2			= LeftArm.Size.Y - 0.5

----
part.Changed:Connect(function()
runService.Heartbeat:Connect(function()
	local shoulderCFrame = Torso.CFrame * SHOULDER_C0_CACHE
	local shoulderCFrame2 = Torso.CFrame * SHOULDER_C0_CACHE2
	local goalPosition = goalPart.Value	
	local planeCF = solveIK:solveIK(shoulderCFrame, goalPosition, ARM_LENGTH)
	local planeCF2 = solveIK:solveIK(shoulderCFrame2, goalPosition, ARM_LENGTH2)
	local correction = CFrame.Angles(math.pi/2, 0, 0)

	motor6_right.C0 = Torso.CFrame:toObjectSpace(planeCF * correction)
	motor6_left.C0 = Torso.CFrame:toObjectSpace(planeCF2 * correction)
end)

runService.Stepped:Connect(function()
	motor6_right.Transform = CFrame.new()
		motor6_left.Transform = CFrame.new()
	end)
end)