General refactoring and tidying up