Refactoring galore

This is actually a sub-optimal refactoring, because filter and query can be placed inside internal, thus simplifying api.h.

However, the regression caused is crazy if I do that.
Uh, this is a mistake, I'll revert it back.