Massive fixes to the optimization process. This fixes #9 and #16