Minor refactoring plus test improvements