Several refactorings

This simplifies the code a lot.