Well, this code still makes my brain hurt, but the patch looks fine to me :-)