unit tests and some refactoring