Fix bugs introduced recently in optimizations.
I should really add unit tests.