Refactored code so that the loop happens elsewhere.