Refactor filtering logic