Refactor search.

Fixes #493
Fixes #536