Tidied up search algorithm