refactor search stack logic to be way safer in a proper module