                    

#include "stdafx.h"
#include "Utils.h"


// free BSTRS 

void FreeBSTRArray(BSTR* pawWords, int pCount)
{
	if (!pawWords)
		return;

    for(int C= 0; C<pCount; C++ ) {
        SysFreeString(pawWords[C]);
		pawWords[C]=NULL;
    }

}



void FreeBSTRs(BSTR* *pawWords, int *pCount)
{
    for(int C= 0; C<*pCount; C++ )
        SysFreeString((*pawWords)[C]);

    free(*pawWords);
    *pawWords= NULL;
    *pCount=   0;
}



void SplitBSTR(BSTR wLine, BSTR* *pawWords, int *pCount)
{
    if(*pawWords)   FreeBSTRs(pawWords, pCount);   // Note: It's not the most effective way of handling this, but it's not used at the moment.

    int Allocated= 10;
    *pawWords= (BSTR*)malloc(Allocated*sizeof(BSTR));
    *pCount= 0;

    WCHAR* wWorkLine= SysAllocString(wLine);

    WCHAR* pwWordStart= NULL;
    bool bInWord= false;
    for(WCHAR* pwCh= wWorkLine; *pwCh; pwCh++ )
    {
        if(!bInWord)
        {
            if(!iswspace(*pwCh))
            {
                pwWordStart= pwCh;
                bInWord= true;
            }

        }else{

            if(iswspace(*pwCh))
            {
                *pwCh= 0;
                bInWord= false;

                if(*pCount >= Allocated)
                {
                    Allocated= Allocated*130/100 + 8;  // TBD: What's the most optimal way here?
                    *pawWords= (BSTR*)realloc(*pawWords, Allocated*sizeof(**pawWords)); 
                }

                (*pawWords)[(*pCount)++]= SysAllocString(pwWordStart);
                pwWordStart= NULL;   // TBD: geht nicht mit BSTRs. --> Kann man nicht nach char konvertieren, und dort das so machen?, oder braucht man irgendwo BSTRs als Result?
            }
        }
    }

    if(pwWordStart)
    {
        if(*pCount >= Allocated)
            *pawWords= (BSTR*)realloc(*pawWords, (++Allocated)*sizeof(**pawWords));
        (*pawWords)[(*pCount)++]= SysAllocString(pwWordStart);
    }
}





BSTR StrToBSTR(const char* Str, int *pLen, int additionalSpace)
{
    int Len= MultiByteToWideChar(CP_ACP, 0, Str, -1, NULL,  0);
    BSTR wStr= SysAllocStringLen(NULL, Len + additionalSpace);
    MultiByteToWideChar(CP_ACP, 0, Str, -1, wStr, Len);
    if(pLen) *pLen= Len-1;
return wStr;
}


char* BSTRtoStr(BSTR wStr, int *pLen, int additionalSpace)
{
    int Len= WideCharToMultiByte(CP_ACP, 0, wStr, -1, NULL, 0, NULL, NULL);
    char* Str= (char*)malloc(Len + additionalSpace);
    WideCharToMultiByte(CP_ACP, 0, wStr, -1, Str, Len, NULL, NULL);
    if(pLen) *pLen= Len-1;
return Str;
}
