Some refactoring and extra tests