Implement unit test and some refactoring