Huge refactor and cleanup. Untested