This is extremely hard to do, which is presumably why this algorithm never had any unit tests in the first place.