Large but spotty refactoring

Let's hope it all works