Refactored code, added in comments