// --------------------------------------------------------------------
//   IMPLEMENTATION FILE (numvec.C)
//   This module exports a NumVec Class.
//
//   Brad Duska
// --------------------------------------------------------------------

#include "bool.h"
#include "numvec.h"
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>


NumVec::NumVec() {
  data = NULL;
   size = 0;
   maxSize = 0;
   increment = NUMVEC_INCREMENT;
   Expand(increment);
}


NumVec::NumVec( const NumVec& anotherVec ) {
  Copy( anotherVec );
}


NumVec NumVec::operator=( const NumVec& anotherVec ) {
  Deallocate( data );
  Copy( anotherVec );
  return * this;
}


NumVec::~NumVec() {
  Deallocate( data );
}


void NumVec::Store(int location, int value)
{
  // if the numvec isn't big enough make it bigger
  if(location >= maxSize) {
    if(location-maxSize >= increment) {
      Expand(location-maxSize+1);
    } else {
      Expand(increment);
    }
  }
  
  // track the max element that has been touched
  if(location >= size) {
    size = location + 1;
  }

  data[location] = value;
}


void NumVec::Print() const {
  for( int i = 0; i < size; i++ )
     fprintf(stderr, "Index: %d, Value: %d\n", i, data[i]);
}


int NumVec::ValueAt( int i ) const {
  if( i < 0 || i >= size ) {
    fprintf(stderr, "NumVec::Value, invalid subscript %d\n", i);
    exit( 1 );
  }
  return data[i];
}

int NumVec::getSize() const {
  return size;
}


void NumVec::Expand(int amount) {
   int * temp = data;

   data = new int[ maxSize + amount ];
   if( data == NULL ) {
     fprintf(stderr, "NumVec::Expand, insufficient memory\n");
     exit( 1 );
   }

   // initialize to 0
   for(int i = 0; i < maxSize+amount; i++) {
      data[i] = 0;
   } 

   // copy old data over
   for(int j = 0; j < size; j++) {
      data[j] = temp[j];
   }

   Deallocate( temp );
   maxSize+=amount;
}


void NumVec::Deallocate( int* & ipoint ) {
  delete ipoint;
  ipoint = NULL;
}


void NumVec::Copy( const NumVec& anotherVec ) {
  data = new int[anotherVec.size];
  if( data == NULL ) {
    fprintf(stderr, "NumVec::Copy, insufficient memory\n");
    exit( 1 );
  }
  for( int i = 0; i < anotherVec.size; i++ ) {
    data[i] = anotherVec.data[i];
  }

  maxSize = anotherVec.size;
  size = anotherVec.size;
  increment = anotherVec.increment;
}


