// uIDList.cpp: implementation of the uIDList class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Simulator.h"
#include "uIDList.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

uIDList::uIDList()
{
    CreateIDList();
}

uIDList::~uIDList()
{
    DestructIDList();
}


void uIDList::AddBackID(int ID)
{
    FreeIDListPtr tempo;

    // special case if this is the only entry
    if (HFreeIDListPtr == NULL)
    {
        tempo = new FREE_ID_LIST;
        tempo->ID=ID;
        tempo->Next=NULL;        
        HFreeIDListPtr=tempo;
    }
    else if (TFreeIDListPtr->ID == ID)
    {
        // in the case of an arc, several lines are given the same ID.  This prevents
        // the add back
    }
    else
    {
        tempo = new FREE_ID_LIST;
        tempo->ID=ID;
        tempo->Next=NULL;  
        TFreeIDListPtr->Next=tempo;
        TFreeIDListPtr=tempo;
    }

}

// Destroys the list
void uIDList::DestructIDList()
{
    FreeIDListPtr tempo,temp1;
    tempo = HFreeIDListPtr;
    while (tempo != NULL)
    {
        temp1=tempo;
        tempo=tempo->Next;
        delete temp1;
        temp1 = NULL;
    }
    HFreeIDListPtr=NULL;
    TFreeIDListPtr=NULL;  


}

// gets a valid ID from the ID linked list, and then removes that entry.
int uIDList::GetNewID()
{
    if (HFreeIDListPtr == NULL)
    {
        return -1;
    }
    else
    {
        int treturn = HFreeIDListPtr->ID;
        FreeIDListPtr tempo = HFreeIDListPtr;
        // special case, only one entry in the list.
        if (HFreeIDListPtr == TFreeIDListPtr)
        {
            TFreeIDListPtr=NULL;
        }
        HFreeIDListPtr = HFreeIDListPtr->Next;
        delete tempo;
        return treturn;
    }
}


void uIDList::CreateIDList()
{
    // create the free ID list
    FreeIDListPtr temp1,temp2;

    temp2 = NULL;
    for (int ix = 0; ix < IDLISTSIZE; ix++)
    {
        temp1 = new FREE_ID_LIST;
        if (ix == 0)
        {
            HFreeIDListPtr=temp1;
        }
        temp1->ID=ix;        
        if (temp2 != NULL)
        {
            temp2->Next=temp1;
        }
        temp2=temp1;
    }
    TFreeIDListPtr = temp2;
    TFreeIDListPtr->Next=NULL;
}






