Refactoring and tests improved