Now that I see it more in detail, we should move the searching bit of the code into it's own method which can be called from this function, but would make it easier to replace it.