Massive refactoring / merging. Untested + likely broken.