#include "stdafx.h"
#include "VariousSmall.h"
#include "atlconv.h"

void Split( CString Source, CString Deliminator, CStringArray& AddIt )
{
	CString		 newCString;
	CString		 tmpCString;
	CString		 AddCString;

	int pos1 = 0;
	int pos = 0;

	newCString = Source;
	do {
		pos1 = 0;
		pos = newCString.Find(Deliminator, pos1);
		if ( pos != -1 ) {
			CString AddCString = newCString.Left(pos);
			if (!AddCString.IsEmpty())
				AddIt.Add(AddCString);

			tmpCString = newCString.Mid(pos + Deliminator.GetLength());
			newCString = tmpCString;
		}
	} while ( pos != -1 );
	
	if (!newCString.IsEmpty())
		AddIt.Add(newCString);
}




int CompareVersion( CString File1, CString File2 )
{
	CStringArray Split1, Split2;
	Split( File1, ",", Split1 );
	Split( File2, ",", Split2 );

	int Value1=0, Value2=0;
	for( int i=0; i <=3; i++)
	{
		Value1 = atoi( Split1.ElementAt(i) );
		Value2 = atoi( Split2.ElementAt(i) );
		if ( Value1 > Value2 )
			return ( 4 - i );
		if ( Value2 > Value1 )
			return ( i - 4 );
	}
	return 0;
}




BOOL DrawBitmap(CDC* pDC, CBitmap* pBmp, int x, int y)
{
	BOOL bReturn = FALSE;
	CDC dcMem;
	if (dcMem.CreateCompatibleDC(pDC))
	{
		BITMAP bmp;
		pBmp->GetObject(sizeof(bmp), &bmp);
		CBitmap* pbmpOld = dcMem.SelectObject(pBmp);
		bReturn = pDC->BitBlt(x, y, bmp.bmWidth, bmp.bmHeight, &dcMem, 0, 0, SRCCOPY);
		dcMem.SelectObject(pbmpOld);
		dcMem.DeleteDC();
	}
	return bReturn;
}



BOOL DrawBitmap(CDC* pDC, CBitmap* pBmp, int x, int y, int w, int h)
{
	BOOL bReturn = FALSE;
	CDC dcMem;
	if (dcMem.CreateCompatibleDC(pDC))
	{
		BITMAP bmp;
		pBmp->GetObject(sizeof(bmp), &bmp);
		CBitmap* pbmpOld = dcMem.SelectObject(pBmp);
		if (w==-1)
			w=bmp.bmWidth;
		if (h==-1)
			h=bmp.bmHeight;
		bReturn = pDC->StretchBlt(x, y, w, h,&dcMem, 0, 0,bmp.bmWidth, bmp.bmHeight, SRCCOPY);
		dcMem.SelectObject(pbmpOld);
		dcMem.DeleteDC();
	}

	return bReturn;
}


BOOL DrawBitmap(CDC* pDC, CBitmap* pBmp, int x, int y, BOOL border)
{
	BOOL bReturn = FALSE;
	CDC dcMem;
	if (dcMem.CreateCompatibleDC(pDC))
	{
		BITMAP bmp;
		pBmp->GetObject(sizeof(bmp), &bmp);
		CBitmap* pbmpOld = dcMem.SelectObject(pBmp);
		bReturn = pDC->BitBlt(x, y, bmp.bmWidth, bmp.bmHeight, &dcMem, 0, 0, SRCCOPY);
		CBrush tempBrush;
		CRect rect2;
		tempBrush.CreateSolidBrush(RGB(0,0,0));
		rect2 = CRect(x-1, y-1, x+bmp.bmWidth+1, y);
		pDC->FillRect(&rect2,&tempBrush);
		rect2 = CRect(x-1, y+bmp.bmHeight, x+bmp.bmWidth+1, y+bmp.bmHeight+1);
		pDC->FillRect(&rect2,&tempBrush);
		rect2 = CRect(x-1, y-1, x, y+bmp.bmHeight+1);
		pDC->FillRect(&rect2,&tempBrush);
		rect2 = CRect(x+bmp.bmWidth, y-1, x+bmp.bmWidth+1, y+bmp.bmHeight+1);
		pDC->FillRect(&rect2,&tempBrush);

		dcMem.SelectObject(pbmpOld);
		dcMem.DeleteDC();
	}
	return bReturn;
}




BOOL ResExtract( UINT ResourceName, LPCSTR ResourceType, LPCSTR pathOutput )
{
	return ResExtract( AfxGetResourceHandle(), MAKEINTRESOURCE(ResourceName), ResourceType, pathOutput );
}




BOOL ResExtract( HMODULE hModule, LPCSTR ResourceName, LPCSTR ResourceType, LPCSTR pathOutput )
{

	if ( GetFileAttributes( pathOutput ) != ( DWORD( -1 ) ) )
	{
		if ( DeleteFile( pathOutput ) == FALSE )
			return FALSE;
	}

	HGLOBAL		hGlobal = NULL;
	HRSRC		hSource = NULL;
	LPVOID		lpVoid  = NULL;
	int			nSize   = 0;
    FILE *fp = NULL;

	hSource = FindResource( hModule, ResourceName, ResourceType );

	if( hSource == NULL )
		return FALSE;

	hGlobal = LoadResource( hModule, hSource );
	if( hGlobal == NULL )
		return FALSE;

	nSize = (UINT)SizeofResource( hModule, hSource );

	lpVoid = LockResource( hGlobal );
	if( lpVoid == NULL )
		return FALSE;


	fp = fopen( pathOutput, "wb" );
	if ( !fp )
		return FALSE;
	else
		fwrite( hGlobal, nSize, 1, fp );
    if ( fclose( fp ) != 0 )
		return FALSE;

	return TRUE;

}





void Delay( DWORD nTimeMs )
{
	MSG msg;
	DWORD endTick;
	BOOL bRet;
	endTick = GetTickCount() + nTimeMs;
	while( GetTickCount() < endTick )
	{
		if( bRet = PeekMessage( &msg, NULL, 0, 0, TRUE ) )
		{ 
			if ( bRet == -1 )
			{
				// handle the error and possibly exit
			}
			else
			{
				TranslateMessage( &msg ); 
				DispatchMessage( &msg ); 
			}
		}
	}
	return;
}




CString GUIDgen()
{
	GUID guid;
	CoCreateGuid(&guid);
	BYTE * str;
	UuidToString((UUID*)&guid, &str);
	CString unique((LPTSTR)str);
	RpcStringFree(&str);
	return unique;
}





CString GetCSIDLPath( long CSIDL_Value )
{
	CString ProgramFilesPath;
	LPITEMIDLIST pidl;
	char TempPath[ MAX_PATH ];
	SHGetFolderLocation( NULL, CSIDL_Value, NULL, 0, &pidl );
	SHGetPathFromIDList( pidl,TempPath );
	return TempPath;
}



LONG GetRegKey(HKEY key, LPCTSTR subkey, LPTSTR retdata)
{
    HKEY hkey;
    LONG retval = RegOpenKeyEx(key, subkey, 0, KEY_QUERY_VALUE, &hkey);

    if (retval == ERROR_SUCCESS) {
        long datasize = MAX_PATH;
        TCHAR data[MAX_PATH];
        RegQueryValue(hkey, NULL, data, &datasize);
        lstrcpy(retdata,data);
        RegCloseKey(hkey);
    }

    return retval;
}





HINSTANCE GotoURL(LPCTSTR url, int showcmd)
{
    TCHAR key[MAX_PATH + MAX_PATH];

    // First try ShellExecute()
    HINSTANCE result = ShellExecute(NULL, _T("open"), url, NULL,NULL, showcmd);

    // If it failed, get the .htm regkey and lookup the program
    if ((UINT)result <= HINSTANCE_ERROR) {

        if (GetRegKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS) {
            lstrcat(key, _T("\\shell\\open\\command"));

            if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) {
                TCHAR *pos;
                pos = _tcsstr(key, _T("\"%1\""));
                if (pos == NULL) {                     // No quotes found
                    pos = _tcsstr(key, _T("%1"));      // Check for %1, without quotes 
                    if (pos == NULL)                   // No parameter at all...
                        pos = key+lstrlen(key)-1;
                    else
                        *pos = '\0';                   // Remove the parameter
                }
                else
                    *pos = '\0';                       // Remove the parameter

                lstrcat(pos, _T(" "));
                lstrcat(pos, url);

                USES_CONVERSION;
                result = (HINSTANCE) WinExec(T2A(key),showcmd);
            }
        }
    }

    return result;
}




BOOL IsDirectory( CString szPath )
{
	DWORD dw;
	dw = GetFileAttributes( szPath );
	return ( dw & FILE_ATTRIBUTE_DIRECTORY );
}


BOOL DeleteDirectory( CString szPath, BOOL DeleteNextRebootIfFails/* = FALSE*/ )
{
	if ( GetFileAttributes( szPath ) == ( DWORD( -1 ) ) )
		return FALSE;
	
	BOOL NeedReboot = FALSE;
	CFileFind ff;
	CString path = szPath;
	if( path.Right( 1 ) != "\\" )
		path += "\\";
	path += "*.*";
	BOOL res = ff.FindFile( path );
	while ( res )
	{
		res = ff.FindNextFile();
		if (! ff.IsDots() )
		{
			if ( ff.IsDirectory() )
			{
				path = ff.GetFilePath();
				if ( NeedReboot )
					DeleteDirectory( path );
				else
					NeedReboot = DeleteDirectory( path );
			}
			else
			{
				SetFileAttributes( ff.GetFilePath(), GetFileAttributes( ff.GetFilePath() ) & ~FILE_ATTRIBUTE_READONLY );
				if ( DeleteFile( ff.GetFilePath() ) == 0 )
					if ( DeleteNextRebootIfFails )
					{
						NeedReboot = TRUE;
						MoveFileEx( ff.GetFilePath(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT );
					}
			}
		}
	}
	ff.Close();
	RemoveDirectory( szPath );
	return ( ! NeedReboot );
}
