Moved query out into it's own library. Fix some bugs.