Oof.  41 lines of conditional below... this implies that the two code paths are different enough that they probably shouldn't be in the same place.  I haven't looked through this too carefully, but perhaps it makes sense to abstract some of this out and put it behind APIs?