refactored if to while statement