ported from tquery
more work