#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tblmgr.h"

TableTag Tb[T_MAXELEMENTS];
static int nElements = 0;  
static unsigned short InitDone = 0;
void DoTblInit();


int IsTblElement(unsigned short port)
{
	int i,nfound;

	if(!InitDone)
	{
		DoTblInit();
		InitDone = 1;
	}

	// the table may contain holes: must proceed to check up to 
	// the . number of elements registered
    for(i=0, nfound = 0; i<T_MAXELEMENTS  && nfound < nElements; i++)
    {
        if(Tb[i].status == ENTRY_USED)
        {
            if(Tb[i].port == port)
                return i;
            nfound++;
        }
    }
    return -1;
}


int RegisterTblElement(unsigned short port)
{
    int i;

	if(!InitDone)
	{
		DoTblInit();
		InitDone = 1;
	}

    if(nElements==T_MAXELEMENTS)
        return -2;      // no room, sorry

    // find next available place
    for(i = 0; i<T_MAXELEMENTS; i++)
        if(Tb[i].status == ENTRY_UNUSED)
            break;  // found

    if(i==T_MAXELEMENTS)
        return -3;      // !!! wtf?? !!!

    Tb[i].status = ENTRY_USED;

    // register element
    Tb[i].port = port;
	nElements++;

    return i;
}

void DoTblInit()
{
	int i;
	for(i=0; i<T_MAXELEMENTS; i++)
		Tb[i].status=ENTRY_UNUSED;
}
