Refactor unwieldy filter function.