# include "relastro.h"

int UpdateChips (Catalog *catalog, int Ncatalog) {

  /* we can measure new image parameters for each non-mosaic chip independently */
  off_t i, Nimage, Nraw, Nref;
  Image *image;
  StarData *raw, *ref;
  Coords *oldCoords;

  image = getimages (&Nimage);

  for (i = 0; i < Nimage; i++) {

    /* skip all except WRP images */
    if (strcmp(&image[i].coords.ctype[4], "-WRP")) continue;

    /* convert measure coordinates to raw entries */
    raw = getImageRaw (catalog, Ncatalog, i, &Nraw, MODE_MOSAIC);
    if (!raw) continue;

    /* convert average coordinates to ref entries */
    ref = getImageRef (catalog, Ncatalog, i, &Nref, MODE_MOSAIC);
    if (!ref) continue;

    // note that Nraw & Nref must be equal: if not, we made a programming error in one of these two functions.
    assert (Nraw == Nref);

    saveCoords (&image[i].coords, i);

    // FitChip does iterative, clipped fitting
    // fprintf (stderr, "image %lld : Nstars: %lld\n", (long long) i, (long long) Nraw);
    if (!FitChip (raw, ref, Nraw, &image[i].coords)) {
      fprintf (stderr, "reject fit for image %s (%lld) : Nstars: %lld\n", image[i].name, (long long) i, (long long) Nraw);
      oldCoords = getCoords (i);
      memcpy (&image[i].coords, oldCoords, sizeof(Coords));
    }

    free (raw);
    free (ref);
  }

  return (TRUE);
}

