Lines 113-117 are repeats. Factor out a function.