refactorize the logic for auto range detection