It's easy to see why you felt the need for a lot of inline comments, this function is too big. You should refactor this into smaller functions. Make them private, or public where it makes sense, and give them their own documentation. These functions should be "in-out style" taking some data, manipulating it, and returning something else. Avoid using shared state between two functions if possible.