Refactoring and query improvements