improved filter and sort logic