This function is also really long (~167 lines). Can you break it up into smaller pieces? This should also simplify unit testing, since you'll be able to separately test each of the pieces.