many fixes and improvements on query