--------------------[ EXTERNAL DATA LOCATING FUNCTIONS ]-----------------------------


function FindFirstClass(Object, Class)
	local FoundObject = nil
	for _, Obj in pairs(Object:GetChildren()) do
		if Obj.ClassName == Class then
			FoundObject = Obj
			break
		end
	end
	return FoundObject
end

function IsIgnored(Obj)
	for _,v in pairs(Ignore) do
		if Obj == v or Obj:IsDescendantOf(v) then
			return true
		end
	end
	return false
end

function GetHitSurfaceCFrame(HitPos,Obj)
	local SurfaceCF = {
		{"Back",Obj.CFrame * CF(0,0,Obj.Size.z)};
		{"Bottom",Obj.CFrame * CF(0,-Obj.Size.y,0)};
		{"Front",Obj.CFrame * CF(0,0,-Obj.Size.z)};
		{"Left",Obj.CFrame * CF(-Obj.Size.x,0,0)};
		{"Right",Obj.CFrame * CF(Obj.Size.x,0,0)};
		{"Top",Obj.CFrame * CF(0,Obj.Size.y,0)}
	}
	local ClosestDist = HUGE
	local ClosestSurface = nil
	for _,v in pairs(SurfaceCF) do
		local SurfaceDist = (HitPos - v[2].p).magnitude
		if SurfaceDist < ClosestDist then
			ClosestDist = SurfaceDist
			ClosestSurface = v
		end
	end
	return ClosestSurface[2]
end

function AdvRayCast(Origin, Direction, Dist, CustomIgnore)
	local NewIgnore = (CustomIgnore and CustomIgnore or Ignore)
	local NewRay = Ray.new(Origin, Direction * (Dist > 999 and 999 or Dist))
	local HitObj, HitPos = game.Workspace:FindPartOnRayWithIgnoreList(NewRay, NewIgnore)
	local LastPos = HitPos
	local FinalHitObj, FinalHitPos = nil, nil
	local RepTimes = math.floor(Dist / 999)
	if (not HitObj) and (Dist > 999) then
		for i = 0, RepTimes do
			local NewDist = (i == RepTimes and  (Dist - (LastPos - Origin).magnitude) or 999)
			local Ray2 = Ray.new(LastPos, Direction * NewDist)
			local HitObj2, HitPos2 = game.Workspace:FindPartOnRayWithIgnoreList(Ray2, NewIgnore)
			if i ~= RepTimes then
				if HitObj2 then
					FinalHitObj, FinalHitPos = HitObj2, HitPos2
					break
				end
			elseif i == RepTimes then
				FinalHitObj, FinalHitPos = HitObj2, HitPos2
			end
			LastPos = HitPos2
		end
		return FinalHitObj, FinalHitPos
	elseif HitObj or (Dist <= 999) then
		return HitObj, HitPos
	end
end
