UPDATE: Tidied code and comments