Pull some code out into functions to make rearranging them a bit easier.