refactor while loop into function