Some refactoring and tests