refactor some code into a loop