added better loop handling