Fix an optimization bug (went into an infinite loop in some circumstances)