This function was already rather long, and this PR adds a lot to it.  Perhaps it can be refactored to be several smaller functions?