More cleanup, more unit tests, more refactoring