adding query logic and cleanup