There is a lot going on in this function. If we are going to keep unit-tests sane/maintainable, we should attempt to break this down into smaller, more testable chunks.