Big old refactor.

Mostly works. Still a few broken things to fix