refactoring logic for faster performance