# include "relphot.h"

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

  int i, Nmeas, Nstar, Nmeas_total, Nstar_total;
  Catalog *catalog, tcatalog;

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

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

  Nmeas_total = Nstar_total = 0;

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

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

    if (!dvo_catalog_open (&tcatalog, skylist[0].regions[i], VERBOSE, "r")) {
      fprintf (stderr, "ERROR: failure reading catalog %s\n", tcatalog.filename);
      exit (1);
    }
    if (VERBOSE && !tcatalog.Naves_disk) fprintf (stderr, "no data in %s, skipping\n", tcatalog.filename);
    Nstar_total += tcatalog.Naverage;
    Nmeas_total += tcatalog.Nmeasure;

    // select only the brighter stars
    bcatalog (&catalog[i], &tcatalog);
    dvo_catalog_unlock (&tcatalog);
    dvo_catalog_free (&tcatalog);
  }

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

  fprintf (stderr, "using %d of %d stars (%d of %d measurements)\n", Nstar, Nstar_total, Nmeas, Nmeas_total);

  // 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.  
*/
