local function N(N)local x=N._waypoints[N._currentWaypoint-1]local o=N._waypoints[N._currentWaypoint]N._events.WaypointReached:Fire(N._agent,x,o)end local function x(x,o)if not getmetatable(x)then return end if not x._humanoid then if o and x._currentWaypoint+1<=#x._waypoints then N(x)x._currentWaypoint+=1 elseif o then x._visualWaypoints=destroyVisualWaypoints(x._visualWaypoints)x._target=nil x._events.Reached:Fire(x._agent,x._waypoints[x._currentWaypoint])else x._visualWaypoints=destroyVisualWaypoints(x._visualWaypoints)x._target=nil declareError(x,x.ErrorType.TargetUnreachable)end return end if o and x._currentWaypoint+1<=#x._waypoints then if x._currentWaypoint+1<#x._waypoints then N(x)end x._currentWaypoint+=1 move(x)elseif o then disconnectMoveConnection(x)x._status=Path.StatusType.Idle x._visualWaypoints=destroyVisualWaypoints(x._visualWaypoints)x._events.Reached:Fire(x._agent,x._waypoints[x._currentWaypoint])else disconnectMoveConnection(x)x._status=Path.StatusType.Idle x._visualWaypoints=destroyVisualWaypoints(x._visualWaypoints)declareError(x,x.ErrorType.TargetUnreachable)end end

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
