Fix tests, refactor some small pieces