Several refactorings

This simplifies the code a lot.

As to benchmarks, I didn't observe any significant difference, and I tested each of these patches individually.