Refined/debugged optimization code.