Refactored code and added more comments