changed each loop into a while loop