Rewritten while loop so it's more readable