updated loop logic