Changed isolated for loops to while loops (based on a patch by Andreas