#include <cdevPacket.h>

cdevPacket::ImportTable * cdevPacket::importTables = NULL;
int                       cdevPacket::maxTables    = 0;


// *****************************************************************************
// * cdevPacket::import :
// *	The import mechanism will walk through the importTables and attempt to
// *	locate an entry that has the same packet version as the cdevPacketBinary
// *	parameter.  If a matching netry is found, then it will be used to decode
// *	the binary and create a cdevPacket object from it, otherwise NULL will
// *	be returned.
// *
// *	Note:  Subclasses of the cdevPacket class that wish to employ this
// *	functionality must register their import methods and their packet 
// *	versions using the registerImportMethod mechanism.
// *****************************************************************************
cdevPacket * cdevPacket::import ( cdevPacketBinary & packet )
	{
	short        packetVersion = 0;
	int          idx           = 0;
	int          found         = 0;
	cdevPacket * result        = NULL;
	
	packet.getVersion(packetVersion);

	while(idx<maxTables && 
	      importTables[idx].packetVersion!=0 && 
	      !found)
		{
		if(packetVersion == importTables[idx].packetVersion)
			{
			result = (*importTables[idx].importMethod)(packet);
			found  = 1; 
			}
		else idx++;
		}
	return result;
	}
	
// *****************************************************************************
// * cdevPacket::registerImportMethod :
// *	This mechanism allows the user to associate an import method with a 
// *	particular packet version.  The ImportMethod must take a reference to 
// *	a cdevPacketBinary as an argument and produce a pointer to a new 
// *	cdevPacket object.
// *****************************************************************************
void cdevPacket::registerImportMethod(short version, ImportMethod method)
	{
	int idx = 0;
	for(idx = 0; 
	    idx<maxTables && 
	    importTables[idx].packetVersion != 0 && 
	    importTables[idx].packetVersion != version; 
	    idx++);

	if(idx==maxTables)
		{
		if(maxTables==0)
			{
			importTables = (ImportTable *)malloc(sizeof(ImportTable));
			memset(importTables, 0, sizeof(ImportTable));
			maxTables    = 1;
			}
		else	{
			importTables = (ImportTable *)realloc(importTables, maxTables*2*sizeof(ImportTable));
			memset(&importTables[maxTables], 0, maxTables*sizeof(ImportTable));
			maxTables *= 2;
			}
		
		}
	importTables[idx].packetVersion = version;
	importTables[idx].importMethod  = method;
	}

