add toposort, use numerical indices, and fix cycle detection