This is a well-tested function. The logic is quite cryptic but it works properly. I made a set of test-cases and ran them, and fixed each one that broke until everything worked correctly. GG2 should have some unit tests :P