Refactored and documented some code related to selection handling