This function is very long. You have already structured code with comments, what each part is doing. Perhaps you should split this logic to several functions and call them here?