Tidied code and added detailed comments