Added some comments to explain the code. Hope it helps.