Reorganize hierarchy, add unit tests, and refactor query printing