#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <tchar.h>

#ifdef _DEBUG
#define ASSERT(x)	assert(x)
#else
#define ASSERT(x)
#endif

typedef int		BOOL;
typedef unsigned char	BYTE;
typedef unsigned short	WORD;
typedef unsigned long	DWORD;
#define FALSE 0
#define TRUE 1

#pragma warning(disable:4103)

#include "hei.h"

/* DEFINITIONS from Ethernet Interface Specification 2.0 */

/* Data format definitions */
#define DF_BIT_IN			0x03
#define DF_BIT_OUT			0x04
#define DF_BYTE_IN			0x10
#define DF_BYTE_OUT			0x11
#define DF_WORD_IN			0x05
#define DF_WORD_OUT			0x06
#define DF_DWORD_IN			0x08
#define DF_DWORD_OUT		0x09
#define DF_DOUBLE_IN		0x12
#define DF_DOUBLE_OUT		0x13
#define DF_FLOAT_IN			0x14
#define DF_FLOAT_OUT		0x15

int GetDFSize(int nDF)
{
	const int anSizes[] =
	{
		-1,	// 0x00
		-1,	// 0x01
		-1,	// 0x02
		0,	// DF_BIT_IN		
		0,	// DF_BIT_OUT		
		2,	// DF_WORD_IN		
		2,	// DF_WORD_OUT
		-1, // 0x07
		4,	// DF_DWORD_IN		
		4,	// DF_DWORD_OUT
		-1,	// 0x0A
		-1,	// 0x0B
		-1,	// 0x0C
		-1,	// 0x0D
		-1,	// 0x0E
		-1,	// 0x0F
		1,	// DF_BYTE_IN		
		1,	// DF_BYTE_OUT		
		8,	// DF_DOUBLE_IN	
		8,	// DF_DOUBLE_OUT	
		4,	// DF_FLOAT_IN		
		4,	// DF_FLOAT_OUT	
	};
	if ((nDF < 0) || (nDF > sizeof(anSizes)/sizeof(anSizes[0])))
		return -1;
	return anSizes[nDF];
}

/* Module option types */
#define MT_EBC				0
#define MT_ECOM				1
#define MT_WPLC				2
#define MT_DRIVE			3
#define MT_ERMA				4

/* Parse codes */
#define PC_SLOT_NUMBER		0x00
#define PC_MODULE_DEF		0x01
#define PC_MODULE_STATUS	0x02
#define PC_BIT_IN_DATA		0x03
#define PC_BIT_OUT_DATA		0x04
#define PC_WORD_IN_DATA		0x05
#define PC_WORD_OUT_DATA	0x06
#define PC_BASE_NUMBER		0x07
#define PC_DWORD_IN_DATA	0x08
#define PC_DWORD_OUT_DATA	0x09
#define PC_OFFSET_NUMBER	0x0A
#define PC_DELAY			0x0D
#define PC_EXT_FN_CODE		0x0E
#define PC_END_BLOCK_VER0	0x0F
#define PC_DOUBLE_IN_DATA	0x12
#define PC_DOUBLE_OUT_DATA	0x13
#define PC_FLOAT_IN_DATA	0x14
#define PC_FLOAT_OUT_DATA	0x15
#define PC_DEVICE_SYSTEM	0x16
#define PC_DATA_DESCRIPT	0x17
#define PC_END_BLOCK		0xFF

/* Parse flags */
#define PF_MODULES			0x0001
#define PF_STATUS			0x0002
#define PF_READ				0x0004

/* Module status flags */
#define MSF_ERROR			0x01
#define MSF_WARNING			0x02
#define MSF_INFO			0x04
#define MSF_INTERNAL		0x08
#define MSF_EXTENDED		0x10

/* Other definitions */

#define MAX_MODULES		16
#define MAX_DEVICES		20
#define MAX_ITEMS		20 
#define MAX_OPTDATA		10

#define QT_NORMAL 0
#define QT_ID		1
#define QT_NAME	2

typedef struct _MIOI
{
	BYTE	nDF;
	BYTE	nElem;
	void*	pData;
	short	nBytes;
} MODULE_IO_ITEM;

class CModule
{
public:
	CModule()
	{
		m_nType			= 0xFF;
		m_nID			= 0;
		m_nOptType		= 0xFF;
		m_nOptFamily	= 0xFF;

		m_nIOItems		= 0;
		memset(m_aIOItems, 0x00, sizeof(m_aIOItems));

		m_nOptItems		= 0;
		memset(m_aOptData, 0xFF, sizeof(m_aOptData));
		
		m_nItemSize		= -1;
		m_pItemData		= NULL;

		m_nFlags = 0;
		m_nError = 0;
		m_nWarning = 0;
		m_nInfo = 0;
		m_nInternal = 0;
		m_nExtdType = 0;
		m_nExtdCount = 0;
		memset(m_aExtdError, 0x00, sizeof(m_aExtdError));
	}

	virtual ~CModule()
	{
		FreeItemMemory();
	}

protected:
	// Module identification variables
	BYTE			m_nType;				/* Module type */
	BYTE			m_nID;					/* Module ID */
	BYTE			m_nOptType;				/* Option type (type 7 only) */
	BYTE			m_nOptFamily;			/* Option family (type 7 only) */

	// Module I/O variables
	int				m_nIOItems;				/* Number of I/O Items */
	MODULE_IO_ITEM	m_aIOItems[MAX_ITEMS];	/* Array of I/O Item definitions */

	int				m_nOptItems;			/* Number of items in m_aOptData */
	BYTE			m_aOptData[MAX_OPTDATA];/* Option data (type 7 only) */

	int				m_nItemSize;			/* Number of allocated bytes */
	BYTE*			m_pItemData;			/* Pointer to allocated array of bytes */

	// Module status variables 
	BYTE			m_nFlags;				/* Module status flags */
	BYTE			m_nError;				/* Module error code */
	BYTE			m_nWarning;				/* Module warning code */
	BYTE			m_nInfo;				/* Module info code */
	BYTE			m_nInternal;			/* Module internal code */
	BYTE			m_nExtdType;			/* Extended error data type */
	BYTE			m_nExtdCount;			/* Count of extended bytes */
	BYTE			m_aExtdError[256];		/* Extended error data */


/* Attributes */
public:
	inline int GetIOItemsCount()
	{
		return m_nIOItems;
	}

	inline BYTE GetBit(int i, int j)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		return (((BYTE*) (m_aIOItems[i].pData))[j/8] & (0x01 << (j % 8))) ? 1 : 0;
	}

	inline BYTE GetByte(int i, int j)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		return ((BYTE*) m_aIOItems[i].pData)[j];
	}

	inline WORD GetWord(int i, int j)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		return ((WORD*) m_aIOItems[i].pData)[j];
	}

	inline DWORD GetDWord(int i, int j)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		return ((DWORD*) m_aIOItems[i].pData)[j];
	}

	inline float GetFloat(int i, int j)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		return ((float*) m_aIOItems[i].pData)[j];
	}

	inline double GetDouble(int i, int j)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		return ((double*) m_aIOItems[i].pData)[j];
	}

	inline void SetBit(int i, int j, BYTE bVal)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);

		BYTE byte =	((BYTE*)m_aIOItems[i].pData)[j/8];
		BYTE mask = 0x01 << (j % 8);
		byte = (byte & ~mask) | (bVal ? mask : 0);
		((BYTE*)m_aIOItems[i].pData)[j/8] = byte;
	}

	inline void SetByte(int i, int j, BYTE bVal)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		((BYTE*) m_aIOItems[i].pData)[j] = bVal;
	}

	inline void SetWord(int i, int j, WORD wVal)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		((WORD*) m_aIOItems[i].pData)[j] = wVal;
	}

	inline void SetDWord(int i, int j, DWORD dwVal)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		((DWORD*) m_aIOItems[i].pData)[j] = dwVal;
	}

	inline void SetFloat(int i, int j, float fVal)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		((float*) m_aIOItems[i].pData)[j] = fVal;
	}

	inline double SetDouble(int i, int j, double dVal)
	{
		ASSERT((i >= 0) && (i < m_nIOItems));
		ASSERT((j >= 0) && (j < m_aIOItems[i].nElem));
		ASSERT(m_aIOItems[i].pData != NULL);
		((double*) m_aIOItems[i].pData)[j] = dVal;
	}

	inline BYTE GetType() 
	{ 
		ASSERT(m_nType != 0xFF);
		return m_nType; 
	}
	
	inline void SetTypeAndID(BYTE nType, BYTE nID) 
	{ 
		ASSERT(m_nType == 0xFF);	/* Avoid multiple assignments */
		m_nType = nType; 
		m_nID = nID;
	}

	inline SetOptTypeAndFamily(BYTE nOptType, BYTE nOptFamily)
	{
		ASSERT(m_nOptType == 0xFF);	/* Avoid multiple assignments */
		m_nOptType = nOptType;
		m_nOptFamily = nOptFamily;
	}

	inline const MODULE_IO_ITEM* GetModuleItemPtr(int nItem)
	{
		ASSERT((nItem >= 0) && (nItem < m_nIOItems));
		return &(m_aIOItems[nItem]);
	}

	BOOL AddItem(BYTE nDF, BYTE nElem)
	{
		if (m_nIOItems >= MAX_ITEMS)
			return FALSE;			/* Item space exceeded */
		
		short nBytes = nElem * GetDFSize(nDF);
		ASSERT(nDF >= 0);
		if (nBytes == 0)
			nBytes = (nElem + 7) / 8;

		m_aIOItems[m_nIOItems].nDF = nDF;
		m_aIOItems[m_nIOItems].nElem = nElem;
		m_aIOItems[m_nIOItems++].nBytes = nBytes;
		return TRUE;
	}
	
	BOOL AddOptItem(BYTE nOpt)
	{
		if (m_nOptItems >= MAX_OPTDATA)
			return FALSE;			/* OptItem space exceeded */
		m_aOptData[m_nOptItems++] = nOpt;
		return TRUE;
	}
	
	BOOL AllocateItemMemory()
	{
		ASSERT(m_nItemSize < 0);	/* avoid multiple allocation */
		int i;
		BYTE* pData;
		m_nItemSize = 0;
		// First: count number of bytes to allocate
		for (i = 0; i < m_nIOItems; i++)
			m_nItemSize += m_aIOItems[i].nBytes;

		// Second: Allocate the memory
		if (m_nItemSize > 0)
		{
			m_pItemData = new BYTE[m_nItemSize];
			if (m_pItemData == NULL)
				return FALSE;
			memset(m_pItemData, 0x00, m_nItemSize);
		}

		// Third: set module item pointers
		pData = m_pItemData;
		for (i = 0; i < m_nIOItems; i++)
		{
			m_aIOItems[i].pData = pData;
			pData += m_aIOItems[i].nBytes;
		}

		return TRUE;
	}

	void FreeItemMemory()
	{
		int i;
		if (m_pItemData != NULL)
		{
			delete [] m_pItemData;
			m_pItemData = NULL;
			m_nItemSize = -1;
		}
		for (i = 0; i < m_nIOItems; i++)
			m_aIOItems[i].pData = NULL;
	}

	void ParseModuleDef(BYTE* pModuleDef, int nLen, int nVer)
	{
		int i, n;

		SetTypeAndID(pModuleDef[0], pModuleDef[1]);

		switch (pModuleDef[0])
		{
		case 0:		// No module data
			break;

		case 1:		// Generic I/O
			ASSERT(nLen == 4);
			if (pModuleDef[2] > 0)
				AddItem(DF_BYTE_IN, pModuleDef[2]);
			if (pModuleDef[3] > 0)
				AddItem(DF_BYTE_OUT, pModuleDef[3]);
			if (pModuleDef[4] > 0)
				AddItem(DF_WORD_IN, pModuleDef[4]);
			if (pModuleDef[5] > 0)
				AddItem(DF_WORD_OUT, pModuleDef[5]);
			break;

		case 3:		// HSC Module
			ASSERT(nLen == 4);
			ASSERT(pModuleDef[1] == 0x18); // else undefined ID
			if (pModuleDef[2] > 0)
				AddItem(DF_BYTE_IN, pModuleDef[2]);
			if (pModuleDef[3] > 0)
				AddItem(DF_BYTE_OUT, pModuleDef[3]);
			if (pModuleDef[4] > 0)
				AddItem(DF_DWORD_IN, pModuleDef[4]);
			if (pModuleDef[5] > 0)
				AddItem(DF_DWORD_OUT, pModuleDef[5]);
			break;

		case 4:		// J300 Hitachi Drive controller card
			ASSERT((nVer > 0) && (nLen == 6));
			if (pModuleDef[2] > 0)
				AddItem(DF_BYTE_IN, pModuleDef[2]);
			if (pModuleDef[3] > 0)
				AddItem(DF_BYTE_OUT, pModuleDef[3]);
			if (pModuleDef[4] > 0)
				AddItem(DF_WORD_IN, pModuleDef[4]);
			if (pModuleDef[5] > 0)
				AddItem(DF_WORD_OUT, pModuleDef[5]);
			if (pModuleDef[6] > 0)
				AddItem(DF_DWORD_IN, pModuleDef[6]);
			if (pModuleDef[7] > 0)
				AddItem(DF_DWORD_OUT, pModuleDef[7]);
			break;

		case 5:
			ASSERT((nVer > 0) && (nLen == 12));
			if (pModuleDef[2] > 0)
				AddItem(DF_BYTE_IN, pModuleDef[2]);
			if (pModuleDef[3] > 0)
				AddItem(DF_BYTE_OUT, pModuleDef[3]);
			if (pModuleDef[4] > 0)
				AddItem(DF_WORD_IN, pModuleDef[4]);
			if (pModuleDef[5] > 0)
				AddItem(DF_WORD_OUT, pModuleDef[5]);
			if (pModuleDef[6] > 0)
				AddItem(DF_DWORD_IN, pModuleDef[6]);
			if (pModuleDef[7] > 0)
				AddItem(DF_DWORD_OUT, pModuleDef[7]);
			if (pModuleDef[8] > 0)
				AddItem(DF_BYTE_IN, pModuleDef[8]);
			if (pModuleDef[9] > 0)
				AddItem(DF_BYTE_OUT, pModuleDef[9]);
			if (pModuleDef[10] > 0)
				AddItem(DF_FLOAT_IN, pModuleDef[10]);
			if (pModuleDef[11] > 0)
				AddItem(DF_FLOAT_OUT, pModuleDef[11]);
			if (pModuleDef[12] > 0)
				AddItem(DF_DOUBLE_IN, pModuleDef[12]);
			if (pModuleDef[13] > 0)
				AddItem(DF_DOUBLE_OUT, pModuleDef[13]);
			break;

		case 7:
			ASSERT(nVer > 0);
			n = pModuleDef[2];
			ASSERT(nLen >= 2 + 2*n);

			for (i = 0; i < n; i++)
				AddItem(pModuleDef[3 + 2*i], pModuleDef[4 + 2*i]);

			if (nLen > 2 + 2*n)
			{
				ASSERT(nLen >= 4 + 2*n);
				SetOptTypeAndFamily(pModuleDef[3 + 2*n], pModuleDef[4 + 2*n]);
				for (i = 4 + 2*n; i < nLen; i++)
					AddOptItem(pModuleDef[i]);
			}
			break;

		default:
			ASSERT(FALSE); /* unexpected module type! */ 
		}
	}

	void ParseModuleStatus(BYTE* pModuleStat, int nLen, int nVer)
	{
		ASSERT(nLen >= 5);
		m_nFlags	= pModuleStat[0];
		m_nError	= pModuleStat[1];
		m_nWarning	= pModuleStat[2];
		m_nInfo		= pModuleStat[3];
		m_nInternal	= pModuleStat[4];
		if ((m_nFlags & MSF_EXTENDED) != 0)
		{
			ASSERT(nLen >= 7);
			m_nExtdType	= pModuleStat[5];
			m_nExtdCount= pModuleStat[6];
			ASSERT(nLen == 7 + m_nExtdCount);
			memcpy(m_aExtdError, pModuleStat + 7, nLen - 7);
		}
	}

	void ReadData(BYTE nDF, BYTE* pSrcData, int nLen)
	{
		int i;
		BOOL bFound = FALSE;
		for (i = 0; i < m_nIOItems; i++)
		{
			if (m_aIOItems[i].nDF == nDF)
			{
				bFound = TRUE;
				ASSERT(m_aIOItems[i].pData != NULL);
				memcpy(m_aIOItems[i].pData, pSrcData, nLen);
				break;
			}
		}
		ASSERT(bFound);
	}

	int WriteData(BYTE nDF, BYTE** ppDestData)
	{
		ASSERT(ppDestData != NULL);
		int i, nLen;
		BOOL bFound = FALSE;
		for (i = 0; i < m_nIOItems; i++)
		{
			if (m_aIOItems[i].nDF == nDF)
			{
				bFound = TRUE;
				ASSERT(m_aIOItems[i].pData != NULL);
				nLen = m_aIOItems[i].nBytes;
				
				**ppDestData = nDF;
				(*ppDestData)++;
				/* Solved temporarily !!!*/
				ASSERT(nLen < 255);
				**ppDestData = nLen;
				(*ppDestData)++;

				memcpy(*ppDestData, m_aIOItems[i].pData, nLen);
				*ppDestData += nLen;
				return nLen;
			}
		}
		//ASSERT(bFound);
		return -1;
	}

	void PrintModuleIOs()
	{
		int i, j;
		const TCHAR* sIOTypes[] = 
		{
			NULL,				// 0x00
			NULL,				// 0x01
			NULL,				// 0x02
			_T("Bit Inputs"),	// DF_BIT_IN	
			_T("Bit Outputs"),	// DF_BIT_OUT	
			_T("Word Inputs"),	// DF_WORD_IN	
			_T("Word Outputs"),	// DF_WORD_OUT
			NULL,				// 0x07
			_T("DWord Inputs"),	// DF_DWORD_IN	
			_T("DWord Outputs"),// DF_DWORD_OUT
			NULL,				// 0x0A
			NULL,				// 0x0B
			NULL,				// 0x0C
			NULL,				// 0x0D
			NULL,				// 0x0E
			NULL,				// 0x0F
			_T("Byte Inputs"),	// DF_BYTE_IN	
			_T("Byte Outputs"),	// DF_BYTE_OUT	
			_T("Double Inputs"),// DF_DOUBLE_IN	
			_T("Double Outputs")// DF_DOUBLE_OUT,
			_T("Float Inputs"),	// DF_FLOAT_IN	
			_T("Float Outputs"),// DF_FLOAT_OUT	
		};

		printf("Module type = %d, Module ID = 0x%02X\n", m_nType, m_nID);

		for (i = 0; i < m_nIOItems; i++)
		{
			ASSERT(m_aIOItems[i].nDF < sizeof(sIOTypes) / sizeof(sIOTypes[0]));
			ASSERT(sIOTypes[m_aIOItems[i].nDF] != NULL);
			printf("%-15s= ", sIOTypes[m_aIOItems[i].nDF]);
			for (j = 0; j < m_aIOItems[i].nElem; j++)
			{
				switch (m_aIOItems[i].nDF)
				{
				case DF_BIT_IN:
				case DF_BIT_OUT:
					printf("%d ", GetBit(i, j));
					break;
				case DF_BYTE_IN:
				case DF_BYTE_OUT:
					printf("0x%02X ", GetByte(i, j));
					break;
				case DF_WORD_IN:
				case DF_WORD_OUT:
					printf("0x%04X ", GetWord(i, j));
					break;
				case DF_DWORD_IN:
				case DF_DWORD_OUT:
					printf("0x%08X ", GetDWord(i, j));
					break;
				case DF_DOUBLE_IN:
				case DF_DOUBLE_OUT:
					printf("%f ", GetDouble(i, j));
					break;
				case DF_FLOAT_IN:
				case DF_FLOAT_OUT:
					printf("%f ", GetFloat(i, j));
					break;
				default:
					ASSERT(FALSE);	// Unexpected type
				}
			}
			printf("\n");
		}
	}

	void PrintModuleStatus()
	{
		int i;
		printf("Status:");
		if (m_nFlags == 0)
			printf(" O.K.\n");
		else
		{
			printf("\n");
			if (m_nFlags & MSF_ERROR)
				printf("Error:    %i\n", m_nError);

			if (m_nFlags & MSF_WARNING)
				printf("Warning:  %i\n", m_nWarning);

			if (m_nFlags & MSF_INFO)
				printf("Info:     %i\n", m_nInfo);
			
			if (m_nFlags & MSF_INTERNAL)
				printf("Error:    %i\n", m_nInternal);
			
			if (m_nFlags & MSF_EXTENDED)
			{
				printf("Extended: type=%i\n", m_nExtdType);
				for (i = 0; i < m_nExtdCount; i++)
					printf(" %3i", m_aExtdError[i]);
				printf("\n");
			}
		}
	}

};

/*
CModule::CModule()
{
	Type			= 0;
	ID				= 0;

	XCount		= 0;
	YCount		= 0;
	WXCount		= 0;
	WYCount		= 0;
	DWXCount		= 0;
	DWYCount		= 0;

	memset(X, 0, sizeof(X));
	memset(Y, 0, sizeof(Y));
	memset(WX, 0, sizeof(WX));
	memset(WY, 0, sizeof(WY));
	memset(DWX, 0, sizeof(DWX));
	memset(DWY, 0, sizeof(DWY));
}

void CModule::Init(BYTE iType, BYTE iID, BYTE iX, BYTE iY, BYTE iWX, BYTE iWY,
				   BYTE iDWX, BYTE iDWY)
{
	Type			= iType;
	ID				= iID;
	XCount			= iX;
	YCount			= iY;
	WXCount			= iWX;
	WYCount			= iWY;
	DWXCount		= iDWX;
	DWYCount		= iDWY;
}
*/

/* Global variables */
CModule g_aModules[MAX_MODULES];



/* Parsing functions */

void ParsePacket(BYTE *pBaseDef, WORD wFlags)
{
	ASSERT((wFlags & ~(PF_MODULES | PF_STATUS | PF_READ)) == 0);

	BOOL Done = FALSE;
	int Slot = -1;
	int Base = 0;
	/*PB*/
	int nVer = 0;	// Ethernet Interface Specification 1.0
	int nCode = 0; 
	int nLen = 0;
	int nOffset = 0;

	CModule* pModule = NULL;

	// Check version
	if ((pBaseDef[0] & 0xF0) == 0xB0)
	{
		nVer = (pBaseDef[0] & 0x0F);
		ASSERT(nVer == 1);	/* Only Revision 1 supported */
		nLen = 2;
	}

	// Determine slot contents
	for(int idx = nLen; !Done; )
	{
		// Get code and type specific data length
//		printf ("idx = %i\n", idx);
		switch (nVer)
		{
		case 0:
			nCode = (pBaseDef[idx] & 0xF0) >> 4;
			nLen = (pBaseDef[idx++] & 0x0F);
			break;

		case 1:
			nCode = pBaseDef[idx++];
			if (nCode != 0xFF)
			{
				nLen = pBaseDef[idx++];
				if (nLen == 255)
				{
					nLen = pBaseDef[idx] + 256*pBaseDef[idx+1];
					idx+=2;
				}
			}
			break;

		default:
			ASSERT(FALSE);
		}

		// Parse data
		switch(nCode)
		{
		case PC_SLOT_NUMBER:
			Slot = nLen;
			ASSERT(Slot < MAX_MODULES);
			pModule = &(g_aModules[Slot]);
			break;

		
		case PC_MODULE_DEF:
			ASSERT(pModule != NULL);
			if (wFlags & PF_MODULES)
				pModule->ParseModuleDef(&pBaseDef[idx], nLen, nVer); 
			idx += 2 + nLen;
			break;

		case PC_MODULE_STATUS:	// Skip
			if (wFlags & PF_STATUS)
				pModule->ParseModuleStatus(&pBaseDef[idx], nLen, nVer);
			idx += nLen;
			break;

		
		case PC_BIT_IN_DATA:	// Skip
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_BIT_IN, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_BIT_OUT_DATA:	// Skip
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_BIT_OUT, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_WORD_IN_DATA:	// Skip
			if (nVer == 0)
				nLen *= 2;
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_WORD_IN, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_WORD_OUT_DATA:	// Skip
			if (nVer == 0)
				nLen *= 2;
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_WORD_OUT, &pBaseDef[idx], nLen);
			idx += nLen;
			break;
		
		case PC_BASE_NUMBER:	// Skip
			Base = nLen;
			break;

		
		case PC_DWORD_IN_DATA:	// Skip
			if (nVer == 0)
				nLen *= 4;
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_DWORD_IN, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_DWORD_OUT_DATA:	// Skip
			if (nVer == 0)
				nLen *= 4;
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_DWORD_OUT, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		
		case PC_OFFSET_NUMBER:	// Unexpected, but parse anyway
			nOffset = pBaseDef[idx] + 256*pBaseDef[idx+1];
			idx += nLen;
			break;

		case PC_DELAY:			// Skip
			idx += nLen;
			break;

		// Unexpected, but parse anyway
		case PC_EXT_FN_CODE:	// Skip
			ASSERT(nVer == 0);
			idx += 2 + pBaseDef[idx+1];
			break;

		case PC_END_BLOCK_VER0:
			ASSERT(nVer == 0);
			Done = TRUE;
			break;
		
		case PC_DOUBLE_IN_DATA:
			ASSERT(nVer > 0);
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_DOUBLE_IN, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_DOUBLE_OUT_DATA:
			ASSERT(nVer > 0);
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_DOUBLE_OUT, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_FLOAT_IN_DATA:
			ASSERT(nVer > 0);
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_FLOAT_IN, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_FLOAT_OUT_DATA:
			ASSERT(nVer > 0);
			if ((wFlags & PF_READ) && (Slot != -1))
				pModule->ReadData(DF_FLOAT_OUT, &pBaseDef[idx], nLen);
			idx += nLen;
			break;

		case PC_DEVICE_SYSTEM:	// Skip
			ASSERT(nVer > 0);
			idx += nLen;
			break;

		case PC_DATA_DESCRIPT:	// Skip
			ASSERT(nVer > 0);
			idx += nLen;
			break;

		case PC_END_BLOCK:
			ASSERT(nVer > 0);
			Done = TRUE;
			break;

		default:
			ASSERT(FALSE);	// Unexpected unknown code
		}
	}
}

BOOL AllocateMemory()
{
	BOOL bOK = TRUE;
	int i;
	for (i = 0; i < MAX_MODULES; i++)
	{
		if (g_aModules[i].GetIOItemsCount() > 0)
			bOK &= g_aModules[i].AllocateItemMemory();
	}
	return bOK;
}

void PrepareDump(BYTE* pData, int nMaxSize)
{
	memset(pData, 0xFF, nMaxSize);
}

void Dump(BYTE* pData, int nMaxSize)
{
	int i, n;
	
	// Find last packet byte
	for (i = 4095; (pData[i] == 0xff) && (i > 0) ; i--)
		n = i;

	printf("Data DUMP:");
	for (i = 0; i <= n; i++)
	{
		if ((i % 16) == 0)
			printf("\n");
		printf("%02x ", pData[i]);
	}
	printf("\n");
}

void PrintBaseState()
{
	for(int Slot = 0; Slot < 16; Slot++)
	{
		CModule* pModule = &g_aModules[Slot];
		if (pModule->GetIOItemsCount() > 0)
		{
			printf("\nSlot = %d\n", Slot);
			pModule->PrintModuleStatus();
			pModule->PrintModuleIOs();
		}
	}
}

int WriteVersion(int nVer, BYTE** ppDestData)
{
	ASSERT((nVer >= 0) && (nVer <= 1)); /* Only Revisions 0 and 1 supported */

	if (nVer > 0)
	{
		**ppDestData = 0xB0 | ((BYTE) nVer);
		(*ppDestData)++;
		**ppDestData =  0x00;
		(*ppDestData)++;
		return 2;
	}
	return 0;
}

int WriteSlot(int nVer, int nSlot, BYTE** ppDestData)
{
	ASSERT((nVer >= 0) && (nVer <= 1)); /* Only Revisions 0 and 1 supported */
	ASSERT(nSlot > 0);
	int nLen = 1;
	switch (nVer)
	{
	case 0:
		ASSERT(nSlot <= 0x0F);
		**ppDestData = (BYTE) nSlot;
		(*ppDestData)++;
		break;

	case 1:
		ASSERT(nSlot < 0x7FFF);
		**ppDestData = PC_SLOT_NUMBER;
		(*ppDestData)++;
		if (nSlot > 255)
		{
			**ppDestData = 255;
			(*ppDestData)++;
			**ppDestData = (nSlot & 0x00FF);
			(*ppDestData)++;
			**ppDestData = (nSlot & 0xFF00) >> 8;
			(*ppDestData)++;
			nLen = 4;
		}
		else
		{
			**ppDestData = (BYTE) nSlot;
			(*ppDestData)++;
			nLen = 2;
		}	
		break;

	default:
		ASSERT(FALSE);
	}
	return nLen;
}

int WriteEnd(BYTE** ppDestData)
{
	ASSERT(ppDestData != NULL);
	**ppDestData = 0xFF;
	(*ppDestData)++;
	return 1;
}
void main(int argc, char *argv[])
	{
	WORD Protocol = HEIP_IPX;
	DWORD ID = 0;
	char Name[256] = "";
	int QueryType = QT_ID;

	printf("EtherIO - Copyright(C) 1997, Host Engineering, Inc.\n");
	printf("Executes IO transaction on specified Hx-EBC device\n\n");

	/*
	** Parse command line
	*/
	for(int Parm = 1; Parm < argc; Parm++)
		{
		if(argv[Parm][0] == '/' || argv[Parm][0] == '-')
			{
			switch(argv[Parm][1])
				{
				case 'P':
				case 'p':
					switch(argv[Parm][2])
						{
						case 'I':
						case 'i':
							Protocol = HEIP_IP;
							break;

						case 'X':
						case 'x':
							Protocol = HEIP_IPX;
							break;

						default:
							printf("%s - Unknown parameter\n", argv[Parm]);
							break;
						}
					break;

				case 'N':
				case 'n':
					QueryType = QT_NAME;
					memset(Name, 0, 256);
					strcpy(Name, argv[Parm]+2);
					break;

				case 'I':
				case 'i':
					QueryType = QT_ID;
					ID = atoi(argv[Parm]+2);
					break;

				case 'h':
				case 'H':
				case '?':
					printf("Usage - EtherIO [Options]\n");
					printf("Options:\n");
					printf("  /Pn  Set protocol\n");
					printf("       n = I for IP\n");
					printf("           X for IPX\n");
					printf("  /Nv  Connect to device named v\n");
					printf("  /Iv  Connect to device number v\n");
					printf("  /?   This screen\n");
					return;

				default:
					printf("%s - Unknown parameter\n", argv[Parm]);
					break;
				}
			}
		}

	/*
	** Initialize required data structures
	*/
	HEITransport TP;
	memset(&TP, 0, sizeof(TP));

	HEIDevice aDevices[MAX_DEVICES];
	memset(aDevices, 0, sizeof(aDevices));

	WORD DeviceCount;
	
	/*
	** Step 1, initialize the driver
	** Called once by app at startup
	*/
	HEIOpen(HEIAPIVERSION);

	/*
	** Step 2, initialize the transport
	*/
	TP.Transport = HEIT_WINSOCK; // Under Win32 this is the only valid transport
	TP.Protocol = Protocol;
	int rc;
	if(!(rc = HEIOpenTransport(&TP, HEIAPIVERSION, 0)))
	{
		if( Protocol== HEIP_IP )
			printf( "Winsock Open, using UDP/IP\n" );
		else
			printf( "Winsock Open, using IPX\n" );

		/*
		** Step 3, resolve the logical address to a device
		** This uses a data query to find all matching devices. There may
		** be more than 1 match.
		*/
		DeviceCount = MAX_DEVICES;

		switch(QueryType)
		{
		case QT_ID:
			if( (rc= HEIQueryDeviceData( &TP, aDevices, &DeviceCount, HEIAPIVERSION, DT_NODE_NUMBER, (BYTE *)&ID, 4 ) )!= 0 )
			{
				printf("Error %04X trying to query for node number\n", rc);
			}
			break;

		case QT_NAME:
			if( (rc= HEIQueryDeviceData( &TP, aDevices, &DeviceCount, HEIAPIVERSION, DT_NODE_NAME, (BYTE *)Name, 256 ) )!= 0 )
			{
				printf("Error %04X trying to query for node name\n", rc);
			}
			break;
		}

		// DeviceCount now contains number of devices found
		if(DeviceCount)
		{
			/*
			** Step 4, open the device. We'll use only the first device and
			** ignore the others.
			*/
			if( !( rc= HEIOpenDevice( &TP, &aDevices[0], HEIAPIVERSION, 25, 3, FALSE ) ) )
			{
				/*
				** Step 5, confirm that it is an Hx-EBC. A more correct way to do this
				** would be to read the module caps (HEIReadSupportInfo) and test 
				** for the functions we wish to use; I'm lazy.
				*/
				DeviceDef DD;
				memset(&DD, 0, sizeof(DD));
				if((rc = HEIReadDeviceDef(&aDevices[0], (BYTE *)&DD, sizeof(DD))) == 0)
				{
					if(DD.ModuleType != 0)
					{
						if(QueryType == QT_ID)
							printf("Module number %u is not an Hx-EBC. Cannot continue...\n", ID);
						else
							printf("Module %s is not an Hx-EBC. Cannot continue...\n", Name);
					}
					else
					{
						// 4K is plenty enough
						BYTE Data[4096]; /*PB: it was 2000*/
						WORD SizeofData = sizeof(Data);

						/*
						** Step 6, optional. Sometime during configuration you can use this 
						** operation to automatically determine whats in the base. This is not a
						** requirement, but it adds a nice capability that many I/O systems
						** don't have.
						*/
						PrepareDump(Data, sizeof(Data));
						rc = HEIReadBaseDef(&aDevices[0], Data, &SizeofData);

						if (rc == 0)
						{
//							Dump(Data, sizeof(Data));

							// Parse the base def response
							ParsePacket(Data, PF_MODULES);
							AllocateMemory();

//							PrepareDump(Data, sizeof(Data));
							rc = HEIReadModuleStatus(&aDevices[0], Data, &SizeofData, FALSE);
//							Dump(Data, sizeof(Data));
							ParsePacket(Data, PF_STATUS);

							/*
							** Step 7, do the IO transactions. You'll do this one about
							** 10^zillionth times. You can use HEIReadIO and HEIWriteIO separately
							** if your system dictates that. You can also use HEIWriteIO alone; it
							** returns the input state (HEIReadIO) in the response packet.
							*/
//							PrepareDump(Data, sizeof(Data));
							SizeofData = sizeof(Data);
							int Error = HEIReadIO(&aDevices[0], Data, &SizeofData);
							if(SizeofData > 0)
							{
//								Dump(Data, sizeof(Data));
								// Parse the read IO response
								ParsePacket(Data, PF_READ);

								// Print the base state
								PrintBaseState();

								
								/* test output values */
								g_aModules[3].SetBit(0,3,1);
								g_aModules[3].SetBit(0,3,1);
								g_aModules[3].SetBit(0,3,1);


								BYTE* pAct = Data;
								WriteVersion(1, &pAct);
								WriteSlot(1, 2, &pAct);
								g_aModules[2].WriteData(DF_BIT_OUT, &pAct);
								WriteEnd(&pAct);
								WORD wReturnData = 0;
								BYTE ReturnData[4096];
								Error = HEIWriteIO(&aDevices[0], Data, pAct-Data, ReturnData, &wReturnData);
							}
							else
							{
								printf("Error 0x%X! Unable to read IO.\n", Error);
							}
						}
						else
						{
							printf("Error 0x%X! Unable to read base def.\n", rc);
						}
					}
				}
				else
				{
					// bad read
					printf("Error %04X trying to read the Device Definition\n", rc);
				}
				
				/*
				** Step 8, close the device
				*/
				HEICloseDevice(&aDevices[0]);
			}
			else
			{
				printf("Error %04X trying to open device %02X %02X %02X %02X %02X %02X\n", 
					rc,
					aDevices[0].ENetAddress[0], 
					aDevices[0].ENetAddress[1], 
					aDevices[0].ENetAddress[2], 
					aDevices[0].ENetAddress[3], 
					aDevices[0].ENetAddress[4], 
					aDevices[0].ENetAddress[5]);
			}
		}
		else
		{
			printf("Sorry! No ethernet devices found\n");
		}

		/*
		** Step 9, terminate the transport
		*/
		HEICloseTransport(&TP);
	}
	else
	{
		printf("Error %04X trying to initialize Winsock Transport\n", rc );
	}

	/*
	** Step 10, terminate the driver
	** Called once by app at shutdown
	*/
	HEIClose();
}


/*	This is binary DUMP of my configuration
b1 00 00 01 01 0f 07 25 01 08 08 00 0a 25 32 00
00 00 00 00 00 00 00 00 02 01 0d 07 10 00 00 0a
10 13 00 00 00 00 00 00 00 00 00 03 01 0f 07 11
01 03 08 00 0a 11 02 00 00 00 00 00 00 00 00 ff

 0: b1 00														Revision 1
 2: 00 01														Slot 1
 4: 01 0f 07 25 01 08 08 00 0a 25 32 00 00 00 00 00 00 00 00	Module #0x25 T1F-08AD-1
23: 00 02														Slot 2
25: 01 0d 07 10 00 00 0a 10 13 00 00 00 00 00 00 00 00			Module #0x10 T1K-16TD2
42: 00 03														Slot 3
44: 01 0f 07 11 01 03 08 00 0a 11 02 00 00 00 00 00 00 00 00	Module #0x11 T1K-08ND3
63: ff															END
  
*/