Huge code refactoring