Wide-reaching fixes, tests, refactor