Implements much of #32 (relationship handling).

There's a lot of work here, and I'm not sure it yet coveres
everything that's needed in #32, but it seems to be working,
and I'm starting to go crazy from looking at code. ;)