refactored code and added commenting