# include "relastro.h"

Catalog *load_catalogs (SkyList *skylist, int *Ncatalog, int subselect) {

  int i, j, k, m, Nstar;
  Catalog *catalog, *pcatalog, tcatalog;

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

  ALLOCATE (catalog, Catalog, skylist[0].Nregions);

  // load data from each region file, only use bright stars
  for (i = 0; i < skylist[0].Nregions; i++) {

    // we only allow output if we do not use a subset.  in this case,
    // the output parameters are correctly set for catalog[i] via pcatalog
    pcatalog = subselect ? &tcatalog : &catalog[i];

    // set up the basic catalog info
    pcatalog[0].filename  = skylist[0].filename[i];
    pcatalog[0].catformat = dvo_catalog_catformat (CATFORMAT);    // set the default catformat from config data
    pcatalog[0].catmode   = dvo_catalog_catmode (CATMODE);        // set the default catmode from config data
    pcatalog[0].catflags  = LOAD_AVES | LOAD_MEAS | LOAD_SECF; // don't need to load all data at this point
    pcatalog[0].Nsecfilt  = GetPhotcodeNsecfilt ();

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

    //outlier rejection
    if (FlagOutlier) {
      FlagOutliers(&tcatalog);
    }

    // select only the brighter stars
    if (subselect) {
      bcatalog (&catalog[i], &tcatalog);
      dvo_catalog_unlock (&tcatalog);
      dvo_catalog_free (&tcatalog);
    } else {
      if (RESET) {
	for (j = 0; j < catalog[i].Naverage; j++) {
	  catalog[i].average[j].flags = 0;
	  m = catalog[i].average[j].measureOffset;
	  for (k = 0; k < catalog[i].average[j].Nmeasure; k++) {
	    catalog[i].measure[m+k].dbFlags = 0;
	  }
	}
      }
    }
  }

  // XXX keep this test?
  Nstar = 0;
  for (i = 0; i < skylist[0].Nregions; i++) {
    Nstar += catalog[i].Naverage;
  }
  if (Nstar < 2) { 
    fprintf (stderr, "warning: insufficient stars %d\n", Nstar);
  }

  // XXX consider only returning the populated catalogs
  *Ncatalog = skylist[0].Nregions;
  return (catalog);
}

/* this function loads all relevant catalog files for the first pass.  it currently loads the data
   read only (SOFT lock) since it assumes the image table has been locked. if we go to the new
   addstar locking paradigm, in which the images and catalogs are updated independently, then we may
   need to use an XCLD lock here.  
*/
