/* テスト */
/*
 * File: utility.cpp
 * Purpose: 
 * - Utility functions for Windows and other ports.
 *
 * Copyright (c) 2009 Paul Blay
 *
 * This work is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, version 2.
 */

#include <string>
#include <vector>

#if defined(WIN32) || defined(_WIN32)

#include <windows.h>
#include <tchar.h>

bool _file_exists(const _TCHAR *fname)
{
	_TCHAR path[MAX_PATH];
	DWORD attrib;

	/* API says we mustn't pass anything larger than MAX_PATH */
	_tcscpy_s(path, _countof(path), fname);

	attrib = GetFileAttributes(path);
	if (attrib == INVALID_FILE_ATTRIBUTES) 
		return FALSE;
	if (attrib & FILE_ATTRIBUTE_DIRECTORY) 
		return FALSE;

	return true;
}

void getprojdir(_TCHAR *projdir)
{
	int i;
	_TCHAR path[1024];
	/* Get program name with full path */
	GetModuleFileName(NULL, path, _countof(path));
	/* Paranoia */
	path[_countof(path) - 1] = '\0';
	/* Get the path */
    for (i = _countof(path); i > 0; i--)
    {
        if (path[i] == '\\')
        {
            /* End of path */
            path[i] = '\0';
            break;
        }
    }
	_tcscpy_s(projdir, 250, path);
}

#endif

/*
 * Conversion code Copyright Codeplug 2009
 */

std::wstring utf8_to_wstr(const std::string &utf8)
{
    // NOTE: we are assuming that the number of bytes in a UTF8 string is 
    //       always >= to the number of wchar_t's required to represent that 
    //       string in UTF16LE - which should hold true
    std::vector<wchar_t> wbuff(utf8.length() + 1);

    // NOTE: this does not NULL terminate the string in wbuff, but this is ok
    //       since it was zero-initialized in the vector constructor
    if (!MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), utf8.length(),
                             &wbuff[0], utf8.length()))
    {
        return L"ErrorW";
    }//if

    return &wbuff[0];
}//utf8_to_wstr

std::string wstr_to_str(const std::wstring &wstr, UINT cp = CP_ACP)
{
    int len = WideCharToMultiByte(cp, 0, wstr.c_str(), wstr.length(), 
                                  0, 0, 0, 0);
    if (!len)
        return "ErrorA";

    std::vector<char> abuff(len + 1);

    // NOTE: this does not NULL terminate the string in abuff, but this is ok
    //       since it was zero-initialized in the vector constructor
    if (!WideCharToMultiByte(cp, 0, wstr.c_str(), wstr.length(), 
                             &abuff[0], len, 0, 0))
    {
        return "ErrorA";
    }//if

    return &abuff[0];
}//wstr_to_str
