I'm pretty sure this code actually works.  It's agonizingly slow, but I'm sincerely not sure there's a non-slow way to reorganize this data, given how much of it there is.
I shall let it run all night, and post the output on dropbox so nobody else has to go through this.