Reorganize query generation

It still looks bad, tho :/