factor out duplicate code