This was really tricky, so I'd appreciate some in-depth code review in this area. As I said, the general logic is fairly complex and non-trivial, but there are a few cases that are a) far more common and b) implementable with far-simpler logic. Personally, I think the additional amount of code is worth it.