better loop logic