Refactor scope detection.