Modified buildQuery function