Checking again the code, I really misunderstood the loop stopping condition and indeed I committed that error. Apologies.