mostly-complete refactor. Testing tomorrow.