Fixed bug where search wouldn't wrap all the way around; refactoring and clean up