# include "relphot.h"

int relphot_objects () {

  int i, j, k, m;
  int Nsecfilt;

  SkyTable *sky = NULL;
  SkyList *skylist = NULL;
  Catalog catalog;

  // load the current sky table (layout of all SkyRegions) 
  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");
  
  // determine the populated SkyRegions overlapping the requested area (default depth)
  skylist = SkyListByPatch (sky, -1, &UserPatch);

  // load data from each region file, only use bright stars
  for (i = 0; i < skylist[0].Nregions; i++) {

    // set up the basic catalog info
    catalog.filename  = skylist[0].filename[i];
    catalog.catformat = dvo_catalog_catformat (CATFORMAT);    // set the default catformat from config data
    catalog.catmode   = dvo_catalog_catmode (CATMODE);        // set the default catmode from config data
    catalog.catflags  = LOAD_AVES | LOAD_MEAS | LOAD_MISS | LOAD_SECF;
    catalog.Nsecfilt  = GetPhotcodeNsecfilt ();

    if (!dvo_catalog_open (&catalog, skylist[0].regions[i], VERBOSE, "w")) {
      fprintf (stderr, "ERROR: failure reading catalog %s\n", catalog.filename);
      exit (1);
    }
    if (!catalog.Naves_disk) {
      if (VERBOSE) fprintf (stderr, "no data in %s, skipping\n", catalog.filename);
      dvo_catalog_unlock (&catalog);
      dvo_catalog_free (&catalog);
      continue;
    }

    // XXX consider what gets reset (only PHOTOM flags)
    if (RESET) {
      Nsecfilt = catalog.Nsecfilt;
      for (j = 0; j < catalog.Naverage; j++) {
	catalog.average[j].flags = 0;
	for (k = 0; k < Nsecfilt; k++) {
	  catalog.secfilt[j*Nsecfilt + k].M    	= NAN;
	  catalog.secfilt[j*Nsecfilt + k].M_20 	= NAN_S_SHORT;
	  catalog.secfilt[j*Nsecfilt + k].M_80 	= NAN_S_SHORT;
	  catalog.secfilt[j*Nsecfilt + k].dM   	= NAN;
	  catalog.secfilt[j*Nsecfilt + k].Xm    = NAN_S_SHORT;
	  catalog.secfilt[j*Nsecfilt + k].Ncode = 0;
	  catalog.secfilt[j*Nsecfilt + k].Nused = 0;
	}
	m = catalog.average[j].measureOffset;
	for (k = 0; k < catalog.average[j].Nmeasure; k++) {
	  catalog.measure[m+k].dbFlags = 0;
	}
      }
    }

    setMave (&catalog, 1);

    if (!UPDATE) {
      dvo_catalog_unlock (&catalog);
      dvo_catalog_free (&catalog);
      continue;
    }
    
    if (VERBOSE) fprintf (stderr, "saving catalog %s\n", catalog.filename);
    dvo_catalog_save (&catalog, VERBOSE); 
    dvo_catalog_unlock (&catalog);
    dvo_catalog_free (&catalog);
  }
  
  return (TRUE);
}
