Another huge refactoring.

This time the code has been reorganized so we have less duplicates.