massive tidy up and refactoring