I checked but it seems well. A point is that I remove a single optimize parameter and it seems to work.

I remove the following:
delay = optimize(4, 1, 9, 1);