
#include <stdlib.h>
#include <stdio.h>

#include "Boolean.h"
#include "Common.h"
#include "DynamicVector.h"


// IMPLEMENTATION DynamicVectorNode

DynamicVectorNode::DynamicVectorNode()
{
  int                   i;

  // Initialize to empty
  next = NULL;
  for (i=0;i<granularity;i++)
    elems[i] = NULL;
}



// IMPLEMENTATION DynamicVector


DynamicVector::DynamicVector()
{
  // Initialize to empty
  first = last = NULL;
  count = lastcount = 0;
}


DynamicVector::~DynamicVector()
{
  freeAllElements();
}


int DynamicVector::addDynamicVectorNode()
{
  // Deal with empty dynamic vector
  if (last == NULL)
    {
      last = first = new DynamicVectorNode();
      if (last == NULL)
	return FALSE; // Memory allocation failed
    }
  else
    {
      last->next = new DynamicVectorNode();
      if (last->next == NULL)
	return FALSE; // Memory allocation failed
      last = last->next;
    }
  return TRUE;
}


int DynamicVector::addElement(void *elem)
{
  // Have we to alloc a new dynamic vector node ?
  if (lastcount == 0)
    {
      // Yes !
      if (!addDynamicVectorNode())
	return FALSE; // Memory allocation failed
    }

  // Assign the element and update counters
  last->elems[lastcount] = elem;
  count++;
  lastcount = count % DynamicVectorNode::granularity;
  
  return TRUE;
}


int DynamicVector::size()
{
  return (count);
}


void DynamicVector::iterateStart()
{
  current = first;
  curcount = 0;
}


int DynamicVector::iterateIsNext()
{
  if (curcount<count)
    return TRUE;
  else
    return FALSE;
}


void* DynamicVector::iterate()
{
  int modulo;
  void  *toreturn;

  modulo = curcount % DynamicVectorNode::granularity;
  toreturn = current->elems[modulo];
  curcount++;
  modulo = curcount % DynamicVectorNode::granularity;
  if (modulo==0)
    current = current->next;

  return toreturn;
}


void DynamicVector::freeAllElements()
{
  DynamicVectorNode   *temp;
  
  // Iterate through DynamicVectorNodes
  temp = first;
  while (temp != NULL)
    {
      temp = temp->next;
      delete first;
      first = temp;
    }

  // Initialize to empty
  first = last = NULL;
  count = lastcount = 0;
}


