Almost finished selection algorithm. Still needs some debugging.