Factoring out minimize code to separate function

In preparation for adding gradient free part.