Tidied code and added comments