# include "relphot.h"

Catalog *load_catalogs (GSCRegion *region, int Nregion, GSCRegion *fullregion) {

  int i, Nstar;
  char filename[256];
  Catalog *catalog, tcatalog;

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

  ALLOCATE (catalog, Catalog, Nregion);

  /* load data from each region file, only use bright stars */
  for (i = 0; i < Nregion; i++) {
    sprintf (filename, "%s/%s", CATDIR, region[i].filename);
    tcatalog.filename = filename;  /* don't free region before catalog! */
    switch (lock_catalog (&tcatalog, LCK_SOFT)) {
    case 0:
      fprintf (stderr, "ERROR: can't lock file %s\n", region[i].filename);
      exit (1);
    case 1:
      gcatalog (&tcatalog, FALSE); /* load from disk */
      break;
    case 2:
      if (VERBOSE) fprintf (stderr, "no data in %s, skipping\n", tcatalog.filename);
      tcatalog.Naverage = 0;
      tcatalog.Nmeasure = 0;
      break;
    default:
      fprintf (stderr, "weird lock_catalog exit state\n");
      exit (1);
    }
    bcatalog (&catalog[i], &tcatalog, fullregion);
  }

  Nstar = 0;
  for (i = 0; i < Nregion; i++) {
    Nstar += catalog[i].Naverage;
  }
  if (Nstar < 2) { 
    fprintf (stderr, "insufficient stars %d\n", Nstar);
    exit (0);
  }
  return (catalog);
}
