#include "moss.h"

/*
******** mossNewCorresp()
**
** pseudo-constructor for mossCorresp struct
** 
** allocates the x0, y0, x1, and y1 arrays to the given length if it
** is non-zero, otherwise sets them to NULL
**
** returns pointer to new mossCorresp if all okay, NULL otherwise
**
** This does NOT use biff
*/
mossCorresp *
mossNewCorresp(int maxNum) {
  mossCorresp *pairs;

  pairs = (mossCorresp *)malloc(1*sizeof(mossCorresp));
  if (pairs) {
    pairs->num = 0;
    pairs->maxNum = maxNum;
    if (maxNum) {
      pairs->x0 = (float*)malloc(maxNum*sizeof(float));
      pairs->y0 = (float*)malloc(maxNum*sizeof(float));
      pairs->x1 = (float*)malloc(maxNum*sizeof(float));
      pairs->y1 = (float*)malloc(maxNum*sizeof(float));
      if (!(pairs->x0 && pairs->y0 && pairs->x1 && pairs->y1))
	return NULL;
    }
    else {
      pairs->x0 = NULL;
      pairs->y0 = NULL;
      pairs->x1 = NULL;
      pairs->y1 = NULL;
    }
  }
  return pairs;
}

/*
******** mossNukeCorresp()
**
** pseudo-destructor for mossCorresp struct
*/
void
mossNukeCorresp(mossCorresp *pairs) {

  if (pairs) {
    if (pairs->x0)
      free(pairs->x0);
    if (pairs->y0)
      free(pairs->y0);
    if (pairs->x1)
      free(pairs->x1);
    if (pairs->y1)
      free(pairs->y1);
    free(pairs);
  }
}

/*
******** mossNewMatrix()
**
** pseudo-constructor for mossMatrix
**
** allocates array of arrays of mossCorresp struct pointers,
** all of given length.  All pointers are initialized to NULL
**
** returns pointer to new mossMatrix struct if all okay, otherwise NULL
**
** This does NOT use biff
*/
mossMatrix *
mossNewMatrix(int size) {
  mossMatrix *matx;
  int i, j;

  matx = (mossMatrix *)malloc(1*sizeof(mossMatrix));
  if (matx) {
    matx->size = size;
    matx->pair = (mossCorresp ***)malloc(size*sizeof(mossCorresp **));
    if (matx->pair) {
      for (i=0; i<=size-1; i++) {
	matx->pair[i] = (mossCorresp **)malloc(size*sizeof(mossCorresp *));
	if (!(matx->pair[i])) {
	  return NULL;
	}
	for (j=0; j<=size-1; j++) {
	  matx->pair[i][j] = NULL;
	}
      }
    }
    else {
      return NULL;
    }
  }
  return matx;
}

/*
******** mossNukeMatrix()
**
** pseudo-destructor for mossMatrix
*/
void
mossNukeMatrix(mossMatrix *matx) {
  int i, j;

  if (matx) {
    if (matx->pair) {
      for (i=0; i<=matx->size-1; i++) {
	if (matx->pair[i]) {
	  for (j=0; j<=matx->size-1; j++) {
	    mossNukeCorresp(matx->pair[i][j]);
	  }
	  free(matx->pair[i]);
	}
      }
      free(matx->pair);
    }
    free(matx);
  }
}
