//
// Copyright (C) Dave Roberts G8KBB 2004
//
// This is a simple demonstration of using
// the vnaread() function via vnadll.dll
// to read the VNA.
// It interprets the variable length message returned.

#include "stdio.h"

#include "stdafx.h"
#include "objbase.h"
#include "iostream.h"

#include "vnaio.h"


void print_last_error_message(void);

int main()
{
	int i;
	VNA_RXBUFFER message;
	short BytesReturned;

	if( vnaread(&message, &BytesReturned) == false )
	{
		print_last_error_message();
	}
	else
	{
		printf("Bytes Returned: %d\n", BytesReturned );
		printf("Last Command Received: 0x%02x\n", message.last_command );
		printf("Return Status 0x%02x\n", message.return_status );
		if( message.return_status != 0 )
		{
			printf("    ");
			if( message.return_status & bVnaStatusAdcTimeoutFlag ) printf("ADC Timeout, ");
			if( message.return_status & bVnaStatusNoVnaPowerFlag ) printf("No VNA Power, ");
			if( message.return_status & bVnaStatusAdcDataReadyFlag ) printf("ADC Data Ready, ");
			if( message.return_status & bVnaStatusAdcConvPendFlag ) printf("ADC Conversion pending");
			printf("\n");
		}
		printf("IO Ports: A = 0x%02x, B = 0x%02x\n", message.ioa, message.iob );
		printf("Number of ADC reads done = %d\n", message.ADC_reads_done );
		if( (message.return_status & bVnaStatusAdcDataReadyFlag ) && (message.ADC_reads_done > 0) )
		{
			if( BytesReturned != (5 +(4*message.ADC_reads_done)))
				printf("Error, expected %d bytes of data, got %d bytes\n", 
						(5 +(4*message.ADC_reads_done)), BytesReturned );
			else
			{
				for(i=0;i<message.ADC_reads_done; i++)
					printf("    ADC result %d = 0x%02x 0x%02x 0x%02x 0x%02x\n", i,
						message.data[i*4], message.data[i*4+1], 
						message.data[i*4+2], message.data[i*4+3]);
			}
		}
	}
	return true;
}

void print_last_error_message()
{
	LPVOID lpMsgBuf;
	DWORD LastError;

	LastError = GetLastError();
	printf("IO Error code %ld\n", LastError );
	FormatMessage( 
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
	    NULL,
		LastError,
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL 
	);
	printf("IO Error message: %s\n",lpMsgBuf);
	// Free the buffer.
	LocalFree( lpMsgBuf );
}
