added comments to complicated and confusing code