Fixed couple bugs in query, and improved logic of querylib.