More refactoring and code tidying