Moved the channel selection code to its own module, added unit tests, and made some small improvements. Most of the code lines changed are adding unit tests.
Progress on #1602.