The nesting is a bit deep here!  It would probably be beneficial to the readability of the code to break this implementation down into functions to better describe what's happening.