I've been taking a look at this as well and came up with a slightly
different approach. The attached patch is intended to go in core (not
contrib) and uses some array-construction facilities that already
exist in core. I'm not sure which approach is better, so I'll throw
this out there with yours for input...
...Robert