Refactor code- use while loop, fix bug when filter