If you put the optimize in the else block it won't work as you have to call optimize at every run call, you are not allowed to skip any.
That's what this error is about.
You have to do the optimize calls before the if-else block.