while we are at it, replace nested for loops with a while loop