tidied code and refactored