Tidy up and add comments to selection code.