Fixed bug in loop handling