fixed the loop termination (thanks to Gyorgy Kalmar)