Added unit tests, more refactoring, and some minor cleanup of code.