# include "delstar.h"

void delete_imagename (FITS_DB *db, char *name) {

  int i, j, k;
  int Nimlist, Nimage;
  int *imlist;
  double trange;
  time_t start, stop;
  Image *image;
  Catalog catalog;
  SkyList *skylist;
  SkyTable *sky;

  /* load sky from correct table */
  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");

  image = gfits_table_get_Image (&db[0].ftable, &Nimage, &db[0].swapped);

  /* find image in db by name */
  imlist = find_images_name (db, name, &Nimlist);
  if (!Nimlist) Shutdown ("image %s not found in db", name);
  
  for (k = 0; k < Nimlist; k++) {

    j = imlist[k];
    if (VERBOSE) fprintf (stderr, "deleting %s\n", image[j].name);
    
    // XXX EAM : need to handle failure
    FindMosaicForImage (image, Nimage, j);
    skylist = SkyListByImage (sky, -1, &image[j]);

    for (i = 0; i < skylist[0].Nregions; i++) {
      if (VERBOSE) fprintf (stderr, "deleting from %s\n", skylist[0].filename[i]);
      catalog.filename = skylist[0].filename[i];  /* don't free region before catalog! */
      catalog.Nsecfilt  = GetPhotcodeNsecfilt ();
      catalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_MISS | LOAD_SECF;

      // an error exit status here is a significant error
      if (!dvo_catalog_open (&catalog, skylist[0].regions[i], VERBOSE, "a")) {
	fprintf (stderr, "ERROR: failure to open catalog file %s\n", catalog.filename);
	exit (2);
      }
      if (!catalog.Nave_disk) {
	dvo_catalog_unlock (&catalog);
	dvo_catalog_free (&catalog);
	continue;
      }

      /* trate is in 0.1 msec / row  - stop is the latest exposure end time */
      /* pad exposure time by 1 sec to require a valid time */
      trange = 1e-4*image[j].NY*image[j].trate + image[j].exptime + 1;  
      start = image[j].tzero;
      stop  = image[j].tzero + trange;
      find_matches (&catalog, image[j].source, start, stop);

      dvo_catalog_save (&catalog, VERBOSE);
      dvo_catalog_unlock (&catalog);
      dvo_catalog_free (&catalog);
    }
  }

  /* delete the identified images */
  gfits_vtable_from_ftable (&db[0].ftable, &db[0].vtable, imlist, Nimlist);
  dvo_image_update (db, VERBOSE);
  dvo_image_unlock (db);

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