Switched to optim function rather than manual optimization