MAINT: move redundant code into a function