Move some shared logic to functions

Pulled from #1116
Worst function migration ever.