# include "getstar.h"

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

  int i;
  SkyTable *sky;
  SkyList *skylist;
  Catalog catalog;
  Catalog output;
  FITS_DB db;

  args (argc, argv);
  set_db (&db);

  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");

  // create an output catalog with the desired name and format options
  output.filename  = OUTPUT;
  output.catformat = dvo_catalog_catformat (CATFORMAT);  // set the default catformat from config data
  output.catmode   = dvo_catalog_catmode (CATMODE);      // set the default catmode from config data
  output.Nsecfilt  = GetPhotcodeNsecfilt ();
  dvo_catalog_open (&output, NULL, VERBOSE, "w");

  switch (MODE) {

    case BY_REGION:
    case BY_RADIUS:

      /* load corresponding sky regions */
      skylist = SkyListByPatch (sky, -1, &REGION);
      for (i = 0; i < skylist[0].Nregions; i++) {
	// set the parameters which guide catalog open/load/create
	catalog.filename = skylist[0].filename[i];
	catalog.Nsecfilt  = GetPhotcodeNsecfilt ();
	catalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_SECF;

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

	/* skip empty catalogs */
	select_by_region (&output, &catalog, &REGION, 0, 0);
      }
      break;

    case BY_IMLIST:
      /* load image list */
    case BY_IMAGE:

      # if (0)
      /* load corresponding sky regions */
      skylist = SkyListByImage (sky, -1, &image, &Nimage);
      for (i = 0; i < skylist[0].Nregions; i++) {
	// set the parameters which guide catalog open/load/create
	catalog.filename = skylist[0].filename[i];
	catalog.Nsecfilt  = GetPhotcodeNsecfilt ();
	catalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_SECF;

	// an error exit status here is a significant error
	if (!dvo_catalog_open (&catalog, skylist[0].regions[i], VERBOSE, "r")) {
	  fprintf (stderr, "ERROR: failure to open/create catalog file %s\n", catalog.filename);
	  exit (2);
	}
	/* skip empty catalogs */
	if (!catalog.Nave_disk) continue;
	stars = select_by_image (&catalog, &image, 0, 0, stars, &Nstars);
      }
      # endif
      fprintf (stderr, "error: BY_IMAGE not implemented\n");
      exit (1);
      break;

    case BY_CATALOG:
      fprintf (stderr, "error: BY_CATALOG not implemented\n");
      exit (1);
      break;
      
    default:
      fprintf (stderr, "error: invalid options\n");
      exit (1);
  }

  /* write out the selected stars */
  // XXX need to set the catalog boundaries by hand? RA0-RA1, DEC0-DEC1
  dvo_catalog_save (&output, VERBOSE);
  dvo_catalog_unlock (&output);
  dvo_catalog_free (&output);
  fprintf (stderr, "SUCCESS\n");
  exit (0);
}
