refactored while loop