# include "uniphot.h"
# include <glob.h>

void update (Image *image, int Nimage, Group *sgroup, int Nsgroup) {

  int i, j, status, Nmin;
  char line[256];
  glob_t pglob;
  double Rmin, Rmax, Dmin, Dmax, x, y, radius;
  Catalog catalog;
  Coords coords;

  /* clear the NOCAL flags */
  for (i = 0; i < Nimage; i++) {
    image[i].code &= ~ID_IMAGE_NOCAL;
  }


  /* apply calculated space-group offset to image Mcal values */
  for (i = 0; i < Nsgroup; i++) {
    for (j = 0; j < sgroup[i].Nimage; j++) {
      sgroup[i].image[j][0].Mcal -= sgroup[i].M;
    }
  }

  /** write image table **/
  wimages (image, Nimage);

  /** update catalog tables **/
  pglob.gl_offs = 0;
  sprintf (line, "%s/*/*.cpt", CATDIR);
  status = glob (line, 0, NULL, &pglob);

  coords.crpix1 = coords.crpix2 = 0.0;
  coords.cdelt1 = coords.cdelt2 = 1.0; /* scale is degrees, radius in degrees */
  coords.pc1_1 = coords.pc2_2 = 1.0;
  coords.pc1_2 = coords.pc2_1 = 0.0;
  strcpy (coords.ctype, "RA---TAN");
  
  for (i = 0; i < pglob.gl_pathc; i++) {
    catalog.filename = pglob.gl_pathv[i];
    if (!gcatalog (&catalog)) continue;

    fits_scan (&catalog.header, "RA0", "%lf",  1, &Rmin);
    fits_scan (&catalog.header, "RA1", "%lf",  1, &Rmax);
    fits_scan (&catalog.header, "DEC0", "%lf", 1, &Dmin);
    fits_scan (&catalog.header, "DEC1", "%lf", 1, &Dmax);
    while (Rmin <   0.0) { Rmin += 360.0; }
    while (Rmin > 360.0) { Rmin -= 360.0; }
    while (Rmax <   0.0) { Rmax += 360.0; }
    while (Rmax > 360.0) { Rmax -= 360.0; }

    coords.crval1 = 0.5*(Rmin + Rmax);
    coords.crval2 = 0.5*(Dmin + Dmax);

    Nmin = 0;
    Rmin = 1000;
    /* primitive version: match catalog with closest sgroup */
    for (j = 0; j < Nsgroup; j++) {
      if (!RD_to_XY (&x, &y, sgroup[j].v1, sgroup[j].v2, &coords)) continue;
      radius = hypot (x, y);
      if ((j == 0) || (radius < Rmin)) {
	Rmin = radius;
	Nmin = j;
      }
    }

    fprintf (stderr, "catalog: %s sgroup: %d %s %f\n", catalog.filename, Nmin, sgroup[Nmin].label, Rmin);
    update_catalog (&catalog, &sgroup[Nmin], (Rmin > 2*RADIUS)); 
    wcatalog (&catalog); 
  }
}      

/* loop over all average 

   if (source equiv photcode)

   loop over sgroups

   if (radius < RADIUS) 
      
   average.M (+/-) source.M
*/

/* loop over all measure 

   if (source equiv photcode)

   loop over sgroups

   if (radius < RADIUS) 
      
   measure.Mcal (+/-) source.M
*/

/* alternative (slower, more robust)

   loop over all average
   loop over all average.Nm
   select measure with source equiv photcode
   match measure to image, get Mcal & offset
   if any offset for average[i] is different, give error
   apply offset to average.M
*/
