Some serious refactoring