some refactoring to make function smaller