# include "photdbc.h"

int main (int argc, char **argv) {

  int i;
  char *skyfile;
  Catalog incatalog;
  Catalog outcatalog;
  SkyTable *sky;
  SkyList *skylist;

  /* get configuration info, args, lockfile */
  initialize (argc, argv);

  // load and copy the image table
  copy_images (argv[1]);

  // the output catalog needs to inherit the SKY_DEPTH of the input catalog
  sky = SkyTableLoadOptimal (CATDIR, NULL, GSCFILE, TRUE, SKY_DEPTH_HST, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");
  skylist = SkyListByPatch (sky, -1, &REGION);
  for (i = 0; i < skylist[0].Nregions; i++) {
    if (i % 100 == 0) fprintf (stderr, "%s\n", skylist[0].regions[i][0].name);

    // set the parameters which guide catalog open/load/create
    incatalog.filename = skylist[0].filename[i];
    incatalog.Nsecfilt = GetPhotcodeNsecfilt ();
    incatalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_SECF;

    // an error exit status here is a significant error
    if (!dvo_catalog_open (&incatalog, skylist[0].regions[i], VERBOSE, "r")) {
      fprintf (stderr, "ERROR: failure to open/create catalog file %s\n", incatalog.filename);
      exit (2);
    }
    // skip empty input catalogs
    if (!incatalog.Naves_disk) {
      dvo_catalog_unlock (&incatalog);
      dvo_catalog_free (&incatalog);
      continue;
    }

    // create output catalog filename
    outcatalog.filename = strsubs (incatalog.filename, CATDIR, argv[1]);
    if (outcatalog.filename == NULL) Shutdown ("error with input catalog name");

    // define outcatalog open parameters
    outcatalog.catformat = dvo_catalog_catformat (CATFORMAT);  // set the default catformat from config data
    outcatalog.catmode   = dvo_catalog_catmode (CATMODE);      // set the default catmode from config data
    outcatalog.Nsecfilt  = incatalog.Nsecfilt;                 // inherit from the incatalog
    outcatalog.catflags  = LOAD_AVES | LOAD_MEAS | LOAD_MISS | LOAD_SECF;

    // output catalogs always represent the same skyregions as the input catalogs
    if (!dvo_catalog_open (&outcatalog, skylist[0].regions[i], VERBOSE, "w")) {
      fprintf (stderr, "ERROR: failure to open/create catalog file %s\n", outcatalog.filename);
      exit (2);
    }

    /* limit number of measures based on selections */
    make_subcatalog (&outcatalog, &incatalog);
	
    // XXX add other filters here:
    join_stars (&outcatalog);
    // unique_measures (catalog);
    // flag_measures (&db, catalog);
    // get_mags (catalog);

    dvo_catalog_save (&outcatalog, VERBOSE);
    dvo_catalog_unlock (&outcatalog);
    dvo_catalog_free (&outcatalog);

    dvo_catalog_unlock (&incatalog);
    dvo_catalog_free (&incatalog);
  }

  ALLOCATE (skyfile, char, strlen(argv[1]) + strlen("/SkyTable.fits") + 1);
  sprintf (skyfile, "%s/SkyTable.fits", argv[1]);
  SkyTableSave (sky, skyfile);
  exit (0);
}
