#include "DrvNT_MD64ioctl.h"
#include <setupapi.h>	
	USHORT	bufOutput[2];
        DWORD   nOutput;
HANDLE OpenDeviceBySN( GUID* pClassGuid, USHORT SerialNumber, PDWORD pError )
{
	HANDLE hDev;
	HDEVINFO hDevinfo;
	SP_DEVICE_INTERFACE_DATA	DeviceInterfaceData;
	DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
	PSP_DEVICE_INTERFACE_DETAIL_DATA	pDetail = NULL;
	DWORD  ReqSize;
	int index= 0;
	do{


	hDevinfo = SetupDiGetClassDevs(	pClassGuid,
									NULL,
									NULL,
									DIGCF_DEVICEINTERFACE |DIGCF_PRESENT );

	if(hDevinfo == INVALID_HANDLE_VALUE)
	{
		*pError = GetLastError();
		return INVALID_HANDLE_VALUE;
	}
	if (!SetupDiEnumDeviceInterfaces(	hDevinfo,
										NULL,
										pClassGuid,
										index,
										&DeviceInterfaceData))
								
	{
		*pError = GetLastError();
		return INVALID_HANDLE_VALUE;
	}


		SetupDiGetDeviceInterfaceDetail(	hDevinfo,
											&DeviceInterfaceData,
											NULL,
											0,
											&ReqSize,
											NULL );

		pDetail = PSP_INTERFACE_DEVICE_DETAIL_DATA(new char[ReqSize]);

		if ( !pDetail )
		{
			*pError = ERROR_NOT_ENOUGH_MEMORY;
			return INVALID_HANDLE_VALUE;
		}
		pDetail->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);

	if (! SetupDiGetDeviceInterfaceDetail(	hDevinfo,
											&DeviceInterfaceData,
											pDetail,
											ReqSize,
											&ReqSize,
											NULL )
											)
	{
		*pError = GetLastError();
		return INVALID_HANDLE_VALUE;
	}


	SetupDiDestroyDeviceInfoList(hDevinfo);


	hDev = CreateFile(
		pDetail->DevicePath,
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);

	if (hDev == INVALID_HANDLE_VALUE)
	{
		*pError = GetLastError();
		return INVALID_HANDLE_VALUE;
	}
			DeviceIoControl(hDev,
						 DRVNT_MD64_IOCTL_GET_SER_NUMBER,
						 NULL,               
						 0,					
						 bufOutput,
						 2,
						 &nOutput,
						 NULL);


			index++;

	}
	while (SerialNumber!=bufOutput[0]);


		*pError = ERROR_SUCCESS;

	return hDev;
}
