# include "relastro.h"

int relastro_objects () {

  int i, j, k, m;

  SkyTable *sky = NULL;
  SkyList *skylist = NULL;
  Catalog catalog;

  // load the current sky table (layout of all SkyRegions) 
  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");
  
  // determine the populated SkyRegions overlapping the requested area (default depth)
  skylist = SkyListByPatch (sky, -1, &UserPatch);

  // 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;
    }

    // XXX consider what gets reset (only ASTROM flags)
    if (RESET) {
      for (j = 0; j < catalog.Naverage; j++) {
	catalog.average[j].code = 0;
	m = catalog.average[j].measureOffset;
	for (k = 0; k < catalog.average[j].Nmeasure; k++) {
	  catalog.measure[m+k].dbFlags = 0;
	}
      }
    }

    UpdateObjects (&catalog, 1);

    if (!UPDATE) {
      dvo_catalog_unlock (&catalog);
      dvo_catalog_free (&catalog);
      continue;
    }
    
    save_catalogs (&catalog, 1);
  }
  
  return (TRUE);
}
