Refactor search.

Fixes #493
Fixes #536
Merge pull request #622 from jcushman/dev-search

Refactor search.