Fix tests, refactor and clean some things up.