Optimized channel-switching algorithm speed.
Moved shared code to separate file.