Replaced nested MAX/MIN with function calls to avoid Hidden Local Variable warnings