Factor out into smaller methods

Still a bit of a dog's breakfast, though