Refactor, fix tests