More robust query algorithm