Merge the common code into a function.