Improved code and added comments