Refactor and fix failing tests