major query refactoring to reduce code and support no media/date queries (#016)