Refactored code, added comments.