Refactoring and tests
Refactoring, polish and tests