/*
 * Unicode string manipulation functions
 *
 * Copyright 2000 Alexandre Julliard
 * Copyright 2005 TransGaming Technologies, Inc
 */

#include <stdlib.h>
#include "wine/unicode.h"

int strcmpiW( const WCHAR *str1, const WCHAR *str2 )
{
    for (;;)
    {
        int ret = toupperW(*str1) - toupperW(*str2);
        if (ret || !*str1) return ret;
        str1++;
        str2++;
    }
}

int strncmpiW( const WCHAR *str1, const WCHAR *str2, int n )
{
    int ret = 0;
    for ( ; n > 0; n--, str1++, str2++)
        if ((ret = toupperW(*str1) - toupperW(*str2)) || !*str1) break;
    return ret;
}

WCHAR *strstrW( const WCHAR *str, const WCHAR *sub )
{
    while (*str)
    {
        const WCHAR *p1 = str, *p2 = sub;
        while (*p1 && *p2 && *p1 == *p2) { p1++; p2++; }
        if (!*p2) return (WCHAR *)str;
        str++;
    }
    return NULL;
}


/* crappy implementations for strtolW and strtoulW
 * these need to be redone properly to parse the UNICODE directly,
 * instead of converting to UTF8 first, as this will only support
 * ASCII numbers */
long int strtolW( const WCHAR *str, WCHAR **end, int base ) 
{
    long int ret;
    int srclen = strlenW(str);
    int dstlen;
    char *str_utf8 = NULL;
    char *end_utf8;

    /* query size of utf8 string */
    dstlen = utf8_wcstombs(str, srclen, NULL, 0) + 1;

    /* make utf8 string, and ensure its null terminated */
    str_utf8 = (char *)malloc(dstlen*sizeof(char));
    utf8_wcstombs(str, srclen, str_utf8, dstlen);
    str_utf8[dstlen-1] = '\0';

    /* convert, and figure out the end */
    ret = strtol(str_utf8, &end_utf8, base);
    if( end ) {
      int len;
      /* figure out how much of the WCHAR string we used */
      len = utf8_mbstowcs(0, str_utf8, end_utf8 - str_utf8, NULL, 0);
      *end = (WCHAR *)str + len;
    }

    free(str_utf8);
    return ret;
}

unsigned long int strtoulW( const WCHAR *str, WCHAR **end, int base )
{
    unsigned long int ret;
    int srclen = strlenW(str);
    int dstlen;
    char *str_utf8 = NULL;
    char *end_utf8;

    /* query size of utf8 string */
    dstlen = utf8_wcstombs(str, srclen, NULL, 0) + 1;

    /* make utf8 string, and ensure its null terminated */
    str_utf8 = (char *)malloc(dstlen*sizeof(char));
    utf8_wcstombs(str, srclen, str_utf8, dstlen);
    str_utf8[dstlen-1] = '\0';

    /* convert, and figure out the end */
    ret = strtoul(str_utf8, &end_utf8, base);
    if( end ) {
      int len;
      /* figure out how much of the WCHAR string we used */
      len = utf8_mbstowcs(0, str_utf8, end_utf8 - str_utf8, NULL, 0);
      *end = (WCHAR *)str + len;
    }

    free(str_utf8);
    return ret;
}

