There is a lot of complexity in this method. Extracting functionality into small, well-named private methods would make this a lot easier to read.