# include "uniphot.h"

int main (int argc, char **argv) {

  int i, Ntgroup, Nsgroup, status;
  Group *tgroup, *sgroup;
  ImageLink *imlinks;
  FITS_DB db;

  /* get configuration info, args, lockfile */
  initialize_uniphot (argc, argv);

  set_db (&db);
  status = dvo_image_lock (&db, ImageCat, 60.0, (UPDATE ? LCK_XCLD : LCK_SOFT));
  if (!status) Shutdown ("ERROR: failure to lock image catalog %s", db.filename);
  if (db.dbstate == LCK_EMPTY) Shutdown ("ERROR: No images in catalog %s (1)", db.filename);
  if (!UPDATE) dvo_image_unlock (&db); 

  /* load images */
  load_images_uniphot (&db);
  
  /* filter image list by selection */
  subset_images (&db);

  tgroup = find_image_tgroups (&db, &imlinks, &Ntgroup);
  sgroup = find_image_sgroups (&db, &imlinks, &Nsgroup);

  /* determine fit values */
  for (i = 0; i < NLOOP; i++) {

    fit_tgroup (tgroup, Ntgroup);
    fit_sgroup (sgroup, Nsgroup); 

  }    

  fprintf (stdout, "# uniphot results for filter %s\n", photcode[0].name);
  fprintf (stdout, "# STATMODE: %s\n", STATMODE);
  fprintf (stdout, "# NLOOP: %d\n", NLOOP);
  fprintf (stdout, "# time groups : %d\n", Ntgroup);
  for (i = 0; i < Ntgroup; i++) {
    fprintf (stdout, "%s %5d %5d %7.4f  %7.4f %7.4f\n", tgroup[i].label, 
	     tgroup[i].Nimage, tgroup[i].Ngood, 0.001*tgroup[i].M, 0.001*tgroup[i].dM, 0.001*tgroup[i].dMsub);
  }
  fprintf (stdout, "\n");

  fprintf (stdout, "# space groups : %d\n", Nsgroup);
  for (i = 0; i < Nsgroup; i++) {
    fprintf (stdout, "%s %5d %5d %7.4f  %7.4f %7.4f\n", sgroup[i].label, 
	     sgroup[i].Nimage, sgroup[i].Ngood, 0.001*sgroup[i].M, 0.001*sgroup[i].dM, 0.001*sgroup[i].dMsub);
  }
  if (!UPDATE) exit (0);

  update (&db, sgroup, Nsgroup);
  dvo_image_unlock (&db); 

  exit (0);
}

/* add a mode to check / force consistency between image.Mcal and
   measure.Mcal.

   use the method in delstar to match image with measure (gregions (image), etc)
*/
