Merge anthm's while loop code (thanks tony!) (bug #2907)