Fix tests and refactor