Rewrote the query function to be closed form.