local function L(L)local C=L._waypoints[L._currentWaypoint-1]local u=L._waypoints[L._currentWaypoint]L._events.WaypointReached:Fire(L._agent,C,u)end local function C(C,u)if not C._humanoid then if u and C._currentWaypoint+1<=#C._waypoints then L(C)C._currentWaypoint+=1 elseif u then C._visualWaypoints=destroyVisualWaypoints(C._visualWaypoints)C._target=nil C._events.Reached:Fire(C._agent,C._waypoints[C._currentWaypoint])else C._visualWaypoints=destroyVisualWaypoints(C._visualWaypoints)C._target=nil declareError(C,C.ErrorType.TargetUnreachable)end return end if u and C._currentWaypoint+1<=#C._waypoints then L(C)C._currentWaypoint+=1 move(C)elseif u then disconnectMoveConnection(C)C._status=Path.StatusType.Idle C._visualWaypoints=destroyVisualWaypoints(C._visualWaypoints)C._events.Reached:Fire(C._agent,C._waypoints[C._currentWaypoint])else disconnectMoveConnection(C)C._status=Path.StatusType.Idle C._visualWaypoints=destroyVisualWaypoints(C._visualWaypoints)declareError(C,C.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)
	
	--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
		invokeWaypointReached(self)
		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
