Major refactoring all around