used a central function for building the query

The query building used a lot of redundant code for parameters based on the config. I introduced a function that takes care of this which makes the code cleaner and more readable.