Nearly there
This post actually spans two days: I decided to work on Saturday to move forward with this optimisation that was really starting to annoy me. Everything is in place now. I have to add a couple of extra helper functions, but this isn't much: the new optimisation for selection is nearly finished. I must say, it looks better than I thought it would. The code is conceptually pretty nice, and much shorter than before. Then also, I have ended up rewriting more or less the entire algorithm, so one would expect it to be better.