// util.cpp

#include "stdafx.h"
#include "Util.h"

// Printf-style TSTRING formatting
TSTRING format(const TCHAR *fmt, ...) {
    if (!fmt) return _T("");
	
	va_list args;
    va_start(args, fmt);
	
    int   result = -1, length = 256;
    TCHAR *buffer = 0;

	while (result == -1) {
        if (buffer) delete [] buffer;
        buffer = new TCHAR [length + 1];
        memset(buffer, 0, length + 1);
        result = _vstprintf_s(buffer, length, fmt, args);
        length *= 2;
    }

    TSTRING s(buffer);
    delete [] buffer;

    va_end(args);
    return s;
}

// Single-byte to TSTRING by system codepage (usually ANSI/1252)
TSTRING TSTRINGify(const char* cstr) {
#ifdef TCHAR_USE_WCHAR_T

	// Get required buffer space, allocate buffer, and convert
	int len = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cstr, -1, NULL, 0);
	wchar_t* buff = new wchar_t[(len+1)];
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cstr, -1, buff, len);
	
	// Tidy up and return
	TSTRING ret = buff;
	delete[] buff;	
	return ret;

#else

	// Not using wchar_t? Then this is simple
	TSTRING ret;
	ret.assign(cstr);
	return ret;

#endif
}
