refactoring for better architecture of selection code
todo: check that we don't have any memory leaks