Replaced hard-coded for loop with more flexible while loop