# include "relastro.h"

// We run through each DVO catalog, updating the measures that come from the modified images
// We need to watch for failures:
// * in UpdateMeasures, in fixImageRaw, we track the cumulative offset for each image
// * after all updates are done, we can check for any bad images and reset them to the
//   original coordinates

int UpdateObjectOffsets (SkyList *skylist) {

  int i;
  Catalog catalog;

  // load data from each region file, only use bright stars
  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;
    }

    // match measurements with images
    initImageBins (&catalog, 1, FALSE);
    findImages (&catalog, 1, FALSE);

    // update the detection coordinates using the new image parameters
    UpdateMeasures (&catalog, 1);

    freeImageBins (1);

    // write the updated detections to disk
    save_catalogs (&catalog, 1);
  }
  
  return (TRUE);
}
