Optimize of search and some refactoring