# include "imregister.h"
# include "imreg.h"

void DeleteSubset (FITS_DB *db, RegImage *image, int Nimage, int *match, int Nmatch) {

  int i, j;
  int *keep, Ndel, Nsubset;
  RegImage *subset;

  ALLOCATE (keep, int, MAX (Nimage, 1));
  for (i = 0; i < Nimage; i++) keep[i] = TRUE;
  fprintf (stderr, "total of %d images\n", Nimage);

  Ndel = 0;
  for (i = 0; i < Nmatch; i++) {
    j = match[i];
    if (j == -1) continue;
    keep[j] = FALSE;
    Ndel ++;
  }
  fprintf (stderr, "delete %d images\n", Ndel);
  if (Ndel == 0) { 
    fprintf (stderr, "SUCCESS\n");
    gfits_db_close (db);
    exit (0);
  }

  /* create new data list */
  Nsubset = Nimage - Ndel;
  ALLOCATE (subset, RegImage, MAX (1, Nsubset));
  fprintf (stderr, "keeping %d images\n", Nsubset);
  for (j = i = 0; i < Nimage; i++) {
    if (!keep[i]) continue;
    subset[j] = image[i];
    j++;
  }

  free (keep);
  free (image);

  /** we may later want to pull this out and put it elsewhere **/
  /** free db[0].theader, db[0].table.buffer? **/
  gfits_table_set_RegImage (&db[0].ftable, subset, Nsubset);
  gfits_db_save (db);
  gfits_db_close (db);
  gfits_db_free (db);

  fprintf (stderr, "SUCCESS\n");
  exit (0);

}
