# include "dvosplit.h"

// dvosplit (outlevel) [-region Rmin Rmax Dmin Dmax]
int main (int argc, char **argv) {

  int i, j, OUT_DEPTH;
  SkyTable *sky;
  SkyList *skylist, *outlist;
  Catalog incatalog, *outcatalogs;
  AveLinks *avelinks;
  char filename[256];

  SetSignals ();
  ConfigInit (&argc, argv);
  args (argc, argv);

  OUT_DEPTH = atoi (argv[1]);

  // load the sky table for the existing database
  sky = SkyTableLoadOptimal (CATDIR, NULL, NULL, SKY_DEPTH_HST, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");

  // get the list of populated regions
  skylist  = SkyListByPatch (sky, -1, &UserPatch);
  
  for (i = 0; i < skylist[0].Nregions; i++) {
    fprintf (stderr, "%s\n", skylist[0].regions[i][0].name);

    // if (current level >  out level) skip: cannot currently merge catalogs
    // if (current level == out level) skip: no action is needed
    if (skylist[0].regions[i][0].depth >= OUT_DEPTH) continue;

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

    // 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 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;
    }

    // change sky.regions[i].depth for these regions
    outlist = SkyListByPatch (sky, OUT_DEPTH, skylist[0].regions[i]);

    outcatalogs = open_output_catalogs (outlist);

    avelinks = split_averages (&incatalog, outlist, outcatalogs); 

    split_measures (&incatalog, outlist, outcatalogs, avelinks); 

    // XXX missing entries have to be reconstructed if they are desired
    // split_missings (&incatalog, outlist, outcatalogs, avelinks); 

    free (avelinks[0].outref);
    free (avelinks[0].outcat);

    dvo_catalog_unlock (&incatalog);

    for (j = 0; j < outlist[0].Nregions; j++) {
      dvo_catalog_unlock (&outcatalogs[j]);
    }

    // adjust depth
    skylist[0].regions[i][0].table = FALSE;
    for (j = 0; j < outlist[0].Nregions; j++) {
      outlist[0].regions[j][0].table = TRUE;
    }
  }

  // save sky table copy
  sprintf (filename, "%s/SkyTable.fits", CATDIR);
  check_file_access (filename, TRUE, VERBOSE);
  if (!SkyTableSave (sky, filename)) {
    fprintf (stderr, "ERROR: failed to save sky table for %s\n", CATDIR);
    exit (1);
  }

  exit (0);
}
