Control variable of loop should be absolute value to avoid looping when backtracking
Add a testing option Add a script with tests Some simplifications of the logic