added comments explaining complex logic