rewrote and generalized search algorithm