More unit tests, refactoring, and bug fixes