This method is very long and difficult to follow. I think it would be a good idea to split it out into more than one method, with each piece of it handling smaller units of work.