added comments to further explain how the code works