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

#include "USB-RFID.h"

int main (int argc, char * argv[])
	{
	// check the DLL version:
	if (USB_RFID_Version() < ((1 << 8) + 22))
		{
		printf ("Wrong DLL Version: expected 1.22, "
			"found %d.%02d\n", USB_RFID_Version() / 0x100,
			USB_RFID_Version() & 0xFF);
		return -1;
		}

	// define the port number:
	const WORD PortNum = 0;

	if (argc != 2)
		{
		// handle a possible command-line error:
		printf ("The COM number must be specified!\n");
		return -2;
		}

	WORD COMNumber;
	if (sscanf (argv[1], "%hu", &COMNumber) != 1)
		{
		// handle a possible command-line error:
		printf ("A valid COM number must be specified!\n");
		return -3;
		}

	// open the port, attach it to COMNumber:
	if (USB_RFID_Open (PortNum, COMNumber))
		{
		// handle a possible error:
		printf ("%s\n", USB_RFID_ErrorMessage (PortNum));
		return 1;
		}

	// setup the device: enable the RFID
	if (USB_RFID_EnableRFID (PortNum, TRUE))
		{
		// handle a possible error:
		printf ("%s\n", USB_RFID_ErrorMessage (PortNum));
		return 2;
		}

	// enable automatic RFID data receiption
	if (USB_RFID_AutoRFID (PortNum))
		{
		// handle a possible error:
		printf ("%s\n", USB_RFID_ErrorMessage (PortNum));
		return 3;
		}

	// main program loop:
	while (true)
		{
		// check for automatic data & obtain the error code:
		const WORD CommandID =
			USB_RFID_RetCheckAutoInput (PortNum);
		const int Result = USB_RFID_State (PortNum);

		if (Result != 0) // handle possible errors
			{
			if (Result == 1)
				printf ("Unexpected command received\n");
			else
				printf ("%s\n", USB_RFID_ErrorMessage (PortNum));
			continue; // do not proceed on errors
			}

		// check if RFID data is ready
		else if (CommandID != 0)
			{
			if (CommandID & USB_RFID_AUTO)
				{
				BYTE Data [8];
				if (USB_RFID_GetLastRFID (PortNum, Data))
					// handle RFID data here
					printf ("%s\n", USB_RFID_ErrorMessage (PortNum));
				else
					{
					const bool valid =
						((unsigned *) Data) [1] != unsigned (-1);
					printf (valid ? "RFID data received: %02X%08Xh\n" :
						"RFID data received: -\n",
						((unsigned *) Data) [1], ((unsigned *) Data) [0]);
					}
				}
			}

		// insert further cases here

		// insert service of other commands here

		}

	//finish the program:
	return 0;
	}
