refactor loop logic