This method is getting pretty long. It would benefit from breaking up a bit into specific methods that do a few small things. Would make the code more readable because you can express the 'flow' of things in method calls, and put the dirty implementations in the methods.