Refactored for simplicity. Added comments.