Refactoring, add unit tests