much more robust query re-writing