// **********************************************
// File: INDEXED.CPP
// IndexedList is an extension of the Array class
// with capabilities to insert and delete at specific places
// This module contains the functions for processing
// requests concerning this class.

#include "muzika.h"

// **********************************************
// IndexedList::insertAt inserts a given object at the
// specified index. All objects at subsequent indexed are
// moved one index forward.

void IndexedList :: insertAt(Object &obj, int index)
{
  if (itemsInContainer > 0) {
    // There are items in the list;
    // reallocate if necessary and insert the object
    // at the specified index
    if (upperbound < itemsInContainer)
      reallocate(itemsInContainer+1);
    insertEntry(index);
    setData(index, &obj);
  }
  else
    // List is empty: just use the Array class's addAt function
    addAt(obj, 0);
  lastElementIndex = itemsInContainer++;
}

// **********************************************
// IndexedList::detachAt removes an entry from the
// specified index without destroying the object. Subsequent
// entries are pulled one index down.

void IndexedList :: detachAt(int index)
{
  // Check the the index is valid, then use the Array class's
  // detach function
  if (index < lowerbound+itemsInContainer)
    detach(index);
}

// **********************************************
// IndexedList::destroyAt removes an entry from the
// specified index and destroys the object. Subsequent
// entries are pulled one index down.

void IndexedList :: destroyAt(int index)
{
  // Check that the index is valid, then use the Array class's
  // destroy function
  if (index < lowerbound+itemsInContainer)
    destroy(index);
}

// **********************************************
// IndexedList::printOn prints the contents of the list
// on the specified stream by calling the contained objects'
// printOn functions. This function is used for saving a melody
// in a file.

void IndexedList :: printOn(ostream &out) const
{
  // Call the contained objects' printOn functions
  for (int index = lowerbound; index < lowerbound+itemsInContainer; ++index)
    objectAt(index).printOn(out);
}
