Here's an improved version of my patch. It's functionally equivalent but with more comprehensible code and more comments. I think this is ready to push to the stable-2.2 branch. Comments and suggestions welcome. Mark