Some code cleanup. Separated out some frequently-used code chunks into a function.