Moves the copy/pasted code into a function.