I extracted this out to a top-level function since it was a bit hard for me to follow in its nested form. I can put it back if there is an objection to doing this, though.