Refactor filtering code