changed a .each loop to while loop