Fix for the loop to end properly