# include "addstar.h"
# include "WISE.h"

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

  char *path;
  int i;
  SkyTable *sky, *skyWISE;
  SkyList *skylist = NULL;
  SkyList *overlap = NULL;
  AddstarClientOptions options;

  // need to construct these options with args_loadWISE...
  options = ConfigInit (&argc, argv);
  options = args_loadWISE (argc, argv, options);

  // load the full sky description table:
  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, TRUE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");
  
  // generate the subset matching the user-selected region
  skylist = SkyListByPatch (sky, -1, &UserPatch);

  // if we only match to existing (already populated) regions, limit the select to those regions:
  if (options.existing_regions) {
    SkyList *tmp;
    tmp = SkyListExistingSubset (skylist, CATDIR);
    SkyListFree (skylist);
    skylist = tmp;
  }

  path = WISE_DIR_PRELIM;

  // the accel.dat file has the raw filenames
  // test if the file exists, or else try the .gz version
  // XXX can we build an accelerator?
  skyWISE = loadWISE_acc (path, "accel.dat");
  
  for (i = 0; i < skyWISE[0].Nregions; i++) {
    // check if any of the skylist entries overlap this WISE catalog:
    overlap = SkyListByBounds_List (skylist, -1, skyWISE[0].regions[i].Rmin, skyWISE[0].regions[i].Rmax, skyWISE[0].regions[i].Dmin, skyWISE[0].regions[i].Dmax);
    if (overlap[0].Nregions == 0) {
      SkyListFree (overlap);
      continue;
    }
    
    fprintf (stderr, "loading %s\n", skyWISE[0].filename[i]);
    loadWISE_as_rawdata (overlap, skyWISE[0].filename[i], options);
    SkyListFree (overlap);
  }
  exit (0);
}  
