Refactor and tests