refactor while loop logic