Adjust logic to be a bit clearer, and add comments.