New maximization function, plus refactoring