I've added some comments to the code to describe what's being done in each part.