Expanded replacement and extension of the optim function
