Made some minor changes and added some comments to make this code clearer.