The JS works! Included a dummy html file that will run the js in your browser's console (F12). It's a mess, will add comments tomorrow and tidy it up
If you want to try and replicate a very strange scope problem, find the iterator j and change it to i. At one point in my program execution this iterator seemed to have scope after the function it was in closed.