--GET THE NEEDED INFO AND PUT IN TABLES

function getwheels(model)
	for _,i in pairs (model:GetChildren()) do
		if i:IsA("BasePart") then
			i.Anchored = false
			if i.Name == "GOING" then
				table.insert(Seats,i)
			--[[	
			elseif i.Name == "Brake" then
				table.insert(Brakes,i)
				--print("Brake found")
			--]]
			end
		elseif i:IsA("Model") then
			getwheels(i)
			if i.Name == "Coupler" then
				if not cplrstr then
					cplrstr = i
				else
					FrontCoupler.model, RearCoupler.model = getclosestcoupler(cplrstr,i)
					cplrstr = nil
				end
			end
		end
	end
end

function scopinggetcoupler(model)
	local cplrs = {}
	local addtable = {}
	for _,i in pairs (model:GetChildren()) do
		if i:IsA("Model") then
			if i.Name == "Coupler" then
				table.insert(cplrs,i)
			else
				addtable = scopinggetcoupler(i)
				for _,i in pairs (addtable) do
					table.insert(cplrs,i)
				end
			end
		end
	end
	return cplrs
end

function scopinggetFront(model)
	local a = model
	if a and a.Parent then
		repeat
			a = a.Parent
		until a:FindFirstChild("Front") or a == workspace or not a.Parent
	end
	if a and a:FindFirstChild("Front") then
		return a.Front
	else
		return nil
	end
end
function scopinggetDrive(model)
	local a = model
	if a and a.Parent then
		repeat
			a = a.Parent
		until a:FindFirstChild("Drive") or a == workspace or not a.Parent
	end
	if a and a:FindFirstChild("Drive") then
		return a.Drive
	else
		return nil
	end
end

function getclosestcoupler(coupler1,coupler2)
	local tg = scopinggetFront(coupler1)
	local front, rear = nil,nil
	if coupler2 and tg then
		local dista = (coupler1.Coupler.Position-tg.Position).magnitude
		local distb = (coupler2.Coupler.Position-tg.Position).magnitude
		front = dista < distb and coupler1 or coupler2
		rear = dista < distb and coupler2 or coupler1
	elseif not coupler2 then
		front = coupler1
	end
	return front,rear
end

function updatewheels()
	for _,k in pairs (Seats) do
		k.MaxSpeed = Throttle*MAXIMUMSPEED
		k.Torque = TORQUE
		if ((k.CFrame*CFrame.new(0,0,3)).p-Front.CFrame.p).magnitude >((k.CFrame*CFrame.new(0,0,-3)).p-Front.CFrame.p).magnitude then
			k.Throttle = Reverser
		else
			k.Throttle = -Reverser
		end
	end
end
