# include "setphot.h"

void update_catalog_setphot (Catalog *catalog, Image *image, off_t *index, off_t Nimage, FlatCorrectionTable *flatcorr) {

  off_t i, j, found;

  // if we are resetting, reset all flags
  DVOMeasureFlags photomFlags = ID_MEAS_POOR_PHOTOM | ID_MEAS_SKIP_PHOTOM | ID_MEAS_PHOTOM_UBERCAL;

  found = 0;    
  for (i = 0; i < catalog[0].Naverage; i++) {

    off_t m = catalog[0].average[i].measureOffset;
    for (j = 0; j < catalog[0].average[i].Nmeasure; j++, m++) {
      off_t idx = catalog[0].measure[m].imageID;
      if (idx <= 0) continue; // detections with imageID == 0 do not have a valid image (eg, ref photcode)

      off_t id = index[idx];
      if (id < 0) continue;

      float Mcal = image[id].Mcal;
      float dMcal = image[id].dMcal;
      float Mcal_offset = 0.0;

      // if we know about a flat-field correction, then we need to apply the sub-chip correction
      int flat_id = image[id].photom_map_id;
      if (flat_id > 0) {
	  Mcal_offset = FlatCorrectionOffset (flatcorr, flat_id, catalog[0].measure[m].Xccd, catalog[0].measure[m].Yccd);
      }

      catalog[0].measure[m].Mcal = Mcal - Mcal_offset;
      catalog[0].measure[m].dMcal = dMcal;
      myAssert(isfinite(catalog[0].measure[m].Mcal), "oops: ubercal made a nan");

      if (RESET) {
	catalog[0].measure[m].dbFlags &= ~photomFlags;
      }

      // if we are setting the zero points from an UBERCAL database, and this detection is from one of those images,
      // then tag the measurement as well
      if (UBERCAL && (image[id].flags & ID_IMAGE_PHOTOM_UBERCAL)) {
	catalog[0].measure[m].dbFlags |=  ID_MEAS_PHOTOM_UBERCAL;
      }

      found ++;
    }
  }

  if (found) {
    fprintf (stderr, "found "OFF_T_FMT" matches\n", found);
  }
}
