#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include "Array.h"

Array
newArray (int maxSize)
{
  Array array=malloc (sizeof (ArrayStruct));
  
  if (array == NULL) {
    fprintf (stderr, "not enough memory to allocate Array\n");
    exit (1);
  }
  else {
    array->maxSize = maxSize;
    array->elements = 0;
    array->dirty = 0;
    array->array = calloc (maxSize, sizeof (void *));
    if (array->array == NULL) {
      fprintf (stderr, "not enough memory to allocate Array\n");
      exit (1);
    }
  }
  return array;
}

void
addToArray (Array array, void *element)
{
  array->array[array->elements++] = element;
  array->dirty=1;
  if (array->elements == array->maxSize) {
    array->maxSize *= 2;
    array->array = realloc (array->array, array->maxSize * sizeof (void *));
    if (array->array == NULL) {
      fprintf (stderr, "not enough memory to allocate Array\n");
      exit (1);
    }
  }
}

void
freeArray (Array array, void (*freefunc) (void *))
{
  int i;

  for (i = 0; i < array->elements; i++) {
    freefunc (array->array[i]);
  }
  free (array->array);
  free (array);
}

void
sortArray (Array array, int (*compare) (const void *, const void *))
{
  qsort (array->array, array->elements, sizeof (void *), compare);
  array->dirty=0;
}



/* sample code for Array routines */


/*int *
copyInt (int i)
{
  int *copy = malloc (sizeof (int));

  *copy = i;
  return copy;
}

int
compare (const void *a, const void *b)
{
  const int int1 = **(int **) a, int2 = **(int **) b;
  if (int1 > int2)
    return 1;
  else if (int1 < int2)
    return -1;
  else
    return 0;
}

void 
printElement (void *element, FILE * file)
{
  int i = *(int *) element;

  fprintf (file, "%d\n", i);
}

int 
main ()
{
  Array array = newArray (10);
  int i;

  for (i = 20; i > 0; i--)
    addToArray (array, copyInt (i));

  for (i = 0; i < array->elements; i++) {
    printElement (array->array[i], stdout);
  }
  printf ("\n\n");
  sortArray (array, compare);
  for (i = 0; i < array->elements; i++) {
    printElement (array->array[i], stdout);
  }
  freeArray (array, free);
  exit (0);
}*/





