MAINT: move more code into separate functions to prevent code duplication in the immediate future