# 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;
  double Rin, Din;

  // 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];

    Rin = average_in[0].R - measure_in[0].dR / 3600.0;
    Din = average_in[0].D - measure_in[0].dD / 3600.0;

    /** dR,dD now represent arcsec **/
    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;

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

    // warn on surprisingly distant detections
    if (fabs(measure_out[Nout].dR) > 10*RADIUS) {
      // ok take declination into account and check again.
      double cosD = cos(RAD_DEG*Din);
      if (fabs(measure_out[Nout].dR*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, Rin, Din);
      }
    }
    return TRUE; // found the matched entry
  }
  return FALSE; // did not find the matched entry
}

