Fix a few optimization bugs