Changed for loop to while loop