Move some shared logic to functions

Pulled from #1116
Okay, I can easily make that change tomorrow morning.