Changed from for loop to while loop