Factoring out filtering logic from the main loop