Missing docstring. I would add both a docstring and a comment explaining the workflow in this very long function.