some refactoring to minimize code duplication