refactored to make selector handling more robust