This only lead to a contributed file, this is neither robust nor fast. But maybe throwing the existing code into a contrib file will make someone come up with an idea.