Refactor js structure to match python

The two files still differ but they are at least similarly structured.
Also, it is now easier to find the main code path.

This is certainly not a best or final design, just a sufficient one.