# include "imregister.h"
# include "imreg.h"

void sortstr (char **S, int *X, int N) {

# define SWAPFUNC(A,B){ \
  char *tmp = S[A]; S[A] = S[B]; S[B] = tmp; \
  int  itmp = X[A]; X[A] = X[B]; X[B] = itmp; \
}
# define COMPARE(A,B)(strcmp(S[A], S[B]) < 0)

  OHANA_SORT (N, COMPARE, SWAPFUNC);

# undef SWAPFUNC
# undef COMPARE

}

/* input is a subset index of image list, output is a new subset */
int *unique_entries (RegImage *image, int Nimage, int *subset, int *Nmatch) {

  int i, j, k, m, Nsubset;
  int N, NMATCH;
  int *match, *entry;
  char idxline[128];
  char **index;

  if (!output.unique) return (subset);

  /* create output index */
  N = 0;
  NMATCH = 1000;
  ALLOCATE (match, int, NMATCH);

  Nsubset = *Nmatch;

  /* index = filename.ccd */
  ALLOCATE (index, char *, Nsubset);
  ALLOCATE (entry, int, Nsubset);
  for (i = 0; i < Nsubset; i++) {
    sprintf (idxline, "%s.%02d", image[subset[i]].filename, image[subset[i]].ccd);
    index[i] = strcreate (idxline);
    entry[i] = subset[i];
  }
  sortstr (index, entry, Nsubset);

  /* find unique sequences */
  for (i = 0; i < Nsubset; ) {
    for (j = i + 1; (j < Nsubset) && (!strcmp (index[i], index[j])); j++);

    /* find first entry with bias != 0, else entry i */
    m = i;
    for (k = i; k < j; k++) {
      if (image[entry[k]].bias != 0) {
	m = k;
	break;
      }
    }
    
    /* add unique entry to output list */
    match[N] = entry[m];
    N ++;
    if (N == NMATCH) {
      NMATCH += 1000;
      REALLOCATE (match, int, NMATCH);
    }

    /* j always points to the next entry */
    i = j;
  }

  for (i = 0; i < Nsubset; i++) free (index[i]);
  free (index);
  free (entry);
  free (subset);

  *Nmatch = N;
  return (match);
}
