Improved a loop so it can exit sooner.