Factor out some duplicated code