//// Defined to disable deprecated functions warning in Visual C++ 2003
//#define _CRT_SECURE_NO_DEPRECATE 1

#include <windows.h>
#include <stdio.h>

#pragma pack(1)       // set byte packing
typedef struct {
	unsigned __int32 bLength;
	char szSerNum[9];
	char szProdName[9];
	unsigned __int64 MinFreq;
	unsigned __int64 MaxFreq;
	struct {
		unsigned __int32 ExtRef:1;
		unsigned __int32 FMWEnabled:1;
		unsigned __int32 Reserved:30;
	} Features;
} RADIO_INFO2;
#pragma pack()       // set back the default packing

typedef int			RADIOHANDLE;

// G39WSB API function type declarations
typedef size_t	(__stdcall *FNCGetRadioList)(RADIO_INFO2 *lpRadioInfo, size_t BufferSize, size_t *Infosize);
typedef int		(__stdcall *FNCOpen)(char *id);
typedef BOOL	(__stdcall *FNCCloseRadioDevice)(RADIOHANDLE hRadio);
typedef BOOL	(__stdcall *FNCGetInfo)(int RADIOHANDLE, RADIO_INFO2 *info);


int main(int argc, char* argv[])
{
	// load the G3 API library
	HMODULE dll=LoadLibrary("wrg39wsbapi.dll");
	if (!dll) 
	{
		puts("WRG39WSBAPI.DLL not found !"); 
		return 0;
	}

	// link G3 API functions
	FNCGetRadioList		GetRadioList		= (FNCGetRadioList)GetProcAddress(dll,"GetRadioList");
	FNCOpen				Open				= (FNCOpen)GetProcAddress(dll,"Open");
	FNCCloseRadioDevice CloseRadioDevice	= (FNCCloseRadioDevice)GetProcAddress(dll,"CloseRadioDevice");
	FNCGetInfo			GetInfo				= (FNCGetInfo)GetProcAddress(dll,"GetInfo");

	// prepare the buffer for 16 RADIO_INFO structures
	RADIO_INFO2 buffer[16];
	size_t		StructSize;

	// get RADIO_INFO structures of all unallocated receivers in the system
	size_t count = GetRadioList(buffer, sizeof(buffer), &StructSize);

	// check whether all structures could be stored in the buffer
	size_t stored = sizeof(buffer)/StructSize;
	if (stored > count) 
		stored = count;

	printf("Found %u receivers, %u are obtained:\n",count,stored);

	if (!stored) 
	{
		FreeLibrary(dll);
		return 0;
	}

	size_t i;
	for (i=0;i<stored;i++) 
	{
		printf("%2u: Device name: %s\n    Serial number: %s\n    Min. freq: %I64u\n    Max freq: %I64u\n\n",i+1,
			buffer[i].szProdName,buffer[i].szSerNum,buffer[i].MinFreq,buffer[i].MaxFreq);
	}

	int hRadio;
	do 
	{
		char id[9];
	
		printf("Enter the serial number to open: ");
		scanf("%8s",id);
		hRadio=Open(id);
		if (!hRadio) 
			puts("Receiver failed to open");
	} while (!hRadio);

	RADIO_INFO2 radio_info;
	radio_info.bLength=sizeof(radio_info);
	GetInfo(hRadio,&radio_info);
	printf("\nOpened:\n    Device name: %s\n    Serial number: %s\n    Min. freq: %I64u\n    Max freq: %I64u\n\n",
		radio_info.szProdName,radio_info.szSerNum,radio_info.MinFreq,radio_info.MaxFreq);

	CloseRadioDevice(hRadio);
	FreeLibrary(dll);

	puts("Press <Enter>");
	getchar();
	getchar();

	return 0;
}
