replaced a potentially problematic while loop