Code tidyup and fixing broken tests.