inner loop updating wrong accumulating variable