Fix some issues with matching

This change improves the match process. It's still not perfect and there are
some edge cases that need fixing.