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

int update_setphot (Image *image, off_t Nimage) {

  SkyRegion UserPatch;
  SkyTable *sky = NULL;
  SkyList *skylist = NULL;
  Catalog catalog;
  off_t i, maxID, *index;

  // create an index for the image IDs
  maxID = 0;
  for (i = 0; i < Nimage; i++) {
    maxID = MAX(maxID, image[i].imageID);
  }
  ALLOCATE (index, off_t, maxID + 1);
  for (i = 0; i < Nimage; i++) {
    if (!image[i].imageID) continue; // images with ID == 0 are virtual
    index[image[i].imageID] = i;
  }
  

  // load the current sky table (layout of all SkyRegions) 
  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, TRUE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");
  
  // determine the populated SkyRegions overlapping the requested area (default depth)
  UserPatch.Rmin = 0;
  UserPatch.Rmax = 360;
  UserPatch.Dmin = -90;
  UserPatch.Dmax = +90;
  skylist = SkyListByPatch (sky, -1, &UserPatch);

  // update measurements for each populated catalog
  for (i = 0; i < skylist[0].Nregions; i++) {

    // set up the basic catalog info
    catalog.filename  = skylist[0].filename[i];
    catalog.catformat = dvo_catalog_catformat (CATFORMAT);    // set the default catformat from config data
    catalog.catmode   = dvo_catalog_catmode (CATMODE);        // set the default catmode from config data
    catalog.catflags  = LOAD_AVES | LOAD_MEAS | LOAD_MISS | LOAD_SECF;
    catalog.Nsecfilt  = GetPhotcodeNsecfilt ();

    if (!dvo_catalog_open (&catalog, skylist[0].regions[i], VERBOSE, "w")) {
      fprintf (stderr, "ERROR: failure reading catalog %s\n", catalog.filename);
      exit (1);
    }
    if (!catalog.Naves_disk) {
      if (VERBOSE) fprintf (stderr, "no data in %s, skipping\n", catalog.filename);
      dvo_catalog_unlock (&catalog);
      dvo_catalog_free (&catalog);
      continue;
    }

    update_catalog_setphot (&catalog, image, index, Nimage);

    if (!UPDATE) {
      dvo_catalog_unlock (&catalog);
      dvo_catalog_free (&catalog);
      continue;
    }
    
    if (VERBOSE) fprintf (stderr, "saving catalog %s\n", catalog.filename);
    
    dvo_catalog_save (&catalog, VERBOSE); 
    dvo_catalog_unlock (&catalog);
    dvo_catalog_free (&catalog);
  }
  return (TRUE);
}      

void update_catalog_setphot (Catalog *catalog, Image *image, off_t *index, off_t Nimage) {

  off_t i, j, m, id, idx, found;
  float Mcal;

  found = 0;    
  for (i = 0; i < catalog[0].Naverage; i++) {

    m = catalog[0].average[i].measureOffset;
    for (j = 0; j < catalog[0].average[i].Nmeasure; j++, m++) {
      idx = catalog[0].measure[m].imageID;
      if (idx <= 0) continue; // detections with imageID == 0 do not have a valid image (eg, ref photcode)

      id = index[idx];
      Mcal = image[id].Mcal;

      catalog[0].measure[m].Mcal = image[id].Mcal;
      found ++;
    }
  }

  if (found) {
    fprintf (stderr, "found "OFF_T_FMT" matches\n", found);
  }
}
