Re-adding optimization and fixing issue #335.