Added comments to explain why some things are done that way, and changed
the logic in some places to be easier to follow.