Refactor loop code