Move some shared logic to functions

Pulled from #1116