# include "addusno.h"

reset_catalog (catalog)
Catalog catalog[];
{

  int i, j, k, n, m, N, M, found;
  int *next, last, this;
  int Nave, Nmeas, Ndel;
  unsigned int flags;
  Measure *tmpmeasure;
  unsigned short NotUSNO, NotProper;

  Nave = catalog[0].Naverage;
 
  /* set up link listed pointers for new measurements */
  Nmeas = catalog[0].Nmeasure;
  ALLOCATE (next, int, Nmeas);
  /* set up pointers for linked list of measurements */
  for (i = 0; i < Nmeas - 1; i++) {
    next[i] = i+1;
  }
  next[i] = -1;
  last = i;
 
  /** find matched stars **/
  NotUSNO = 0xffff ^ ID_USNO;
  NotProper = 0xffff ^ ID_PROPER;
  for (i = 0; i < Nave; i++) {
    found = FALSE;
    if (catalog[0].average[i].code & ID_USNO) {
      catalog[0].average[i].code &= NotUSNO;
      found = TRUE;
    }
    if (catalog[0].average[i].code & ID_PROPER) {
      catalog[0].average[i].code &= NotProper;
      found = TRUE;
    }
    if (found) {
      M = catalog[0].average[i].offset;
      Ndel = 0;
      for (k = 0; k < catalog[0].average[i].Nm; k++) {
	if (catalog[0].measure[M+k].t == 0) {
	  if (M+k > 0) {
	    this = next[M+k];
	    if (next[M+k] == -1) {
	      next[M+k-1] = -1;
	    } else {
	      for (j = M+k+1; (j < Nmeas) && (next[j] == -2); j++);
	      if (j == Nmeas) {
		next[M+k-1] = -1;
		fprintf (stderr, "warning, why didn't I find last link to start with?\n");
	      }
	      else {
		next[M+k-1] = this;
	      }
	    }
	  }
	  next[M+k] = -2; /* delete link */
	  Ndel ++;
	}
      }
      catalog[0].average[i].Nm -= Ndel;
      Nmeas -= Ndel;
    }
  }
  
  /* fix order of Measure (memory intensive, but fast) */
  N = 0; 
  ALLOCATE (tmpmeasure, Measure, Nmeas);
  for (i = 0; i < Nave; i++) {
    n = catalog[0].average[i].offset;
    catalog[0].average[i].offset = N;
    for (k = 0; k < catalog[0].average[i].Nm; k++, N++) {
      tmpmeasure[N] = catalog[0].measure[n]; 
      n = next[n];
    }
  }
  free (catalog[0].measure);
  catalog[0].measure = tmpmeasure;
    
  if (VERBOSE) fprintf (stderr, "deleted %d reference %d -> %d)\n", 
			catalog[0].Nmeasure - Nmeas, catalog[0].Nmeasure, Nmeas);
  catalog[0].Nmeasure = Nmeas;
}

