some refactoring and tidying