Factor out lots of common code into a function.