I've created a proper UDF out of my code, and added Allen's proper way of filtering.