Move some shared logic to functions

Pulled from #1116
This function is over-indented.