refactor while loop