# include "relphot.h"

void reload_catalogs (SkyList *skylist) {

  int i;
  int status;
  struct stat filestat;
  Catalog catalog;

  if (VERBOSE) fprintf (stderr, "re-loading catalog data\n");

  /* load data from each region file */
  for (i = 0; i < skylist[0].Nregions; i++) {
    catalog.filename = skylist[0].filename[i];

    // only update existing db tables
    status = stat (catalog.filename, &filestat);
    if ((status == -1) && (errno == ENOENT)) {
      if (VERBOSE) fprintf (stderr, "no file %s, skipping\n", catalog.filename);
      continue;
    }

    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 ();               // set the desired number in case we need to create the catalog

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

    initImageBins  (&catalog, 1);
    initMosaicBins (&catalog, 1);
    initGridBins   (&catalog, 1);

    findImages (&catalog, 1);
    findMosaics (&catalog, 1);

    setMrelFinal (&catalog);
    dvo_catalog_save (&catalog, VERBOSE); 
    dvo_catalog_unlock (&catalog);
    dvo_catalog_free (&catalog);

    freeImageBins (1);
    freeMosaicBins (1);
    freeGridBins (1);
  }
}
