fix loop error logic