Query optimizations

Last big pull request to finish everything up. All the features should be working, let me know if I missed anything.