Horribly large commit of mysterious but necessary fixes and refactors.