#include <stdio.h>
// Link to ws2_32.lib
#include <winsock2.h>
#include <ws2bth.h>
#include <BluetoothAPIs.h>

//------------------------------------------------------------------------
// Function: BT_SetService
// Purpose: Registers a new SDP record
//------------------------------------------------------------------------
#define SDP_RECORD_SIZE   0x0000004f
#define SDP_CHANNEL_OFFSET 32

struct
{
	BTHNS_SETBLOB   b;
	unsigned char   uca[SDP_RECORD_SIZE];
} bigBlob;

BOOL BT_SetService()
{
   ULONG recordHandle = 0;
   ULONG ulSdpVersion = BTH_SDP_VERSION;
   BLOB blob;
   WSAQUERYSET Service;

   // Bluetooth device profile record sample
   BYTE rgbSdpRecord[] = {
         0x35, 0x4d, 0x09, 0x00, 0x01, 0x35, 0x11, 0x1c,
         0x29, 0xf9, 0xc0, 0xfd, 0xbb, 0x6e, 0x47, 0x97,
         0x9f, 0xa9, 0x3e, 0xc9, 0xa8, 0x54, 0x29, 0x0c,
         0x09, 0x00, 0x04, 0x35, 0x0c, 0x35, 0x03, 0x19,
         0x01, 0x00, 0x35, 0x05, 0x19, 0x00, 0x03, 0x08,
         0x1a, 0x09, 0x00, 0x06, 0x35, 0x09, 0x09, 0x65,
         0x6e, 0x09, 0x00, 0x6a, 0x09, 0x01, 0x00, 0x09,
         0x00, 0x09, 0x35, 0x08, 0x35, 0x06, 0x19, 0x11,
         0x05, 0x09, 0x01, 0x00, 0x09, 0x01, 0x00, 0x25,
         0x06, 0x53, 0x65, 0x72, 0x69, 0x61, 0x6c
   };


   bigBlob.b.pRecordHandle   = (HANDLE *)&recordHandle;
   bigBlob.b.pSdpVersion     = &ulSdpVersion;
   // bigBlob.b.fSecurity       = 0;
   // bigBlob.b.fOptions        = 0;
   bigBlob.b.ulRecordLength  = SDP_RECORD_SIZE;
   memcpy (bigBlob.b.pRecord, rgbSdpRecord, SDP_RECORD_SIZE);
   
   blob.cbSize    = sizeof(BTHNS_SETBLOB) + SDP_RECORD_SIZE - 1;
   blob.pBlobData = (PBYTE) &bigBlob;

   memset (&Service, 0, sizeof(Service));
   Service.dwSize = sizeof(Service);
   Service.lpBlob = &blob;
   Service.dwNameSpace = NS_BTH;

   if (WSASetService(&Service,RNRSERVICE_REGISTER,0) == SOCKET_ERROR)
   {
	   printf("WSASetService() failed with error code %d\n", WSAGetLastError ());
      return FALSE;
   }
   else
   {
	   printf("WSASetService() is working!\n");
	   return TRUE;
   }
}

int main(int argc, char **argv)
{
	WSADATA wsd;
	BOOL RetVal;

		if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
	{
		printf("Unable to load Winsock! Error code is %d\n", WSAGetLastError());
		return 1;
	}
	else
		printf("WSAStartup() is OK, Winsock lib loaded!\n");


	RetVal = BT_SetService();

	printf("The return value is: %d\n", RetVal);
	
	if(WSACleanup() == 0)
		printf("WSACleanup() is OK!\n");
	else
		printf("WSACleanup() failed miserabily with error code %d\n", WSAGetLastError());
	return 0;
}
