Improved SMW query code.

Change-Id: I6f6cf305378cbb95401592db0e90f034ab001b56