Implementing query filtering, some code cleanup