Some extra refactoring of tests, cleanup and misc fixes