Well, let's just say I tried, and tried, and tried even more. What I wrote at least works fine for all the tests I've done, but if anyone has a better idea I'd be very glad to learn.