local G=false local function E(G,x)x(G)for G,S in next,G:GetChildren()do E(S,x)end end local function x(G,E)local x=G repeat x=x.Parent if x==nil then return nil end until x:IsA(E)return x end local function S(G)local x={}E(G,function(G)if G:IsA("\066\097\115\101\080\097\114\116")and(G.Parent.Name~="\083"and(G.Parent.Name~="\084\097\105\108\082\111\116\111\114"and G.Parent.Name~="\084\111\112\082\111\116\111\114"))then x[#x+1]=G end end)return x end local function w(G,E)assert(type(E)=="\116\097\098\108\101","\086\097\108\117\101\115 \105\115 \110\111\116 \097 \116\097\098\108\101")for E,x in next,E do if type(E)=="\110\117\109\098\101\114"then x.Parent=G else G[E]=x end end return G end local function s(G,E)return w(Instance.new(G),E)end local k={"\084\111\112\083\117\114\102\097\099\101","\066\111\116\116\111\109\083\117\114\102\097\099\101","\076\101\102\116\083\117\114\102\097\099\101","\082\105\103\104\116\083\117\114\102\097\099\101","\070\114\111\110\116\083\117\114\102\097\099\101","\066\097\099\107\083\117\114\102\097\099\101"}local D={"\072\105\110\103\101";"\077\111\116\111\114";"\083\116\101\112\112\105\110\103\077\111\116\111\114"}local function q(G)for E,x in pairs(k)do for E,S in pairs(D)do if G[x].Name==S then return true end end end return false end local function p(E)if G then return false end if q(E)then return false end local x=E:GetConnectedParts()if#x==1 then return false end for G,E in pairs(x)do if q(E)then return false elseif not E:IsDescendantOf(script.Parent)then return false end end return true end local function N(G,E,x,S)x=x or"\087\101\108\100"local k=E:FindFirstChild("\113\082\101\108\097\116\105\118\101\067\070\114\097\109\101\087\101\108\100\086\097\108\117\101")local D=E:FindFirstChild("\113\067\070\114\097\109\101\087\101\108\100\084\104\105\110\103\121")or Instance.new(x)w(D,{Name="\113\067\070\114\097\109\101\087\101\108\100\084\104\105\110\103\121";Part0=G;Part1=E;C0=CFrame.new(),C1=k and k.Value or E.CFrame:toObjectSpace(G.CFrame);Parent=E})if not k then k=s("\067\070\114\097\109\101\086\097\108\117\101",{Parent=E;Name="\113\082\101\108\097\116\105\118\101\067\070\114\097\109\101\087\101\108\100\086\097\108\117\101",Archivable=true;Value=D.C1})end return D end local function B(G,E,x,S)for G,S in pairs(G)do if S~=E then N(E,S,x,E)end end if not S then for G,E in pairs(G)do E.Anchored=false end E.Anchored=false end end local function z()local G=x(script,"\084\111\111\108")local E=S(script.Parent)local w=G and(G:FindFirstChild("\072\097\110\100\108\101")and(G.Handle:IsA("\066\097\115\101\080\097\114\116")and G.Handle))or script.Parent:IsA("\077\111\100\101\108")and script.Parent.PrimaryPart or E[1]if w then B(E,w,"\087\101\108\100",false)else warn("\113\087\101\108\100 - \085\110\097\098\108\101 \116\111 \119\101\108\100 \112\097\114\116")end return G end local L=z()if L and script.ClassName=="\083\099\114\105\112\116"then script.Parent.AncestryChanged:connect(function()z()end)end


local NEVER_BREAK_JOINTS = false -- If you set this to true it will never break joints (this can create some welding issues, but can save stuff like hinges).


local function CallOnChildren(Instance, FunctionToCall)
	-- Calls a function on each of the children of a certain object, using recursion.  

	FunctionToCall(Instance)

	for _, Child in next, Instance:GetChildren() do
		CallOnChildren(Child, FunctionToCall)
	end
end

local function GetNearestParent(Instance, ClassName)
	-- Returns the nearest parent of a certain class, or returns nil

	local Ancestor = Instance
	repeat
		Ancestor = Ancestor.Parent
		if Ancestor == nil then
			return nil
		end
	until Ancestor:IsA(ClassName)

	return Ancestor
end

local function GetBricks(StartInstance)
	local List = {}

	-- if StartInstance:IsA("BasePart") then
	-- 	List[#List+1] = StartInstance
	-- end

	CallOnChildren(StartInstance, function(Item)
		if Item:IsA("BasePart") and 
			Item.Parent.Name ~= ("S") and
			Item.Parent.Name ~= ("TailRotor")and
			Item.Parent.Name ~= ("TopRotor") then
			List[#List+1] = Item;
		end
	end)

	return List
end

local function Modify(Instance, Values)
	-- Modifies an Instance by using a table.  

	assert(type(Values) == "table", "Values is not a table");

	for Index, Value in next, Values do
		if type(Index) == "number" then
			Value.Parent = Instance
		else
			Instance[Index] = Value
		end
	end
	return Instance
end

local function Make(ClassType, Properties)
	-- Using a syntax hack to create a nice way to Make new items.  

	return Modify(Instance.new(ClassType), Properties)
end

local Surfaces = {"TopSurface", "BottomSurface", "LeftSurface", "RightSurface", "FrontSurface", "BackSurface"}
local HingSurfaces = {"Hinge", "Motor", "SteppingMotor"}

local function HasWheelJoint(Part)
	for _, SurfaceName in pairs(Surfaces) do
		for _, HingSurfaceName in pairs(HingSurfaces) do
			if Part[SurfaceName].Name == HingSurfaceName then
				return true
			end
		end
	end
	
	return false
end

local function ShouldBreakJoints(Part)
	--- We do not want to break joints of wheels/hinges. This takes the utmost care to not do this. There are
	--  definitely some edge cases. 

	if NEVER_BREAK_JOINTS then
		return false
	end
	
	if HasWheelJoint(Part) then
		return false
	end
	
	local Connected = Part:GetConnectedParts()
	
	if #Connected == 1 then
		return false
	end
	
	for _, Item in pairs(Connected) do
		if HasWheelJoint(Item) then
			return false
		elseif not Item:IsDescendantOf(script.Parent) then
			return false
		end
	end
	
	return true
end

local function WeldTogether(Part0, Part1, JointType, WeldParent)
	--- Weld's 2 parts together
	-- @param Part0 The first part
	-- @param Part1 The second part (Dependent part most of the time).
	-- @param [JointType] The type of joint. Defaults to weld.
	-- @param [WeldParent] Parent of the weld, Defaults to Part0 (so GC is better).
	-- @return The weld created.

	JointType = JointType or "Weld"
	local RelativeValue = Part1:FindFirstChild("qRelativeCFrameWeldValue")
	
	local NewWeld = Part1:FindFirstChild("qCFrameWeldThingy") or Instance.new(JointType)
	Modify(NewWeld, {
		Name = "qCFrameWeldThingy";
		Part0  = Part0;
		Part1  = Part1;
		C0     = CFrame.new();--Part0.CFrame:inverse();
		C1     = RelativeValue and RelativeValue.Value or Part1.CFrame:toObjectSpace(Part0.CFrame); --Part1.CFrame:inverse() * Part0.CFrame;-- Part1.CFrame:inverse();
		Parent = Part1;
	})

	if not RelativeValue then
		RelativeValue = Make("CFrameValue", {
			Parent     = Part1;
			Name       = "qRelativeCFrameWeldValue";
			Archivable = true;
			Value      = NewWeld.C1;
		})
	end

	return NewWeld
end

local function WeldParts(Parts, MainPart, JointType, DoNotUnanchor)
	-- @param Parts The Parts to weld. Should be anchored to prevent really horrible results.
	-- @param MainPart The part to weld the model to (can be in the model).
	-- @param [JointType] The type of joint. Defaults to weld. 
	-- @parm DoNotUnanchor Boolean, if true, will not unachor the model after cmopletion.
	
	for _, Part in pairs(Parts) do
		if Part ~= MainPart then
			WeldTogether(MainPart, Part, JointType, MainPart)
		end
	end

	if not DoNotUnanchor then
		for _, Part in pairs(Parts) do
			Part.Anchored = false
		end
		MainPart.Anchored = false
	end
end

local function PerfectionWeld()	
	local Tool = GetNearestParent(script, "Tool")

	local Parts = GetBricks(script.Parent)
	local PrimaryPart = Tool and Tool:FindFirstChild("Handle") and Tool.Handle:IsA("BasePart") and Tool.Handle or script.Parent:IsA("Model") and script.Parent.PrimaryPart or Parts[1]

	if PrimaryPart then
		WeldParts(Parts, PrimaryPart, "Weld", false)
	else
		warn("qWeld - Unable to weld part")
	end
	
	return Tool
end

local Tool = PerfectionWeld()


if Tool and script.ClassName == "Script" then
	--- Don't bother with local scripts

	script.Parent.AncestryChanged:connect(function()
		PerfectionWeld()
	end)
end
