local function v(v)local U=v._waypoints[v._currentWaypoint-1]local L=v._waypoints[v._currentWaypoint]v._events.WaypointReached:Fire(v._agent,U,L)end local function U(U,L)if not getmetatable(U)then return end if not U._humanoid then if L and U._currentWaypoint+1<=#U._waypoints then v(U)U._currentWaypoint+=1 elseif L then U._visualWaypoints=destroyVisualWaypoints(U._visualWaypoints)U._target=nil U._events.Reached:Fire(U._agent,U._waypoints[U._currentWaypoint])else U._visualWaypoints=destroyVisualWaypoints(U._visualWaypoints)U._target=nil declareError(U,U.ErrorType.TargetUnreachable)end return end if L and U._currentWaypoint+1<=#U._waypoints then if U._currentWaypoint+1<#U._waypoints then v(U)end U._currentWaypoint+=1 move(U)elseif L then disconnectMoveConnection(U)U._status=Path.StatusType.Idle U._visualWaypoints=destroyVisualWaypoints(U._visualWaypoints)U._events.Reached:Fire(U._agent,U._waypoints[U._currentWaypoint])else disconnectMoveConnection(U)U._status=Path.StatusType.Idle U._visualWaypoints=destroyVisualWaypoints(U._visualWaypoints)declareError(U,U.ErrorType.TargetUnreachable)end end
--Fire the WaypointReached event
local function invokeWaypointReached(self)
	local lastWaypoint = self._waypoints[self._currentWaypoint - 1]
	local nextWaypoint = self._waypoints[self._currentWaypoint]
	self._events.WaypointReached:Fire(self._agent, lastWaypoint, nextWaypoint)
end

local function moveToFinished(self, reached)
	--Stop execution if Path is destroyed
	if not getmetatable(self) then
		return
	end

	--Handle case for non-humanoids
	if not self._humanoid then
		if reached and self._currentWaypoint + 1 <= #self._waypoints then
			invokeWaypointReached(self)
			self._currentWaypoint += 1
		elseif reached then
			self._visualWaypoints = destroyVisualWaypoints(self._visualWaypoints)
			self._target = nil
			self._events.Reached:Fire(self._agent, self._waypoints[self._currentWaypoint])
		else
			self._visualWaypoints = destroyVisualWaypoints(self._visualWaypoints)
			self._target = nil
			declareError(self, self.ErrorType.TargetUnreachable)
		end
		return
	end

	if reached and self._currentWaypoint + 1 <= #self._waypoints then --Waypoint reached
		if self._currentWaypoint + 1 < #self._waypoints then
			invokeWaypointReached(self)
		end
		self._currentWaypoint += 1
		move(self)
	elseif reached then --Target reached, pathfinding ends
		disconnectMoveConnection(self)
		self._status = Path.StatusType.Idle
		self._visualWaypoints = destroyVisualWaypoints(self._visualWaypoints)
		self._events.Reached:Fire(self._agent, self._waypoints[self._currentWaypoint])
	else --Target unreachable
		disconnectMoveConnection(self)
		self._status = Path.StatusType.Idle
		self._visualWaypoints = destroyVisualWaypoints(self._visualWaypoints)
		declareError(self, self.ErrorType.TargetUnreachable)
	end
end
