Refactoring and fix tests