# include "imregister.h"
# include "spreg.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 spectrum list, output is a new subset */
int *unique_entries (Spectrum *spectrum, int Nspectrum, int *subset, int *Nmatch) {

  int i, j, 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 */
  ALLOCATE (index, char *, Nsubset);
  ALLOCATE (entry, int, Nsubset);
  for (i = 0; i < Nsubset; i++) {
    sprintf (idxline, "%s", spectrum[subset[i]].filename);
    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++);
    m = i;
    
    /* 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);
}
