First implementation of the optimization. Still a few things to do to have a nice
performance.