SOLVED: the variable $i is used in several places in an ambiguous way, a...

... change of variable used in cycle $i for $j is made.