I think you could extract a few small methods here and make this method substantially easier to read.