Refactored a bit and added a couple of comments for clarity.