Moved optimization code into its own class.