Unless there is a reason that I didn't see, this should be factored out in unmask(). Both unmask_3d() and unmask_nd() are private functions that are not subject to the same constraint as unmask() itself. The call to check_niimgs() should be factored out too.