Fix remaining broken tests; some refactoring.