Refactored code. Added comments.