// Common, group WinWrap
// see CW Mutex
// Copyright Alexander Liss

#include "mutex.h"


// creates or opens a mutex
Mutex::Mutex( BOOL bInitialOwner, LPCTSTR lpName, LPSECURITY_ATTRIBUTES lpSA): 
attributes(1)
{
    handle = ::CreateMutex( lpSA, bInitialOwner, lpName);

    if (is_valid_handle(handle)) 
	{
        if (lpName)
		{
            DWORD g = GetLastError();

			if(g == ERROR_ALREADY_EXISTS)
				attributes &=~(DWORD)1; 

		}
        
        status = NO_ERROR;
    }
    else 
        status = GetLastError();
}

// opens an existing named mutex
Mutex::Mutex( LPCTSTR lpName, BOOL bInheritHandle, DWORD dwDesiredAccess):
attributes(0) 
{
    handle = ::OpenMutex( dwDesiredAccess, bInheritHandle, lpName);

    if (is_valid_handle(handle)) 
        status = NO_ERROR;
    else 
        status = GetLastError();
}


BOOL Mutex::release() 
{
	if(!is_valid_handle(handle)) return FALSE;

    return ::ReleaseMutex(handle);
}