Refactor and fix tests