JNIEXPORT jbyteArray JNICALL Java_com_intel_bluetooth_NativeTestInterfaces_testUUIDConversion
(JNIEnv *env, jclass, jbyteArray uuidValue) {
	GUID g;
	// pin array
	jbyte *bytes = env->GetByteArrayElements(uuidValue, 0);
	// build UUID
	convertUUIDBytesToGUID(bytes, &g);
	// unpin array
	env->ReleaseByteArrayElements(uuidValue, bytes, 0);

	char m[1064];
	unsigned char* d = g.Data4;
	sprintf_s(m, 1064, "{%u , %u, %u, {%u , %u, %u , %u, %u, %u , %u, %u}}", g.Data1, g.Data2, g.Data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]);
	debug(("UUID = %s", m));

	jbyteArray uuidValueConverted = env->NewByteArray(16);
	jbyte *bytesConverted = env->GetByteArrayElements(uuidValueConverted, 0);

	convertGUIDToUUIDBytes(&g, bytesConverted);

	env->ReleaseByteArrayElements(uuidValueConverted, bytesConverted, 0);

	return uuidValueConverted;
}
JNIEXPORT jlong JNICALL Java_com_intel_bluetooth_BluetoothStackWIDCOMM_l2ServerOpenImpl
(JNIEnv *env, jobject, jbyteArray uuidValue, jboolean authenticate, jboolean encrypt, jstring name, jint receiveMTU, jint transmitMTU, jint assignPsm) {
    if (stack == NULL) {
        throwIOException(env, cSTACK_CLOSED);
        return 0;
    }
    EnterCriticalSection(&stack->csCommIf);
    WIDCOMMStackL2CapServer* srv = NULL;
//VC6   __try {
        srv = stack->createL2CapServer();
        if (srv == NULL) {
            throwBluetoothConnectionException(env, BT_CONNECTION_ERROR_NO_RESOURCES, "No free connections Objects in Pool");
            open_l2server_return 0;
        }
        debug(("l2s(%i) L2CapConn server handle created", srv->internalHandle));
        if (srv->hConnectionEvent == NULL) {
            throwRuntimeException(env, "fails to CreateEvent");
            open_l2server_return 0;
        }
        srv->transmitMTU = (UINT16)transmitMTU;
        srv->receiveMTU = (UINT16)receiveMTU;

        jbyte *bytes = env->GetByteArrayElements(uuidValue, 0);
        convertUUIDBytesToGUID(bytes, &(srv->service_guid));
        env->ReleaseByteArrayElements(uuidValue, bytes, 0);

        CL2CapIf *l2CapIf;
        l2CapIf = &srv->l2CapIf;

        if (!l2CapIf->AssignPsmValue(&(srv->service_guid), (UINT16)assignPsm)) {
            throwBluetoothConnectionException(env, BT_CONNECTION_ERROR_UNKNOWN_PSM, "failed to assign PSM");
            open_l2server_return 0;
        }
        l2CapIf->Register();

        const char *cname = env->GetStringUTFChars(name, 0);
        #ifdef _WIN32_WCE
            swprintf_s((wchar_t*)srv->service_name, BT_MAX_SERVICE_NAME_LEN, L"%s", cname);
        #else // _WIN32_WCE
            sprintf_s(srv->service_name, BT_MAX_SERVICE_NAME_LEN, "%s", cname);
        #endif // #else // _WIN32_WCE
        env->ReleaseStringUTFChars(name, cname);

        srv->service_guids_len = 1;
        srv->service_guids = new GUID[srv->service_guids_len];
        if (srv->service_guids == NULL) {
            throwIOException(env, cOUT_OF_MEMORY);
            open_l2server_return 0;
        }
		memcpy(&(srv->service_guids[0]), &(srv->service_guid), sizeof(GUID));

        srv->proto_num_elem = 1;
        srv->proto_elem_list = new tSDP_PROTOCOL_ELEM[srv->proto_num_elem];
		if (srv->proto_elem_list == NULL) {
            throwIOException(env, cOUT_OF_MEMORY);
            open_l2server_return 0;
        }
		srv->proto_elem_list[0].protocol_uuid = 0x0100; // L2CAP
		srv->proto_elem_list[0].num_params = 1;
		srv->proto_elem_list[0].params[0] = l2CapIf->GetPsm();

        UINT8 sec_level = BTM_SEC_NONE;
        if (authenticate) {
            sec_level = BTM_SEC_IN_AUTHENTICATE;
        }
        if (encrypt) {
            sec_level = sec_level | BTM_SEC_IN_ENCRYPT;
        }
        if (!l2CapIf->SetSecurityLevel(srv->service_name, sec_level, TRUE)) {
            throwBluetoothConnectionException(env, BT_CONNECTION_ERROR_SECURITY_BLOCK, "Error setting security level");
            open_l2server_return 0;
        }

        jlong handle = srv->internalHandle;
        srv = NULL;
        open_l2server_return handle;
/*VC6} __finally { } */
}
/* Some code stolen from BlueCove. */
static int findHaggleService(BT_ADDR *pb)
{
	BTHNS_RESTRICTIONBLOB queryservice;
	unsigned char uuid[] = HAGGLE_BLUETOOTH_SDP_UUID;
	BLOB blob;
	WSAQUERYSET queryset;
	SOCKADDR_BTH sa;
	HANDLE hLookupSearchServices;
	int found = 0;

	memset(&queryservice, 0, sizeof(queryservice));

	queryservice.type = SDP_SERVICE_SEARCH_REQUEST;

	convertUUIDBytesToGUID((char *) uuid, &queryservice.uuids[0].u.uuid128);

	//UUID is full 128 bits
	queryservice.uuids[0].uuidType = SDP_ST_UUID128;

	// build BLOB pointing to service query

	blob.cbSize = sizeof(queryservice);
	blob.pBlobData = (BYTE *) & queryservice;

	// build query
	memset(&queryset, 0, sizeof(WSAQUERYSET));

	queryset.dwSize = sizeof(WSAQUERYSET);
	queryset.dwNameSpace = NS_BTH;
	queryset.lpBlob = &blob;


	// Build address
	memset(&sa, 0, sizeof(sa));
	sa.addressFamily = AF_BT;
	sa.btAddr = *pb;
	CSADDR_INFO csai;
	memset(&csai, 0, sizeof(csai));
	csai.RemoteAddr.lpSockaddr = (sockaddr *) &sa;
	csai.RemoteAddr.iSockaddrLength = sizeof(sa);
	queryset.lpcsaBuffer = &csai;

	// begin query

	if (WSALookupServiceBegin(&queryset, 0, &hLookupSearchServices)) {
		int last_error = WSAGetLastError();
		CM_DBG("WSALookupServiceBegin error [%s]", StrError(last_error));
		return -1;
	}
	// fetch results
	int bufSize = 0x2000;
	void *buf = malloc(bufSize);

	if (buf == NULL) {
		WSALookupServiceEnd(hLookupSearchServices);
		return NULL;
	}
	memset(buf, 0, bufSize);

	LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
	pwsaResults->dwSize = sizeof(WSAQUERYSET);
	pwsaResults->dwNameSpace = NS_BTH;
	pwsaResults->lpBlob = NULL;

	DWORD size = bufSize;

	if (WSALookupServiceNext(hLookupSearchServices, LUP_RETURN_TYPE | LUP_RETURN_BLOB | LUP_RETURN_ADDR, &size, pwsaResults)) {
		int last_error = WSAGetLastError();

		switch (last_error) {
		case WSANO_DATA:
			//HAGGLE_DBG("SDP: no data\n");
			found = -1;
			break;
		case WSA_E_NO_MORE:
			//HAGGLE_DBG("End of SDP list\n");
			break;
		case WSAENOTCONN:
			found = -1;
			HAGGLE_DBG("Could not connect to SDP service\n");
			break;
		case WSASERVICE_NOT_FOUND:
			found = 0;
			HAGGLE_DBG("SDP Service not found\n");
			break;
		default:
			CM_DBG("WSALookupServiceNext error [%s]\n", StrError(last_error));
			found = -1;
		}
	} else {
		unsigned long cChannel = 0;
		found = 1;
		HAGGLE_DBG("Found Haggle service\n");
		if (ERROR_SUCCESS == FindRFCOMMChannel(
			pwsaResults->lpBlob->pBlobData,
			pwsaResults->lpBlob->cbSize,
			&cChannel)) {
			HAGGLE_DBG("RFCOMM channel is %d\n", (int)cChannel);
			found = cChannel;
		}
	}
	WSALookupServiceEnd(hLookupSearchServices);
	free(buf);

	return found;
}