Fixed a typecast issue and added comments to clarify what functions did.