Added the building of the query, at least till the joins