Various fixes and improvements to the optimizer