fix loop bugs