# include "markstar.h"

find_bright_stars (catalog, catstats, filename)
Catalog catalog[];
CatStats catstats[];
char *filename;
{

  int i, j, first_j, Nave, Ngsc;
  Catalog GSCdata;
  double MinRA, MinDEC, MaxRA, MaxDEC, RaCenter, DecCenter;
  Coords *tcoords;
  float *X1, *Y1, *X2, *Y2;
  int *N1, *N2, *match;
  char *mark;
  double dX, dY, dR, RADIUS2, BRIGHT_RADIUS, radius;

  load_gsc_data (&GSCdata, filename);

  Nave = catalog[0].Naverage;
  Ngsc = GSCdata.Naverage;
    
  X1 = catstats[0].X;
  Y1 = catstats[0].Y;
  N1 = catstats[0].N;
  ALLOCATE (mark, char, Nave);
  ALLOCATE (match, int, Nave);
  ALLOCATE (X2, float, Ngsc);
  ALLOCATE (Y2, float, Ngsc);
  ALLOCATE (N2, int, Ngsc);
  bzero (mark, Nave);

  tcoords = &catstats[0].coords;
  for (i = 0; i < Ngsc; i++) {
    fRD_to_XY (&X2[i], &Y2[i], GSCdata.average[i].R, GSCdata.average[i].D, tcoords);
    N2[i] = i;
  }
  if (Ngsc > 1) sort_lists (X2, Y2, N2, Ngsc);
  
  /* max radius (mag = -1) */
  BRIGHT_RADIUS = BRIGHT_SLOPE * (-1.0 - BRIGHT_MAG);

  /** find catalog stars near GSC stars **/
  for (i = j = 0; (i < Nave) && (j < Ngsc); ) {
    
    dX = X1[i] - X2[j];

    if (dX <= -2*BRIGHT_RADIUS) {
      i++;
      continue;
    }
    if (dX >= 2*BRIGHT_RADIUS) {
      j++;
      continue;
    }

    /* negative dX: j is too large, positive dX, i is too large */
    first_j = j;
    for (; (dX > -2*BRIGHT_RADIUS) && (j < Ngsc); j++) {
      radius = MAX (BRIGHT_SLOPE * (0.001*GSCdata.average[N2[j]].M - BRIGHT_MAG), 0.0);
      RADIUS2 = radius*radius;
      dX = X1[i] - X2[j];
      dY = Y1[i] - Y2[j];
      dR = dX*dX + dY*dY;
      if (dR < RADIUS2) {  /* new measurement of this star */
	mark[i] = TRUE;
	match[i] = N2[j];
      }
    }
    j = first_j;
    i++;
  }
  
  /* done with search, mark selected stars */
  
  for (i = 0; i < Nave; i++) {
    if (mark[i]) {
      catalog[0].average[N1[i]].code = ID_BLEED;
    }
  } 
  
}

	/* for test purposes, like determining the parameters, uncomment this 
	n = N1[i];
	m = N2[j];
	fprintf (stdout, "%f %f %f %f %f %f\n", 
GSCdata.average[m].R, GSCdata.average[m].D, 
		 0.001*GSCdata.average[m].M, 
catalog[0].average[n].R, catalog[0].average[n].D, 0.001*catalog[0].average[n].M); */
  
  /* for test purposes, like determining the parameters, uncomment this 
  clear_lockfile (); 
  fprintf (stderr, "SUCCESS\n");
  exit (0); */



	n = N1[i];
	m = N2[j];
	RD_to_XY (&X, &Y, Ghostdata[0].average[m].R, Ghostdata[0].average[m].D, &image[0].coords);
	fprintf (stdout, "%f %f %f %f %f %f %d %f %f\n",
		 Ghostdata[0].average[m].R, Ghostdata[0].average[m].D, 
		 0.001*Ghostdata[0].average[m].M, catalog[0].average[n].R, 
		 catalog[0].average[n].D, 0.001*catalog[0].average[n].M, 
		 catalog[0].average[n].Nm, X, Y);
