Refactored code and added code comments