# include "addstar.h"

int find_matches (SkyRegion *region, Stars *stars, unsigned int NstarsIn, Catalog *catalog, AddstarClientOptions options) {

  off_t i, j, n, N, J, Nstars;
  double RADIUS, RADIUS2;
  double *X1, *Y1, *X2, *Y2;
  double dX, dY, dR;
  off_t *N1, *N2, *next_meas;
  off_t Nave, NAVE, Nmeas, NMEAS, Nmatch;
  int Nsecfilt, Nsec, status;
  unsigned int objID, catID;
  Coords tcoords;

  if (NSTAR_GROUP <= 0) {
      fprintf (stderr, "ERROR: NSTAR_GROUP NOT SET!\n");
      exit (1);
  }

  /* photcode data - must by of type DEP; options.photcode is equiv photcode for all input
     images this function requires incoming stars to have the same photcode.equiv value.  if
     this value is not a valid photcode (ie, 0), then no modification is made to the average 
     magnitudes (Nsec will be -1) */

  Nsecfilt = GetPhotcodeNsecfilt ();
  Nsec     = GetPhotcodeNsec (options.photcode);

  /** allocate local arrays (stars) **/
  ALLOCATE (X1, double, NstarsIn);
  ALLOCATE (Y1, double, NstarsIn);
  ALLOCATE (N1, off_t,  NstarsIn);

  /** allocate local arrays (catalog) **/
  NAVE = Nave = catalog[0].Naverage;
  ALLOCATE (X2, double, NAVE);
  ALLOCATE (Y2, double, NAVE);
  ALLOCATE (N2, off_t,  NAVE);
  ALLOCATE (catalog[0].found, off_t, NAVE);
  /* for secfilt j and star i, secfilt[i*Nsecfilt+j] */

  /* internal counters */
  Nmatch = 0;
  NMEAS = Nmeas = catalog[0].Nmeasure;
  
  // current max obj ID for this catalog
  objID = catalog[0].objID;
  catID = catalog[0].catID;

  /* project onto rectilinear grid with 1 arcsec pixels. the choice of ZEA projection has the
   * advantage that every point in R,D has a mapping to a unique X,Y.  However, note that not all
   * possible X,Y points map back to R,D and the local plate scale changes substantially far from
   * the projection pole.  a better mapping might be ARC, not yet implemented (see
   * coordops.update.c).  We use the center of the region (catalog) for crval1,2. 
   */
  tcoords.crval1 = 0.5*(region[0].Rmin + region[0].Rmax);
  if (region[0].Dmax < 90) {
    tcoords.crval2 = 0.5*(region[0].Dmin + region[0].Dmax);
  } else {
    tcoords.crval2 = 90.0;
  }
  tcoords.crpix1 = 0;
  tcoords.crpix2 = 0;
  tcoords.cdelt1 = tcoords.cdelt2 = 1.0 / 3600.0;
  tcoords.pc1_1 = tcoords.pc2_2 = 1.0;
  tcoords.pc1_2 = tcoords.pc2_1 = 0.0;
  tcoords.Npolyterms = 1;
  strcpy (tcoords.ctype, "DEC--ARC");

  /* build spatial index (RA sort) referencing input array sequence */
  Nstars = 0;
  for (i = 0; i < NstarsIn; i++) {
    status = RD_to_XY (&X1[Nstars], &Y1[Nstars], stars[i].average.R, stars[i].average.D, &tcoords);
    if (!status) continue;
    N1[Nstars] = i;
    Nstars ++;
  }
  if (Nstars < 1) {
    if (VERBOSE) fprintf (stderr, "skipping %s, no overlapping stars\n", catalog[0].filename);
    free (catalog[0].found);
    free (X1);
    free (Y1);
    free (N1);
    free (X2);
    free (Y2);
    free (N2);
    return (0);
  }
  if (Nstars > 1) sort_coords_index (X1, Y1, N1, Nstars);
  
  /* build spatial index (RA sort) */
  for (i = 0; i < Nave; i++) {
    RD_to_XY (&X2[i], &Y2[i], catalog[0].average[i].R, catalog[0].average[i].D, &tcoords);
    N2[i] = i;
    catalog[0].found[N2[i]] = -1;
  }
  if (Nave > 1) sort_coords_index (X2, Y2, N2, Nave);

  /* set up pointers for linked list of measure */
  if (catalog[0].sorted && (catalog[0].Nmeasure == catalog[0].Nmeas_disk)) {
    next_meas = init_measure_links (catalog[0].average, Nave, catalog[0].measure, Nmeas);
  } else {
    next_meas = build_measure_links (catalog[0].average, Nave, catalog[0].measure, Nmeas);
  }    

  /* choose a radius for matches (defined in args.c or ImageOptions.c) */
  RADIUS = options.radius;
  RADIUS2 = RADIUS*RADIUS;

  /** find matched stars **/
  // XXX could use NSTAR_GROUP to do this match more quicky if NSTAR_GROUP > 1
  for (i = j = 0; (i < Nstars) && (j < Nave); ) {
    if (!finite(X1[i]) || !finite(Y1[i])) { 
      i++; 
      continue;
    }
    if (!finite(X2[j]) || !finite(Y2[j])) { 
      j++; 
      continue;
    }

    /* negative dX: j is too large */
    dX = X1[i] - X2[j];
    if (dX <= -1.02*RADIUS) {
      i++;
      continue;
    }
    /* positive dX, i is too large */
    if (dX >= 1.02*RADIUS) {
      j++;
      continue;
    }

    /* within match range; look for matches */
    for (J = j; (dX > -1.02*RADIUS) && (J < Nave); J++) {
      dX = X1[i] - X2[J];
      dY = Y1[i] - Y2[J];
      dR = dX*dX + dY*dY;
      if (dR > RADIUS2) continue;

      /*** a match is found, add to average, measure ***/
      Nmatch ++;
      n = N2[J];
      N = N1[i];

      /* make sure there is space for next entry */
      if (Nmeas >= NMEAS) {
	NMEAS = Nmeas + 1000;
	REALLOCATE (next_meas, off_t, NMEAS);

	REALLOCATE (catalog[0].measure, Measure, NMEAS);
      }

      /* add to end of measurement list */
      add_meas_link (&catalog[0].average[n], next_meas, Nmeas, NMEAS);

      /** add measurements for this star **/

      // set the new measurements
      catalog[0].measure[Nmeas]          = stars[N].measure;

      // the following measure elements cannot be set until here:
      catalog[0].measure[Nmeas].dR       = 3600.0*(catalog[0].average[n].R - stars[N].average.R);
      catalog[0].measure[Nmeas].dD       = 3600.0*(catalog[0].average[n].D - stars[N].average.D);
      catalog[0].measure[Nmeas].dbFlags  = 0;
      catalog[0].measure[Nmeas].averef   = n; // this must be an absolute sequence number, if partial average is loaded 
      catalog[0].measure[Nmeas].objID    = catalog[0].average[n].objID;
      catalog[0].measure[Nmeas].catID    = catalog[0].catID;

      // rationalize dR:
      if (catalog[0].measure[Nmeas].dR > +180.0*3600.0) {
	  // average on high end of boundary, move star up
	  stars[N].average.R += 360.0;
	  catalog[0].measure[Nmeas].dR = 3600.0*(catalog[0].average[n].R - stars[N].average.R);
      }
      if (catalog[0].measure[Nmeas].dR < -180.0*3600.0) {
	  // average on low end of boundary, move star down
	  stars[N].average.R -= 360.0;
	  catalog[0].measure[Nmeas].dR = 3600.0*(catalog[0].average[n].R - stars[N].average.R);
      }
      if (fabs(catalog[0].measure[Nmeas].dR) > 10*RADIUS) {
	  fprintf (stderr, "error: %10.6f,%10.6f vs %10.6f,%10.6f (%f,%f vs %f,%f)\n", 
		   catalog[0].average[n].R, catalog[0].average[n].D, 
		   stars[N].average.R, stars[N].average.D,
		   X1[i], X2[J], 
		   Y1[i], Y2[J]);
      }

      /* adds the measurement to the calibration if appropriate color terms are found */
      /* we call this before (optionally) setting the average magnitude to avoid auto-correlations */
      if (options.calibrate) {
	AddToCalibration (&catalog[0].average[n], &catalog[0].secfilt[n*Nsecfilt], catalog[0].measure, &catalog[0].measure[Nmeas], next_meas, N);
      }

      /* set the average magnitude if not already set and if photcode.equiv is not 0 */
      /* in UPDATE mode, this value is not saved; use relphot to recalculate */
      if (Nsec > -1) { 
	if (isnan(catalog[0].secfilt[n*Nsecfilt+Nsec].M)) {
	  catalog[0].secfilt[n*Nsecfilt+Nsec].M = PhotCat (&catalog[0].measure[Nmeas]);
	}
      }

      /*** flag multiple stars */
      /* this image star matches more than one catalog star */
      if (stars[N].found > -1) {
	catalog[0].measure[stars[N].found].dbFlags |= ID_MEAS_BLEND_MEAS;
	catalog[0].measure[Nmeas].dbFlags |= ID_MEAS_BLEND_MEAS;
      } 
      if (stars[N].found == -2) { /* this image star matches a catalog star on a neighboring catalog */
	catalog[0].measure[Nmeas].dbFlags |= ID_MEAS_BLEND_MEAS_X;
      } 
      if (stars[N].found == -1) { /* this image star matches only this catalog star */
	stars[N].found = Nmeas;  /* save first match, in case coincidences are found */
      }
      /* this catalog star matches more than one image star */
      if (catalog[0].found[n] > -1) {
	catalog[0].measure[catalog[0].found[n]].dbFlags |= ID_MEAS_BLEND_OBJ;
	catalog[0].measure[Nmeas].dbFlags |= ID_MEAS_BLEND_OBJ;
      } else {
	catalog[0].found[n] = Nmeas;
      }
      /* Nm is updated, but not written out in -update mode (for existing entries)
	 Nm is recalculated in build_meas_links if loaded table is not sorted */
      catalog[0].average[n].Nmeasure ++;
      Nmeas ++;

      if (!options.update) {
	/* in UPDATE mode, newly calculated coordinates are not saved */
	update_coords (&catalog[0].average[n], &catalog[0].measure[0], next_meas);
      }
    }
    i++;
  }

  /* incorporate unmatched image stars, if this star is in field of this catalog */
  /* these new entries are all written out in UPDATE mode */ 
  for (i = 0; (i < Nstars) && !options.only_match; i += NSTAR_GROUP) {
    /* make sure there is space for next entry */
    if (Nmeas >= NMEAS - NSTAR_GROUP) {
      NMEAS = Nmeas + 1000;
      REALLOCATE (next_meas, off_t, NMEAS);
      REALLOCATE (catalog[0].measure, Measure, NMEAS);
    }
    if (Nave >= NAVE) {
      NAVE = Nave + 1000;
      REALLOCATE (catalog[0].average, Average, NAVE);
      REALLOCATE (catalog[0].secfilt, SecFilt, NAVE*catalog[0].Nsecfilt);
    }

    if (stars[i].found >= 0) continue;
    if (!IN_REGION (stars[i].average.R, stars[i].average.D)) continue;

    dvo_average_init (&catalog[0].average[Nave]);
    catalog[0].average[Nave].R         	   = stars[i].average.R;
    catalog[0].average[Nave].D         	   = stars[i].average.D;

    catalog[0].average[Nave].Nmeasure      = NSTAR_GROUP;
    catalog[0].average[Nave].measureOffset = Nmeas;
    catalog[0].average[Nave].objID     	   = objID;
    catalog[0].average[Nave].catID     	   = catID;

    if (PSPS_ID) {
        catalog[0].average[Nave].extID = CreatePSPSObjectID(catalog[0].average[Nave].R, catalog[0].average[Nave].D);
    }

    objID ++;

    for (j = 0; j < Nsecfilt; j++) {
      dvo_secfilt_init (&catalog[0].secfilt[Nave*Nsecfilt+j]);
    }

    for (j = 0; j < NSTAR_GROUP; j++) {
      // supply the measurments from this detection
      catalog[0].measure[Nmeas]           = stars[i + j].measure;

      // the following measure elements cannot be set until here:
      catalog[0].measure[Nmeas].dR       	= 0.0;
      catalog[0].measure[Nmeas].dD       	= 0.0;
      catalog[0].measure[Nmeas].dbFlags 	= 0;
      catalog[0].measure[Nmeas].averef   	= Nave; // XXX EAM : must be absolute Nave if partial read
      catalog[0].measure[Nmeas].objID     = catalog[0].average[Nave].objID;
      catalog[0].measure[Nmeas].catID     = catalog[0].catID;

      /* set the average magnitude if not already set and the photcode.equiv is not 0 */
      /* in UPDATE mode, this value is not saved; use relphot to recalculate */
      if (Nsec > -1) { 
          catalog[0].secfilt[Nave*Nsecfilt+Nsec].M = PhotCat (&catalog[0].measure[Nmeas]);
      }

      /* next[Nmeas] should always be -1 in this context (it is always the only
         measurement for the star) */
      stars[i].found = Nmeas;
      next_meas[Nmeas] = -1;  // initial value here update below
      Nmeas ++;
    }
    for (j = 0; j < NSTAR_GROUP - 1; j++) {
      next_meas[Nmeas - NSTAR_GROUP + j] = Nmeas - NSTAR_GROUP + j + 1;
    }
    Nave ++;
  }
      
  REALLOCATE (catalog[0].average, Average, Nave);
  REALLOCATE (catalog[0].measure, Measure, Nmeas);
 
  if (options.nosort) {
    catalog[0].sorted = FALSE;
  } else {
    catalog[0].sorted = TRUE;
    catalog[0].measure = sort_measure (catalog[0].average, Nave, catalog[0].measure, Nmeas, next_meas);
  }

  /* note stars which have been found in this catalog */
  for (i = 0; i < NstarsIn; i++) {
    if (stars[i].found > -1) {
      stars[i].found = -2;
    }
  }

  /* check if the catalog has changed?  if no change, no need to write */
  catalog[0].objID    = objID; // new max value, save on catalog close
  catalog[0].Naverage = Nave;
  catalog[0].Nmeasure = Nmeas;
  catalog[0].Nsecf_mem = Nave*Nsecfilt;
  if (VERBOSE) fprintf (stderr, "Nstars, Nave, Nmeas: "OFF_T_FMT" "OFF_T_FMT" "OFF_T_FMT", ("OFF_T_FMT" matches)\n",  Nstars,  Nave,  Nmeas,  Nmatch);

  free (catalog[0].found);
  free (X1);
  free (Y1);
  free (N1);
  free (N2);
  free (X2);
  free (Y2);
  free (next_meas);

  return (Nmatch);
}

/* 
   notes:
   
   for finding if a catalog star is in an image or an image star is in the catalog:
   
   catalogs have boundaries defined by RA and DEC, but they may curve in projection
   images have boundaries which are lines in pixels coords, but curve in RA and DEC
   
   catalog[0].found[Ncat] but stars[Nstar].found
   
*/
