# include "gastro2.h"

void gproject (CmpCatalog *Target, RefCatalog *Ref, RefCatalog *Subset) {

  int i, N;
  double X, Y, M, Moff;
  double XMIN, XMAX, YMIN, YMAX, MMIN, MMAX;
  Coords *coords;
  StarData *in, *out;

  Subset[0] = Ref[0];

  ALLOCATE (Subset[0].stars, StarData, MAX (1, Ref[0].N));

  in     = Ref[0].stars;
  out    = Subset[0].stars;
  coords = &Target[0].coords;

  Moff = Ref[0].Moff;

  XMIN = -0.5*NFIELD*Target[0].header.Naxis[0];
  XMAX =  0.5*NFIELD*Target[0].header.Naxis[0] + Target[0].header.Naxis[0];
  YMIN = -0.5*NFIELD*Target[0].header.Naxis[1];
  YMAX =  0.5*NFIELD*Target[0].header.Naxis[1] + Target[0].header.Naxis[1];
 
  /* need to allow some leeway? use a fixed +/- 0.5 mag for now */
  MMAX = Target[0].lum.Mmax + 0.5;
  MMIN = Target[0].lum.Mmin - 0.5;

  if (MMAX < Ref[0].lum.Mmin + Moff) 
    fprintf (stderr, "warning: reference catalog probably too faint:  %5.3f < %5.3f\n", Target[0].lum.Mmax, Ref[0].lum.Mmin + Moff);

  if (MMIN > Ref[0].lum.Mmax + Moff) 
    fprintf (stderr, "warning: reference catalog probably too bright: %5.3f > %5.3f\n", Target[0].lum.Mmin, Ref[0].lum.Mmax + Moff);

  for (N = i = 0; i < Ref[0].N; i++) {
    RD_to_XY (&X, &Y, in[i].R, in[i].D, coords);
    M = in[i].M + Moff;

    if (X < XMIN) continue;
    if (X > XMAX) continue;
    if (Y < YMIN) continue;
    if (Y > YMAX) continue;

    if (MAGLIMS) {
      if (M < MMIN) continue;
      if (M > MMAX) continue;
    }

    out[N] = in[i];
    out[N].X = X;
    out[N].Y = Y;
    out[N].M = M;
    N++;
  }

  if (N < 3) {
    fprintf (stderr, "ERROR: too few reference stars accepted\n");
    exit (1);
  }
    
  Subset[0].N = N;
  REALLOCATE (Subset[0].stars, StarData, MAX (1, Subset[0].N));

}

/* in this function, we convert the Ra & Dec coords to the rough X, Y coords
   we also convert the magnitudes to the approximate system with Ref[0].Moff 
   also, reduce the domain to those within X, Y, M limits 
*/

