More unit tests and minor refactoring