This is a pretty large method. I'd try to extract several methods out of this to make things more readable.