[Bug 1874] improved query methodology, closed some security holes and
added some error/sanity checking.  Also now sorts the final list.