Improvements to filtering. Fixes #486 and #431