Some refactoring of code and tests