refactor some looping logic