Rather large refactoring