Refactored query rewriter to better handle edge cases.