Completely rewrote the query algorithm