Some refactoring and tidying up code