Code refactoring and added tests