Refactor, clean up and generally make code tidier