some refactoring to reduce code complexity and duplication