Bugfix to handle query strings correctly

I just pulled in some code from elsewhere that I believe you wrote originally anyway. :)