Refactor the query function

More sophisticated queries are now possible, as they can be nested.