I just read a similar solution on this thread. It dealt with sorting, but maybe the logic can help your search. Post number 14.