Refactor serveral duplicate loops into a method

Nothing major here, just a bit of code tidy. I found myself in this file and all the duplicate loops were screaming at me.