segmentation and some refactoring