This method is pretty complex.  It may make sense to extract some functionality into separate methods.