the real code now, from my old hg repo.
I'm sparing you from the commit history :)