Various tidying up and refactoring.