Changed .each to while loop