Skip non-matching avg paths and fix a sorting bug.

Also comment the bejesus out of this complicated function!