Added unit tests, minor refactoring