Refactor loops to something more sensible