convert for each loop to more efficient while loop