Fix some bugs in the optimizer