Better xref query. Some refactoring on scanning and errors