added search close algorythm
Generalized the function to fix direction if index out of bounds