Refactor all this repeated code into a function or a loop.