Query modularization and cleanup