Sync with trunk r63174.
[reactos.git] / dll / win32 / urlmon / uri.c
index 2aee38a..052af22 100644 (file)
  */
 
 #include "urlmon_main.h"
-#include "wine/debug.h"
 
-#define NO_SHLWAPI_REG
-#include "shlwapi.h"
+#include <strsafe.h>
 
-#define UINT_MAX 0xffffffff
-#define USHORT_MAX 0xffff
+#define URI_DISPLAY_NO_ABSOLUTE_URI         0x1
+#define URI_DISPLAY_NO_DEFAULT_PORT_AUTH    0x2
 
 #define ALLOW_NULL_TERM_SCHEME          0x01
 #define ALLOW_NULL_TERM_USER_NAME       0x02
 #define SKIP_IP_FUTURE_CHECK            0x10
 #define IGNORE_PORT_DELIMITER           0x20
 
-WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
+#define RAW_URI_FORCE_PORT_DISP     0x1
+#define RAW_URI_CONVERT_TO_DOS_PATH 0x2
+
+#define COMBINE_URI_FORCE_FLAG_USE  0x1
 
 static const IID IID_IUriObj = {0x4b364760,0x9f51,0x11df,{0x98,0x1c,0x08,0x00,0x20,0x0c,0x9a,0x66}};
 
 typedef struct {
-    const IUriVtbl  *lpIUriVtbl;
+    IUri                IUri_iface;
+    IUriBuilderFactory  IUriBuilderFactory_iface;
+    IPersistStream      IPersistStream_iface;
+    IMarshal            IMarshal_iface;
+
     LONG ref;
 
     BSTR            raw_uri;
@@ -47,7 +52,7 @@ typedef struct {
     WCHAR           *canon_uri;
     DWORD           canon_size;
     DWORD           canon_len;
-    BOOL            display_absolute;
+    BOOL            display_modifiers;
     DWORD           create_flags;
 
     INT             scheme_start;
@@ -62,7 +67,8 @@ typedef struct {
     DWORD           host_len;
     Uri_HOST_TYPE   host_type;
 
-    USHORT          port;
+    INT             port_offset;
+    DWORD           port;
     BOOL            has_port;
 
     INT             authority_start;
@@ -82,7 +88,7 @@ typedef struct {
 } Uri;
 
 typedef struct {
-    const IUriBuilderVtbl  *lpIUriBuilderVtbl;
+    IUriBuilder IUriBuilder_iface;
     LONG ref;
 
     Uri *uri;
@@ -142,6 +148,7 @@ typedef struct {
     BOOL            has_implicit_scheme;
     BOOL            has_implicit_ip;
     UINT            implicit_ipv4;
+    BOOL            must_have_path;
 
     const WCHAR     *scheme;
     DWORD           scheme_len;
@@ -220,7 +227,7 @@ static const struct {
     {URL_SCHEME_HTTPS,  443},
 };
 
-/* List of 3 character top level domain names Windows seems to recognize.
+/* List of 3-character top level domain names Windows seems to recognize.
  * There might be more, but, these are the only ones I've found so far.
  */
 static const struct {
@@ -245,11 +252,11 @@ static Uri *get_uri_obj(IUri *uri)
 }
 
 static inline BOOL is_alpha(WCHAR val) {
-       return ((val >= 'a' && val <= 'z') || (val >= 'A' && val <= 'Z'));
+    return ((val >= 'a' && val <= 'z') || (val >= 'A' && val <= 'Z'));
 }
 
 static inline BOOL is_num(WCHAR val) {
-       return (val >= '0' && val <= '9');
+    return (val >= '0' && val <= '9');
 }
 
 static inline BOOL is_drive_path(const WCHAR *str) {
@@ -257,7 +264,7 @@ static inline BOOL is_drive_path(const WCHAR *str) {
 }
 
 static inline BOOL is_unc_path(const WCHAR *str) {
-    return (str[0] == '\\' && str[0] == '\\');
+    return (str[0] == '\\' && str[1] == '\\');
 }
 
 static inline BOOL is_forbidden_dos_path_char(WCHAR val) {
@@ -265,7 +272,7 @@ static inline BOOL is_forbidden_dos_path_char(WCHAR val) {
 }
 
 /* A URI is implicitly a file path if it begins with
- * a drive letter (eg X:) or starts with "\\" (UNC path).
+ * a drive letter (e.g. X:) or starts with "\\" (UNC path).
  */
 static inline BOOL is_implicit_file_path(const WCHAR *str) {
     return (is_unc_path(str) || (is_alpha(str[0]) && str[1] == ':'));
@@ -315,7 +322,7 @@ static inline BOOL is_gendelim(WCHAR val) {
 
 /* Characters that delimit the end of the authority
  * section of a URI. Sometimes a '\\' is considered
- * an authority delimeter.
+ * an authority delimiter.
  */
 static inline BOOL is_auth_delim(WCHAR val, BOOL acceptSlash) {
     return (val == '#' || val == '/' || val == '?' ||
@@ -337,6 +344,22 @@ static inline BOOL is_path_delim(WCHAR val) {
     return (!val || val == '#' || val == '?');
 }
 
+static inline BOOL is_slash(WCHAR c)
+{
+    return c == '/' || c == '\\';
+}
+
+static BOOL is_default_port(URL_SCHEME scheme, DWORD port) {
+    DWORD i;
+
+    for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
+        if(default_ports[i].scheme == scheme && default_ports[i].port)
+            return TRUE;
+    }
+
+    return FALSE;
+}
+
 /* List of schemes types Windows seems to expect to be hierarchical. */
 static inline BOOL is_hierarchical_scheme(URL_SCHEME type) {
     return(type == URL_SCHEME_HTTP || type == URL_SCHEME_FTP ||
@@ -374,12 +397,12 @@ static void apply_default_flags(DWORD *flags) {
 /* Determines if the URI is hierarchical using the information already parsed into
  * data and using the current location of parsing in the URI string.
  *
- * Windows considers a URI hierarchical if on of the following is true:
+ * Windows considers a URI hierarchical if one of the following is true:
  *  A.) It's a wildcard scheme.
  *  B.) It's an implicit file scheme.
  *  C.) It's a known hierarchical scheme and it has two '\\' after the scheme name.
  *      (the '\\' will be converted into "//" during canonicalization).
- *  D.) It's not a relative URI and "//" appears after the scheme name.
+ *  D.) "//" appears after the scheme name (or at the beginning if no scheme is given).
  */
 static inline BOOL is_hierarchical_uri(const WCHAR **ptr, const parse_data *data) {
     const WCHAR *start = *ptr;
@@ -391,114 +414,16 @@ static inline BOOL is_hierarchical_uri(const WCHAR **ptr, const parse_data *data
     else if(is_hierarchical_scheme(data->scheme_type) && (*ptr)[0] == '\\' && (*ptr)[1] == '\\') {
         *ptr += 2;
         return TRUE;
-    } else if(!data->is_relative && check_hierarchical(ptr))
+    } else if(data->scheme_type != URL_SCHEME_MAILTO && check_hierarchical(ptr))
         return TRUE;
 
     *ptr = start;
     return FALSE;
 }
 
-/* Checks if the two Uri's are logically equivalent. It's a simple
- * comparison, since they are both of type Uri, and it can access
- * the properties of each Uri directly without the need to go
- * through the "IUri_Get*" interface calls.
- */
-static BOOL are_equal_simple(const Uri *a, const Uri *b) {
-    if(a->scheme_type == b->scheme_type) {
-        const BOOL known_scheme = a->scheme_type != URL_SCHEME_UNKNOWN;
-        const BOOL are_hierarchical =
-                (a->authority_start > -1 && b->authority_start > -1);
-
-        if(a->scheme_type == URL_SCHEME_FILE) {
-            if(a->canon_len == b->canon_len)
-                return !StrCmpIW(a->canon_uri, b->canon_uri);
-        }
-
-        /* Only compare the scheme names (if any) if their unknown scheme types. */
-        if(!known_scheme) {
-            if((a->scheme_start > -1 && b->scheme_start > -1) &&
-               (a->scheme_len == b->scheme_len)) {
-                /* Make sure the schemes are the same. */
-                if(StrCmpNW(a->canon_uri+a->scheme_start, b->canon_uri+b->scheme_start, a->scheme_len))
-                    return FALSE;
-            } else if(a->scheme_len != b->scheme_len)
-                /* One of the Uri's has a scheme name, while the other doesn't. */
-                return FALSE;
-        }
-
-        /* If they have a userinfo component, perform case sensitive compare. */
-        if((a->userinfo_start > -1 && b->userinfo_start > -1) &&
-           (a->userinfo_len == b->userinfo_len)) {
-            if(StrCmpNW(a->canon_uri+a->userinfo_start, b->canon_uri+b->userinfo_start, a->userinfo_len))
-                return FALSE;
-        } else if(a->userinfo_len != b->userinfo_len)
-            /* One of the Uri's had a userinfo, while the other one doesn't. */
-            return FALSE;
-
-        /* Check if they have a host name. */
-        if((a->host_start > -1 && b->host_start > -1) &&
-           (a->host_len == b->host_len)) {
-            /* Perform a case insensitive compare if they are a known scheme type. */
-            if(known_scheme) {
-                if(StrCmpNIW(a->canon_uri+a->host_start, b->canon_uri+b->host_start, a->host_len))
-                    return FALSE;
-            } else if(StrCmpNW(a->canon_uri+a->host_start, b->canon_uri+b->host_start, a->host_len))
-                return FALSE;
-        } else if(a->host_len != b->host_len)
-            /* One of the Uri's had a host, while the other one didn't. */
-            return FALSE;
-
-        if(a->has_port && b->has_port) {
-            if(a->port != b->port)
-                return FALSE;
-        } else if(a->has_port || b->has_port)
-            /* One had a port, while the other one didn't. */
-            return FALSE;
-
-        /* Windows is weird with how it handles paths. For example
-         * One URI could be "http://google.com" (after canonicalization)
-         * and one could be "http://google.com/" and the IsEqual function
-         * would still evaluate to TRUE, but, only if they are both hierarchical
-         * URIs.
-         */
-        if((a->path_start > -1 && b->path_start > -1) &&
-           (a->path_len == b->path_len)) {
-            if(StrCmpNW(a->canon_uri+a->path_start, b->canon_uri+b->path_start, a->path_len))
-                return FALSE;
-        } else if(are_hierarchical && a->path_len == -1 && b->path_len == 0) {
-            if(*(a->canon_uri+a->path_start) != '/')
-                return FALSE;
-        } else if(are_hierarchical && b->path_len == 1 && a->path_len == 0) {
-            if(*(b->canon_uri+b->path_start) != '/')
-                return FALSE;
-        } else if(a->path_len != b->path_len)
-            return FALSE;
-
-        /* Compare the query strings of the two URIs. */
-        if((a->query_start > -1 && b->query_start > -1) &&
-           (a->query_len == b->query_len)) {
-            if(StrCmpNW(a->canon_uri+a->query_start, b->canon_uri+b->query_start, a->query_len))
-                return FALSE;
-        } else if(a->query_len != b->query_len)
-            return FALSE;
-
-        if((a->fragment_start > -1 && b->fragment_start > -1) &&
-           (a->fragment_len == b->fragment_len)) {
-            if(StrCmpNW(a->canon_uri+a->fragment_start, b->canon_uri+b->fragment_start, a->fragment_len))
-                return FALSE;
-        } else if(a->fragment_len != b->fragment_len)
-            return FALSE;
-
-        /* If we get here, the two URIs are equivalent. */
-        return TRUE;
-    }
-
-    return FALSE;
-}
-
 /* Computes the size of the given IPv6 address.
- * Each h16 component is 16bits, if there is an IPv4 address, it's
- * 32bits. If there's an elision it can be 16bits to 128bits, depending
+ * Each h16 component is 16 bits. If there is an IPv4 address, it's
+ * 32 bits. If there's an elision it can be 16 to 128 bits, depending
  * on the number of other components.
  *
  * Modeled after google-url's CheckIPv6ComponentsSize function
@@ -512,7 +437,7 @@ static void compute_ipv6_comps_size(ipv6_address *address) {
 
     if(address->elision) {
         /* An elision can be anywhere from 2 bytes up to 16 bytes.
-         * It size depends on the size of the h16 and IPv4 components.
+         * Its size depends on the size of the h16 and IPv4 components.
          */
         address->elision_size = 16 - address->components_size;
         if(address->elision_size < 2)
@@ -538,7 +463,7 @@ static int hex_to_int(WCHAR val) {
  * the two characters following the '%' aren't valid hex values then
  * this function returns the NULL character.
  *
- * Eg.
+ * E.g.
  *  "%2E" will result in '.' being returned by this function.
  */
 static WCHAR decode_pct_val(const WCHAR *ptr) {
@@ -568,21 +493,6 @@ static inline void pct_encode_val(WCHAR val, WCHAR *dest) {
     dest[2] = hexDigits[val & 0xf];
 }
 
-/* Scans the range of characters [str, end] and returns the last occurrence
- * of 'ch' or returns NULL.
- */
-static const WCHAR *str_last_of(const WCHAR *str, const WCHAR *end, WCHAR ch) {
-    const WCHAR *ptr = end;
-
-    while(ptr >= str) {
-        if(*ptr == ch)
-            return ptr;
-        --ptr;
-    }
-
-    return NULL;
-}
-
 /* Attempts to parse the domain name from the host.
  *
  * This function also includes the Top-level Domain (TLD) name
@@ -590,10 +500,10 @@ static const WCHAR *str_last_of(const WCHAR *str, const WCHAR *end, WCHAR ch) {
  * a valid domain name it will assign 'domain_start' the offset
  * into 'host' where the domain name starts.
  *
- * It's implied that if a domain name its range is implied to be
+ * It's implied that if there is a domain name its range is:
  * [host+domain_start, host+host_len).
  */
-static void find_domain_name(const WCHAR *host, DWORD host_len,
+void find_domain_name(const WCHAR *host, DWORD host_len,
                              INT *domain_start) {
     const WCHAR *last_tld, *sec_last_tld, *end;
 
@@ -602,17 +512,17 @@ static void find_domain_name(const WCHAR *host, DWORD host_len,
     *domain_start = -1;
 
     /* There has to be at least enough room for a '.' followed by a
-     * 3 character TLD for a domain to even exist in the host name.
+     * 3-character TLD for a domain to even exist in the host name.
      */
     if(host_len < 4)
         return;
 
-    last_tld = str_last_of(host, end, '.');
+    last_tld = memrchrW(host, '.', host_len);
     if(!last_tld)
         /* http://hostname -> has no domain name. */
         return;
 
-    sec_last_tld = str_last_of(host, last_tld-1, '.');
+    sec_last_tld = memrchrW(host, '.', last_tld-host);
     if(!sec_last_tld) {
         /* If the '.' is at the beginning of the host there
          * has to be at least 3 characters in the TLD for it
@@ -626,7 +536,7 @@ static void find_domain_name(const WCHAR *host, DWORD host_len,
         } else if(last_tld-host == 3) {
             DWORD i;
 
-            /* If there's three characters in front of last_tld and
+            /* If there are three characters in front of last_tld and
              * they are on the list of recognized TLDs, then this
              * host doesn't have a domain (since the host only contains
              * a TLD name.
@@ -656,14 +566,14 @@ static void find_domain_name(const WCHAR *host, DWORD host_len,
         DWORD i;
         /* If the sec_last_tld is 3 characters long it HAS to be on the list of
          * recognized to still be considered part of the TLD name, otherwise
-         * its considered the domain name.
+         * it's considered the domain name.
          *  Ex: www.google.com.uk -> google.com.uk as the domain name.
          *      www.google.foo.uk -> foo.uk as the domain name.
          */
         if(last_tld - (sec_last_tld+1) == 3) {
             for(i = 0; i < sizeof(recognized_tlds)/sizeof(recognized_tlds[0]); ++i) {
                 if(!StrCmpNIW(sec_last_tld+1, recognized_tlds[i].tld_name, 3)) {
-                    const WCHAR *domain = str_last_of(host, sec_last_tld-1, '.');
+                    const WCHAR *domain = memrchrW(host, '.', sec_last_tld-host);
 
                     if(!domain)
                         *domain_start = 0;
@@ -681,7 +591,7 @@ static void find_domain_name(const WCHAR *host, DWORD host_len,
              * part of the TLD.
              *  Ex: www.google.fo.uk -> google.fo.uk as the domain name.
              */
-            const WCHAR *domain = str_last_of(host, sec_last_tld-1, '.');
+            const WCHAR *domain = memrchrW(host, '.', sec_last_tld-host);
 
             if(!domain)
                 *domain_start = 0;
@@ -703,8 +613,6 @@ static void find_domain_name(const WCHAR *host, DWORD host_len,
 /* Removes the dot segments from a hierarchical URIs path component. This
  * function performs the removal in place.
  *
- * This is a modified version of Qt's QUrl function "removeDotsFromPath".
- *
  * This function returns the new length of the path string.
  */
 static DWORD remove_dot_segments(WCHAR *path, DWORD path_len) {
@@ -714,48 +622,46 @@ static DWORD remove_dot_segments(WCHAR *path, DWORD path_len) {
     DWORD len;
 
     while(in < end) {
-        /* A.  if the input buffer begins with a prefix of "/./" or "/.",
-         *     where "." is a complete path segment, then replace that
-         *     prefix with "/" in the input buffer; otherwise,
+        /* Move the first path segment in the input buffer to the end of
+         * the output buffer, and any subsequent characters up to, including
+         * the next "/" character (if any) or the end of the input buffer.
          */
-        if(in <= end - 3 && in[0] == '/' && in[1] == '.' && in[2] == '/') {
-            in += 2;
-            continue;
-        } else if(in == end - 2 && in[0] == '/' && in[1] == '.') {
-            *out++ = '/';
-            in += 2;
+        while(in < end && !is_slash(*in))
+            *out++ = *in++;
+        if(in == end)
             break;
-        }
+        *out++ = *in++;
 
-        /* B.  if the input buffer begins with a prefix of "/../" or "/..",
-         *     where ".." is a complete path segment, then replace that
-         *     prefix with "/" in the input buffer and remove the last
-         *     segment and its preceding "/" (if any) from the output
-         *     buffer; otherwise,
-         */
-        if(in <= end - 4 && in[0] == '/' && in[1] == '.' && in[2] == '.' && in[3] == '/') {
-            while(out > path && *(--out) != '/');
+        while(in < end) {
+            if(*in != '.')
+                break;
 
-            in += 3;
-            continue;
-        } else if(in == end - 3 && in[0] == '/' && in[1] == '.' && in[2] == '.') {
-            while(out > path && *(--out) != '/');
+            /* Handle ending "/." */
+            if(in + 1 == end) {
+                ++in;
+                break;
+            }
 
-            if(*out == '/')
-                ++out;
+            /* Handle "/./" */
+            if(is_slash(in[1])) {
+                in += 2;
+                continue;
+            }
 
-            in += 3;
-            break;
-        }
+            /* If we don't have "/../" or ending "/.." */
+            if(in[1] != '.' || (in + 2 != end && !is_slash(in[2])))
+                break;
 
-        /* C.  move the first path segment in the input buffer to the end of
-         *     the output buffer, including the initial "/" character (if
-         *     any) and any subsequent characters up to, but not including,
-         *     the next "/" character or the end of the input buffer.
-         */
-        *out++ = *in++;
-        while(in < end && *in != '/')
-            *out++ = *in++;
+            /* Find the slash preceding out pointer and move out pointer to it */
+            if(out > path+1 && is_slash(*--out))
+                --out;
+            while(out > path && !is_slash(*(--out)));
+            if(is_slash(*out))
+                ++out;
+            in += 2;
+            if(in != end)
+                ++in;
+        }
     }
 
     len = out - path;
@@ -779,18 +685,18 @@ static INT find_file_extension(const WCHAR *path, DWORD path_len) {
 /* Computes the location where the elision should occur in the IPv6
  * address using the numerical values of each component stored in
  * 'values'. If the address shouldn't contain an elision then 'index'
- * is assigned -1 as it's value. Otherwise 'index' will contain the
+ * is assigned -1 as its value. Otherwise 'index' will contain the
  * starting index (into values) where the elision should be, and 'count'
  * will contain the number of cells the elision covers.
  *
  * NOTES:
- *  Windows will expand an elision if the elision only represents 1 h16
- *  component of the URI.
+ *  Windows will expand an elision if the elision only represents one h16
+ *  component of the address.
  *
  *  Ex: [1::2:3:4:5:6:7] -> [1:0:2:3:4:5:6:7]
  *
  *  If the IPv6 address contains an IPv4 address, the IPv4 address is also
- *  considered for being included as part of an elision if all it's components
+ *  considered for being included as part of an elision if all its components
  *  are zeros.
  *
  *  Ex: [1:2:3:4:5:6:0.0.0.0] -> [1:2:3:4:5:6::]
@@ -847,35 +753,35 @@ static void compute_elision_location(const ipv6_address *address, const USHORT v
  * characters inside of the URI string.
  */
 static BSTR pre_process_uri(LPCWSTR uri) {
-    BSTR ret;
+    const WCHAR *start, *end, *ptr;
+    WCHAR *ptr2;
     DWORD len;
-    const WCHAR *start, *end;
-    WCHAR *buf, *ptr;
-
-    len = lstrlenW(uri);
+    BSTR ret;
 
     start = uri;
     /* Skip leading controls and whitespace. */
-    while(iscntrlW(*start) || isspaceW(*start)) ++start;
+    while(*start && (iscntrlW(*start) || isspaceW(*start))) ++start;
 
-    end = uri+len-1;
-    if(start == end)
-        /* URI consisted only of control/whitespace. */
-        ret = SysAllocStringLen(NULL, 0);
-    else {
-        while(iscntrlW(*end) || isspaceW(*end)) --end;
+    /* URI consisted only of control/whitespace. */
+    if(!*start)
+        return SysAllocStringLen(NULL, 0);
 
-        buf = heap_alloc(((end+1)-start)*sizeof(WCHAR));
-        if(!buf)
-            return NULL;
+    end = start + strlenW(start);
+    while(--end > start && (iscntrlW(*end) || isspaceW(*end)));
 
-        for(ptr = buf; start < end+1; ++start) {
-            if(!iscntrlW(*start))
-                *ptr++ = *start;
-        }
+    len = ++end - start;
+    for(ptr = start; ptr < end; ptr++) {
+        if(iscntrlW(*ptr))
+            len--;
+    }
+
+    ret = SysAllocStringLen(NULL, len);
+    if(!ret)
+        return NULL;
 
-        ret = SysAllocStringLen(buf, ptr-buf);
-        heap_free(buf);
+    for(ptr = start, ptr2=ret; ptr < end; ptr++) {
+        if(!iscntrlW(*ptr))
+            *ptr2++ = *ptr;
     }
 
     return ret;
@@ -905,7 +811,7 @@ static UINT ipv4toui(const WCHAR *ip, DWORD len) {
     return ret;
 }
 
-/* Converts an IPv4 address in numerical form into it's fully qualified
+/* Converts an IPv4 address in numerical form into its fully qualified
  * string form. This function returns the number of characters written
  * to 'dest'. If 'dest' is NULL this function will return the number of
  * characters that would have been written.
@@ -933,7 +839,20 @@ static DWORD ui2ipv4(WCHAR *dest, UINT address) {
     return ret;
 }
 
-/* Converts an h16 component (from an IPv6 address) into it's
+static DWORD ui2str(WCHAR *dest, UINT value) {
+    static const WCHAR formatW[] = {'%','u',0};
+    DWORD ret = 0;
+
+    if(!dest) {
+        WCHAR tmp[11];
+        ret = sprintfW(tmp, formatW, value);
+    } else
+        ret = sprintfW(dest, formatW, value);
+
+    return ret;
+}
+
+/* Converts a h16 component (from an IPv6 address) into its
  * numerical value.
  *
  * This function assumes that the h16 component has already been validated.
@@ -950,7 +869,7 @@ static USHORT h16tous(h16 component) {
     return ret;
 }
 
-/* Converts an IPv6 address into it's 128 bits (16 bytes) numerical value.
+/* Converts an IPv6 address into its 128 bits (16 bytes) numerical value.
  *
  * This function assumes that the ipv6_address has already been validated.
  */
@@ -961,10 +880,10 @@ static BOOL ipv6_to_number(const ipv6_address *address, USHORT number[8]) {
     for(i = 0; i < address->h16_count; ++i) {
         if(address->elision) {
             if(address->components[i].str > address->elision && !already_passed_elision) {
-                /* Means we just passed the elision and need to add it's values to
+                /* Means we just passed the elision and need to add its values to
                  * 'number' before we do anything else.
                  */
-                DWORD j = 0;
+                INT j;
                 for(j = 0; j < address->elision_size; j+=2)
                     number[cur_component++] = 0;
 
@@ -977,9 +896,9 @@ static BOOL ipv6_to_number(const ipv6_address *address, USHORT number[8]) {
 
     /* Case when the elision appears after the h16 components. */
     if(!already_passed_elision && address->elision) {
-        for(i = 0; i < address->elision_size; i+=2)
+        INT j;
+        for(j = 0; j < address->elision_size; j+=2)
             number[cur_component++] = 0;
-        already_passed_elision = TRUE;
     }
 
     if(address->ipv4) {
@@ -1041,7 +960,7 @@ static BOOL check_dec_octet(const WCHAR **ptr) {
     ++(*ptr);
 
     c2 = *ptr;
-    /* Since the 1 digit requirment was meet, it doesn't
+    /* Since the 1-digit requirement was met, it doesn't
      * matter if this is a DIGIT value, it's considered a
      * dec-octet.
      */
@@ -1248,7 +1167,7 @@ static BOOL parse_scheme(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD
 
             TRACE("(%p %p %x): URI is an implicit file path.\n", ptr, data, flags);
         } else {
-            /* Window's does not consider anything that can implicitly be a file
+            /* Windows does not consider anything that can implicitly be a file
              * path to be a valid URI if the ALLOW_IMPLICIT_FILE_SCHEME flag is not set...
              */
             TRACE("(%p %p %x): URI is implicitly a file path, but, the ALLOW_IMPLICIT_FILE_SCHEME flag wasn't set.\n",
@@ -1256,10 +1175,10 @@ static BOOL parse_scheme(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD
             return FALSE;
         }
     } else if(!parse_scheme_name(ptr, data, extras)) {
-        /* No Scheme was found, this means it could be:
+        /* No scheme was found, this means it could be:
          *      a) an implicit Wildcard scheme
          *      b) a relative URI
-         *      c) a invalid URI.
+         *      c) an invalid URI.
          */
         if(flags & Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME) {
             data->scheme = wildcardW;
@@ -1316,19 +1235,13 @@ static BOOL parse_username(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
 }
 
 static BOOL parse_password(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
-    const WCHAR *start = *ptr;
-
-    if(**ptr != ':')
-        return TRUE;
-
-    ++(*ptr);
     data->password = *ptr;
 
     while(**ptr != '@') {
         if(**ptr == '%') {
             if(!check_pct_encoded(ptr)) {
                 if(data->scheme_type != URL_SCHEME_UNKNOWN) {
-                    *ptr = start;
+                    *ptr = data->password;
                     data->password = NULL;
                     return FALSE;
                 }
@@ -1337,7 +1250,7 @@ static BOOL parse_password(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
         } else if(extras & ALLOW_NULL_TERM_PASSWORD && !**ptr)
             break;
         else if(is_auth_delim(**ptr, data->scheme_type != URL_SCHEME_UNKNOWN)) {
-            *ptr = start;
+            *ptr = data->password;
             data->password = NULL;
             return FALSE;
         }
@@ -1363,10 +1276,10 @@ static BOOL parse_password(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
  *      ex:
  *          ftp://user:pass:word@winehq.org
  *
- *      Would yield, "user" as the username and "pass:word" as the password.
+ *      would yield "user" as the username and "pass:word" as the password.
  *
  *  2)  Windows allows any character to appear in the "userinfo" part of
- *      a URI, as long as it's not an authority delimeter character set.
+ *      a URI, as long as it's not an authority delimiter character set.
  */
 static void parse_userinfo(const WCHAR **ptr, parse_data *data, DWORD flags) {
     const WCHAR *start = *ptr;
@@ -1376,12 +1289,15 @@ static void parse_userinfo(const WCHAR **ptr, parse_data *data, DWORD flags) {
         return;
     }
 
-    if(!parse_password(ptr, data, flags, 0)) {
-        *ptr = start;
-        data->username = NULL;
-        data->username_len = 0;
-        TRACE("(%p %p %x): URI contained no userinfo.\n", ptr, data, flags);
-        return;
+    if(**ptr == ':') {
+        ++(*ptr);
+        if(!parse_password(ptr, data, flags, 0)) {
+            *ptr = start;
+            data->username = NULL;
+            data->username_len = 0;
+            TRACE("(%p %p %x): URI contained no userinfo.\n", ptr, data, flags);
+            return;
+        }
     }
 
     if(**ptr != '@') {
@@ -1427,7 +1343,7 @@ static BOOL parse_port(const WCHAR **ptr, parse_data *data, DWORD flags) {
 
         port = port*10 + (**ptr-'0');
 
-        if(port > USHORT_MAX) {
+        if(port > USHRT_MAX) {
             *ptr = data->port;
             data->port = NULL;
             return FALSE;
@@ -1448,7 +1364,7 @@ static BOOL parse_port(const WCHAR **ptr, parse_data *data, DWORD flags) {
 /* Attempts to parse a IPv4 address from the URI.
  *
  * NOTES:
- *  Window's normalizes IPv4 addresses, This means there's three
+ *  Windows normalizes IPv4 addresses, This means there are three
  *  possibilities for the URI to contain an IPv4 address.
  *      1)  A well formed address (ex. 192.2.2.2).
  *      2)  A partially formed address. For example "192.0" would
@@ -1474,6 +1390,9 @@ static BOOL parse_ipv4address(const WCHAR **ptr, parse_data *data, DWORD flags)
             data->has_implicit_ip = TRUE;
     }
 
+    data->host_len = *ptr - data->host;
+    data->host_type = Uri_HOST_IPV4;
+
     /* Check if what we found is the only part of the host name (if it isn't
      * we don't have an IPv4 address).
      */
@@ -1485,16 +1404,13 @@ static BOOL parse_ipv4address(const WCHAR **ptr, parse_data *data, DWORD flags)
             return FALSE;
         }
     } else if(!is_auth_delim(**ptr, !is_unknown)) {
-        /* Found more data which belongs the host, so this isn't an IPv4. */
+        /* Found more data which belongs to the host, so this isn't an IPv4. */
         *ptr = data->host;
         data->host = NULL;
         data->has_implicit_ip = FALSE;
         return FALSE;
     }
 
-    data->host_len = *ptr - data->host;
-    data->host_type = Uri_HOST_IPV4;
-
     TRACE("(%p %p %x): IPv4 address found. host=%s host_len=%d host_type=%d\n",
         ptr, data, flags, debugstr_wn(data->host, data->host_len),
         data->host_len, data->host_type);
@@ -1516,16 +1432,19 @@ static BOOL parse_ipv4address(const WCHAR **ptr, parse_data *data, DWORD flags)
  *  Windows doesn't like host names which start with '[' and end with ']'
  *  and don't contain a valid IP literal address in between them.
  *
- *  On Windows if an '[' is encountered in the host name the ':' no longer
- *  counts as a delimiter until you reach the next ']' or an "authority delimeter".
+ *  On Windows if a '[' is encountered in the host name the ':' no longer
+ *  counts as a delimiter until you reach the next ']' or an "authority delimiter".
  *
  *  A reg-name CAN be empty.
  */
 static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
     const BOOL has_start_bracket = **ptr == '[';
     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
+    const BOOL is_res = data->scheme_type == URL_SCHEME_RES;
     BOOL inside_brackets = has_start_bracket;
-    BOOL ignore_col = extras & IGNORE_PORT_DELIMITER;
+
+    /* res URIs don't have ports. */
+    BOOL ignore_col = (extras & IGNORE_PORT_DELIMITER) || is_res;
 
     /* We have to be careful with file schemes. */
     if(data->scheme_type == URL_SCHEME_FILE) {
@@ -1535,7 +1454,7 @@ static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
          * path can also have a '|' instead of a ':' after the drive letter.
          */
         if(is_drive_path(*ptr)) {
-            /* Regular old drive paths don't have a host type (or host name). */
+            /* Regular old drive paths have no host type (or host name). */
             data->host_type = Uri_HOST_UNKNOWN;
             data->host = *ptr;
             data->host_len = 0;
@@ -1547,7 +1466,11 @@ static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
 
     data->host = *ptr;
 
-    while(!is_auth_delim(**ptr, known_scheme)) {
+    /* For res URIs, everything before the first '/' is
+     * considered the host.
+     */
+    while((!is_res && !is_auth_delim(**ptr, known_scheme)) ||
+          (is_res && **ptr && **ptr != '/')) {
         if(**ptr == ':' && !ignore_col) {
             /* We can ignore ':' if were inside brackets.*/
             if(!inside_brackets) {
@@ -1563,7 +1486,7 @@ static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
                         return FALSE;
                     } else
                         /* Windows gives up on trying to parse a port when it
-                         * encounters 1 invalid port.
+                         * encounters an invalid port.
                          */
                         ignore_col = TRUE;
                 } else {
@@ -1571,7 +1494,7 @@ static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
                     break;
                 }
             }
-        } else if(**ptr == '%' && known_scheme) {
+        } else if(**ptr == '%' && (known_scheme && !is_res)) {
             /* Has to be a legit % encoded value. */
             if(!check_pct_encoded(ptr)) {
                 *ptr = data->host;
@@ -1579,6 +1502,10 @@ static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
                 return FALSE;
             } else
                 continue;
+        } else if(is_res && is_forbidden_dos_path_char(**ptr)) {
+            *ptr = data->host;
+            data->host = NULL;
+            return FALSE;
         } else if(**ptr == ']')
             inside_brackets = FALSE;
         else if(**ptr == '[')
@@ -1603,7 +1530,7 @@ static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWO
         data->host_len = *ptr - data->host;
 
     /* If the host is empty, then it's an unknown host type. */
-    if(data->host_len == 0)
+    if(data->host_len == 0 || is_res)
         data->host_type = Uri_HOST_UNKNOWN;
     else
         data->host_type = Uri_HOST_DNS;
@@ -1683,7 +1610,7 @@ static BOOL parse_ipv6address(const WCHAR **ptr, parse_data *data, DWORD flags)
                 /* An IPv6 address can have no more than 8 h16 components. */
                 if(ip.h16_count >= 8) {
                     *ptr = start;
-                    TRACE("(%p %p %x): Not a IPv6 address, to many h16 components.\n",
+                    TRACE("(%p %p %x): Not a IPv6 address, too many h16 components.\n",
                         ptr, data, flags);
                     return FALSE;
                 }
@@ -1751,7 +1678,7 @@ static BOOL parse_ipv6address(const WCHAR **ptr, parse_data *data, DWORD flags)
 
     if(ip.elision_size == 2) {
         /* For some reason on Windows if an elision that represents
-         * only 1 h16 component is encountered at the very begin or
+         * only one h16 component is encountered at the very begin or
          * end of an IPv6 address, Windows does not consider it a
          * valid IPv6 address.
          *
@@ -1773,7 +1700,7 @@ static BOOL parse_ipv6address(const WCHAR **ptr, parse_data *data, DWORD flags)
 
     TRACE("(%p %p %x): Found valid IPv6 literal %s len=%d\n",
         ptr, data, flags, debugstr_wn(start, *ptr-start),
-        *ptr-start);
+        (int)(*ptr-start));
     return TRUE;
 }
 
@@ -1815,7 +1742,7 @@ static BOOL parse_ipvfuture(const WCHAR **ptr, parse_data *data, DWORD flags) {
     data->host_type = Uri_HOST_UNKNOWN;
 
     TRACE("(%p %p %x): Parsed IPvFuture address %s len=%d\n", ptr, data, flags,
-        debugstr_wn(start, *ptr-start), *ptr-start);
+          debugstr_wn(start, *ptr-start), (int)(*ptr-start));
 
     return TRUE;
 }
@@ -1908,10 +1835,7 @@ static BOOL parse_path_hierarchical(const WCHAR **ptr, parse_data *data, DWORD f
     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
 
     if(is_path_delim(**ptr)) {
-        if(data->scheme_type == URL_SCHEME_WILDCARD) {
-            /* Wildcard schemes don't get a '/' attached if their path is
-             * empty.
-             */
+        if(data->scheme_type == URL_SCHEME_WILDCARD && !data->must_have_path) {
             data->path = NULL;
             data->path_len = 0;
         } else if(!(flags & Uri_CREATE_NO_CANONICALIZE)) {
@@ -1972,7 +1896,7 @@ static BOOL parse_path_hierarchical(const WCHAR **ptr, parse_data *data, DWORD f
     return TRUE;
 }
 
-/* Parses the path of a opaque URI (much less strict then the parser
+/* Parses the path of an opaque URI (much less strict than the parser
  * for a hierarchical URI).
  *
  * NOTE:
@@ -1985,8 +1909,15 @@ static BOOL parse_path_hierarchical(const WCHAR **ptr, parse_data *data, DWORD f
 static BOOL parse_path_opaque(const WCHAR **ptr, parse_data *data, DWORD flags) {
     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
+    const BOOL is_mailto = data->scheme_type == URL_SCHEME_MAILTO;
 
-    data->path = *ptr;
+    if (is_mailto && (*ptr)[0] == '/' && (*ptr)[1] == '/')
+    {
+        if ((*ptr)[2]) data->path = *ptr + 2;
+        else data->path = NULL;
+    }
+    else
+        data->path = *ptr;
 
     while(!is_path_delim(**ptr)) {
         if(**ptr == '%' && known_scheme) {
@@ -2006,7 +1937,7 @@ static BOOL parse_path_opaque(const WCHAR **ptr, parse_data *data, DWORD flags)
         ++(*ptr);
     }
 
-    data->path_len = *ptr - data->path;
+    if (data->path) data->path_len = *ptr - data->path;
     TRACE("(%p %p %x): Parsed opaque URI path %s len=%d\n", ptr, data, flags,
         debugstr_wn(data->path, data->path_len), data->path_len);
     return TRUE;
@@ -2014,7 +1945,7 @@ static BOOL parse_path_opaque(const WCHAR **ptr, parse_data *data, DWORD flags)
 
 /* Determines how the URI should be parsed after the scheme information.
  *
- * If the scheme is followed, by "//" then, it is treated as an hierarchical URI
+ * If the scheme is followed by "//", then it is treated as a hierarchical URI
  * which then the authority and path information will be parsed out. Otherwise, the
  * URI will be treated as an opaque URI which the authority information is not parsed
  * out.
@@ -2032,12 +1963,23 @@ static BOOL parse_path_opaque(const WCHAR **ptr, parse_data *data, DWORD flags)
  * NOTES:
  *  If the URI is of an unknown scheme type and has a "//" following the scheme then it
  *  is treated as a hierarchical URI, but, if the CREATE_NO_CRACK_UNKNOWN_SCHEMES flag is
- *  set then it is considered an opaque URI reguardless of what follows the scheme information
+ *  set then it is considered an opaque URI regardless of what follows the scheme information
  *  (per MSDN documentation).
  */
 static BOOL parse_hierpart(const WCHAR **ptr, parse_data *data, DWORD flags) {
     const WCHAR *start = *ptr;
 
+    data->must_have_path = FALSE;
+
+    /* For javascript: URIs, simply set everything as a path */
+    if(data->scheme_type == URL_SCHEME_JAVASCRIPT) {
+        data->path = *ptr;
+        data->path_len = strlenW(*ptr);
+        data->is_opaque = TRUE;
+        *ptr += data->path_len;
+        return TRUE;
+    }
+
     /* Checks if the authority information needs to be parsed. */
     if(is_hierarchical_uri(ptr, data)) {
         /* Only treat it as a hierarchical URI if the scheme_type is known or
@@ -2048,13 +1990,20 @@ static BOOL parse_hierpart(const WCHAR **ptr, parse_data *data, DWORD flags) {
             TRACE("(%p %p %x): Treating URI as an hierarchical URI.\n", ptr, data, flags);
             data->is_opaque = FALSE;
 
+            if(data->scheme_type == URL_SCHEME_WILDCARD && !data->has_implicit_scheme) {
+                if(**ptr == '/' && *(*ptr+1) == '/') {
+                    data->must_have_path = TRUE;
+                    *ptr += 2;
+                }
+            }
+
             /* TODO: Handle hierarchical URI's, parse authority then parse the path. */
             if(!parse_authority(ptr, data, flags))
                 return FALSE;
 
             return parse_path_hierarchical(ptr, data, flags);
         } else
-            /* Reset ptr to it's starting position so opaque path parsing
+            /* Reset ptr to its starting position so opaque path parsing
              * begins at the correct location.
              */
             *ptr = start;
@@ -2077,8 +2026,8 @@ static BOOL parse_hierpart(const WCHAR **ptr, parse_data *data, DWORD flags) {
  *
  * NOTES:
  *  If NO_DECODE_EXTRA_INFO flag is set, then invalid percent encoded
- *  data is allowed appear in the query string. For unknown scheme types
- *  invalid percent encoded data is allowed to appear reguardless.
+ *  data is allowed to appear in the query string. For unknown scheme types
+ *  invalid percent encoded data is allowed to appear regardless.
  */
 static BOOL parse_query(const WCHAR **ptr, parse_data *data, DWORD flags) {
     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
@@ -2116,8 +2065,8 @@ static BOOL parse_query(const WCHAR **ptr, parse_data *data, DWORD flags) {
  *
  * NOTES:
  *  If NO_DECODE_EXTRA_INFO flag is set, then invalid percent encoded
- *  data is allowed appear in the query string. For unknown scheme types
- *  invalid percent encoded data is allowed to appear reguardless.
+ *  data is allowed to appear in the query string. For unknown scheme types
+ *  invalid percent encoded data is allowed to appear regardless.
  */
 static BOOL parse_fragment(const WCHAR **ptr, parse_data *data, DWORD flags) {
     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
@@ -2194,7 +2143,7 @@ static BOOL canonicalize_username(const parse_data *data, Uri *uri, DWORD flags,
         if(*ptr == '%') {
             /* Only decode % encoded values for known scheme types. */
             if(data->scheme_type != URL_SCHEME_UNKNOWN) {
-                /* See if the value really needs decoded. */
+                /* See if the value really needs decoding. */
                 WCHAR val = decode_pct_val(ptr);
                 if(is_unreserved(val)) {
                     if(!computeOnly)
@@ -2252,7 +2201,7 @@ static BOOL canonicalize_password(const parse_data *data, Uri *uri, DWORD flags,
         if(*ptr == '%') {
             /* Only decode % encoded values for known scheme types. */
             if(data->scheme_type != URL_SCHEME_UNKNOWN) {
-                /* See if the value really needs decoded. */
+                /* See if the value really needs decoding. */
                 WCHAR val = decode_pct_val(ptr);
                 if(is_unreserved(val)) {
                     if(!computeOnly)
@@ -2328,7 +2277,7 @@ static BOOL canonicalize_userinfo(const parse_data *data, Uri *uri, DWORD flags,
  * Things that happen:
  *  1)  If Uri_CREATE_NO_CANONICALIZE flag is not set, then the reg_name is
  *      lower cased. Unless it's an unknown scheme type, which case it's
- *      no lower cased reguardless.
+ *      no lower cased regardless.
  *
  *  2)  Unreserved % encoded characters are decoded for known
  *      scheme types.
@@ -2338,6 +2287,9 @@ static BOOL canonicalize_userinfo(const parse_data *data, Uri *uri, DWORD flags,
  *      it isn't an unknown scheme type.
  *
  *  4)  If it's a file scheme and the host is "localhost" it's removed.
+ *
+ *  5)  If it's a file scheme and Uri_CREATE_FILE_USE_DOS_PATH is set,
+ *      then the UNC path characters are added before the host name.
  */
 static BOOL canonicalize_reg_name(const parse_data *data, Uri *uri,
                                   DWORD flags, BOOL computeOnly) {
@@ -2346,8 +2298,6 @@ static BOOL canonicalize_reg_name(const parse_data *data, Uri *uri,
     const WCHAR *ptr;
     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
 
-    uri->host_start = uri->canon_len;
-
     if(data->scheme_type == URL_SCHEME_FILE &&
        data->host_len == lstrlenW(localhostW)) {
         if(!StrCmpNIW(data->host, localhostW, data->host_len)) {
@@ -2358,11 +2308,22 @@ static BOOL canonicalize_reg_name(const parse_data *data, Uri *uri,
         }
     }
 
+    if(data->scheme_type == URL_SCHEME_FILE && flags & Uri_CREATE_FILE_USE_DOS_PATH) {
+        if(!computeOnly) {
+            uri->canon_uri[uri->canon_len] = '\\';
+            uri->canon_uri[uri->canon_len+1] = '\\';
+        }
+        uri->canon_len += 2;
+        uri->authority_start = uri->canon_len;
+    }
+
+    uri->host_start = uri->canon_len;
+
     for(ptr = data->host; ptr < data->host+data->host_len; ++ptr) {
         if(*ptr == '%' && known_scheme) {
             WCHAR val = decode_pct_val(ptr);
             if(is_unreserved(val)) {
-                /* If NO_CANONICALZE is not set, then windows lower cases the
+                /* If NO_CANONICALIZE is not set, then windows lower cases the
                  * decoded value.
                  */
                 if(!(flags & Uri_CREATE_NO_CANONICALIZE) && isupperW(val)) {
@@ -2432,8 +2393,8 @@ static BOOL canonicalize_implicit_ipv4address(const parse_data *data, Uri *uri,
     uri->host_start = uri->canon_len;
 
     TRACE("%u\n", data->implicit_ipv4);
-    /* For unknown scheme types Window's doesn't convert
-     * the value into an IP address, but, it still considers
+    /* For unknown scheme types Windows doesn't convert
+     * the value into an IP address, but it still considers
      * it an IPv4 address.
      */
     if(data->scheme_type == URL_SCHEME_UNKNOWN) {
@@ -2464,7 +2425,7 @@ static BOOL canonicalize_implicit_ipv4address(const parse_data *data, Uri *uri,
  * If the parse_data represents a URI that has an implicit IPv4 address
  * (ex. http://256/, this function will convert 256 into 0.0.1.0). If
  * the implicit IP address exceeds the value of UINT_MAX (maximum value
- * for an IPv4 address) it's canonicalized as if were a reg-name.
+ * for an IPv4 address) it's canonicalized as if it were a reg-name.
  *
  * If the parse_data contains a partial or full IPv4 address it normalizes it.
  * A partial IPv4 address is something like "192.0" and would be normalized to
@@ -2472,7 +2433,7 @@ static BOOL canonicalize_implicit_ipv4address(const parse_data *data, Uri *uri,
  * be normalized to "192.2.1.3".
  *
  * NOTES:
- *  Window's ONLY normalizes IPv4 address for known scheme types (one that isn't
+ *  Windows ONLY normalizes IPv4 address for known scheme types (one that isn't
  *  URL_SCHEME_UNKNOWN). For unknown scheme types, it simply copies the data from
  *  the original URI into the canonicalized URI, but, it still recognizes URI's
  *  host type as HOST_IPV4.
@@ -2554,11 +2515,11 @@ static BOOL canonicalize_ipv4address(const parse_data *data, Uri *uri, DWORD fla
 /* Attempts to canonicalize the IPv6 address of the URI.
  *
  * Multiple things happen during the canonicalization of an IPv6 address:
- *  1)  Any leading zero's in an h16 component are removed.
+ *  1)  Any leading zero's in a h16 component are removed.
  *      Ex: [0001:0022::] -> [1:22::]
  *
  *  2)  The longest sequence of zero h16 components are compressed
- *      into a "::" (elision). If there's a tie, the first is choosen.
+ *      into a "::" (elision). If there's a tie, the first is chosen.
  *
  *      Ex: [0:0:0:0:1:6:7:8]   -> [::1:6:7:8]
  *          [0:0:0:0:1:2::]     -> [::1:2:0:0]
@@ -2568,7 +2529,7 @@ static BOOL canonicalize_ipv4address(const parse_data *data, Uri *uri, DWORD fla
  *      also normalized.
  *      Ex: [::001.002.022.000] -> [::1.2.22.0]
  *
- *  4)  If an elision is present, but, only represents 1 h16 component
+ *  4)  If an elision is present, but, only represents one h16 component
  *      it's expanded.
  *
  *      Ex: [1::2:3:4:5:6:7] -> [1:0:2:3:4:5:6:7]
@@ -2751,7 +2712,7 @@ static BOOL canonicalize_port(const parse_data *data, Uri *uri, DWORD flags, BOO
     USHORT default_port = 0;
     DWORD i;
 
-    uri->has_port = FALSE;
+    uri->port_offset = -1;
 
     /* Check if the scheme has a default port. */
     for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
@@ -2762,8 +2723,7 @@ static BOOL canonicalize_port(const parse_data *data, Uri *uri, DWORD flags, BOO
         }
     }
 
-    if(data->port || has_default_port)
-        uri->has_port = TRUE;
+    uri->has_port = data->has_port || has_default_port;
 
     /* Possible cases:
      *  1)  Has a port which is the default port.
@@ -2771,38 +2731,44 @@ static BOOL canonicalize_port(const parse_data *data, Uri *uri, DWORD flags, BOO
      *  3)  Doesn't have a port, but, scheme has a default port.
      *  4)  No port.
      */
-    if(has_default_port && data->port && data->port_value == default_port) {
+    if(has_default_port && data->has_port && data->port_value == default_port) {
         /* If it's the default port and this flag isn't set, don't do anything. */
         if(flags & Uri_CREATE_NO_CANONICALIZE) {
-            /* Copy the original port over. */
-            if(!computeOnly) {
+            uri->port_offset = uri->canon_len-uri->authority_start;
+            if(!computeOnly)
                 uri->canon_uri[uri->canon_len] = ':';
-                memcpy(uri->canon_uri+uri->canon_len+1, data->port, data->port_len*sizeof(WCHAR));
+            ++uri->canon_len;
+
+            if(data->port) {
+                /* Copy the original port over. */
+                if(!computeOnly)
+                    memcpy(uri->canon_uri+uri->canon_len, data->port, data->port_len*sizeof(WCHAR));
+                uri->canon_len += data->port_len;
+            } else {
+                if(!computeOnly)
+                    uri->canon_len += ui2str(uri->canon_uri+uri->canon_len, data->port_value);
+                else
+                    uri->canon_len += ui2str(NULL, data->port_value);
             }
-            uri->canon_len += data->port_len+1;
         }
 
         uri->port = default_port;
-    } else if(data->port) {
+    } else if(data->has_port) {
+        uri->port_offset = uri->canon_len-uri->authority_start;
         if(!computeOnly)
             uri->canon_uri[uri->canon_len] = ':';
         ++uri->canon_len;
 
-        if(flags & Uri_CREATE_NO_CANONICALIZE) {
+        if(flags & Uri_CREATE_NO_CANONICALIZE && data->port) {
             /* Copy the original over without changes. */
             if(!computeOnly)
                 memcpy(uri->canon_uri+uri->canon_len, data->port, data->port_len*sizeof(WCHAR));
             uri->canon_len += data->port_len;
         } else {
-            const WCHAR formatW[] = {'%','u',0};
-            INT len = 0;
             if(!computeOnly)
-                len = sprintfW(uri->canon_uri+uri->canon_len, formatW, data->port_value);
-            else {
-                WCHAR tmp[6];
-                len = sprintfW(tmp, formatW, data->port_value);
-            }
-            uri->canon_len += len;
+                uri->canon_len += ui2str(uri->canon_uri+uri->canon_len, data->port_value);
+            else
+                uri->canon_len += ui2str(NULL, data->port_value);
         }
 
         uri->port = data->port_value;
@@ -2826,7 +2792,7 @@ static BOOL canonicalize_authority(const parse_data *data, Uri *uri, DWORD flags
     if(!canonicalize_port(data, uri, flags, computeOnly))
         return FALSE;
 
-    if(uri->host_start != -1)
+    if(uri->host_start != -1 || (data->is_relative && (data->password || data->username)))
         uri->authority_len = uri->canon_len - uri->authority_start;
     else
         uri->authority_start = -1;
@@ -2839,7 +2805,7 @@ static BOOL canonicalize_authority(const parse_data *data, Uri *uri, DWORD flags
  * Things that happen:
  *  1). Forbidden characters are percent encoded, unless the NO_ENCODE_FORBIDDEN
  *      flag is set or it's a file URI. Forbidden characters are always encoded
- *      for file schemes reguardless and forbidden characters are never encoded
+ *      for file schemes regardless and forbidden characters are never encoded
  *      for unknown scheme types.
  *
  *  2). For known scheme types '\\' are changed to '/'.
@@ -2859,141 +2825,135 @@ static BOOL canonicalize_authority(const parse_data *data, Uri *uri, DWORD flags
  * NOTES:
  *      file://c:/test%20test   -> file:///c:/test%2520test
  *      file://c:/test%3Etest   -> file:///c:/test%253Etest
+ * if Uri_CREATE_FILE_USE_DOS_PATH is not set:
  *      file:///c:/test%20test  -> file:///c:/test%20test
  *      file:///c:/test%test    -> file:///c:/test%25test
  */
-static BOOL canonicalize_path_hierarchical(const parse_data *data, Uri *uri,
-                                           DWORD flags, BOOL computeOnly) {
+static DWORD canonicalize_path_hierarchical(const WCHAR *path, DWORD path_len, URL_SCHEME scheme_type, BOOL has_host, DWORD flags,
+        WCHAR *ret_path) {
+    const BOOL known_scheme = scheme_type != URL_SCHEME_UNKNOWN;
+    const BOOL is_file = scheme_type == URL_SCHEME_FILE;
+    const BOOL is_res = scheme_type == URL_SCHEME_RES;
     const WCHAR *ptr;
-    const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
-    const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
-
     BOOL escape_pct = FALSE;
+    DWORD len = 0;
 
-    if(!data->path) {
-        uri->path_start = -1;
-        uri->path_len = 0;
-        return TRUE;
-    }
+    if(!path)
+        return 0;
 
-    uri->path_start = uri->canon_len;
-    ptr = data->path;
+    ptr = path;
 
-    if(is_file && uri->host_start == -1) {
+    if(is_file && !has_host) {
         /* Check if a '/' needs to be appended for the file scheme. */
-        if(data->path_len > 1 && is_drive_path(ptr) && !(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
-            if(!computeOnly)
-                uri->canon_uri[uri->canon_len] = '/';
-            uri->canon_len++;
+        if(path_len > 1 && is_drive_path(ptr) && !(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
+            if(ret_path)
+                ret_path[len] = '/';
+            len++;
             escape_pct = TRUE;
         } else if(*ptr == '/') {
             if(!(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
                 /* Copy the extra '/' over. */
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = '/';
-                ++uri->canon_len;
+                if(ret_path)
+                    ret_path[len] = '/';
+                len++;
             }
             ++ptr;
         }
 
         if(is_drive_path(ptr)) {
-            if(!computeOnly) {
-                uri->canon_uri[uri->canon_len] = *ptr;
-                /* If theres a '|' after the drive letter, convert it to a ':'. */
-                uri->canon_uri[uri->canon_len+1] = ':';
+            if(ret_path) {
+                ret_path[len] = *ptr;
+                /* If there's a '|' after the drive letter, convert it to a ':'. */
+                ret_path[len+1] = ':';
             }
             ptr += 2;
-            uri->canon_len += 2;
+            len += 2;
         }
     }
 
-    for(; ptr < data->path+data->path_len; ++ptr) {
-        if(*ptr == '%') {
+    if(!is_file && *path && *path != '/') {
+        /* Prepend a '/' to the path if it doesn't have one. */
+        if(ret_path)
+            ret_path[len] = '/';
+        len++;
+    }
+
+    for(; ptr < path+path_len; ++ptr) {
+        BOOL do_default_action = TRUE;
+
+        if(*ptr == '%' && !is_res) {
             const WCHAR *tmp = ptr;
             WCHAR val;
 
-            /* Check if the % represents a valid encoded char, or if it needs encoded. */
-            BOOL force_encode = !check_pct_encoded(&tmp) && is_file;
+            /* Check if the % represents a valid encoded char, or if it needs encoding. */
+            BOOL force_encode = !check_pct_encoded(&tmp) && is_file && !(flags&Uri_CREATE_FILE_USE_DOS_PATH);
             val = decode_pct_val(ptr);
 
             if(force_encode || escape_pct) {
                 /* Escape the percent sign in the file URI. */
-                if(!computeOnly)
-                    pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
-                uri->canon_len += 3;
+                if(ret_path)
+                    pct_encode_val(*ptr, ret_path+len);
+                len += 3;
+                do_default_action = FALSE;
             } else if((is_unreserved(val) && known_scheme) ||
-                      (is_file && (is_unreserved(val) || is_reserved(val)))) {
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = val;
-                ++uri->canon_len;
+                      (is_file && (is_unreserved(val) || is_reserved(val) ||
+                      (val && flags&Uri_CREATE_FILE_USE_DOS_PATH && !is_forbidden_dos_path_char(val))))) {
+                if(ret_path)
+                    ret_path[len] = val;
+                len++;
 
                 ptr += 2;
                 continue;
-            } else {
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
             }
         } else if(*ptr == '/' && is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
             /* Convert the '/' back to a '\\'. */
-            if(!computeOnly)
-                uri->canon_uri[uri->canon_len] = '\\';
-            ++uri->canon_len;
+            if(ret_path)
+                ret_path[len] = '\\';
+            len++;
+            do_default_action = FALSE;
         } else if(*ptr == '\\' && known_scheme) {
-            if(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
-                /* Don't convert the '\\' to a '/'. */
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
-            } else {
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = '/';
-                ++uri->canon_len;
+            if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH))) {
+                /* Convert '\\' into a '/'. */
+                if(ret_path)
+                    ret_path[len] = '/';
+                len++;
+                do_default_action = FALSE;
             }
-        } else if(known_scheme && !is_unreserved(*ptr) && !is_reserved(*ptr) &&
+        } else if(known_scheme && !is_res && !is_unreserved(*ptr) && !is_reserved(*ptr) &&
                   (!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS) || is_file)) {
-            if(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
-                /* Don't escape the character. */
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
-            } else {
+            if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH))) {
                 /* Escape the forbidden character. */
-                if(!computeOnly)
-                    pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
-                uri->canon_len += 3;
+                if(ret_path)
+                    pct_encode_val(*ptr, ret_path+len);
+                len += 3;
+                do_default_action = FALSE;
             }
-        } else {
-            if(!computeOnly)
-                uri->canon_uri[uri->canon_len] = *ptr;
-            ++uri->canon_len;
         }
-    }
 
-    uri->path_len = uri->canon_len - uri->path_start;
+        if(do_default_action) {
+            if(ret_path)
+                ret_path[len] = *ptr;
+            len++;
+        }
+    }
 
     /* Removing the dot segments only happens when it's not in
      * computeOnly mode and it's not a wildcard scheme. File schemes
      * with USE_DOS_PATH set don't get dot segments removed.
      */
     if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) &&
-       data->scheme_type != URL_SCHEME_WILDCARD) {
-        if(!(flags & Uri_CREATE_NO_CANONICALIZE) && !computeOnly) {
+       scheme_type != URL_SCHEME_WILDCARD) {
+        if(!(flags & Uri_CREATE_NO_CANONICALIZE) && ret_path) {
             /* Remove the dot segments (if any) and reset everything to the new
              * correct length.
              */
-            DWORD new_len = remove_dot_segments(uri->canon_uri+uri->path_start, uri->path_len);
-            uri->canon_len -= uri->path_len-new_len;
-            uri->path_len = new_len;
+            len = remove_dot_segments(ret_path, len);
         }
     }
 
-    if(!computeOnly)
-        TRACE("Canonicalized path %s len=%d\n",
-            debugstr_wn(uri->canon_uri+uri->path_start, uri->path_len),
-            uri->path_len);
-
-    return TRUE;
+    if(ret_path)
+        TRACE("Canonicalized path %s len=%d\n", debugstr_wn(ret_path, len), len);
+    return len;
 }
 
 /* Attempts to canonicalize the path for an opaque URI.
@@ -3018,6 +2978,7 @@ static BOOL canonicalize_path_opaque(const parse_data *data, Uri *uri, DWORD fla
     const WCHAR *ptr;
     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
+    const BOOL is_mk = data->scheme_type == URL_SCHEME_MK;
 
     if(!data->path) {
         uri->path_start = -1;
@@ -3027,6 +2988,21 @@ static BOOL canonicalize_path_opaque(const parse_data *data, Uri *uri, DWORD fla
 
     uri->path_start = uri->canon_len;
 
+    if(is_mk){
+        /* hijack this flag for SCHEME_MK to tell the function when to start
+         * converting slashes */
+        flags |= Uri_CREATE_FILE_USE_DOS_PATH;
+    }
+
+    /* For javascript: URIs, simply copy path part without any canonicalization */
+    if(data->scheme_type == URL_SCHEME_JAVASCRIPT) {
+        if(!computeOnly)
+            memcpy(uri->canon_uri+uri->canon_len, data->path, data->path_len*sizeof(WCHAR));
+        uri->path_len = data->path_len;
+        uri->canon_len += data->path_len;
+        return TRUE;
+    }
+
     /* Windows doesn't allow a "//" to appear after the scheme
      * of a URI, if it's an opaque URI.
      */
@@ -3041,6 +3017,8 @@ static BOOL canonicalize_path_opaque(const parse_data *data, Uri *uri, DWORD fla
     }
 
     for(ptr = data->path; ptr < data->path+data->path_len; ++ptr) {
+        BOOL do_default_action = TRUE;
+
         if(*ptr == '%' && known_scheme) {
             WCHAR val = decode_pct_val(ptr);
 
@@ -3051,57 +3029,50 @@ static BOOL canonicalize_path_opaque(const parse_data *data, Uri *uri, DWORD fla
 
                 ptr += 2;
                 continue;
-            } else {
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
             }
         } else if(*ptr == '/' && is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
             if(!computeOnly)
                 uri->canon_uri[uri->canon_len] = '\\';
             ++uri->canon_len;
-        } else if(*ptr == '\\' && is_file) {
-            if(!(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
+            do_default_action = FALSE;
+        } else if(*ptr == '\\') {
+            if((data->is_relative || is_mk || is_file) && !(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
                 /* Convert to a '/'. */
                 if(!computeOnly)
                     uri->canon_uri[uri->canon_len] = '/';
                 ++uri->canon_len;
-            } else {
-                /* Just copy it over. */
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
+                do_default_action = FALSE;
             }
+        } else if(is_mk && *ptr == ':' && ptr + 1 < data->path + data->path_len && *(ptr + 1) == ':') {
+            flags &= ~Uri_CREATE_FILE_USE_DOS_PATH;
         } else if(known_scheme && !is_unreserved(*ptr) && !is_reserved(*ptr) &&
                   !(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS)) {
-            if(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
-                /* Forbidden characters aren't percent encoded for file schemes
-                 * with USE_DOS_PATH set.
-                 */
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
-            } else if(data->scheme_type == URL_SCHEME_MK && *ptr == '\\') {
-                /* MK URIs don't get '\\' percent encoded. */
-                if(!computeOnly)
-                    uri->canon_uri[uri->canon_len] = *ptr;
-                ++uri->canon_len;
-            } else {
+            if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH))) {
                 if(!computeOnly)
                     pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
                 uri->canon_len += 3;
+                do_default_action = FALSE;
             }
-        } else {
+        }
+
+        if(do_default_action) {
             if(!computeOnly)
                 uri->canon_uri[uri->canon_len] = *ptr;
             ++uri->canon_len;
         }
     }
 
+    if(is_mk && !computeOnly && !(flags & Uri_CREATE_NO_CANONICALIZE)) {
+        DWORD new_len = remove_dot_segments(uri->canon_uri + uri->path_start,
+                                            uri->canon_len - uri->path_start);
+        uri->canon_len = uri->path_start + new_len;
+    }
+
     uri->path_len = uri->canon_len - uri->path_start;
 
-    TRACE("(%p %p %x %d): Canonicalized opaque URI path %s len=%d\n", data, uri, flags, computeOnly,
-        debugstr_wn(uri->canon_uri+uri->path_start, uri->path_len), uri->path_len);
+    if(!computeOnly)
+        TRACE("(%p %p %x %d): Canonicalized opaque URI path %s len=%d\n", data, uri, flags, computeOnly,
+            debugstr_wn(uri->canon_uri+uri->path_start, uri->path_len), uri->path_len);
     return TRUE;
 }
 
@@ -3112,11 +3083,18 @@ static BOOL canonicalize_path_opaque(const parse_data *data, Uri *uri, DWORD fla
  * URI is opaque it canonicalizes the path of the URI.
  */
 static BOOL canonicalize_hierpart(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
-    uri->display_absolute = TRUE;
+    if(!data->is_opaque || (data->is_relative && (data->password || data->username))) {
+        /* "//" is only added for non-wildcard scheme types.
+         *
+         * A "//" is only added to a relative URI if it has a
+         * host or port component (this only happens if a IUriBuilder
+         * is generating an IUri).
+         */
+        if((data->is_relative && (data->host || data->has_port)) ||
+           (!data->is_relative && data->scheme_type != URL_SCHEME_WILDCARD)) {
+            if(data->scheme_type == URL_SCHEME_WILDCARD)
+                FIXME("Here\n");
 
-    if(!data->is_opaque) {
-        /* "//" is only added for non-wildcard scheme types. */
-        if(data->scheme_type != URL_SCHEME_WILDCARD) {
             if(!computeOnly) {
                 INT pos = uri->canon_len;
 
@@ -3129,10 +3107,18 @@ static BOOL canonicalize_hierpart(const parse_data *data, Uri *uri, DWORD flags,
         if(!canonicalize_authority(data, uri, flags, computeOnly))
             return FALSE;
 
-        /* TODO: Canonicalize the path of the URI. */
-        if(!canonicalize_path_hierarchical(data, uri, flags, computeOnly))
-            return FALSE;
-
+        if(data->is_relative && (data->password || data->username)) {
+            if(!canonicalize_path_opaque(data, uri, flags, computeOnly))
+                return FALSE;
+        } else {
+            if(!computeOnly)
+                uri->path_start = uri->canon_len;
+            uri->path_len = canonicalize_path_hierarchical(data->path, data->path_len, data->scheme_type, data->host_len != 0,
+                    flags, computeOnly ? NULL : uri->canon_uri+uri->canon_len);
+            uri->canon_len += uri->path_len;
+            if(!computeOnly && !uri->path_len)
+                uri->path_start = -1;
+        }
     } else {
         /* Opaque URI's don't have an authority. */
         uri->userinfo_start = uri->userinfo_split = -1;
@@ -3144,6 +3130,7 @@ static BOOL canonicalize_hierpart(const parse_data *data, Uri *uri, DWORD flags,
         uri->authority_start = -1;
         uri->authority_len = 0;
         uri->domain_offset = -1;
+        uri->port_offset = -1;
 
         if(is_hierarchical_scheme(data->scheme_type)) {
             DWORD i;
@@ -3151,7 +3138,7 @@ static BOOL canonicalize_hierpart(const parse_data *data, Uri *uri, DWORD flags,
             /* Absolute URIs aren't displayed for known scheme types
              * which should be hierarchical URIs.
              */
-            uri->display_absolute = FALSE;
+            uri->display_modifiers |= URI_DISPLAY_NO_ABSOLUTE_URI;
 
             /* Windows also sets the port for these (if they have one). */
             for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
@@ -3314,7 +3301,7 @@ static BOOL canonicalize_scheme(const parse_data *data, Uri *uri, DWORD flags, B
             uri->scheme_start = pos;
 
             TRACE("(%p %p %x): Canonicalized scheme=%s, len=%d.\n", data, uri, flags,
-                    debugstr_wn(uri->canon_uri,  uri->scheme_len), data->scheme_len);
+                    debugstr_wn(uri->canon_uri+uri->scheme_start,  data->scheme_len), data->scheme_len);
         }
 
         /* This happens in both computation modes. */
@@ -3324,7 +3311,7 @@ static BOOL canonicalize_scheme(const parse_data *data, Uri *uri, DWORD flags, B
     return TRUE;
 }
 
-/* Compute's what the length of the URI specified by the parse_data will be
+/* Computes what the length of the URI specified by the parse_data will be
  * after canonicalization occurs using the specified flags.
  *
  * This function will return a non-zero value indicating the length of the canonicalized
@@ -3364,18 +3351,18 @@ static int compute_canonicalized_length(const parse_data *data, DWORD flags) {
 }
 
 /* Canonicalizes the URI data specified in the parse_data, using the given flags. If the
- * canonicalization succeededs it will store all the canonicalization information
+ * canonicalization succeeds it will store all the canonicalization information
  * in the pointer to the Uri.
  *
  * To canonicalize a URI this function first computes what the length of the URI
- * specified by the parse_data will be. Once this is done it will then perfom the actual
+ * specified by the parse_data will be. Once this is done it will then perform the actual
  * canonicalization of the URI.
  */
 static HRESULT canonicalize_uri(const parse_data *data, Uri *uri, DWORD flags) {
     INT len;
 
     uri->canon_uri = NULL;
-    len = uri->canon_size = uri->canon_len = 0;
+    uri->canon_size = uri->canon_len = 0;
 
     TRACE("(%p %p %x): beginning to canonicalize URI %s.\n", data, uri, flags, debugstr_w(data->uri));
 
@@ -3394,14 +3381,12 @@ static HRESULT canonicalize_uri(const parse_data *data, Uri *uri, DWORD flags) {
     uri->canon_size = len;
     if(!canonicalize_scheme(data, uri, flags, FALSE)) {
         ERR("(%p %p %x): Unable to canonicalize the scheme of the URI.\n", data, uri, flags);
-        heap_free(uri->canon_uri);
         return E_INVALIDARG;
     }
     uri->scheme_type = data->scheme_type;
 
     if(!canonicalize_hierpart(data, uri, flags, FALSE)) {
         ERR("(%p %p %x): Unable to canonicalize the heirpart of the URI\n", data, uri, flags);
-        heap_free(uri->canon_uri);
         return E_INVALIDARG;
     }
 
@@ -3422,7 +3407,7 @@ static HRESULT canonicalize_uri(const parse_data *data, Uri *uri, DWORD flags) {
      */
     if(uri->canon_len < uri->canon_size) {
         /* This happens if the URI is hierarchical and dot
-         * segments were removed from it's path.
+         * segments were removed from its path.
          */
         WCHAR *tmp = heap_realloc(uri->canon_uri, (uri->canon_len+1)*sizeof(WCHAR));
         if(!tmp)
@@ -3510,12 +3495,9 @@ static HRESULT set_builder_component(LPWSTR *component, DWORD *component_len, LP
     return S_OK;
 }
 
-#define URI(x)         ((IUri*)  &(x)->lpIUriVtbl)
-#define URIBUILDER(x)  ((IUriBuilder*)  &(x)->lpIUriBuilderVtbl)
-
 static void reset_builder(UriBuilder *builder) {
     if(builder->uri)
-        IUri_Release(URI(builder->uri));
+        IUri_Release(&builder->uri->IUri_iface);
     builder->uri = NULL;
 
     heap_free(builder->fragment);
@@ -3720,8 +3702,11 @@ static void setup_port(const UriBuilder *builder, parse_data *data, DWORD flags)
 
 static HRESULT validate_path(const UriBuilder *builder, parse_data *data, DWORD flags) {
     const WCHAR *ptr = NULL;
+    const WCHAR *component;
     const WCHAR **pptr;
     DWORD expected_len;
+    BOOL check_len = TRUE;
+    BOOL valid = FALSE;
 
     if(builder->path) {
         ptr = builder->path;
@@ -3730,29 +3715,31 @@ static HRESULT validate_path(const UriBuilder *builder, parse_data *data, DWORD
               builder->uri && builder->uri->path_start > -1) {
         ptr = builder->uri->canon_uri+builder->uri->path_start;
         expected_len = builder->uri->path_len;
+    } else {
+        static const WCHAR nullW[] = {0};
+        ptr = nullW;
+        check_len = FALSE;
+        expected_len = -1;
     }
 
-    if(ptr) {
-        BOOL valid = FALSE;
-        const WCHAR *component = ptr;
-        pptr = &ptr;
-
-        /* How the path is validated depends on what type of
-         * URI it is.
-         */
-        valid = data->is_opaque ?
-            parse_path_opaque(pptr, data, flags) : parse_path_hierarchical(pptr, data, flags);
+    component = ptr;
+    pptr = &ptr;
 
-        if(!valid || expected_len != data->path_len) {
-            TRACE("(%p %p %x): Invalid path componet %s.\n", builder, data, flags,
-                debugstr_wn(component, expected_len));
-            return INET_E_INVALID_URL;
-        }
+    /* How the path is validated depends on what type of
+     * URI it is.
+     */
+    valid = data->is_opaque ?
+        parse_path_opaque(pptr, data, flags) : parse_path_hierarchical(pptr, data, flags);
 
-        TRACE("(%p %p %x): Valid path component %s len=%d.\n", builder, data, flags,
-            debugstr_wn(data->path, data->path_len), data->path_len);
+    if(!valid || (check_len && expected_len != data->path_len)) {
+        TRACE("(%p %p %x): Invalid path component %s.\n", builder, data, flags,
+            debugstr_wn(component, expected_len) );
+        return INET_E_INVALID_URL;
     }
 
+    TRACE("(%p %p %x): Valid path component %s len=%d.\n", builder, data, flags,
+        debugstr_wn(data->path, data->path_len), data->path_len);
+
     return S_OK;
 }
 
@@ -3805,7 +3792,7 @@ static HRESULT validate_fragment(const UriBuilder *builder, parse_data *data, DW
         const WCHAR *component = ptr;
         pptr = &ptr;
 
-        if(parse_query(pptr, data, flags) && expected_len == data->fragment_len)
+        if(parse_fragment(pptr, data, flags) && expected_len == data->fragment_len)
             TRACE("(%p %p %x): Valid fragment component %s len=%d.\n", builder, data, flags,
                 debugstr_wn(data->fragment, data->fragment_len), data->fragment_len);
         else {
@@ -3847,11 +3834,15 @@ static HRESULT validate_components(const UriBuilder *builder, parse_data *data,
     if(FAILED(hr))
         return hr;
 
-    /* The URI is opaque if it doesn't have an authority component. */
-    data->is_opaque = !data->username && !data->password && !data->host;
-
     setup_port(builder, data, flags);
 
+    /* The URI is opaque if it doesn't have an authority component. */
+    if(!data->is_relative)
+        data->is_opaque = !data->username && !data->password && !data->host && !data->has_port
+            && data->scheme_type != URL_SCHEME_FILE;
+    else
+        data->is_opaque = !data->host && !data->has_port;
+
     hr = validate_path(builder, data, flags);
     if(FAILED(hr))
         return hr;
@@ -3869,61 +3860,368 @@ static HRESULT validate_components(const UriBuilder *builder, parse_data *data,
     return S_OK;
 }
 
-static HRESULT build_uri(const UriBuilder *builder, IUri **uri, DWORD create_flags,
-                         DWORD use_orig_flags, DWORD encoding_mask)
+static HRESULT compare_file_paths(const Uri *a, const Uri *b, BOOL *ret)
 {
-    HRESULT hr;
-    parse_data data;
+    WCHAR *canon_path_a, *canon_path_b;
+    DWORD len_a, len_b;
 
-    if(!uri)
-        return E_POINTER;
+    if(!a->path_len) {
+        *ret = !b->path_len;
+        return S_OK;
+    }
 
-    if(encoding_mask && (!builder->uri || builder->modified_props)) {
-        *uri = NULL;
-        return E_NOTIMPL;
+    if(!b->path_len) {
+        *ret = FALSE;
+        return S_OK;
     }
 
-    /* Decide what flags should be used when creating the Uri. */
-    if((use_orig_flags & UriBuilder_USE_ORIGINAL_FLAGS) && builder->uri)
-        create_flags = builder->uri->create_flags;
-    else {
-        if(has_invalid_flag_combination(create_flags)) {
-            *uri = NULL;
-            return E_INVALIDARG;
-        }
+    /* Fast path */
+    if(a->path_len == b->path_len && !memicmpW(a->canon_uri+a->path_start, b->canon_uri+b->path_start, a->path_len)) {
+        *ret = TRUE;
+        return S_OK;
+    }
 
-        /* Set the default flags if they don't cause a conflict. */
-        apply_default_flags(&create_flags);
+    len_a = canonicalize_path_hierarchical(a->canon_uri+a->path_start, a->path_len, a->scheme_type, FALSE, 0, NULL);
+    len_b = canonicalize_path_hierarchical(b->canon_uri+b->path_start, b->path_len, b->scheme_type, FALSE, 0, NULL);
+
+    canon_path_a = heap_alloc(len_a*sizeof(WCHAR));
+    if(!canon_path_a)
+        return E_OUTOFMEMORY;
+    canon_path_b = heap_alloc(len_b*sizeof(WCHAR));
+    if(!canon_path_b) {
+        heap_free(canon_path_a);
+        return E_OUTOFMEMORY;
     }
 
-    /* Return the base IUri if no changes have been made and the create_flags match. */
-    if(builder->uri && !builder->modified_props && builder->uri->create_flags == create_flags) {
-        *uri = URI(builder->uri);
-        IUri_AddRef(*uri);
+    len_a = canonicalize_path_hierarchical(a->canon_uri+a->path_start, a->path_len, a->scheme_type, FALSE, 0, canon_path_a);
+    len_b = canonicalize_path_hierarchical(b->canon_uri+b->path_start, b->path_len, b->scheme_type, FALSE, 0, canon_path_b);
+
+    *ret = len_a == len_b && !memicmpW(canon_path_a, canon_path_b, len_a);
+
+    heap_free(canon_path_a);
+    heap_free(canon_path_b);
+    return S_OK;
+}
+
+/* Checks if the two Uri's are logically equivalent. It's a simple
+ * comparison, since they are both of type Uri, and it can access
+ * the properties of each Uri directly without the need to go
+ * through the "IUri_Get*" interface calls.
+ */
+static HRESULT compare_uris(const Uri *a, const Uri *b, BOOL *ret) {
+    const BOOL known_scheme = a->scheme_type != URL_SCHEME_UNKNOWN;
+    const BOOL are_hierarchical = a->authority_start > -1 && b->authority_start > -1;
+    HRESULT hres;
+
+    *ret = FALSE;
+
+    if(a->scheme_type != b->scheme_type)
         return S_OK;
+
+    /* Only compare the scheme names (if any) if their unknown scheme types. */
+    if(!known_scheme) {
+        if((a->scheme_start > -1 && b->scheme_start > -1) &&
+           (a->scheme_len == b->scheme_len)) {
+            /* Make sure the schemes are the same. */
+            if(StrCmpNW(a->canon_uri+a->scheme_start, b->canon_uri+b->scheme_start, a->scheme_len))
+                return S_OK;
+        } else if(a->scheme_len != b->scheme_len)
+            /* One of the Uri's has a scheme name, while the other doesn't. */
+            return S_OK;
     }
 
-    hr = validate_components(builder, &data, create_flags);
+    /* If they have a userinfo component, perform case sensitive compare. */
+    if((a->userinfo_start > -1 && b->userinfo_start > -1) &&
+       (a->userinfo_len == b->userinfo_len)) {
+        if(StrCmpNW(a->canon_uri+a->userinfo_start, b->canon_uri+b->userinfo_start, a->userinfo_len))
+            return S_OK;
+    } else if(a->userinfo_len != b->userinfo_len)
+        /* One of the Uri's had a userinfo, while the other one doesn't. */
+        return S_OK;
+
+    /* Check if they have a host name. */
+    if((a->host_start > -1 && b->host_start > -1) &&
+       (a->host_len == b->host_len)) {
+        /* Perform a case insensitive compare if they are a known scheme type. */
+        if(known_scheme) {
+            if(StrCmpNIW(a->canon_uri+a->host_start, b->canon_uri+b->host_start, a->host_len))
+                return S_OK;
+        } else if(StrCmpNW(a->canon_uri+a->host_start, b->canon_uri+b->host_start, a->host_len))
+            return S_OK;
+    } else if(a->host_len != b->host_len)
+        /* One of the Uri's had a host, while the other one didn't. */
+        return S_OK;
+
+    if(a->has_port && b->has_port) {
+        if(a->port != b->port)
+            return S_OK;
+    } else if(a->has_port || b->has_port)
+        /* One had a port, while the other one didn't. */
+        return S_OK;
+
+    /* Windows is weird with how it handles paths. For example
+     * One URI could be "http://google.com" (after canonicalization)
+     * and one could be "http://google.com/" and the IsEqual function
+     * would still evaluate to TRUE, but, only if they are both hierarchical
+     * URIs.
+     */
+    if(a->scheme_type == URL_SCHEME_FILE) {
+        BOOL cmp;
+
+        hres = compare_file_paths(a, b, &cmp);
+        if(FAILED(hres) || !cmp)
+            return hres;
+    } else if((a->path_start > -1 && b->path_start > -1) &&
+       (a->path_len == b->path_len)) {
+        if(StrCmpNW(a->canon_uri+a->path_start, b->canon_uri+b->path_start, a->path_len))
+            return S_OK;
+    } else if(are_hierarchical && a->path_len == -1 && b->path_len == 0) {
+        if(*(a->canon_uri+a->path_start) != '/')
+            return S_OK;
+    } else if(are_hierarchical && b->path_len == 1 && a->path_len == 0) {
+        if(*(b->canon_uri+b->path_start) != '/')
+            return S_OK;
+    } else if(a->path_len != b->path_len)
+        return S_OK;
+
+    /* Compare the query strings of the two URIs. */
+    if((a->query_start > -1 && b->query_start > -1) &&
+       (a->query_len == b->query_len)) {
+        if(StrCmpNW(a->canon_uri+a->query_start, b->canon_uri+b->query_start, a->query_len))
+            return S_OK;
+    } else if(a->query_len != b->query_len)
+        return S_OK;
+
+    if((a->fragment_start > -1 && b->fragment_start > -1) &&
+       (a->fragment_len == b->fragment_len)) {
+        if(StrCmpNW(a->canon_uri+a->fragment_start, b->canon_uri+b->fragment_start, a->fragment_len))
+            return S_OK;
+    } else if(a->fragment_len != b->fragment_len)
+        return S_OK;
+
+    /* If we get here, the two URIs are equivalent. */
+    *ret = TRUE;
+    return S_OK;
+}
+
+static void convert_to_dos_path(const WCHAR *path, DWORD path_len,
+                                WCHAR *output, DWORD *output_len)
+{
+    const WCHAR *ptr = path;
+
+    if(path_len > 3 && *ptr == '/' && is_drive_path(path+1))
+        /* Skip over the leading / before the drive path. */
+        ++ptr;
+
+    for(; ptr < path+path_len; ++ptr) {
+        if(*ptr == '/') {
+            if(output)
+                *output++ = '\\';
+            (*output_len)++;
+        } else {
+            if(output)
+                *output++ = *ptr;
+            (*output_len)++;
+        }
+    }
+}
+
+/* Generates a raw uri string using the parse_data. */
+static DWORD generate_raw_uri(const parse_data *data, BSTR uri, DWORD flags) {
+    DWORD length = 0;
+
+    if(data->scheme) {
+        if(uri) {
+            memcpy(uri, data->scheme, data->scheme_len*sizeof(WCHAR));
+            uri[data->scheme_len] = ':';
+        }
+        length += data->scheme_len+1;
+    }
+
+    if(!data->is_opaque) {
+        /* For the "//" which appears before the authority component. */
+        if(uri) {
+            uri[length] = '/';
+            uri[length+1] = '/';
+        }
+        length += 2;
+
+        /* Check if we need to add the "\\" before the host name
+         * of a UNC server name in a DOS path.
+         */
+        if(flags & RAW_URI_CONVERT_TO_DOS_PATH &&
+           data->scheme_type == URL_SCHEME_FILE && data->host) {
+            if(uri) {
+                uri[length] = '\\';
+                uri[length+1] = '\\';
+            }
+            length += 2;
+        }
+    }
+
+    if(data->username) {
+        if(uri)
+            memcpy(uri+length, data->username, data->username_len*sizeof(WCHAR));
+        length += data->username_len;
+    }
+
+    if(data->password) {
+        if(uri) {
+            uri[length] = ':';
+            memcpy(uri+length+1, data->password, data->password_len*sizeof(WCHAR));
+        }
+        length += data->password_len+1;
+    }
+
+    if(data->password || data->username) {
+        if(uri)
+            uri[length] = '@';
+        ++length;
+    }
+
+    if(data->host) {
+        /* IPv6 addresses get the brackets added around them if they don't already
+         * have them.
+         */
+        const BOOL add_brackets = data->host_type == Uri_HOST_IPV6 && *(data->host) != '[';
+        if(add_brackets) {
+            if(uri)
+                uri[length] = '[';
+            ++length;
+        }
+
+        if(uri)
+            memcpy(uri+length, data->host, data->host_len*sizeof(WCHAR));
+        length += data->host_len;
+
+        if(add_brackets) {
+            if(uri)
+                uri[length] = ']';
+            length++;
+        }
+    }
+
+    if(data->has_port) {
+        /* The port isn't included in the raw uri if it's the default
+         * port for the scheme type.
+         */
+        DWORD i;
+        BOOL is_default = FALSE;
+
+        for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
+            if(data->scheme_type == default_ports[i].scheme &&
+               data->port_value == default_ports[i].port)
+                is_default = TRUE;
+        }
+
+        if(!is_default || flags & RAW_URI_FORCE_PORT_DISP) {
+            if(uri)
+                uri[length] = ':';
+            ++length;
+
+            if(uri)
+                length += ui2str(uri+length, data->port_value);
+            else
+                length += ui2str(NULL, data->port_value);
+        }
+    }
+
+    /* Check if a '/' should be added before the path for hierarchical URIs. */
+    if(!data->is_opaque && data->path && *(data->path) != '/') {
+        if(uri)
+            uri[length] = '/';
+        ++length;
+    }
+
+    if(data->path) {
+        if(!data->is_opaque && data->scheme_type == URL_SCHEME_FILE &&
+           flags & RAW_URI_CONVERT_TO_DOS_PATH) {
+            DWORD len = 0;
+
+            if(uri)
+                convert_to_dos_path(data->path, data->path_len, uri+length, &len);
+            else
+                convert_to_dos_path(data->path, data->path_len, NULL, &len);
+
+            length += len;
+        } else {
+            if(uri)
+                memcpy(uri+length, data->path, data->path_len*sizeof(WCHAR));
+            length += data->path_len;
+        }
+    }
+
+    if(data->query) {
+        if(uri)
+            memcpy(uri+length, data->query, data->query_len*sizeof(WCHAR));
+        length += data->query_len;
+    }
+
+    if(data->fragment) {
+        if(uri)
+            memcpy(uri+length, data->fragment, data->fragment_len*sizeof(WCHAR));
+        length += data->fragment_len;
+    }
+
+    if(uri)
+        TRACE("(%p %p): Generated raw uri=%s len=%d\n", data, uri, debugstr_wn(uri, length), length);
+    else
+        TRACE("(%p %p): Computed raw uri len=%d\n", data, uri, length);
+
+    return length;
+}
+
+static HRESULT generate_uri(const UriBuilder *builder, const parse_data *data, Uri *uri, DWORD flags) {
+    HRESULT hr;
+    DWORD length = generate_raw_uri(data, NULL, 0);
+    uri->raw_uri = SysAllocStringLen(NULL, length);
+    if(!uri->raw_uri)
+        return E_OUTOFMEMORY;
+
+    generate_raw_uri(data, uri->raw_uri, 0);
+
+    hr = canonicalize_uri(data, uri, flags);
     if(FAILED(hr)) {
-        *uri = NULL;
+        if(hr == E_INVALIDARG)
+            return INET_E_INVALID_URL;
         return hr;
     }
 
-    return E_NOTIMPL;
+    uri->create_flags = flags;
+    return S_OK;
+}
+
+static inline Uri* impl_from_IUri(IUri *iface)
+{
+    return CONTAINING_RECORD(iface, Uri, IUri_iface);
 }
 
-#define URI_THIS(iface) DEFINE_THIS(Uri, IUri, iface)
+static inline void destroy_uri_obj(Uri *This)
+{
+    SysFreeString(This->raw_uri);
+    heap_free(This->canon_uri);
+    heap_free(This);
+}
 
 static HRESULT WINAPI Uri_QueryInterface(IUri *iface, REFIID riid, void **ppv)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
 
     if(IsEqualGUID(&IID_IUnknown, riid)) {
         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
-        *ppv = URI(This);
+        *ppv = &This->IUri_iface;
     }else if(IsEqualGUID(&IID_IUri, riid)) {
         TRACE("(%p)->(IID_IUri %p)\n", This, ppv);
-        *ppv = URI(This);
+        *ppv = &This->IUri_iface;
+    }else if(IsEqualGUID(&IID_IUriBuilderFactory, riid)) {
+        TRACE("(%p)->(IID_IUriBuilderFactory %p)\n", This, ppv);
+        *ppv = &This->IUriBuilderFactory_iface;
+    }else if(IsEqualGUID(&IID_IPersistStream, riid)) {
+        TRACE("(%p)->(IID_IPersistStream %p)\n", This, ppv);
+        *ppv = &This->IPersistStream_iface;
+    }else if(IsEqualGUID(&IID_IMarshal, riid)) {
+        TRACE("(%p)->(IID_IMarshal %p)\n", This, ppv);
+        *ppv = &This->IMarshal_iface;
     }else if(IsEqualGUID(&IID_IUriObj, riid)) {
         TRACE("(%p)->(IID_IUriObj %p)\n", This, ppv);
         *ppv = This;
@@ -3940,7 +4238,7 @@ static HRESULT WINAPI Uri_QueryInterface(IUri *iface, REFIID riid, void **ppv)
 
 static ULONG WINAPI Uri_AddRef(IUri *iface)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
     LONG ref = InterlockedIncrement(&This->ref);
 
     TRACE("(%p) ref=%d\n", This, ref);
@@ -3950,40 +4248,39 @@ static ULONG WINAPI Uri_AddRef(IUri *iface)
 
 static ULONG WINAPI Uri_Release(IUri *iface)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
     LONG ref = InterlockedDecrement(&This->ref);
 
     TRACE("(%p) ref=%d\n", This, ref);
 
-    if(!ref) {
-        SysFreeString(This->raw_uri);
-        heap_free(This->canon_uri);
-        heap_free(This);
-    }
+    if(!ref)
+        destroy_uri_obj(This);
 
     return ref;
 }
 
 static HRESULT WINAPI Uri_GetPropertyBSTR(IUri *iface, Uri_PROPERTY uriProp, BSTR *pbstrProperty, DWORD dwFlags)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
     HRESULT hres;
-    TRACE("(%p)->(%d %p %x)\n", This, uriProp, pbstrProperty, dwFlags);
+    TRACE("(%p %s)->(%d %p %x)\n", This, debugstr_w(This->canon_uri), uriProp, pbstrProperty, dwFlags);
 
+    if(!This->create_flags)
+        return E_UNEXPECTED;
     if(!pbstrProperty)
         return E_POINTER;
 
     if(uriProp > Uri_PROPERTY_STRING_LAST) {
-        /* Windows allocates an empty BSTR for invalid Uri_PROPERTY's. */
-        *pbstrProperty = SysAllocStringLen(NULL, 0);
-        if(!(*pbstrProperty))
-            return E_OUTOFMEMORY;
-
         /* It only returns S_FALSE for the ZONE property... */
-        if(uriProp == Uri_PROPERTY_ZONE)
+        if(uriProp == Uri_PROPERTY_ZONE) {
+            *pbstrProperty = SysAllocStringLen(NULL, 0);
+            if(!(*pbstrProperty))
+                return E_OUTOFMEMORY;
             return S_FALSE;
-        else
-            return S_OK;
+        }
+
+        *pbstrProperty = NULL;
+        return E_INVALIDARG;
     }
 
     /* Don't have support for flags yet. */
@@ -3994,7 +4291,7 @@ static HRESULT WINAPI Uri_GetPropertyBSTR(IUri *iface, Uri_PROPERTY uriProp, BST
 
     switch(uriProp) {
     case Uri_PROPERTY_ABSOLUTE_URI:
-        if(!This->display_absolute) {
+        if(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI) {
             *pbstrProperty = SysAllocStringLen(NULL, 0);
             hres = S_FALSE;
         } else {
@@ -4036,7 +4333,12 @@ static HRESULT WINAPI Uri_GetPropertyBSTR(IUri *iface, Uri_PROPERTY uriProp, BST
         break;
     case Uri_PROPERTY_AUTHORITY:
         if(This->authority_start > -1) {
-            *pbstrProperty = SysAllocStringLen(This->canon_uri+This->authority_start, This->authority_len);
+            if(This->port_offset > -1 && is_default_port(This->scheme_type, This->port) &&
+               This->display_modifiers & URI_DISPLAY_NO_DEFAULT_PORT_AUTH)
+                /* Don't include the port in the authority component. */
+                *pbstrProperty = SysAllocStringLen(This->canon_uri+This->authority_start, This->port_offset);
+            else
+                *pbstrProperty = SysAllocStringLen(This->canon_uri+This->authority_start, This->authority_len);
             hres = S_OK;
         } else {
             *pbstrProperty = SysAllocStringLen(NULL, 0);
@@ -4251,10 +4553,12 @@ static HRESULT WINAPI Uri_GetPropertyBSTR(IUri *iface, Uri_PROPERTY uriProp, BST
 
 static HRESULT WINAPI Uri_GetPropertyLength(IUri *iface, Uri_PROPERTY uriProp, DWORD *pcchProperty, DWORD dwFlags)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
     HRESULT hres;
-    TRACE("(%p)->(%d %p %x)\n", This, uriProp, pcchProperty, dwFlags);
+    TRACE("(%p %s)->(%d %p %x)\n", This, debugstr_w(This->canon_uri), uriProp, pcchProperty, dwFlags);
 
+    if(!This->create_flags)
+        return E_UNEXPECTED;
     if(!pcchProperty)
         return E_INVALIDARG;
 
@@ -4270,7 +4574,7 @@ static HRESULT WINAPI Uri_GetPropertyLength(IUri *iface, Uri_PROPERTY uriProp, D
 
     switch(uriProp) {
     case Uri_PROPERTY_ABSOLUTE_URI:
-        if(!This->display_absolute) {
+        if(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI) {
             *pcchProperty = 0;
             hres = S_FALSE;
         } else {
@@ -4292,7 +4596,13 @@ static HRESULT WINAPI Uri_GetPropertyLength(IUri *iface, Uri_PROPERTY uriProp, D
 
         break;
     case Uri_PROPERTY_AUTHORITY:
-        *pcchProperty = This->authority_len;
+        if(This->port_offset > -1 &&
+           This->display_modifiers & URI_DISPLAY_NO_DEFAULT_PORT_AUTH &&
+           is_default_port(This->scheme_type, This->port))
+            /* Only count up until the port in the authority. */
+            *pcchProperty = This->port_offset;
+        else
+            *pcchProperty = This->authority_len;
         hres = (This->authority_start > -1) ? S_OK : S_FALSE;
         break;
     case Uri_PROPERTY_DISPLAY_URI:
@@ -4379,11 +4689,13 @@ static HRESULT WINAPI Uri_GetPropertyLength(IUri *iface, Uri_PROPERTY uriProp, D
 
 static HRESULT WINAPI Uri_GetPropertyDWORD(IUri *iface, Uri_PROPERTY uriProp, DWORD *pcchProperty, DWORD dwFlags)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
     HRESULT hres;
 
-    TRACE("(%p)->(%d %p %x)\n", This, uriProp, pcchProperty, dwFlags);
+    TRACE("(%p %s)->(%d %p %x)\n", This, debugstr_w(This->canon_uri), uriProp, pcchProperty, dwFlags);
 
+    if(!This->create_flags)
+        return E_UNEXPECTED;
     if(!pcchProperty)
         return E_INVALIDARG;
 
@@ -4431,15 +4743,16 @@ static HRESULT WINAPI Uri_GetPropertyDWORD(IUri *iface, Uri_PROPERTY uriProp, DW
 
 static HRESULT WINAPI Uri_HasProperty(IUri *iface, Uri_PROPERTY uriProp, BOOL *pfHasProperty)
 {
-    Uri *This = URI_THIS(iface);
-    TRACE("(%p)->(%d %p)\n", This, uriProp, pfHasProperty);
+    Uri *This = impl_from_IUri(iface);
+
+    TRACE("(%p %s)->(%d %p)\n", This, debugstr_w(This->canon_uri), uriProp, pfHasProperty);
 
     if(!pfHasProperty)
         return E_INVALIDARG;
 
     switch(uriProp) {
     case Uri_PROPERTY_ABSOLUTE_URI:
-        *pfHasProperty = This->display_absolute;
+        *pfHasProperty = !(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI);
         break;
     case Uri_PROPERTY_AUTHORITY:
         *pfHasProperty = This->authority_start > -1;
@@ -4509,130 +4822,131 @@ static HRESULT WINAPI Uri_HasProperty(IUri *iface, Uri_PROPERTY uriProp, BOOL *p
 static HRESULT WINAPI Uri_GetAbsoluteUri(IUri *iface, BSTR *pstrAbsoluteUri)
 {
     TRACE("(%p)->(%p)\n", iface, pstrAbsoluteUri);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_ABSOLUTE_URI, pstrAbsoluteUri, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_ABSOLUTE_URI, pstrAbsoluteUri, 0);
 }
 
 static HRESULT WINAPI Uri_GetAuthority(IUri *iface, BSTR *pstrAuthority)
 {
     TRACE("(%p)->(%p)\n", iface, pstrAuthority);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_AUTHORITY, pstrAuthority, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_AUTHORITY, pstrAuthority, 0);
 }
 
 static HRESULT WINAPI Uri_GetDisplayUri(IUri *iface, BSTR *pstrDisplayUri)
 {
     TRACE("(%p)->(%p)\n", iface, pstrDisplayUri);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_DISPLAY_URI, pstrDisplayUri, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_DISPLAY_URI, pstrDisplayUri, 0);
 }
 
 static HRESULT WINAPI Uri_GetDomain(IUri *iface, BSTR *pstrDomain)
 {
     TRACE("(%p)->(%p)\n", iface, pstrDomain);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_DOMAIN, pstrDomain, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_DOMAIN, pstrDomain, 0);
 }
 
 static HRESULT WINAPI Uri_GetExtension(IUri *iface, BSTR *pstrExtension)
 {
     TRACE("(%p)->(%p)\n", iface, pstrExtension);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_EXTENSION, pstrExtension, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_EXTENSION, pstrExtension, 0);
 }
 
 static HRESULT WINAPI Uri_GetFragment(IUri *iface, BSTR *pstrFragment)
 {
     TRACE("(%p)->(%p)\n", iface, pstrFragment);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_FRAGMENT, pstrFragment, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_FRAGMENT, pstrFragment, 0);
 }
 
 static HRESULT WINAPI Uri_GetHost(IUri *iface, BSTR *pstrHost)
 {
     TRACE("(%p)->(%p)\n", iface, pstrHost);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_HOST, pstrHost, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_HOST, pstrHost, 0);
 }
 
 static HRESULT WINAPI Uri_GetPassword(IUri *iface, BSTR *pstrPassword)
 {
     TRACE("(%p)->(%p)\n", iface, pstrPassword);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_PASSWORD, pstrPassword, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_PASSWORD, pstrPassword, 0);
 }
 
 static HRESULT WINAPI Uri_GetPath(IUri *iface, BSTR *pstrPath)
 {
     TRACE("(%p)->(%p)\n", iface, pstrPath);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_PATH, pstrPath, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_PATH, pstrPath, 0);
 }
 
 static HRESULT WINAPI Uri_GetPathAndQuery(IUri *iface, BSTR *pstrPathAndQuery)
 {
     TRACE("(%p)->(%p)\n", iface, pstrPathAndQuery);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_PATH_AND_QUERY, pstrPathAndQuery, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_PATH_AND_QUERY, pstrPathAndQuery, 0);
 }
 
 static HRESULT WINAPI Uri_GetQuery(IUri *iface, BSTR *pstrQuery)
 {
     TRACE("(%p)->(%p)\n", iface, pstrQuery);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_QUERY, pstrQuery, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_QUERY, pstrQuery, 0);
 }
 
 static HRESULT WINAPI Uri_GetRawUri(IUri *iface, BSTR *pstrRawUri)
 {
     TRACE("(%p)->(%p)\n", iface, pstrRawUri);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_RAW_URI, pstrRawUri, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_RAW_URI, pstrRawUri, 0);
 }
 
 static HRESULT WINAPI Uri_GetSchemeName(IUri *iface, BSTR *pstrSchemeName)
 {
     TRACE("(%p)->(%p)\n", iface, pstrSchemeName);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_SCHEME_NAME, pstrSchemeName, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_SCHEME_NAME, pstrSchemeName, 0);
 }
 
 static HRESULT WINAPI Uri_GetUserInfo(IUri *iface, BSTR *pstrUserInfo)
 {
     TRACE("(%p)->(%p)\n", iface, pstrUserInfo);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_USER_INFO, pstrUserInfo, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_USER_INFO, pstrUserInfo, 0);
 }
 
 static HRESULT WINAPI Uri_GetUserName(IUri *iface, BSTR *pstrUserName)
 {
     TRACE("(%p)->(%p)\n", iface, pstrUserName);
-    return Uri_GetPropertyBSTR(iface, Uri_PROPERTY_USER_NAME, pstrUserName, 0);
+    return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_USER_NAME, pstrUserName, 0);
 }
 
 static HRESULT WINAPI Uri_GetHostType(IUri *iface, DWORD *pdwHostType)
 {
     TRACE("(%p)->(%p)\n", iface, pdwHostType);
-    return Uri_GetPropertyDWORD(iface, Uri_PROPERTY_HOST_TYPE, pdwHostType, 0);
+    return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_HOST_TYPE, pdwHostType, 0);
 }
 
 static HRESULT WINAPI Uri_GetPort(IUri *iface, DWORD *pdwPort)
 {
     TRACE("(%p)->(%p)\n", iface, pdwPort);
-    return Uri_GetPropertyDWORD(iface, Uri_PROPERTY_PORT, pdwPort, 0);
+    return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_PORT, pdwPort, 0);
 }
 
 static HRESULT WINAPI Uri_GetScheme(IUri *iface, DWORD *pdwScheme)
 {
-    Uri *This = URI_THIS(iface);
-    TRACE("(%p)->(%p)\n", This, pdwScheme);
-    return Uri_GetPropertyDWORD(iface, Uri_PROPERTY_SCHEME, pdwScheme, 0);
+    TRACE("(%p)->(%p)\n", iface, pdwScheme);
+    return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_SCHEME, pdwScheme, 0);
 }
 
 static HRESULT WINAPI Uri_GetZone(IUri *iface, DWORD *pdwZone)
 {
     TRACE("(%p)->(%p)\n", iface, pdwZone);
-    return Uri_GetPropertyDWORD(iface, Uri_PROPERTY_ZONE,pdwZone, 0);
+    return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_ZONE,pdwZone, 0);
 }
 
 static HRESULT WINAPI Uri_GetProperties(IUri *iface, DWORD *pdwProperties)
 {
-    Uri *This = URI_THIS(iface);
-    TRACE("(%p)->(%p)\n", This, pdwProperties);
+    Uri *This = impl_from_IUri(iface);
+    TRACE("(%p %s)->(%p)\n", This, debugstr_w(This->canon_uri), pdwProperties);
 
+    if(!This->create_flags)
+        return E_UNEXPECTED;
     if(!pdwProperties)
         return E_INVALIDARG;
 
     /* All URIs have these. */
     *pdwProperties = Uri_HAS_DISPLAY_URI|Uri_HAS_RAW_URI|Uri_HAS_SCHEME|Uri_HAS_HOST_TYPE;
 
-    if(This->display_absolute)
+    if(!(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI))
         *pdwProperties |= Uri_HAS_ABSOLUTE_URI;
 
     if(This->scheme_start > -1)
@@ -4671,11 +4985,13 @@ static HRESULT WINAPI Uri_GetProperties(IUri *iface, DWORD *pdwProperties)
 
 static HRESULT WINAPI Uri_IsEqual(IUri *iface, IUri *pUri, BOOL *pfEqual)
 {
-    Uri *This = URI_THIS(iface);
+    Uri *This = impl_from_IUri(iface);
     Uri *other;
 
-    TRACE("(%p)->(%p %p)\n", This, pUri, pfEqual);
+    TRACE("(%p %s)->(%p %p)\n", This, debugstr_w(This->canon_uri), pUri, pfEqual);
 
+    if(!This->create_flags)
+        return E_UNEXPECTED;
     if(!pfEqual)
         return E_POINTER;
 
@@ -4687,19 +5003,15 @@ static HRESULT WINAPI Uri_IsEqual(IUri *iface, IUri *pUri, BOOL *pfEqual)
     }
 
     /* Try to convert it to a Uri (allows for a more simple comparison). */
-    if((other = get_uri_obj(pUri)))
-        *pfEqual = are_equal_simple(This, other);
-    else {
-        /* Do it the hard way. */
+    if(!(other = get_uri_obj(pUri))) {
         FIXME("(%p)->(%p %p) No support for unknown IUri's yet.\n", iface, pUri, pfEqual);
         return E_NOTIMPL;
     }
 
-    return S_OK;
+    TRACE("comparing to %s\n", debugstr_w(other->canon_uri));
+    return compare_uris(This, other, pfEqual);
 }
 
-#undef URI_THIS
-
 static const IUriVtbl UriVtbl = {
     Uri_QueryInterface,
     Uri_AddRef,
@@ -4731,663 +5043,2272 @@ static const IUriVtbl UriVtbl = {
     Uri_IsEqual
 };
 
-/***********************************************************************
- *           CreateUri (urlmon.@)
- *
- * Creates a new IUri object using the URI represented by pwzURI. This function
- * parses and validates the components of pwzURI and then canonicalizes the
- * parsed components.
- *
- * PARAMS
- *  pwzURI      [I] The URI to parse, validate, and canonicalize.
- *  dwFlags     [I] Flags which can affect how the parsing/canonicalization is performed.
- *  dwReserved  [I] Reserved (not used).
- *  ppURI       [O] The resulting IUri after parsing/canonicalization occurs.
- *
- * RETURNS
- *  Success: Returns S_OK. ppURI contains the pointer to the newly allocated IUri.
- *  Failure: E_INVALIDARG if there's invalid flag combinations in dwFlags, or an
- *           invalid parameters, or pwzURI doesn't represnt a valid URI.
- *           E_OUTOFMEMORY if any memory allocation fails.
- *
- * NOTES
- *  Default flags:
- *      Uri_CREATE_CANONICALIZE, Uri_CREATE_DECODE_EXTRA_INFO, Uri_CREATE_CRACK_UNKNOWN_SCHEMES,
- *      Uri_CREATE_PRE_PROCESS_HTML_URI, Uri_CREATE_NO_IE_SETTINGS.
- */
-HRESULT WINAPI CreateUri(LPCWSTR pwzURI, DWORD dwFlags, DWORD_PTR dwReserved, IUri **ppURI)
+static inline Uri* impl_from_IUriBuilderFactory(IUriBuilderFactory *iface)
 {
-    const DWORD supported_flags = Uri_CREATE_ALLOW_RELATIVE|Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME|
-        Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME|Uri_CREATE_NO_CANONICALIZE|Uri_CREATE_CANONICALIZE|
-        Uri_CREATE_DECODE_EXTRA_INFO|Uri_CREATE_NO_DECODE_EXTRA_INFO|Uri_CREATE_CRACK_UNKNOWN_SCHEMES|
-        Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES|Uri_CREATE_PRE_PROCESS_HTML_URI|Uri_CREATE_NO_PRE_PROCESS_HTML_URI|
-        Uri_CREATE_NO_IE_SETTINGS|Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS|Uri_CREATE_FILE_USE_DOS_PATH;
-    Uri *ret;
-    HRESULT hr;
-    parse_data data;
+    return CONTAINING_RECORD(iface, Uri, IUriBuilderFactory_iface);
+}
 
-    TRACE("(%s %x %x %p)\n", debugstr_w(pwzURI), dwFlags, (DWORD)dwReserved, ppURI);
+static HRESULT WINAPI UriBuilderFactory_QueryInterface(IUriBuilderFactory *iface, REFIID riid, void **ppv)
+{
+    Uri *This = impl_from_IUriBuilderFactory(iface);
+    return IUri_QueryInterface(&This->IUri_iface, riid, ppv);
+}
 
-    if(!ppURI)
-        return E_INVALIDARG;
+static ULONG WINAPI UriBuilderFactory_AddRef(IUriBuilderFactory *iface)
+{
+    Uri *This = impl_from_IUriBuilderFactory(iface);
+    return IUri_AddRef(&This->IUri_iface);
+}
 
-    if(!pwzURI || !*pwzURI) {
-        *ppURI = NULL;
-        return E_INVALIDARG;
-    }
+static ULONG WINAPI UriBuilderFactory_Release(IUriBuilderFactory *iface)
+{
+    Uri *This = impl_from_IUriBuilderFactory(iface);
+    return IUri_Release(&This->IUri_iface);
+}
 
-    /* Check for invalid flags. */
-    if(has_invalid_flag_combination(dwFlags)) {
-        *ppURI = NULL;
+static HRESULT WINAPI UriBuilderFactory_CreateIUriBuilder(IUriBuilderFactory *iface,
+                                                          DWORD dwFlags,
+                                                          DWORD_PTR dwReserved,
+                                                          IUriBuilder **ppIUriBuilder)
+{
+    Uri *This = impl_from_IUriBuilderFactory(iface);
+    TRACE("(%p)->(%08x %08x %p)\n", This, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
+
+    if(!ppIUriBuilder)
+        return E_POINTER;
+
+    if(dwFlags || dwReserved) {
+        *ppIUriBuilder = NULL;
         return E_INVALIDARG;
     }
 
-    /* Currently unsupported. */
-    if(dwFlags & ~supported_flags)
-        FIXME("Ignoring unsupported flag(s) %x\n", dwFlags & ~supported_flags);
+    return CreateIUriBuilder(NULL, 0, 0, ppIUriBuilder);
+}
 
-    ret = heap_alloc(sizeof(Uri));
-    if(!ret)
-        return E_OUTOFMEMORY;
+static HRESULT WINAPI UriBuilderFactory_CreateInitializedIUriBuilder(IUriBuilderFactory *iface,
+                                                                     DWORD dwFlags,
+                                                                     DWORD_PTR dwReserved,
+                                                                     IUriBuilder **ppIUriBuilder)
+{
+    Uri *This = impl_from_IUriBuilderFactory(iface);
+    TRACE("(%p)->(%08x %08x %p)\n", This, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
 
-    ret->lpIUriVtbl = &UriVtbl;
-    ret->ref = 1;
+    if(!ppIUriBuilder)
+        return E_POINTER;
 
-    /* Explicitly set the default flags if it doesn't cause a flag conflict. */
-    apply_default_flags(&dwFlags);
+    if(dwFlags || dwReserved) {
+        *ppIUriBuilder = NULL;
+        return E_INVALIDARG;
+    }
 
-    /* Pre process the URI, unless told otherwise. */
-    if(!(dwFlags & Uri_CREATE_NO_PRE_PROCESS_HTML_URI))
-        ret->raw_uri = pre_process_uri(pwzURI);
-    else
-        ret->raw_uri = SysAllocString(pwzURI);
+    return CreateIUriBuilder(&This->IUri_iface, 0, 0, ppIUriBuilder);
+}
 
-    if(!ret->raw_uri) {
-        heap_free(ret);
+static const IUriBuilderFactoryVtbl UriBuilderFactoryVtbl = {
+    UriBuilderFactory_QueryInterface,
+    UriBuilderFactory_AddRef,
+    UriBuilderFactory_Release,
+    UriBuilderFactory_CreateIUriBuilder,
+    UriBuilderFactory_CreateInitializedIUriBuilder
+};
+
+static inline Uri* impl_from_IPersistStream(IPersistStream *iface)
+{
+    return CONTAINING_RECORD(iface, Uri, IPersistStream_iface);
+}
+
+static HRESULT WINAPI PersistStream_QueryInterface(IPersistStream *iface, REFIID riid, void **ppvObject)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    return IUri_QueryInterface(&This->IUri_iface, riid, ppvObject);
+}
+
+static ULONG WINAPI PersistStream_AddRef(IPersistStream *iface)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    return IUri_AddRef(&This->IUri_iface);
+}
+
+static ULONG WINAPI PersistStream_Release(IPersistStream *iface)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    return IUri_Release(&This->IUri_iface);
+}
+
+static HRESULT WINAPI PersistStream_GetClassID(IPersistStream *iface, CLSID *pClassID)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    TRACE("(%p)->(%p)\n", This, pClassID);
+
+    if(!pClassID)
+        return E_INVALIDARG;
+
+    *pClassID = CLSID_CUri;
+    return S_OK;
+}
+
+static HRESULT WINAPI PersistStream_IsDirty(IPersistStream *iface)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    TRACE("(%p)\n", This);
+    return S_FALSE;
+}
+
+struct persist_uri {
+    DWORD size;
+    DWORD unk1[2];
+    DWORD create_flags;
+    DWORD unk2[3];
+    DWORD fields_no;
+    BYTE data[1];
+};
+
+static HRESULT WINAPI PersistStream_Load(IPersistStream *iface, IStream *pStm)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    struct persist_uri *data;
+    parse_data parse;
+    DWORD size;
+    HRESULT hr;
+
+    TRACE("(%p)->(%p)\n", This, pStm);
+
+    if(This->create_flags)
+        return E_UNEXPECTED;
+    if(!pStm)
+        return E_INVALIDARG;
+
+    hr = IStream_Read(pStm, &size, sizeof(DWORD), NULL);
+    if(FAILED(hr))
+        return hr;
+    data = heap_alloc(size);
+    if(!data)
         return E_OUTOFMEMORY;
+    hr = IStream_Read(pStm, data->unk1, size-sizeof(DWORD)-2, NULL);
+    if(FAILED(hr)) {
+        heap_free(data);
+        return hr;
     }
 
-    memset(&data, 0, sizeof(parse_data));
-    data.uri = ret->raw_uri;
+    if(size < sizeof(struct persist_uri)) {
+        heap_free(data);
+        return S_OK;
+    }
 
-    /* Validate and parse the URI into it's components. */
-    if(!parse_uri(&data, dwFlags)) {
-        /* Encountered an unsupported or invalid URI */
-        SysFreeString(ret->raw_uri);
-        heap_free(ret);
-        *ppURI = NULL;
-        return E_INVALIDARG;
+    if(*(DWORD*)data->data != Uri_PROPERTY_RAW_URI) {
+        heap_free(data);
+        ERR("Can't find raw_uri\n");
+        return E_UNEXPECTED;
     }
 
-    /* Canonicalize the URI. */
-    hr = canonicalize_uri(&data, ret, dwFlags);
+    This->raw_uri = SysAllocString((WCHAR*)(data->data+sizeof(DWORD)*2));
+    if(!This->raw_uri) {
+        heap_free(data);
+        return E_OUTOFMEMORY;
+    }
+    This->create_flags = data->create_flags;
+    heap_free(data);
+    TRACE("%x %s\n", This->create_flags, debugstr_w(This->raw_uri));
+
+    memset(&parse, 0, sizeof(parse_data));
+    parse.uri = This->raw_uri;
+    if(!parse_uri(&parse, This->create_flags)) {
+        SysFreeString(This->raw_uri);
+        This->create_flags = 0;
+        return E_UNEXPECTED;
+    }
+
+    hr = canonicalize_uri(&parse, This, This->create_flags);
     if(FAILED(hr)) {
-        SysFreeString(ret->raw_uri);
-        heap_free(ret);
-        *ppURI = NULL;
+        SysFreeString(This->raw_uri);
+        This->create_flags = 0;
         return hr;
     }
 
-    ret->create_flags = dwFlags;
+    return S_OK;
+}
+
+static inline BYTE* persist_stream_add_strprop(Uri *This, BYTE *p, DWORD type, DWORD len, WCHAR *data)
+{
+    len *= sizeof(WCHAR);
+    *(DWORD*)p = type;
+    p += sizeof(DWORD);
+    *(DWORD*)p = len+sizeof(WCHAR);
+    p += sizeof(DWORD);
+    memcpy(p, data, len);
+    p += len;
+    *(WCHAR*)p = 0;
+    return p+sizeof(WCHAR);
+}
+
+static inline void persist_stream_save(Uri *This, IStream *pStm, BOOL marshal, struct persist_uri *data)
+{
+    BYTE *p = NULL;
+
+    data->create_flags = This->create_flags;
+
+    if(This->create_flags) {
+        data->fields_no = 1;
+        p = persist_stream_add_strprop(This, data->data, Uri_PROPERTY_RAW_URI,
+                SysStringLen(This->raw_uri), This->raw_uri);
+    }
+    if(This->scheme_type!=URL_SCHEME_HTTP && This->scheme_type!=URL_SCHEME_HTTPS
+            && This->scheme_type!=URL_SCHEME_FTP)
+        return;
+
+    if(This->fragment_len) {
+        data->fields_no++;
+        p = persist_stream_add_strprop(This, p, Uri_PROPERTY_FRAGMENT,
+                This->fragment_len, This->canon_uri+This->fragment_start);
+    }
+
+    if(This->host_len) {
+        data->fields_no++;
+        if(This->host_type == Uri_HOST_IPV6)
+            p = persist_stream_add_strprop(This, p, Uri_PROPERTY_HOST,
+                    This->host_len-2, This->canon_uri+This->host_start+1);
+        else
+            p = persist_stream_add_strprop(This, p, Uri_PROPERTY_HOST,
+                    This->host_len, This->canon_uri+This->host_start);
+    }
+
+    if(This->userinfo_split > -1) {
+        data->fields_no++;
+        p = persist_stream_add_strprop(This, p, Uri_PROPERTY_PASSWORD,
+                This->userinfo_len-This->userinfo_split-1,
+                This->canon_uri+This->userinfo_start+This->userinfo_split+1);
+    }
+
+    if(This->path_len) {
+        data->fields_no++;
+        p = persist_stream_add_strprop(This, p, Uri_PROPERTY_PATH,
+                This->path_len, This->canon_uri+This->path_start);
+    } else if(marshal) {
+        WCHAR no_path = '/';
+        data->fields_no++;
+        p = persist_stream_add_strprop(This, p, Uri_PROPERTY_PATH, 1, &no_path);
+    }
+
+    if(This->has_port) {
+        data->fields_no++;
+        *(DWORD*)p = Uri_PROPERTY_PORT;
+        p += sizeof(DWORD);
+        *(DWORD*)p = sizeof(DWORD);
+        p += sizeof(DWORD);
+        *(DWORD*)p = This->port;
+        p += sizeof(DWORD);
+    }
+
+    if(This->query_len) {
+        data->fields_no++;
+        p = persist_stream_add_strprop(This, p, Uri_PROPERTY_QUERY,
+                This->query_len, This->canon_uri+This->query_start);
+    }
+
+    if(This->scheme_len) {
+        data->fields_no++;
+        p = persist_stream_add_strprop(This, p, Uri_PROPERTY_SCHEME_NAME,
+                This->scheme_len, This->canon_uri+This->scheme_start);
+    }
+
+    if(This->userinfo_start>-1 && This->userinfo_split!=0) {
+        data->fields_no++;
+        if(This->userinfo_split > -1)
+            p = persist_stream_add_strprop(This, p, Uri_PROPERTY_USER_NAME,
+                    This->userinfo_split, This->canon_uri+This->userinfo_start);
+        else
+            p = persist_stream_add_strprop(This, p, Uri_PROPERTY_USER_NAME,
+                    This->userinfo_len, This->canon_uri+This->userinfo_start);
+    }
+}
+
+static HRESULT WINAPI PersistStream_Save(IPersistStream *iface, IStream *pStm, BOOL fClearDirty)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    struct persist_uri *data;
+    ULARGE_INTEGER size;
+    HRESULT hres;
+
+    TRACE("(%p)->(%p %x)\n", This, pStm, fClearDirty);
+
+    if(!pStm)
+        return E_INVALIDARG;
+
+    hres = IPersistStream_GetSizeMax(&This->IPersistStream_iface, &size);
+    if(FAILED(hres))
+        return hres;
+
+    data = heap_alloc_zero(size.u.LowPart);
+    if(!data)
+        return E_OUTOFMEMORY;
+    data->size = size.u.LowPart;
+    persist_stream_save(This, pStm, FALSE, data);
+
+    hres = IStream_Write(pStm, data, data->size-2, NULL);
+    heap_free(data);
+    return hres;
+}
+
+static HRESULT WINAPI PersistStream_GetSizeMax(IPersistStream *iface, ULARGE_INTEGER *pcbSize)
+{
+    Uri *This = impl_from_IPersistStream(iface);
+    TRACE("(%p)->(%p)\n", This, pcbSize);
+
+    if(!pcbSize)
+        return E_INVALIDARG;
+
+    pcbSize->u.LowPart = 2+sizeof(struct persist_uri);
+    pcbSize->u.HighPart = 0;
+    if(This->create_flags)
+        pcbSize->u.LowPart += (SysStringLen(This->raw_uri)+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    else /* there's no place for fields no */
+        pcbSize->u.LowPart -= sizeof(DWORD);
+    if(This->scheme_type!=URL_SCHEME_HTTP && This->scheme_type!=URL_SCHEME_HTTPS
+            && This->scheme_type!=URL_SCHEME_FTP)
+        return S_OK;
+
+    if(This->fragment_len)
+        pcbSize->u.LowPart += (This->fragment_len+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    if(This->host_len) {
+        if(This->host_type == Uri_HOST_IPV6)
+            pcbSize->u.LowPart += (This->host_len-1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+        else
+            pcbSize->u.LowPart += (This->host_len+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    }
+    if(This->userinfo_split > -1)
+        pcbSize->u.LowPart += (This->userinfo_len-This->userinfo_split)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    if(This->path_len)
+        pcbSize->u.LowPart += (This->path_len+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    if(This->has_port)
+        pcbSize->u.LowPart += 3*sizeof(DWORD);
+    if(This->query_len)
+        pcbSize->u.LowPart += (This->query_len+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    if(This->scheme_len)
+        pcbSize->u.LowPart += (This->scheme_len+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    if(This->userinfo_start>-1 && This->userinfo_split!=0) {
+        if(This->userinfo_split > -1)
+            pcbSize->u.LowPart += (This->userinfo_split+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+        else
+            pcbSize->u.LowPart += (This->userinfo_len+1)*sizeof(WCHAR) + 2*sizeof(DWORD);
+    }
+    return S_OK;
+}
+
+static const IPersistStreamVtbl PersistStreamVtbl = {
+    PersistStream_QueryInterface,
+    PersistStream_AddRef,
+    PersistStream_Release,
+    PersistStream_GetClassID,
+    PersistStream_IsDirty,
+    PersistStream_Load,
+    PersistStream_Save,
+    PersistStream_GetSizeMax
+};
+
+static inline Uri* impl_from_IMarshal(IMarshal *iface)
+{
+    return CONTAINING_RECORD(iface, Uri, IMarshal_iface);
+}
+
+static HRESULT WINAPI Marshal_QueryInterface(IMarshal *iface, REFIID riid, void **ppvObject)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    return IUri_QueryInterface(&This->IUri_iface, riid, ppvObject);
+}
 
-    *ppURI = URI(ret);
+static ULONG WINAPI Marshal_AddRef(IMarshal *iface)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    return IUri_AddRef(&This->IUri_iface);
+}
+
+static ULONG WINAPI Marshal_Release(IMarshal *iface)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    return IUri_Release(&This->IUri_iface);
+}
+
+static HRESULT WINAPI Marshal_GetUnmarshalClass(IMarshal *iface, REFIID riid, void *pv,
+        DWORD dwDestContext, void *pvDestContext, DWORD mshlflags, CLSID *pCid)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    TRACE("(%p)->(%s %p %x %p %x %p)\n", This, debugstr_guid(riid), pv,
+            dwDestContext, pvDestContext, mshlflags, pCid);
+
+    if(!pCid || (dwDestContext!=MSHCTX_LOCAL && dwDestContext!=MSHCTX_NOSHAREDMEM
+                && dwDestContext!=MSHCTX_INPROC))
+        return E_INVALIDARG;
+
+    *pCid = CLSID_CUri;
+    return S_OK;
+}
+
+struct inproc_marshal_uri {
+    DWORD size;
+    DWORD mshlflags;
+    DWORD unk[4]; /* process identifier? */
+    Uri *uri;
+};
+
+static HRESULT WINAPI Marshal_GetMarshalSizeMax(IMarshal *iface, REFIID riid, void *pv,
+        DWORD dwDestContext, void *pvDestContext, DWORD mshlflags, DWORD *pSize)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    ULARGE_INTEGER size;
+    HRESULT hres;
+    TRACE("(%p)->(%s %p %x %p %x %p)\n", This, debugstr_guid(riid), pv,
+            dwDestContext, pvDestContext, mshlflags, pSize);
+
+    if(!pSize || (dwDestContext!=MSHCTX_LOCAL && dwDestContext!=MSHCTX_NOSHAREDMEM
+                && dwDestContext!=MSHCTX_INPROC))
+        return E_INVALIDARG;
+
+    if(dwDestContext == MSHCTX_INPROC) {
+        *pSize = sizeof(struct inproc_marshal_uri);
+        return S_OK;
+    }
+
+    hres = IPersistStream_GetSizeMax(&This->IPersistStream_iface, &size);
+    if(FAILED(hres))
+        return hres;
+    if(!This->path_len && (This->scheme_type==URL_SCHEME_HTTP
+                || This->scheme_type==URL_SCHEME_HTTPS
+                || This->scheme_type==URL_SCHEME_FTP))
+        size.u.LowPart += 3*sizeof(DWORD);
+    *pSize = size.u.LowPart+2*sizeof(DWORD);
+    return S_OK;
+}
+
+static HRESULT WINAPI Marshal_MarshalInterface(IMarshal *iface, IStream *pStm, REFIID riid,
+        void *pv, DWORD dwDestContext, void *pvDestContext, DWORD mshlflags)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    DWORD *data;
+    DWORD size;
+    HRESULT hres;
+
+    TRACE("(%p)->(%p %s %p %x %p %x)\n", This, pStm, debugstr_guid(riid), pv,
+            dwDestContext, pvDestContext, mshlflags);
+
+    if(!pStm || mshlflags!=MSHLFLAGS_NORMAL || (dwDestContext!=MSHCTX_LOCAL
+                && dwDestContext!=MSHCTX_NOSHAREDMEM && dwDestContext!=MSHCTX_INPROC))
+        return E_INVALIDARG;
+
+    if(dwDestContext == MSHCTX_INPROC) {
+        struct inproc_marshal_uri data;
+
+        data.size = sizeof(data);
+        data.mshlflags = MSHCTX_INPROC;
+        data.unk[0] = 0;
+        data.unk[1] = 0;
+        data.unk[2] = 0;
+        data.unk[3] = 0;
+        data.uri = This;
+
+        hres = IStream_Write(pStm, &data, data.size, NULL);
+        if(FAILED(hres))
+            return hres;
+
+        IUri_AddRef(&This->IUri_iface);
+        return S_OK;
+    }
+
+    hres = IMarshal_GetMarshalSizeMax(iface, riid, pv, dwDestContext,
+            pvDestContext, mshlflags, &size);
+    if(FAILED(hres))
+        return hres;
+
+    data = heap_alloc_zero(size);
+    if(!data)
+        return E_OUTOFMEMORY;
+
+    data[0] = size;
+    data[1] = dwDestContext;
+    data[2] = size-2*sizeof(DWORD);
+    persist_stream_save(This, pStm, TRUE, (struct persist_uri*)(data+2));
+
+    hres = IStream_Write(pStm, data, data[0]-2, NULL);
+    heap_free(data);
+    return hres;
+}
+
+static HRESULT WINAPI Marshal_UnmarshalInterface(IMarshal *iface,
+        IStream *pStm, REFIID riid, void **ppv)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    DWORD header[2];
+    HRESULT hres;
+
+    TRACE("(%p)->(%p %s %p)\n", This, pStm, debugstr_guid(riid), ppv);
+
+    if(This->create_flags)
+        return E_UNEXPECTED;
+    if(!pStm || !riid || !ppv)
+        return E_INVALIDARG;
+
+    hres = IStream_Read(pStm, header, sizeof(header), NULL);
+    if(FAILED(hres))
+        return hres;
+
+    if(header[1]!=MSHCTX_LOCAL && header[1]!=MSHCTX_NOSHAREDMEM
+            && header[1]!=MSHCTX_INPROC)
+        return E_UNEXPECTED;
+
+    if(header[1] == MSHCTX_INPROC) {
+        struct inproc_marshal_uri data;
+        parse_data parse;
+
+        hres = IStream_Read(pStm, data.unk, sizeof(data)-2*sizeof(DWORD), NULL);
+        if(FAILED(hres))
+            return hres;
+
+        This->raw_uri = SysAllocString(data.uri->raw_uri);
+        if(!This->raw_uri) {
+            return E_OUTOFMEMORY;
+        }
+
+        memset(&parse, 0, sizeof(parse_data));
+        parse.uri = This->raw_uri;
+
+        if(!parse_uri(&parse, data.uri->create_flags))
+            return E_INVALIDARG;
+
+        hres = canonicalize_uri(&parse, This, data.uri->create_flags);
+        if(FAILED(hres))
+            return hres;
+
+        This->create_flags = data.uri->create_flags;
+        IUri_Release(&data.uri->IUri_iface);
+
+        return IUri_QueryInterface(&This->IUri_iface, riid, ppv);
+    }
+
+    hres = IPersistStream_Load(&This->IPersistStream_iface, pStm);
+    if(FAILED(hres))
+        return hres;
+
+    return IUri_QueryInterface(&This->IUri_iface, riid, ppv);
+}
+
+static HRESULT WINAPI Marshal_ReleaseMarshalData(IMarshal *iface, IStream *pStm)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    LARGE_INTEGER off;
+    DWORD header[2];
+    HRESULT hres;
+
+    TRACE("(%p)->(%p)\n", This, pStm);
+
+    if(!pStm)
+        return E_INVALIDARG;
+
+    hres = IStream_Read(pStm, header, 2*sizeof(DWORD), NULL);
+    if(FAILED(hres))
+        return hres;
+
+    if(header[1] == MSHCTX_INPROC) {
+        struct inproc_marshal_uri data;
+
+        hres = IStream_Read(pStm, data.unk, sizeof(data)-2*sizeof(DWORD), NULL);
+        if(FAILED(hres))
+            return hres;
+
+        IUri_Release(&data.uri->IUri_iface);
+        return S_OK;
+    }
+
+    off.u.LowPart = header[0]-sizeof(header)-2;
+    off.u.HighPart = 0;
+    return IStream_Seek(pStm, off, STREAM_SEEK_CUR, NULL);
+}
+
+static HRESULT WINAPI Marshal_DisconnectObject(IMarshal *iface, DWORD dwReserved)
+{
+    Uri *This = impl_from_IMarshal(iface);
+    TRACE("(%p)->(%x)\n", This, dwReserved);
+    return S_OK;
+}
+
+static const IMarshalVtbl MarshalVtbl = {
+    Marshal_QueryInterface,
+    Marshal_AddRef,
+    Marshal_Release,
+    Marshal_GetUnmarshalClass,
+    Marshal_GetMarshalSizeMax,
+    Marshal_MarshalInterface,
+    Marshal_UnmarshalInterface,
+    Marshal_ReleaseMarshalData,
+    Marshal_DisconnectObject
+};
+
+HRESULT Uri_Construct(IUnknown *pUnkOuter, LPVOID *ppobj)
+{
+    Uri *ret = heap_alloc_zero(sizeof(Uri));
+
+    TRACE("(%p %p)\n", pUnkOuter, ppobj);
+
+    *ppobj = ret;
+    if(!ret)
+        return E_OUTOFMEMORY;
+
+    ret->IUri_iface.lpVtbl = &UriVtbl;
+    ret->IUriBuilderFactory_iface.lpVtbl = &UriBuilderFactoryVtbl;
+    ret->IPersistStream_iface.lpVtbl = &PersistStreamVtbl;
+    ret->IMarshal_iface.lpVtbl = &MarshalVtbl;
+    ret->ref = 1;
+
+    *ppobj = &ret->IUri_iface;
     return S_OK;
 }
 
 /***********************************************************************
- *           CreateUriWithFragment (urlmon.@)
+ *           CreateUri (urlmon.@)
  *
- * Creates a new IUri object. This is almost the same as CreateUri, expect that
- * it allows you to explicitly specify a fragment (pwzFragment) for pwzURI.
+ * Creates a new IUri object using the URI represented by pwzURI. This function
+ * parses and validates the components of pwzURI and then canonicalizes the
+ * parsed components.
  *
  * PARAMS
- *  pwzURI      [I] The URI to parse and perform canonicalization on.
- *  pwzFragment [I] The explict fragment string which should be added to pwzURI.
- *  dwFlags     [I] The flags which will be passed to CreateUri.
+ *  pwzURI      [I] The URI to parse, validate, and canonicalize.
+ *  dwFlags     [I] Flags which can affect how the parsing/canonicalization is performed.
  *  dwReserved  [I] Reserved (not used).
- *  ppURI       [O] The resulting IUri after parsing/canonicalization.
+ *  ppURI       [O] The resulting IUri after parsing/canonicalization occurs.
  *
  * RETURNS
- *  Success: S_OK. ppURI contains the pointer to the newly allocated IUri.
- *  Failure: E_INVALIDARG if pwzURI already contains a fragment and pwzFragment
- *           isn't NULL. Will also return E_INVALIDARG for the same reasons as
- *           CreateUri will. E_OUTOFMEMORY if any allocations fail.
+ *  Success: Returns S_OK. ppURI contains the pointer to the newly allocated IUri.
+ *  Failure: E_INVALIDARG if there are invalid flag combinations in dwFlags, or an
+ *           invalid parameter, or pwzURI doesn't represent a valid URI.
+ *           E_OUTOFMEMORY if any memory allocation fails.
+ *
+ * NOTES
+ *  Default flags:
+ *      Uri_CREATE_CANONICALIZE, Uri_CREATE_DECODE_EXTRA_INFO, Uri_CREATE_CRACK_UNKNOWN_SCHEMES,
+ *      Uri_CREATE_PRE_PROCESS_HTML_URI, Uri_CREATE_NO_IE_SETTINGS.
  */
-HRESULT WINAPI CreateUriWithFragment(LPCWSTR pwzURI, LPCWSTR pwzFragment, DWORD dwFlags,
-                                     DWORD_PTR dwReserved, IUri **ppURI)
+HRESULT WINAPI CreateUri(LPCWSTR pwzURI, DWORD dwFlags, DWORD_PTR dwReserved, IUri **ppURI)
 {
-    HRESULT hres;
-    TRACE("(%s %s %x %x %p)\n", debugstr_w(pwzURI), debugstr_w(pwzFragment), dwFlags, (DWORD)dwReserved, ppURI);
+    const DWORD supported_flags = Uri_CREATE_ALLOW_RELATIVE|Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME|
+        Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME|Uri_CREATE_NO_CANONICALIZE|Uri_CREATE_CANONICALIZE|
+        Uri_CREATE_DECODE_EXTRA_INFO|Uri_CREATE_NO_DECODE_EXTRA_INFO|Uri_CREATE_CRACK_UNKNOWN_SCHEMES|
+        Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES|Uri_CREATE_PRE_PROCESS_HTML_URI|Uri_CREATE_NO_PRE_PROCESS_HTML_URI|
+        Uri_CREATE_NO_IE_SETTINGS|Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS|Uri_CREATE_FILE_USE_DOS_PATH;
+    Uri *ret;
+    HRESULT hr;
+    parse_data data;
+
+    TRACE("(%s %x %x %p)\n", debugstr_w(pwzURI), dwFlags, (DWORD)dwReserved, ppURI);
+
+    if(!ppURI)
+        return E_INVALIDARG;
+
+    if(!pwzURI) {
+        *ppURI = NULL;
+        return E_INVALIDARG;
+    }
+
+    /* Check for invalid flags. */
+    if(has_invalid_flag_combination(dwFlags)) {
+        *ppURI = NULL;
+        return E_INVALIDARG;
+    }
+
+    /* Currently unsupported. */
+    if(dwFlags & ~supported_flags)
+        FIXME("Ignoring unsupported flag(s) %x\n", dwFlags & ~supported_flags);
+
+    hr = Uri_Construct(NULL, (void**)&ret);
+    if(FAILED(hr)) {
+        *ppURI = NULL;
+        return hr;
+    }
+
+    /* Explicitly set the default flags if it doesn't cause a flag conflict. */
+    apply_default_flags(&dwFlags);
+
+    /* Pre process the URI, unless told otherwise. */
+    if(!(dwFlags & Uri_CREATE_NO_PRE_PROCESS_HTML_URI))
+        ret->raw_uri = pre_process_uri(pwzURI);
+    else
+        ret->raw_uri = SysAllocString(pwzURI);
+
+    if(!ret->raw_uri) {
+        heap_free(ret);
+        return E_OUTOFMEMORY;
+    }
+
+    memset(&data, 0, sizeof(parse_data));
+    data.uri = ret->raw_uri;
+
+    /* Validate and parse the URI into its components. */
+    if(!parse_uri(&data, dwFlags)) {
+        /* Encountered an unsupported or invalid URI */
+        IUri_Release(&ret->IUri_iface);
+        *ppURI = NULL;
+        return E_INVALIDARG;
+    }
+
+    /* Canonicalize the URI. */
+    hr = canonicalize_uri(&data, ret, dwFlags);
+    if(FAILED(hr)) {
+        IUri_Release(&ret->IUri_iface);
+        *ppURI = NULL;
+        return hr;
+    }
+
+    ret->create_flags = dwFlags;
+
+    *ppURI = &ret->IUri_iface;
+    return S_OK;
+}
+
+/***********************************************************************
+ *           CreateUriWithFragment (urlmon.@)
+ *
+ * Creates a new IUri object. This is almost the same as CreateUri, expect that
+ * it allows you to explicitly specify a fragment (pwzFragment) for pwzURI.
+ *
+ * PARAMS
+ *  pwzURI      [I] The URI to parse and perform canonicalization on.
+ *  pwzFragment [I] The explicit fragment string which should be added to pwzURI.
+ *  dwFlags     [I] The flags which will be passed to CreateUri.
+ *  dwReserved  [I] Reserved (not used).
+ *  ppURI       [O] The resulting IUri after parsing/canonicalization.
+ *
+ * RETURNS
+ *  Success: S_OK. ppURI contains the pointer to the newly allocated IUri.
+ *  Failure: E_INVALIDARG if pwzURI already contains a fragment and pwzFragment
+ *           isn't NULL. Will also return E_INVALIDARG for the same reasons as
+ *           CreateUri will. E_OUTOFMEMORY if any allocation fails.
+ */
+HRESULT WINAPI CreateUriWithFragment(LPCWSTR pwzURI, LPCWSTR pwzFragment, DWORD dwFlags,
+                                     DWORD_PTR dwReserved, IUri **ppURI)
+{
+    HRESULT hres;
+    TRACE("(%s %s %x %x %p)\n", debugstr_w(pwzURI), debugstr_w(pwzFragment), dwFlags, (DWORD)dwReserved, ppURI);
+
+    if(!ppURI)
+        return E_INVALIDARG;
+
+    if(!pwzURI) {
+        *ppURI = NULL;
+        return E_INVALIDARG;
+    }
+
+    /* Check if a fragment should be appended to the URI string. */
+    if(pwzFragment) {
+        WCHAR *uriW;
+        DWORD uri_len, frag_len;
+        BOOL add_pound;
+
+        /* Check if the original URI already has a fragment component. */
+        if(StrChrW(pwzURI, '#')) {
+            *ppURI = NULL;
+            return E_INVALIDARG;
+        }
+
+        uri_len = lstrlenW(pwzURI);
+        frag_len = lstrlenW(pwzFragment);
+
+        /* If the fragment doesn't start with a '#', one will be added. */
+        add_pound = *pwzFragment != '#';
+
+        if(add_pound)
+            uriW = heap_alloc((uri_len+frag_len+2)*sizeof(WCHAR));
+        else
+            uriW = heap_alloc((uri_len+frag_len+1)*sizeof(WCHAR));
+
+        if(!uriW)
+            return E_OUTOFMEMORY;
+
+        memcpy(uriW, pwzURI, uri_len*sizeof(WCHAR));
+        if(add_pound)
+            uriW[uri_len++] = '#';
+        memcpy(uriW+uri_len, pwzFragment, (frag_len+1)*sizeof(WCHAR));
+
+        hres = CreateUri(uriW, dwFlags, 0, ppURI);
+
+        heap_free(uriW);
+    } else
+        /* A fragment string wasn't specified, so just forward the call. */
+        hres = CreateUri(pwzURI, dwFlags, 0, ppURI);
+
+    return hres;
+}
+
+static HRESULT build_uri(const UriBuilder *builder, IUri **uri, DWORD create_flags,
+                         DWORD use_orig_flags, DWORD encoding_mask)
+{
+    HRESULT hr;
+    parse_data data;
+    Uri *ret;
+
+    if(!uri)
+        return E_POINTER;
+
+    if(encoding_mask && (!builder->uri || builder->modified_props)) {
+        *uri = NULL;
+        return E_NOTIMPL;
+    }
+
+    /* Decide what flags should be used when creating the Uri. */
+    if((use_orig_flags & UriBuilder_USE_ORIGINAL_FLAGS) && builder->uri)
+        create_flags = builder->uri->create_flags;
+    else {
+        if(has_invalid_flag_combination(create_flags)) {
+            *uri = NULL;
+            return E_INVALIDARG;
+        }
+
+        /* Set the default flags if they don't cause a conflict. */
+        apply_default_flags(&create_flags);
+    }
+
+    /* Return the base IUri if no changes have been made and the create_flags match. */
+    if(builder->uri && !builder->modified_props && builder->uri->create_flags == create_flags) {
+        *uri = &builder->uri->IUri_iface;
+        IUri_AddRef(*uri);
+        return S_OK;
+    }
+
+    hr = validate_components(builder, &data, create_flags);
+    if(FAILED(hr)) {
+        *uri = NULL;
+        return hr;
+    }
+
+    hr = Uri_Construct(NULL, (void**)&ret);
+    if(FAILED(hr)) {
+        *uri = NULL;
+        return hr;
+    }
+
+    hr = generate_uri(builder, &data, ret, create_flags);
+    if(FAILED(hr)) {
+        IUri_Release(&ret->IUri_iface);
+        *uri = NULL;
+        return hr;
+    }
+
+    *uri = &ret->IUri_iface;
+    return S_OK;
+}
+
+static inline UriBuilder* impl_from_IUriBuilder(IUriBuilder *iface)
+{
+    return CONTAINING_RECORD(iface, UriBuilder, IUriBuilder_iface);
+}
+
+static HRESULT WINAPI UriBuilder_QueryInterface(IUriBuilder *iface, REFIID riid, void **ppv)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+
+    if(IsEqualGUID(&IID_IUnknown, riid)) {
+        TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
+        *ppv = &This->IUriBuilder_iface;
+    }else if(IsEqualGUID(&IID_IUriBuilder, riid)) {
+        TRACE("(%p)->(IID_IUriBuilder %p)\n", This, ppv);
+        *ppv = &This->IUriBuilder_iface;
+    }else {
+        TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
+        *ppv = NULL;
+        return E_NOINTERFACE;
+    }
+
+    IUnknown_AddRef((IUnknown*)*ppv);
+    return S_OK;
+}
+
+static ULONG WINAPI UriBuilder_AddRef(IUriBuilder *iface)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    LONG ref = InterlockedIncrement(&This->ref);
+
+    TRACE("(%p) ref=%d\n", This, ref);
+
+    return ref;
+}
+
+static ULONG WINAPI UriBuilder_Release(IUriBuilder *iface)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    LONG ref = InterlockedDecrement(&This->ref);
+
+    TRACE("(%p) ref=%d\n", This, ref);
+
+    if(!ref) {
+        if(This->uri) IUri_Release(&This->uri->IUri_iface);
+        heap_free(This->fragment);
+        heap_free(This->host);
+        heap_free(This->password);
+        heap_free(This->path);
+        heap_free(This->query);
+        heap_free(This->scheme);
+        heap_free(This->username);
+        heap_free(This);
+    }
+
+    return ref;
+}
+
+static HRESULT WINAPI UriBuilder_CreateUriSimple(IUriBuilder *iface,
+                                                 DWORD        dwAllowEncodingPropertyMask,
+                                                 DWORD_PTR    dwReserved,
+                                                 IUri       **ppIUri)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    HRESULT hr;
+    TRACE("(%p)->(%d %d %p)\n", This, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+
+    hr = build_uri(This, ppIUri, 0, UriBuilder_USE_ORIGINAL_FLAGS, dwAllowEncodingPropertyMask);
+    if(hr == E_NOTIMPL)
+        FIXME("(%p)->(%d %d %p)\n", This, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    return hr;
+}
+
+static HRESULT WINAPI UriBuilder_CreateUri(IUriBuilder *iface,
+                                           DWORD        dwCreateFlags,
+                                           DWORD        dwAllowEncodingPropertyMask,
+                                           DWORD_PTR    dwReserved,
+                                           IUri       **ppIUri)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    HRESULT hr;
+    TRACE("(%p)->(0x%08x %d %d %p)\n", This, dwCreateFlags, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+
+    if(dwCreateFlags == -1)
+        hr = build_uri(This, ppIUri, 0, UriBuilder_USE_ORIGINAL_FLAGS, dwAllowEncodingPropertyMask);
+    else
+        hr = build_uri(This, ppIUri, dwCreateFlags, 0, dwAllowEncodingPropertyMask);
+
+    if(hr == E_NOTIMPL)
+        FIXME("(%p)->(0x%08x %d %d %p)\n", This, dwCreateFlags, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    return hr;
+}
+
+static HRESULT WINAPI UriBuilder_CreateUriWithFlags(IUriBuilder *iface,
+                                         DWORD        dwCreateFlags,
+                                         DWORD        dwUriBuilderFlags,
+                                         DWORD        dwAllowEncodingPropertyMask,
+                                         DWORD_PTR    dwReserved,
+                                         IUri       **ppIUri)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    HRESULT hr;
+    TRACE("(%p)->(0x%08x 0x%08x %d %d %p)\n", This, dwCreateFlags, dwUriBuilderFlags,
+        dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+
+    hr = build_uri(This, ppIUri, dwCreateFlags, dwUriBuilderFlags, dwAllowEncodingPropertyMask);
+    if(hr == E_NOTIMPL)
+        FIXME("(%p)->(0x%08x 0x%08x %d %d %p)\n", This, dwCreateFlags, dwUriBuilderFlags,
+            dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    return hr;
+}
+
+static HRESULT WINAPI  UriBuilder_GetIUri(IUriBuilder *iface, IUri **ppIUri)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p)\n", This, ppIUri);
+
+    if(!ppIUri)
+        return E_POINTER;
+
+    if(This->uri) {
+        IUri *uri = &This->uri->IUri_iface;
+        IUri_AddRef(uri);
+        *ppIUri = uri;
+    } else
+        *ppIUri = NULL;
+
+    return S_OK;
+}
+
+static HRESULT WINAPI UriBuilder_SetIUri(IUriBuilder *iface, IUri *pIUri)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p)\n", This, pIUri);
+
+    if(pIUri) {
+        Uri *uri;
+
+        if((uri = get_uri_obj(pIUri))) {
+            /* Only reset the builder if its Uri isn't the same as
+             * the Uri passed to the function.
+             */
+            if(This->uri != uri) {
+                reset_builder(This);
+
+                This->uri = uri;
+                if(uri->has_port)
+                    This->port = uri->port;
+
+                IUri_AddRef(pIUri);
+            }
+        } else {
+            FIXME("(%p)->(%p) Unknown IUri types not supported yet.\n", This, pIUri);
+            return E_NOTIMPL;
+        }
+    } else if(This->uri)
+        /* Only reset the builder if its Uri isn't NULL. */
+        reset_builder(This);
+
+    return S_OK;
+}
+
+static HRESULT WINAPI UriBuilder_GetFragment(IUriBuilder *iface, DWORD *pcchFragment, LPCWSTR *ppwzFragment)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchFragment, ppwzFragment);
+
+    if(!This->uri || This->uri->fragment_start == -1 || This->modified_props & Uri_HAS_FRAGMENT)
+        return get_builder_component(&This->fragment, &This->fragment_len, NULL, 0, ppwzFragment, pcchFragment);
+    else
+        return get_builder_component(&This->fragment, &This->fragment_len, This->uri->canon_uri+This->uri->fragment_start,
+                                     This->uri->fragment_len, ppwzFragment, pcchFragment);
+}
+
+static HRESULT WINAPI UriBuilder_GetHost(IUriBuilder *iface, DWORD *pcchHost, LPCWSTR *ppwzHost)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchHost, ppwzHost);
+
+    if(!This->uri || This->uri->host_start == -1 || This->modified_props & Uri_HAS_HOST)
+        return get_builder_component(&This->host, &This->host_len, NULL, 0, ppwzHost, pcchHost);
+    else {
+        if(This->uri->host_type == Uri_HOST_IPV6)
+            /* Don't include the '[' and ']' around the address. */
+            return get_builder_component(&This->host, &This->host_len, This->uri->canon_uri+This->uri->host_start+1,
+                                         This->uri->host_len-2, ppwzHost, pcchHost);
+        else
+            return get_builder_component(&This->host, &This->host_len, This->uri->canon_uri+This->uri->host_start,
+                                         This->uri->host_len, ppwzHost, pcchHost);
+    }
+}
+
+static HRESULT WINAPI UriBuilder_GetPassword(IUriBuilder *iface, DWORD *pcchPassword, LPCWSTR *ppwzPassword)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchPassword, ppwzPassword);
+
+    if(!This->uri || This->uri->userinfo_split == -1 || This->modified_props & Uri_HAS_PASSWORD)
+        return get_builder_component(&This->password, &This->password_len, NULL, 0, ppwzPassword, pcchPassword);
+    else {
+        const WCHAR *start = This->uri->canon_uri+This->uri->userinfo_start+This->uri->userinfo_split+1;
+        DWORD len = This->uri->userinfo_len-This->uri->userinfo_split-1;
+        return get_builder_component(&This->password, &This->password_len, start, len, ppwzPassword, pcchPassword);
+    }
+}
+
+static HRESULT WINAPI UriBuilder_GetPath(IUriBuilder *iface, DWORD *pcchPath, LPCWSTR *ppwzPath)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchPath, ppwzPath);
+
+    if(!This->uri || This->uri->path_start == -1 || This->modified_props & Uri_HAS_PATH)
+        return get_builder_component(&This->path, &This->path_len, NULL, 0, ppwzPath, pcchPath);
+    else
+        return get_builder_component(&This->path, &This->path_len, This->uri->canon_uri+This->uri->path_start,
+                                     This->uri->path_len, ppwzPath, pcchPath);
+}
+
+static HRESULT WINAPI UriBuilder_GetPort(IUriBuilder *iface, BOOL *pfHasPort, DWORD *pdwPort)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pfHasPort, pdwPort);
+
+    if(!pfHasPort) {
+        if(pdwPort)
+            *pdwPort = 0;
+        return E_POINTER;
+    }
+
+    if(!pdwPort) {
+        *pfHasPort = FALSE;
+        return E_POINTER;
+    }
+
+    *pfHasPort = This->has_port;
+    *pdwPort = This->port;
+    return S_OK;
+}
+
+static HRESULT WINAPI UriBuilder_GetQuery(IUriBuilder *iface, DWORD *pcchQuery, LPCWSTR *ppwzQuery)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchQuery, ppwzQuery);
+
+    if(!This->uri || This->uri->query_start == -1 || This->modified_props & Uri_HAS_QUERY)
+        return get_builder_component(&This->query, &This->query_len, NULL, 0, ppwzQuery, pcchQuery);
+    else
+        return get_builder_component(&This->query, &This->query_len, This->uri->canon_uri+This->uri->query_start,
+                                     This->uri->query_len, ppwzQuery, pcchQuery);
+}
+
+static HRESULT WINAPI UriBuilder_GetSchemeName(IUriBuilder *iface, DWORD *pcchSchemeName, LPCWSTR *ppwzSchemeName)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchSchemeName, ppwzSchemeName);
+
+    if(!This->uri || This->uri->scheme_start == -1 || This->modified_props & Uri_HAS_SCHEME_NAME)
+        return get_builder_component(&This->scheme, &This->scheme_len, NULL, 0, ppwzSchemeName, pcchSchemeName);
+    else
+        return get_builder_component(&This->scheme, &This->scheme_len, This->uri->canon_uri+This->uri->scheme_start,
+                                     This->uri->scheme_len, ppwzSchemeName, pcchSchemeName);
+}
+
+static HRESULT WINAPI UriBuilder_GetUserName(IUriBuilder *iface, DWORD *pcchUserName, LPCWSTR *ppwzUserName)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p %p)\n", This, pcchUserName, ppwzUserName);
+
+    if(!This->uri || This->uri->userinfo_start == -1 || This->uri->userinfo_split == 0 ||
+       This->modified_props & Uri_HAS_USER_NAME)
+        return get_builder_component(&This->username, &This->username_len, NULL, 0, ppwzUserName, pcchUserName);
+    else {
+        const WCHAR *start = This->uri->canon_uri+This->uri->userinfo_start;
+
+        /* Check if there's a password in the userinfo section. */
+        if(This->uri->userinfo_split > -1)
+            /* Don't include the password. */
+            return get_builder_component(&This->username, &This->username_len, start,
+                                         This->uri->userinfo_split, ppwzUserName, pcchUserName);
+        else
+            return get_builder_component(&This->username, &This->username_len, start,
+                                         This->uri->userinfo_len, ppwzUserName, pcchUserName);
+    }
+}
+
+static HRESULT WINAPI UriBuilder_SetFragment(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    return set_builder_component(&This->fragment, &This->fragment_len, pwzNewValue, '#',
+                                 &This->modified_props, Uri_HAS_FRAGMENT);
+}
+
+static HRESULT WINAPI UriBuilder_SetHost(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+
+    /* Host name can't be set to NULL. */
+    if(!pwzNewValue)
+        return E_INVALIDARG;
+
+    return set_builder_component(&This->host, &This->host_len, pwzNewValue, 0,
+                                 &This->modified_props, Uri_HAS_HOST);
+}
+
+static HRESULT WINAPI UriBuilder_SetPassword(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    return set_builder_component(&This->password, &This->password_len, pwzNewValue, 0,
+                                 &This->modified_props, Uri_HAS_PASSWORD);
+}
+
+static HRESULT WINAPI UriBuilder_SetPath(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    return set_builder_component(&This->path, &This->path_len, pwzNewValue, 0,
+                                 &This->modified_props, Uri_HAS_PATH);
+}
+
+static HRESULT WINAPI UriBuilder_SetPort(IUriBuilder *iface, BOOL fHasPort, DWORD dwNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%d %d)\n", This, fHasPort, dwNewValue);
+
+    This->has_port = fHasPort;
+    This->port = dwNewValue;
+    This->modified_props |= Uri_HAS_PORT;
+    return S_OK;
+}
+
+static HRESULT WINAPI UriBuilder_SetQuery(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    return set_builder_component(&This->query, &This->query_len, pwzNewValue, '?',
+                                 &This->modified_props, Uri_HAS_QUERY);
+}
+
+static HRESULT WINAPI UriBuilder_SetSchemeName(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+
+    /* Only set the scheme name if it's not NULL or empty. */
+    if(!pwzNewValue || !*pwzNewValue)
+        return E_INVALIDARG;
+
+    return set_builder_component(&This->scheme, &This->scheme_len, pwzNewValue, 0,
+                                 &This->modified_props, Uri_HAS_SCHEME_NAME);
+}
+
+static HRESULT WINAPI UriBuilder_SetUserName(IUriBuilder *iface, LPCWSTR pwzNewValue)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    return set_builder_component(&This->username, &This->username_len, pwzNewValue, 0,
+                                 &This->modified_props, Uri_HAS_USER_NAME);
+}
+
+static HRESULT WINAPI UriBuilder_RemoveProperties(IUriBuilder *iface, DWORD dwPropertyMask)
+{
+    const DWORD accepted_flags = Uri_HAS_AUTHORITY|Uri_HAS_DOMAIN|Uri_HAS_EXTENSION|Uri_HAS_FRAGMENT|Uri_HAS_HOST|
+                                 Uri_HAS_PASSWORD|Uri_HAS_PATH|Uri_HAS_PATH_AND_QUERY|Uri_HAS_QUERY|
+                                 Uri_HAS_USER_INFO|Uri_HAS_USER_NAME;
+
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(0x%08x)\n", This, dwPropertyMask);
+
+    if(dwPropertyMask & ~accepted_flags)
+        return E_INVALIDARG;
+
+    if(dwPropertyMask & Uri_HAS_FRAGMENT)
+        UriBuilder_SetFragment(iface, NULL);
+
+    /* Even though you can't set the host name to NULL or an
+     * empty string, you can still remove it... for some reason.
+     */
+    if(dwPropertyMask & Uri_HAS_HOST)
+        set_builder_component(&This->host, &This->host_len, NULL, 0,
+                              &This->modified_props, Uri_HAS_HOST);
+
+    if(dwPropertyMask & Uri_HAS_PASSWORD)
+        UriBuilder_SetPassword(iface, NULL);
+
+    if(dwPropertyMask & Uri_HAS_PATH)
+        UriBuilder_SetPath(iface, NULL);
+
+    if(dwPropertyMask & Uri_HAS_PORT)
+        UriBuilder_SetPort(iface, FALSE, 0);
+
+    if(dwPropertyMask & Uri_HAS_QUERY)
+        UriBuilder_SetQuery(iface, NULL);
+
+    if(dwPropertyMask & Uri_HAS_USER_NAME)
+        UriBuilder_SetUserName(iface, NULL);
+
+    return S_OK;
+}
+
+static HRESULT WINAPI UriBuilder_HasBeenModified(IUriBuilder *iface, BOOL *pfModified)
+{
+    UriBuilder *This = impl_from_IUriBuilder(iface);
+    TRACE("(%p)->(%p)\n", This, pfModified);
+
+    if(!pfModified)
+        return E_POINTER;
+
+    *pfModified = This->modified_props > 0;
+    return S_OK;
+}
+
+static const IUriBuilderVtbl UriBuilderVtbl = {
+    UriBuilder_QueryInterface,
+    UriBuilder_AddRef,
+    UriBuilder_Release,
+    UriBuilder_CreateUriSimple,
+    UriBuilder_CreateUri,
+    UriBuilder_CreateUriWithFlags,
+    UriBuilder_GetIUri,
+    UriBuilder_SetIUri,
+    UriBuilder_GetFragment,
+    UriBuilder_GetHost,
+    UriBuilder_GetPassword,
+    UriBuilder_GetPath,
+    UriBuilder_GetPort,
+    UriBuilder_GetQuery,
+    UriBuilder_GetSchemeName,
+    UriBuilder_GetUserName,
+    UriBuilder_SetFragment,
+    UriBuilder_SetHost,
+    UriBuilder_SetPassword,
+    UriBuilder_SetPath,
+    UriBuilder_SetPort,
+    UriBuilder_SetQuery,
+    UriBuilder_SetSchemeName,
+    UriBuilder_SetUserName,
+    UriBuilder_RemoveProperties,
+    UriBuilder_HasBeenModified,
+};
+
+/***********************************************************************
+ *           CreateIUriBuilder (urlmon.@)
+ */
+HRESULT WINAPI CreateIUriBuilder(IUri *pIUri, DWORD dwFlags, DWORD_PTR dwReserved, IUriBuilder **ppIUriBuilder)
+{
+    UriBuilder *ret;
+
+    TRACE("(%p %x %x %p)\n", pIUri, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
+
+    if(!ppIUriBuilder)
+        return E_POINTER;
+
+    ret = heap_alloc_zero(sizeof(UriBuilder));
+    if(!ret)
+        return E_OUTOFMEMORY;
+
+    ret->IUriBuilder_iface.lpVtbl = &UriBuilderVtbl;
+    ret->ref = 1;
+
+    if(pIUri) {
+        Uri *uri;
+
+        if((uri = get_uri_obj(pIUri))) {
+            if(!uri->create_flags) {
+                heap_free(ret);
+                return E_UNEXPECTED;
+            }
+            IUri_AddRef(pIUri);
+            ret->uri = uri;
+
+            if(uri->has_port)
+                /* Windows doesn't set 'has_port' to TRUE in this case. */
+                ret->port = uri->port;
+
+        } else {
+            heap_free(ret);
+            *ppIUriBuilder = NULL;
+            FIXME("(%p %x %x %p): Unknown IUri types not supported yet.\n", pIUri, dwFlags,
+                (DWORD)dwReserved, ppIUriBuilder);
+            return E_NOTIMPL;
+        }
+    }
+
+    *ppIUriBuilder = &ret->IUriBuilder_iface;
+    return S_OK;
+}
+
+/* Merges the base path with the relative path and stores the resulting path
+ * and path len in 'result' and 'result_len'.
+ */
+static HRESULT merge_paths(parse_data *data, const WCHAR *base, DWORD base_len, const WCHAR *relative,
+                           DWORD relative_len, WCHAR **result, DWORD *result_len, DWORD flags)
+{
+    const WCHAR *end = NULL;
+    DWORD base_copy_len = 0;
+    WCHAR *ptr;
+
+    if(base_len) {
+        if(data->scheme_type == URL_SCHEME_MK && *relative == '/') {
+            /* Find '::' segment */
+            for(end = base; end < base+base_len-1; end++) {
+                if(end[0] == ':' && end[1] == ':') {
+                    end++;
+                    break;
+                }
+            }
+
+            /* If not found, try finding the end of @xxx: */
+            if(end == base+base_len-1)
+                end = *base == '@' ? memchr(base, ':', base_len) : NULL;
+        }else {
+            /* Find the characters that will be copied over from the base path. */
+            end = memrchrW(base, '/', base_len);
+            if(!end && data->scheme_type == URL_SCHEME_FILE)
+                /* Try looking for a '\\'. */
+                end = memrchrW(base, '\\', base_len);
+        }
+    }
+
+    if(end) {
+        base_copy_len = (end+1)-base;
+        *result = heap_alloc((base_copy_len+relative_len+1)*sizeof(WCHAR));
+    } else
+        *result = heap_alloc((relative_len+1)*sizeof(WCHAR));
+
+    if(!(*result)) {
+        *result_len = 0;
+        return E_OUTOFMEMORY;
+    }
+
+    ptr = *result;
+    if(end) {
+        memcpy(ptr, base, base_copy_len*sizeof(WCHAR));
+        ptr += base_copy_len;
+    }
+
+    memcpy(ptr, relative, relative_len*sizeof(WCHAR));
+    ptr += relative_len;
+    *ptr = '\0';
+
+    *result_len = (ptr-*result);
+    TRACE("ret %s\n", debugstr_wn(*result, *result_len));
+    return S_OK;
+}
+
+static HRESULT combine_uri(Uri *base, Uri *relative, DWORD flags, IUri **result, DWORD extras) {
+    Uri *ret;
+    HRESULT hr;
+    parse_data data;
+    Uri *proc_uri = base;
+    DWORD create_flags = 0, len = 0;
+
+    memset(&data, 0, sizeof(parse_data));
+
+    /* Base case is when the relative Uri has a scheme name,
+     * if it does, then 'result' will contain the same data
+     * as the relative Uri.
+     */
+    if(relative->scheme_start > -1) {
+        data.uri = SysAllocString(relative->raw_uri);
+        if(!data.uri) {
+            *result = NULL;
+            return E_OUTOFMEMORY;
+        }
+
+        parse_uri(&data, Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME);
+
+        hr = Uri_Construct(NULL, (void**)&ret);
+        if(FAILED(hr)) {
+            *result = NULL;
+            return hr;
+        }
+
+        if(extras & COMBINE_URI_FORCE_FLAG_USE) {
+            if(flags & URL_DONT_SIMPLIFY)
+                create_flags |= Uri_CREATE_NO_CANONICALIZE;
+            if(flags & URL_DONT_UNESCAPE_EXTRA_INFO)
+                create_flags |= Uri_CREATE_NO_DECODE_EXTRA_INFO;
+        }
+
+        ret->raw_uri = data.uri;
+        hr = canonicalize_uri(&data, ret, create_flags);
+        if(FAILED(hr)) {
+            IUri_Release(&ret->IUri_iface);
+            *result = NULL;
+            return hr;
+        }
+
+        apply_default_flags(&create_flags);
+        ret->create_flags = create_flags;
+
+        *result = &ret->IUri_iface;
+    } else {
+        WCHAR *path = NULL;
+        DWORD raw_flags = 0;
+
+        if(base->scheme_start > -1) {
+            data.scheme = base->canon_uri+base->scheme_start;
+            data.scheme_len = base->scheme_len;
+            data.scheme_type = base->scheme_type;
+        } else {
+            data.is_relative = TRUE;
+            data.scheme_type = URL_SCHEME_UNKNOWN;
+            create_flags |= Uri_CREATE_ALLOW_RELATIVE;
+        }
+
+        if(relative->authority_start > -1)
+            proc_uri = relative;
+
+        if(proc_uri->authority_start > -1) {
+            if(proc_uri->userinfo_start > -1 && proc_uri->userinfo_split != 0) {
+                data.username = proc_uri->canon_uri+proc_uri->userinfo_start;
+                data.username_len = (proc_uri->userinfo_split > -1) ? proc_uri->userinfo_split : proc_uri->userinfo_len;
+            }
+
+            if(proc_uri->userinfo_split > -1) {
+                data.password = proc_uri->canon_uri+proc_uri->userinfo_start+proc_uri->userinfo_split+1;
+                data.password_len = proc_uri->userinfo_len-proc_uri->userinfo_split-1;
+            }
+
+            if(proc_uri->host_start > -1) {
+                data.host = proc_uri->canon_uri+proc_uri->host_start;
+                data.host_len = proc_uri->host_len;
+                data.host_type = proc_uri->host_type;
+            }
+
+            if(proc_uri->has_port) {
+                data.has_port = TRUE;
+                data.port_value = proc_uri->port;
+            }
+        } else if(base->scheme_type != URL_SCHEME_FILE)
+            data.is_opaque = TRUE;
+
+        if(proc_uri == relative || relative->path_start == -1 || !relative->path_len) {
+            if(proc_uri->path_start > -1) {
+                data.path = proc_uri->canon_uri+proc_uri->path_start;
+                data.path_len = proc_uri->path_len;
+            } else if(!data.is_opaque) {
+                /* Just set the path as a '/' if the base didn't have
+                 * one and if it's a hierarchical URI.
+                 */
+                static const WCHAR slashW[] = {'/',0};
+                data.path = slashW;
+                data.path_len = 1;
+            }
+
+            if(relative->query_start > -1)
+                proc_uri = relative;
+
+            if(proc_uri->query_start > -1) {
+                data.query = proc_uri->canon_uri+proc_uri->query_start;
+                data.query_len = proc_uri->query_len;
+            }
+        } else {
+            const WCHAR *ptr, **pptr;
+            DWORD path_offset = 0, path_len = 0;
+
+            /* There's two possibilities on what will happen to the path component
+             * of the result IUri. First, if the relative path begins with a '/'
+             * then the resulting path will just be the relative path. Second, if
+             * relative path doesn't begin with a '/' then the base path and relative
+             * path are merged together.
+             */
+            if(relative->path_len && *(relative->canon_uri+relative->path_start) == '/' && data.scheme_type != URL_SCHEME_MK) {
+                WCHAR *tmp = NULL;
+                BOOL copy_drive_path = FALSE;
+
+                /* If the relative IUri's path starts with a '/', then we
+                 * don't use the base IUri's path. Unless the base IUri
+                 * is a file URI, in which case it uses the drive path of
+                 * the base IUri (if it has any) in the new path.
+                 */
+                if(base->scheme_type == URL_SCHEME_FILE) {
+                    if(base->path_len > 3 && *(base->canon_uri+base->path_start) == '/' &&
+                       is_drive_path(base->canon_uri+base->path_start+1)) {
+                        path_len += 3;
+                        copy_drive_path = TRUE;
+                    }
+                }
+
+                path_len += relative->path_len;
+
+                path = heap_alloc((path_len+1)*sizeof(WCHAR));
+                if(!path) {
+                    *result = NULL;
+                    return E_OUTOFMEMORY;
+                }
+
+                tmp = path;
+
+                /* Copy the base paths, drive path over. */
+                if(copy_drive_path) {
+                    memcpy(tmp, base->canon_uri+base->path_start, 3*sizeof(WCHAR));
+                    tmp += 3;
+                }
+
+                memcpy(tmp, relative->canon_uri+relative->path_start, relative->path_len*sizeof(WCHAR));
+                path[path_len] = '\0';
+            } else {
+                /* Merge the base path with the relative path. */
+                hr = merge_paths(&data, base->canon_uri+base->path_start, base->path_len,
+                                 relative->canon_uri+relative->path_start, relative->path_len,
+                                 &path, &path_len, flags);
+                if(FAILED(hr)) {
+                    *result = NULL;
+                    return hr;
+                }
+
+                /* If the resulting IUri is a file URI, the drive path isn't
+                 * reduced out when the dot segments are removed.
+                 */
+                if(path_len >= 3 && data.scheme_type == URL_SCHEME_FILE && !data.host) {
+                    if(*path == '/' && is_drive_path(path+1))
+                        path_offset = 2;
+                    else if(is_drive_path(path))
+                        path_offset = 1;
+                }
+            }
 
-    if(!ppURI)
-        return E_INVALIDARG;
+            /* Check if the dot segments need to be removed from the path. */
+            if(!(flags & URL_DONT_SIMPLIFY) && !data.is_opaque) {
+                DWORD offset = (path_offset > 0) ? path_offset+1 : 0;
+                DWORD new_len = remove_dot_segments(path+offset,path_len-offset);
+
+                if(new_len != path_len) {
+                    WCHAR *tmp = heap_realloc(path, (offset+new_len+1)*sizeof(WCHAR));
+                    if(!tmp) {
+                        heap_free(path);
+                        *result = NULL;
+                        return E_OUTOFMEMORY;
+                    }
 
-    if(!pwzURI) {
-        *ppURI = NULL;
-        return E_INVALIDARG;
-    }
+                    tmp[new_len+offset] = '\0';
+                    path = tmp;
+                    path_len = new_len+offset;
+                }
+            }
 
-    /* Check if a fragment should be appended to the URI string. */
-    if(pwzFragment) {
-        WCHAR *uriW;
-        DWORD uri_len, frag_len;
-        BOOL add_pound;
+            if(relative->query_start > -1) {
+                data.query = relative->canon_uri+relative->query_start;
+                data.query_len = relative->query_len;
+            }
 
-        /* Check if the original URI already has a fragment component. */
-        if(StrChrW(pwzURI, '#')) {
-            *ppURI = NULL;
-            return E_INVALIDARG;
+            /* Make sure the path component is valid. */
+            ptr = path;
+            pptr = &ptr;
+            if((data.is_opaque && !parse_path_opaque(pptr, &data, 0)) ||
+               (!data.is_opaque && !parse_path_hierarchical(pptr, &data, 0))) {
+                heap_free(path);
+                *result = NULL;
+                return E_INVALIDARG;
+            }
         }
 
-        uri_len = lstrlenW(pwzURI);
-        frag_len = lstrlenW(pwzFragment);
-
-        /* If the fragment doesn't start with a '#', one will be added. */
-        add_pound = *pwzFragment != '#';
+        if(relative->fragment_start > -1) {
+            data.fragment = relative->canon_uri+relative->fragment_start;
+            data.fragment_len = relative->fragment_len;
+        }
 
-        if(add_pound)
-            uriW = heap_alloc((uri_len+frag_len+2)*sizeof(WCHAR));
-        else
-            uriW = heap_alloc((uri_len+frag_len+1)*sizeof(WCHAR));
+        if(flags & URL_DONT_SIMPLIFY)
+            raw_flags |= RAW_URI_FORCE_PORT_DISP;
+        if(flags & URL_FILE_USE_PATHURL)
+            raw_flags |= RAW_URI_CONVERT_TO_DOS_PATH;
 
-        if(!uriW)
+        len = generate_raw_uri(&data, data.uri, raw_flags);
+        data.uri = SysAllocStringLen(NULL, len);
+        if(!data.uri) {
+            heap_free(path);
+            *result = NULL;
             return E_OUTOFMEMORY;
+        }
 
-        memcpy(uriW, pwzURI, uri_len*sizeof(WCHAR));
-        if(add_pound)
-            uriW[uri_len++] = '#';
-        memcpy(uriW+uri_len, pwzFragment, (frag_len+1)*sizeof(WCHAR));
-
-        hres = CreateUri(uriW, dwFlags, 0, ppURI);
+        generate_raw_uri(&data, data.uri, raw_flags);
 
-        heap_free(uriW);
-    } else
-        /* A fragment string wasn't specified, so just forward the call. */
-        hres = CreateUri(pwzURI, dwFlags, 0, ppURI);
+        hr = Uri_Construct(NULL, (void**)&ret);
+        if(FAILED(hr)) {
+            SysFreeString(data.uri);
+            heap_free(path);
+            *result = NULL;
+            return hr;
+        }
 
-    return hres;
-}
+        if(flags & URL_DONT_SIMPLIFY)
+            create_flags |= Uri_CREATE_NO_CANONICALIZE;
+        if(flags & URL_FILE_USE_PATHURL)
+            create_flags |= Uri_CREATE_FILE_USE_DOS_PATH;
+
+        ret->raw_uri = data.uri;
+        hr = canonicalize_uri(&data, ret, create_flags);
+        if(FAILED(hr)) {
+            IUri_Release(&ret->IUri_iface);
+            *result = NULL;
+            return hr;
+        }
 
-#define URIBUILDER_THIS(iface) DEFINE_THIS(UriBuilder, IUriBuilder, iface)
+        if(flags & URL_DONT_SIMPLIFY)
+            ret->display_modifiers |= URI_DISPLAY_NO_DEFAULT_PORT_AUTH;
 
-static HRESULT WINAPI UriBuilder_QueryInterface(IUriBuilder *iface, REFIID riid, void **ppv)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
+        apply_default_flags(&create_flags);
+        ret->create_flags = create_flags;
+        *result = &ret->IUri_iface;
 
-    if(IsEqualGUID(&IID_IUnknown, riid)) {
-        TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
-        *ppv = URIBUILDER(This);
-    }else if(IsEqualGUID(&IID_IUriBuilder, riid)) {
-        TRACE("(%p)->(IID_IUri %p)\n", This, ppv);
-        *ppv = URIBUILDER(This);
-    }else {
-        TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
-        *ppv = NULL;
-        return E_NOINTERFACE;
+        heap_free(path);
     }
 
-    IUnknown_AddRef((IUnknown*)*ppv);
     return S_OK;
 }
 
-static ULONG WINAPI UriBuilder_AddRef(IUriBuilder *iface)
+/***********************************************************************
+ *           CoInternetCombineIUri (urlmon.@)
+ */
+HRESULT WINAPI CoInternetCombineIUri(IUri *pBaseUri, IUri *pRelativeUri, DWORD dwCombineFlags,
+                                     IUri **ppCombinedUri, DWORD_PTR dwReserved)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    LONG ref = InterlockedIncrement(&This->ref);
+    HRESULT hr;
+    IInternetProtocolInfo *info;
+    Uri *relative, *base;
+    TRACE("(%p %p %x %p %x)\n", pBaseUri, pRelativeUri, dwCombineFlags, ppCombinedUri, (DWORD)dwReserved);
 
-    TRACE("(%p) ref=%d\n", This, ref);
+    if(!ppCombinedUri)
+        return E_INVALIDARG;
 
-    return ref;
-}
+    if(!pBaseUri || !pRelativeUri) {
+        *ppCombinedUri = NULL;
+        return E_INVALIDARG;
+    }
 
-static ULONG WINAPI UriBuilder_Release(IUriBuilder *iface)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    LONG ref = InterlockedDecrement(&This->ref);
+    relative = get_uri_obj(pRelativeUri);
+    base = get_uri_obj(pBaseUri);
+    if(!relative || !base) {
+        *ppCombinedUri = NULL;
+        FIXME("(%p %p %x %p %x) Unknown IUri types not supported yet.\n",
+            pBaseUri, pRelativeUri, dwCombineFlags, ppCombinedUri, (DWORD)dwReserved);
+        return E_NOTIMPL;
+    }
 
-    TRACE("(%p) ref=%d\n", This, ref);
+    info = get_protocol_info(base->canon_uri);
+    if(info) {
+        WCHAR result[INTERNET_MAX_URL_LENGTH+1];
+        DWORD result_len = 0;
 
-    if(!ref) {
-        if(This->uri) IUri_Release(URI(This->uri));
-        heap_free(This->fragment);
-        heap_free(This->host);
-        heap_free(This->password);
-        heap_free(This->path);
-        heap_free(This->query);
-        heap_free(This->scheme);
-        heap_free(This->username);
-        heap_free(This);
+        hr = IInternetProtocolInfo_CombineUrl(info, base->canon_uri, relative->canon_uri, dwCombineFlags,
+                                              result, INTERNET_MAX_URL_LENGTH+1, &result_len, 0);
+        IInternetProtocolInfo_Release(info);
+        if(SUCCEEDED(hr)) {
+            hr = CreateUri(result, Uri_CREATE_ALLOW_RELATIVE, 0, ppCombinedUri);
+            if(SUCCEEDED(hr))
+                return hr;
+        }
     }
 
-    return ref;
+    return combine_uri(base, relative, dwCombineFlags, ppCombinedUri, 0);
 }
 
-static HRESULT WINAPI UriBuilder_CreateUriSimple(IUriBuilder *iface,
-                                                 DWORD        dwAllowEncodingPropertyMask,
-                                                 DWORD_PTR    dwReserved,
-                                                 IUri       **ppIUri)
+/***********************************************************************
+ *           CoInternetCombineUrlEx (urlmon.@)
+ */
+HRESULT WINAPI CoInternetCombineUrlEx(IUri *pBaseUri, LPCWSTR pwzRelativeUrl, DWORD dwCombineFlags,
+                                      IUri **ppCombinedUri, DWORD_PTR dwReserved)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
+    IUri *relative;
+    Uri *base;
     HRESULT hr;
-    TRACE("(%p)->(%d %d %p)\n", This, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    IInternetProtocolInfo *info;
 
-    hr = build_uri(This, ppIUri, 0, UriBuilder_USE_ORIGINAL_FLAGS, dwAllowEncodingPropertyMask);
-    if(hr == E_NOTIMPL)
-        FIXME("(%p)->(%d %d %p)\n", This, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
-    return hr;
-}
+    TRACE("(%p %s %x %p %x) stub\n", pBaseUri, debugstr_w(pwzRelativeUrl), dwCombineFlags,
+        ppCombinedUri, (DWORD)dwReserved);
 
-static HRESULT WINAPI UriBuilder_CreateUri(IUriBuilder *iface,
-                                           DWORD        dwCreateFlags,
-                                           DWORD        dwAllowEncodingPropertyMask,
-                                           DWORD_PTR    dwReserved,
-                                           IUri       **ppIUri)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    HRESULT hr;
-    TRACE("(%p)->(0x%08x %d %d %p)\n", This, dwCreateFlags, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    if(!ppCombinedUri)
+        return E_POINTER;
 
-    if(dwCreateFlags == -1)
-        hr = build_uri(This, ppIUri, 0, UriBuilder_USE_ORIGINAL_FLAGS, dwAllowEncodingPropertyMask);
-    else
-        hr = build_uri(This, ppIUri, dwCreateFlags, 0, dwAllowEncodingPropertyMask);
+    if(!pwzRelativeUrl) {
+        *ppCombinedUri = NULL;
+        return E_UNEXPECTED;
+    }
 
-    if(hr == E_NOTIMPL)
-        FIXME("(%p)->(0x%08x %d %d %p)\n", This, dwCreateFlags, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
-    return hr;
-}
+    if(!pBaseUri) {
+        *ppCombinedUri = NULL;
+        return E_INVALIDARG;
+    }
 
-static HRESULT WINAPI UriBuilder_CreateUriWithFlags(IUriBuilder *iface,
-                                         DWORD        dwCreateFlags,
-                                         DWORD        dwUriBuilderFlags,
-                                         DWORD        dwAllowEncodingPropertyMask,
-                                         DWORD_PTR    dwReserved,
-                                         IUri       **ppIUri)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    HRESULT hr;
-    TRACE("(%p)->(0x%08x 0x%08x %d %d %p)\n", This, dwCreateFlags, dwUriBuilderFlags,
-        dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    base = get_uri_obj(pBaseUri);
+    if(!base) {
+        *ppCombinedUri = NULL;
+        FIXME("(%p %s %x %p %x) Unknown IUri's not supported yet.\n", pBaseUri, debugstr_w(pwzRelativeUrl),
+            dwCombineFlags, ppCombinedUri, (DWORD)dwReserved);
+        return E_NOTIMPL;
+    }
 
-    hr = build_uri(This, ppIUri, dwCreateFlags, dwUriBuilderFlags, dwAllowEncodingPropertyMask);
-    if(hr == E_NOTIMPL)
-        FIXME("(%p)->(0x%08x 0x%08x %d %d %p)\n", This, dwCreateFlags, dwUriBuilderFlags,
-            dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
+    info = get_protocol_info(base->canon_uri);
+    if(info) {
+        WCHAR result[INTERNET_MAX_URL_LENGTH+1];
+        DWORD result_len = 0;
+
+        hr = IInternetProtocolInfo_CombineUrl(info, base->canon_uri, pwzRelativeUrl, dwCombineFlags,
+                                              result, INTERNET_MAX_URL_LENGTH+1, &result_len, 0);
+        IInternetProtocolInfo_Release(info);
+        if(SUCCEEDED(hr)) {
+            hr = CreateUri(result, Uri_CREATE_ALLOW_RELATIVE, 0, ppCombinedUri);
+            if(SUCCEEDED(hr))
+                return hr;
+        }
+    }
+
+    hr = CreateUri(pwzRelativeUrl, Uri_CREATE_ALLOW_RELATIVE|Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME, 0, &relative);
+    if(FAILED(hr)) {
+        *ppCombinedUri = NULL;
+        return hr;
+    }
+
+    hr = combine_uri(base, get_uri_obj(relative), dwCombineFlags, ppCombinedUri, COMBINE_URI_FORCE_FLAG_USE);
+
+    IUri_Release(relative);
     return hr;
 }
 
-static HRESULT WINAPI  UriBuilder_GetIUri(IUriBuilder *iface, IUri **ppIUri)
+static HRESULT parse_canonicalize(const Uri *uri, DWORD flags, LPWSTR output,
+                                  DWORD output_len, DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p)\n", This, ppIUri);
+    const WCHAR *ptr = NULL;
+    WCHAR *path = NULL;
+    const WCHAR **pptr;
+    WCHAR buffer[INTERNET_MAX_URL_LENGTH+1];
+    DWORD len = 0;
+    BOOL reduce_path;
 
-    if(!ppIUri)
-        return E_POINTER;
+    /* URL_UNESCAPE only has effect if none of the URL_ESCAPE flags are set. */
+    const BOOL allow_unescape = !(flags & URL_ESCAPE_UNSAFE) &&
+                                !(flags & URL_ESCAPE_SPACES_ONLY) &&
+                                !(flags & URL_ESCAPE_PERCENT);
 
-    if(This->uri) {
-        IUri *uri = URI(This->uri);
-        IUri_AddRef(uri);
-        *ppIUri = uri;
-    } else
-        *ppIUri = NULL;
 
-    return S_OK;
-}
+    /* Check if the dot segments need to be removed from the
+     * path component.
+     */
+    if(uri->scheme_start > -1 && uri->path_start > -1) {
+        ptr = uri->canon_uri+uri->scheme_start+uri->scheme_len+1;
+        pptr = &ptr;
+    }
+    reduce_path = !(flags & URL_NO_META) &&
+                  !(flags & URL_DONT_SIMPLIFY) &&
+                  ptr && check_hierarchical(pptr);
 
-static HRESULT WINAPI UriBuilder_SetIUri(IUriBuilder *iface, IUri *pIUri)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p)\n", This, pIUri);
+    for(ptr = uri->canon_uri; ptr < uri->canon_uri+uri->canon_len; ++ptr) {
+        BOOL do_default_action = TRUE;
 
-    if(pIUri) {
-        Uri *uri;
+        /* Keep track of the path if we need to remove dot segments from
+         * it later.
+         */
+        if(reduce_path && !path && ptr == uri->canon_uri+uri->path_start)
+            path = buffer+len;
 
-        if((uri = get_uri_obj(pIUri))) {
-            /* Only reset the builder if it's Uri isn't the same as
-             * the Uri passed to the function.
-             */
-            if(This->uri != uri) {
-                reset_builder(This);
+        /* Check if it's time to reduce the path. */
+        if(reduce_path && ptr == uri->canon_uri+uri->path_start+uri->path_len) {
+            DWORD current_path_len = (buffer+len) - path;
+            DWORD new_path_len = remove_dot_segments(path, current_path_len);
 
-                This->uri = uri;
-                if(uri->has_port)
-                    This->port = uri->port;
+            /* Update the current length. */
+            len -= (current_path_len-new_path_len);
+            reduce_path = FALSE;
+        }
 
-                IUri_AddRef(pIUri);
+        if(*ptr == '%') {
+            const WCHAR decoded = decode_pct_val(ptr);
+            if(decoded) {
+                if(allow_unescape && (flags & URL_UNESCAPE)) {
+                    buffer[len++] = decoded;
+                    ptr += 2;
+                    do_default_action = FALSE;
+                }
+            }
+
+            /* See if %'s needed to encoded. */
+            if(do_default_action && (flags & URL_ESCAPE_PERCENT)) {
+                pct_encode_val(*ptr, buffer+len);
+                len += 3;
+                do_default_action = FALSE;
+            }
+        } else if(*ptr == ' ') {
+            if((flags & URL_ESCAPE_SPACES_ONLY) &&
+               !(flags & URL_ESCAPE_UNSAFE)) {
+                pct_encode_val(*ptr, buffer+len);
+                len += 3;
+                do_default_action = FALSE;
+            }
+        } else if(!is_reserved(*ptr) && !is_unreserved(*ptr)) {
+            if(flags & URL_ESCAPE_UNSAFE) {
+                pct_encode_val(*ptr, buffer+len);
+                len += 3;
+                do_default_action = FALSE;
             }
-        } else {
-            FIXME("(%p)->(%p) Unknown IUri types not supported yet.\n", This, pIUri);
-            return E_NOTIMPL;
         }
-    } else if(This->uri)
-        /* Only reset the builder if it's Uri isn't NULL. */
-        reset_builder(This);
 
-    return S_OK;
-}
+        if(do_default_action)
+            buffer[len++] = *ptr;
+    }
 
-static HRESULT WINAPI UriBuilder_GetFragment(IUriBuilder *iface, DWORD *pcchFragment, LPCWSTR *ppwzFragment)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchFragment, ppwzFragment);
+    /* Sometimes the path is the very last component of the IUri, so
+     * see if the dot segments need to be reduced now.
+     */
+    if(reduce_path && path) {
+        DWORD current_path_len = (buffer+len) - path;
+        DWORD new_path_len = remove_dot_segments(path, current_path_len);
 
-    if(!This->uri || This->uri->fragment_start == -1 || This->modified_props & Uri_HAS_FRAGMENT)
-        return get_builder_component(&This->fragment, &This->fragment_len, NULL, 0, ppwzFragment, pcchFragment);
+        /* Update the current length. */
+        len -= (current_path_len-new_path_len);
+    }
+
+    buffer[len++] = 0;
+
+    /* The null terminator isn't included in the length. */
+    *result_len = len-1;
+    if(len > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
     else
-        return get_builder_component(&This->fragment, &This->fragment_len, This->uri->canon_uri+This->uri->fragment_start,
-                                     This->uri->fragment_len, ppwzFragment, pcchFragment);
+        memcpy(output, buffer, len*sizeof(WCHAR));
+
+    return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_GetHost(IUriBuilder *iface, DWORD *pcchHost, LPCWSTR *ppwzHost)
+static HRESULT parse_friendly(IUri *uri, LPWSTR output, DWORD output_len,
+                              DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchHost, ppwzHost);
+    HRESULT hr;
+    DWORD display_len;
+    BSTR display;
 
-    if(!This->uri || This->uri->host_start == -1 || This->modified_props & Uri_HAS_HOST)
-        return get_builder_component(&This->host, &This->host_len, NULL, 0, ppwzHost, pcchHost);
-    else {
-        if(This->uri->host_type == Uri_HOST_IPV6)
-            /* Don't include the '[' and ']' around the address. */
-            return get_builder_component(&This->host, &This->host_len, This->uri->canon_uri+This->uri->host_start+1,
-                                         This->uri->host_len-2, ppwzHost, pcchHost);
-        else
-            return get_builder_component(&This->host, &This->host_len, This->uri->canon_uri+This->uri->host_start,
-                                         This->uri->host_len, ppwzHost, pcchHost);
+    hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_DISPLAY_URI, &display_len, 0);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
     }
-}
 
-static HRESULT WINAPI UriBuilder_GetPassword(IUriBuilder *iface, DWORD *pcchPassword, LPCWSTR *ppwzPassword)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchPassword, ppwzPassword);
+    *result_len = display_len;
+    if(display_len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
 
-    if(!This->uri || This->uri->userinfo_split == -1 || This->modified_props & Uri_HAS_PASSWORD)
-        return get_builder_component(&This->password, &This->password_len, NULL, 0, ppwzPassword, pcchPassword);
-    else {
-        const WCHAR *start = This->uri->canon_uri+This->uri->userinfo_start+This->uri->userinfo_split+1;
-        DWORD len = This->uri->userinfo_len-This->uri->userinfo_split-1;
-        return get_builder_component(&This->password, &This->password_len, start, len, ppwzPassword, pcchPassword);
+    hr = IUri_GetDisplayUri(uri, &display);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
     }
-}
-
-static HRESULT WINAPI UriBuilder_GetPath(IUriBuilder *iface, DWORD *pcchPath, LPCWSTR *ppwzPath)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchPath, ppwzPath);
 
-    if(!This->uri || This->uri->path_start == -1 || This->modified_props & Uri_HAS_PATH)
-        return get_builder_component(&This->path, &This->path_len, NULL, 0, ppwzPath, pcchPath);
-    else
-        return get_builder_component(&This->path, &This->path_len, This->uri->canon_uri+This->uri->path_start,
-                                     This->uri->path_len, ppwzPath, pcchPath);
+    memcpy(output, display, (display_len+1)*sizeof(WCHAR));
+    SysFreeString(display);
+    return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_GetPort(IUriBuilder *iface, BOOL *pfHasPort, DWORD *pdwPort)
+static HRESULT parse_rootdocument(const Uri *uri, LPWSTR output, DWORD output_len,
+                                  DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pfHasPort, pdwPort);
+    static const WCHAR colon_slashesW[] = {':','/','/'};
 
-    if(!pfHasPort) {
-        if(pdwPort)
-            *pdwPort = 0;
-        return E_POINTER;
+    WCHAR *ptr;
+    DWORD len = 0;
+
+    /* Windows only returns the root document if the URI has an authority
+     * and it's not an unknown scheme type or a file scheme type.
+     */
+    if(uri->authority_start == -1 ||
+       uri->scheme_type == URL_SCHEME_UNKNOWN ||
+       uri->scheme_type == URL_SCHEME_FILE) {
+        *result_len = 0;
+        if(!output_len)
+            return STRSAFE_E_INSUFFICIENT_BUFFER;
+
+        output[0] = 0;
+        return S_OK;
     }
 
-    if(!pdwPort) {
-        *pfHasPort = FALSE;
-        return E_POINTER;
+    len = uri->scheme_len+uri->authority_len;
+    /* For the "://" and '/' which will be added. */
+    len += 4;
+
+    if(len+1 > output_len) {
+        *result_len = len;
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
     }
 
-    *pfHasPort = This->has_port;
-    *pdwPort = This->port;
+    ptr = output;
+    memcpy(ptr, uri->canon_uri+uri->scheme_start, uri->scheme_len*sizeof(WCHAR));
+
+    /* Add the "://". */
+    ptr += uri->scheme_len;
+    memcpy(ptr, colon_slashesW, sizeof(colon_slashesW));
+
+    /* Add the authority. */
+    ptr += sizeof(colon_slashesW)/sizeof(WCHAR);
+    memcpy(ptr, uri->canon_uri+uri->authority_start, uri->authority_len*sizeof(WCHAR));
+
+    /* Add the '/' after the authority. */
+    ptr += uri->authority_len;
+    *ptr = '/';
+    ptr[1] = 0;
+
+    *result_len = len;
     return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_GetQuery(IUriBuilder *iface, DWORD *pcchQuery, LPCWSTR *ppwzQuery)
+static HRESULT parse_document(const Uri *uri, LPWSTR output, DWORD output_len,
+                              DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchQuery, ppwzQuery);
+    DWORD len = 0;
 
-    if(!This->uri || This->uri->query_start == -1 || This->modified_props & Uri_HAS_QUERY)
-        return get_builder_component(&This->query, &This->query_len, NULL, 0, ppwzQuery, pcchQuery);
+    /* It has to be a known scheme type, but, it can't be a file
+     * scheme. It also has to hierarchical.
+     */
+    if(uri->scheme_type == URL_SCHEME_UNKNOWN ||
+       uri->scheme_type == URL_SCHEME_FILE ||
+       uri->authority_start == -1) {
+        *result_len = 0;
+        if(output_len < 1)
+            return STRSAFE_E_INSUFFICIENT_BUFFER;
+
+        output[0] = 0;
+        return S_OK;
+    }
+
+    if(uri->fragment_start > -1)
+        len = uri->fragment_start;
     else
-        return get_builder_component(&This->query, &This->query_len, This->uri->canon_uri+This->uri->query_start,
-                                     This->uri->query_len, ppwzQuery, pcchQuery);
-}
+        len = uri->canon_len;
 
-static HRESULT WINAPI UriBuilder_GetSchemeName(IUriBuilder *iface, DWORD *pcchSchemeName, LPCWSTR *ppwzSchemeName)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchSchemeName, ppwzSchemeName);
+    *result_len = len;
+    if(len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
 
-    if(!This->uri || This->uri->scheme_start == -1 || This->modified_props & Uri_HAS_SCHEME_NAME)
-        return get_builder_component(&This->scheme, &This->scheme_len, NULL, 0, ppwzSchemeName, pcchSchemeName);
-    else
-        return get_builder_component(&This->scheme, &This->scheme_len, This->uri->canon_uri+This->uri->scheme_start,
-                                     This->uri->scheme_len, ppwzSchemeName, pcchSchemeName);
+    memcpy(output, uri->canon_uri, len*sizeof(WCHAR));
+    output[len] = 0;
+    return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_GetUserName(IUriBuilder *iface, DWORD *pcchUserName, LPCWSTR *ppwzUserName)
+static HRESULT parse_path_from_url(const Uri *uri, LPWSTR output, DWORD output_len,
+                                   DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p %p)\n", This, pcchUserName, ppwzUserName);
+    const WCHAR *path_ptr;
+    WCHAR buffer[INTERNET_MAX_URL_LENGTH+1];
+    WCHAR *ptr;
+
+    if(uri->scheme_type != URL_SCHEME_FILE) {
+        *result_len = 0;
+        if(output_len > 0)
+            output[0] = 0;
+        return E_INVALIDARG;
+    }
 
-    if(!This->uri || This->uri->userinfo_start == -1 || This->uri->userinfo_split == 0 ||
-       This->modified_props & Uri_HAS_USER_NAME)
-        return get_builder_component(&This->username, &This->username_len, NULL, 0, ppwzUserName, pcchUserName);
-    else {
-        const WCHAR *start = This->uri->canon_uri+This->uri->userinfo_start;
+    ptr = buffer;
+    if(uri->host_start > -1) {
+        static const WCHAR slash_slashW[] = {'\\','\\'};
 
-        /* Check if there's a password in the userinfo section. */
-        if(This->uri->userinfo_split > -1)
-            /* Don't include the password. */
-            return get_builder_component(&This->username, &This->username_len, start,
-                                         This->uri->userinfo_split, ppwzUserName, pcchUserName);
-        else
-            return get_builder_component(&This->username, &This->username_len, start,
-                                         This->uri->userinfo_len, ppwzUserName, pcchUserName);
+        memcpy(ptr, slash_slashW, sizeof(slash_slashW));
+        ptr += sizeof(slash_slashW)/sizeof(WCHAR);
+        memcpy(ptr, uri->canon_uri+uri->host_start, uri->host_len*sizeof(WCHAR));
+        ptr += uri->host_len;
     }
-}
 
-static HRESULT WINAPI UriBuilder_SetFragment(IUriBuilder *iface, LPCWSTR pwzNewValue)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
-    return set_builder_component(&This->fragment, &This->fragment_len, pwzNewValue, '#',
-                                 &This->modified_props, Uri_HAS_FRAGMENT);
-}
+    path_ptr = uri->canon_uri+uri->path_start;
+    if(uri->path_len > 3 && *path_ptr == '/' && is_drive_path(path_ptr+1))
+        /* Skip past the '/' in front of the drive path. */
+        ++path_ptr;
 
-static HRESULT WINAPI UriBuilder_SetHost(IUriBuilder *iface, LPCWSTR pwzNewValue)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    for(; path_ptr < uri->canon_uri+uri->path_start+uri->path_len; ++path_ptr, ++ptr) {
+        BOOL do_default_action = TRUE;
 
-    /* Host name can't be set to NULL. */
-    if(!pwzNewValue)
-        return E_INVALIDARG;
+        if(*path_ptr == '%') {
+            const WCHAR decoded = decode_pct_val(path_ptr);
+            if(decoded) {
+                *ptr = decoded;
+                path_ptr += 2;
+                do_default_action = FALSE;
+            }
+        } else if(*path_ptr == '/') {
+            *ptr = '\\';
+            do_default_action = FALSE;
+        }
 
-    return set_builder_component(&This->host, &This->host_len, pwzNewValue, 0,
-                                 &This->modified_props, Uri_HAS_HOST);
-}
+        if(do_default_action)
+            *ptr = *path_ptr;
+    }
 
-static HRESULT WINAPI UriBuilder_SetPassword(IUriBuilder *iface, LPCWSTR pwzNewValue)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
-    return set_builder_component(&This->password, &This->password_len, pwzNewValue, 0,
-                                 &This->modified_props, Uri_HAS_PASSWORD);
-}
+    *ptr = 0;
 
-static HRESULT WINAPI UriBuilder_SetPath(IUriBuilder *iface, LPCWSTR pwzNewValue)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
-    return set_builder_component(&This->path, &This->path_len, pwzNewValue, 0,
-                                 &This->modified_props, Uri_HAS_PATH);
+    *result_len = ptr-buffer;
+    if(*result_len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
+
+    memcpy(output, buffer, (*result_len+1)*sizeof(WCHAR));
+    return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_SetPort(IUriBuilder *iface, BOOL fHasPort, DWORD dwNewValue)
+static HRESULT parse_url_from_path(IUri *uri, LPWSTR output, DWORD output_len,
+                                   DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%d %d)\n", This, fHasPort, dwNewValue);
+    HRESULT hr;
+    BSTR received;
+    DWORD len = 0;
+
+    hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_ABSOLUTE_URI, &len, 0);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
+
+    *result_len = len;
+    if(len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
+
+    hr = IUri_GetAbsoluteUri(uri, &received);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
+
+    memcpy(output, received, (len+1)*sizeof(WCHAR));
+    SysFreeString(received);
 
-    This->has_port = fHasPort;
-    This->port = dwNewValue;
-    This->modified_props |= Uri_HAS_PORT;
     return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_SetQuery(IUriBuilder *iface, LPCWSTR pwzNewValue)
+static HRESULT parse_schema(IUri *uri, LPWSTR output, DWORD output_len,
+                            DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
-    return set_builder_component(&This->query, &This->query_len, pwzNewValue, '?',
-                                 &This->modified_props, Uri_HAS_QUERY);
-}
+    HRESULT hr;
+    DWORD len;
+    BSTR received;
 
-static HRESULT WINAPI UriBuilder_SetSchemeName(IUriBuilder *iface, LPCWSTR pwzNewValue)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
+    hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_SCHEME_NAME, &len, 0);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-    /* Only set the scheme name if it's not NULL or empty. */
-    if(!pwzNewValue || !*pwzNewValue)
-        return E_INVALIDARG;
+    *result_len = len;
+    if(len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
 
-    return set_builder_component(&This->scheme, &This->scheme_len, pwzNewValue, 0,
-                                 &This->modified_props, Uri_HAS_SCHEME_NAME);
-}
+    hr = IUri_GetSchemeName(uri, &received);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-static HRESULT WINAPI UriBuilder_SetUserName(IUriBuilder *iface, LPCWSTR pwzNewValue)
-{
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
-    return set_builder_component(&This->username, &This->username_len, pwzNewValue, 0,
-                                 &This->modified_props, Uri_HAS_USER_NAME);
+    memcpy(output, received, (len+1)*sizeof(WCHAR));
+    SysFreeString(received);
+
+    return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_RemoveProperties(IUriBuilder *iface, DWORD dwPropertyMask)
+static HRESULT parse_site(IUri *uri, LPWSTR output, DWORD output_len, DWORD *result_len)
 {
-    const DWORD accepted_flags = Uri_HAS_AUTHORITY|Uri_HAS_DOMAIN|Uri_HAS_EXTENSION|Uri_HAS_FRAGMENT|Uri_HAS_HOST|
-                                 Uri_HAS_PASSWORD|Uri_HAS_PATH|Uri_HAS_PATH_AND_QUERY|Uri_HAS_QUERY|
-                                 Uri_HAS_USER_INFO|Uri_HAS_USER_NAME;
+    HRESULT hr;
+    DWORD len;
+    BSTR received;
 
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(0x%08x)\n", This, dwPropertyMask);
+    hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_HOST, &len, 0);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-    if(dwPropertyMask & ~accepted_flags)
-        return E_INVALIDARG;
+    *result_len = len;
+    if(len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
 
-    if(dwPropertyMask & Uri_HAS_FRAGMENT)
-        UriBuilder_SetFragment(iface, NULL);
+    hr = IUri_GetHost(uri, &received);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-    /* Even though you can't set the host name to NULL or an
-     * empty string, you can still remove it... for some reason.
-     */
-    if(dwPropertyMask & Uri_HAS_HOST)
-        set_builder_component(&This->host, &This->host_len, NULL, 0,
-                              &This->modified_props, Uri_HAS_HOST);
+    memcpy(output, received, (len+1)*sizeof(WCHAR));
+    SysFreeString(received);
 
-    if(dwPropertyMask & Uri_HAS_PASSWORD)
-        UriBuilder_SetPassword(iface, NULL);
+    return S_OK;
+}
 
-    if(dwPropertyMask & Uri_HAS_PATH)
-        UriBuilder_SetPath(iface, NULL);
+static HRESULT parse_domain(IUri *uri, LPWSTR output, DWORD output_len, DWORD *result_len)
+{
+    HRESULT hr;
+    DWORD len;
+    BSTR received;
 
-    if(dwPropertyMask & Uri_HAS_PORT)
-        UriBuilder_SetPort(iface, FALSE, 0);
+    hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_DOMAIN, &len, 0);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-    if(dwPropertyMask & Uri_HAS_QUERY)
-        UriBuilder_SetQuery(iface, NULL);
+    *result_len = len;
+    if(len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
 
-    if(dwPropertyMask & Uri_HAS_USER_NAME)
-        UriBuilder_SetUserName(iface, NULL);
+    hr = IUri_GetDomain(uri, &received);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
+
+    memcpy(output, received, (len+1)*sizeof(WCHAR));
+    SysFreeString(received);
 
     return S_OK;
 }
 
-static HRESULT WINAPI UriBuilder_HasBeenModified(IUriBuilder *iface, BOOL *pfModified)
+static HRESULT parse_anchor(IUri *uri, LPWSTR output, DWORD output_len, DWORD *result_len)
 {
-    UriBuilder *This = URIBUILDER_THIS(iface);
-    TRACE("(%p)->(%p)\n", This, pfModified);
+    HRESULT hr;
+    DWORD len;
+    BSTR received;
 
-    if(!pfModified)
-        return E_POINTER;
+    hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_FRAGMENT, &len, 0);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-    *pfModified = This->modified_props > 0;
-    return S_OK;
-}
+    *result_len = len;
+    if(len+1 > output_len)
+        return STRSAFE_E_INSUFFICIENT_BUFFER;
 
-#undef URIBUILDER_THIS
+    hr = IUri_GetFragment(uri, &received);
+    if(FAILED(hr)) {
+        *result_len = 0;
+        return hr;
+    }
 
-static const IUriBuilderVtbl UriBuilderVtbl = {
-    UriBuilder_QueryInterface,
-    UriBuilder_AddRef,
-    UriBuilder_Release,
-    UriBuilder_CreateUriSimple,
-    UriBuilder_CreateUri,
-    UriBuilder_CreateUriWithFlags,
-    UriBuilder_GetIUri,
-    UriBuilder_SetIUri,
-    UriBuilder_GetFragment,
-    UriBuilder_GetHost,
-    UriBuilder_GetPassword,
-    UriBuilder_GetPath,
-    UriBuilder_GetPort,
-    UriBuilder_GetQuery,
-    UriBuilder_GetSchemeName,
-    UriBuilder_GetUserName,
-    UriBuilder_SetFragment,
-    UriBuilder_SetHost,
-    UriBuilder_SetPassword,
-    UriBuilder_SetPath,
-    UriBuilder_SetPort,
-    UriBuilder_SetQuery,
-    UriBuilder_SetSchemeName,
-    UriBuilder_SetUserName,
-    UriBuilder_RemoveProperties,
-    UriBuilder_HasBeenModified,
-};
+    memcpy(output, received, (len+1)*sizeof(WCHAR));
+    SysFreeString(received);
+
+    return S_OK;
+}
 
 /***********************************************************************
- *           CreateIUriBuilder (urlmon.@)
+ *           CoInternetParseIUri (urlmon.@)
  */
-HRESULT WINAPI CreateIUriBuilder(IUri *pIUri, DWORD dwFlags, DWORD_PTR dwReserved, IUriBuilder **ppIUriBuilder)
+HRESULT WINAPI CoInternetParseIUri(IUri *pIUri, PARSEACTION ParseAction, DWORD dwFlags,
+                                   LPWSTR pwzResult, DWORD cchResult, DWORD *pcchResult,
+                                   DWORD_PTR dwReserved)
 {
-    UriBuilder *ret;
+    HRESULT hr;
+    Uri *uri;
+    IInternetProtocolInfo *info;
 
-    TRACE("(%p %x %x %p)\n", pIUri, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
+    TRACE("(%p %d %x %p %d %p %x)\n", pIUri, ParseAction, dwFlags, pwzResult,
+        cchResult, pcchResult, (DWORD)dwReserved);
 
-    if(!ppIUriBuilder)
+    if(!pcchResult)
         return E_POINTER;
 
-    ret = heap_alloc_zero(sizeof(UriBuilder));
-    if(!ret)
-        return E_OUTOFMEMORY;
-
-    ret->lpIUriBuilderVtbl = &UriBuilderVtbl;
-    ret->ref = 1;
-
-    if(pIUri) {
-        Uri *uri;
+    if(!pwzResult || !pIUri) {
+        *pcchResult = 0;
+        return E_INVALIDARG;
+    }
 
-        if((uri = get_uri_obj(pIUri))) {
-            IUri_AddRef(pIUri);
-            ret->uri = uri;
+    if(!(uri = get_uri_obj(pIUri))) {
+        *pcchResult = 0;
+        FIXME("(%p %d %x %p %d %p %x) Unknown IUri's not supported for this action.\n",
+            pIUri, ParseAction, dwFlags, pwzResult, cchResult, pcchResult, (DWORD)dwReserved);
+        return E_NOTIMPL;
+    }
 
-            if(uri->has_port)
-                /* Windows doesn't set 'has_port' to TRUE in this case. */
-                ret->port = uri->port;
+    info = get_protocol_info(uri->canon_uri);
+    if(info) {
+        hr = IInternetProtocolInfo_ParseUrl(info, uri->canon_uri, ParseAction, dwFlags,
+                                            pwzResult, cchResult, pcchResult, 0);
+        IInternetProtocolInfo_Release(info);
+        if(SUCCEEDED(hr)) return hr;
+    }
 
-        } else {
-            heap_free(ret);
-            *ppIUriBuilder = NULL;
-            FIXME("(%p %x %x %p): Unknown IUri types not supported yet.\n", pIUri, dwFlags,
-                (DWORD)dwReserved, ppIUriBuilder);
-            return E_NOTIMPL;
-        }
+    switch(ParseAction) {
+    case PARSE_CANONICALIZE:
+        hr = parse_canonicalize(uri, dwFlags, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_FRIENDLY:
+        hr = parse_friendly(pIUri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_ROOTDOCUMENT:
+        hr = parse_rootdocument(uri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_DOCUMENT:
+        hr = parse_document(uri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_PATH_FROM_URL:
+        hr = parse_path_from_url(uri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_URL_FROM_PATH:
+        hr = parse_url_from_path(pIUri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_SCHEMA:
+        hr = parse_schema(pIUri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_SITE:
+        hr = parse_site(pIUri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_DOMAIN:
+        hr = parse_domain(pIUri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_LOCATION:
+    case PARSE_ANCHOR:
+        hr = parse_anchor(pIUri, pwzResult, cchResult, pcchResult);
+        break;
+    case PARSE_SECURITY_URL:
+    case PARSE_MIME:
+    case PARSE_SERVER:
+    case PARSE_SECURITY_DOMAIN:
+        *pcchResult = 0;
+        hr = E_FAIL;
+        break;
+    default:
+        *pcchResult = 0;
+        hr = E_NOTIMPL;
+        FIXME("(%p %d %x %p %d %p %x) Partial stub.\n", pIUri, ParseAction, dwFlags,
+            pwzResult, cchResult, pcchResult, (DWORD)dwReserved);
     }
 
-    *ppIUriBuilder = URIBUILDER(ret);
-    return S_OK;
+    return hr;
 }