Factor out common code, finishing touches before PR