def url_parse_query (query, encoding=None):
    """Parse and re-join the given CGI query."""
    if isinstance(query, unicode):
        if encoding is None:
            encoding = url_encoding
        query = query.encode(encoding, 'ignore')
    # if ? is in the query, split it off, seen at msdn.microsoft.com
    append = ""
    while '?' in query:
        query, rest = query.rsplit('?', 1)
        append = '?'+url_parse_query(rest)+append
    l = []
    for k, v, sep in parse_qsl(query, keep_blank_values=True):
        k = url_quote_part(k, '/-:,;')
        if v:
            v = url_quote_part(v, '/-:,;')
            l.append("%s=%s%s" % (k, v, sep))
        elif v is None:
            l.append("%s%s" % (k, sep))
        else:
            # some sites do not work when the equal sign is missing
            l.append("%s=%s" % (k, sep))
    return ''.join(l) + append