Is it possible to refactor some of the functionality outside of this loop into multiple smaller methods?

Currently it's really dense and hard to read / follow.