# include "dvomerge.h"

// average and measure pointers to the objects of interest and their first / current measurement
int replace_match (Average *average_out, Measure *measure_out, Average *average_in, Measure *measure_in) {

  int Nout;
  unsigned int averef;
  unsigned int catID;

  // find the matching photcode in the object's list of measurements
  for (Nout = 0; Nout < average_out[0].Nmeasure; Nout ++) {
    if (measure_out[Nout].photcode != measure_in[0].photcode) continue;
    
    // set the new measurements
    averef = measure_out[Nout].averef;
    catID  = measure_out[Nout].catID;
    measure_out[Nout] = measure_in[0];

    // old code: find R,D using average_in[0], the get offset relative to average_out[0].  no longer
    // needed since we carry around R,D
    // double Rin = average_in[0].R - measure_in[0].dR / 3600.0;
    // double Din = average_in[0].D - measure_in[0].dD / 3600.0;
    // measure_out[Nout].dR = 3600.0*(average_out[0].R - Rin);
    // measure_out[Nout].dD = 3600.0*(average_out[0].D - Din);

    measure_out[Nout].dbFlags  = 0;  // XXX why reset these?
    measure_out[Nout].averef   = averef;
    measure_out[Nout].objID    = average_out[0].objID;
    measure_out[Nout].catID    = catID;

    float dRoff = dvoOffsetR(&measure_out[Nout], average_out);

    // rationalize dR
    if (dRoff > +180.0*3600.0) {
      // average on high end of boundary, move star up
      measure_out[Nout].R += 360.0;
      dRoff -= 360.0*3600.0;
    }
    if (dRoff < -180.0*3600.0) {
      // average on low end of boundary, move star down
      measure_out[Nout].R -= 360.0;
      dRoff += 360.0*3600.0;
    }

    // warn on surprisingly distant detections
    if (fabs(dRoff) > 10*RADIUS) {
      // ok take declination into account and check again.
      double cosD = cos(RAD_DEG*average_out[0].D);
      if (fabs(dRoff*cosD) > 10*RADIUS) {
	fprintf (stderr, "surprisingly distant detection: %10.6f,%10.6f vs %10.6f,%10.6f\n", 
		 average_out[0].R, average_out[0].D, measure_out[Nout].R, measure_out[Nout].D);
      }
    }
    return TRUE; // found the matched entry
  }
  return FALSE; // did not find the matched entry
}

