Massive refactoring; untested