Code refactoring and some tests