rewritten to use a while loop