# include "addstar.h"

dimages (FILE *f, Image *image, int Nimages) {
  
  int i, j, Ntimage, ntimage, mode;
  int start, end, tstart, tend, status;
  char line[256];
  struct stat filestat;
  Image *timage;
  Header header;

  /* use cp to make backup copy */
  sprintf (line, "cp %s %s~\0", ImageCat, ImageCat);
  status = system (line);
  if (status) {
    fprintf (stderr, "ERROR: unable to create %s~, exiting\n", ImageCat);
    Shutdown ();
  }
  mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
  sprintf (line, "%s~\0", ImageCat);
  chmod (line, mode);

  /* check if image datafile exists, get header */
  fseek (f, 0, SEEK_SET); 
  if (!fits_fread_header (f, &header)) {
    fprintf (stderr, "Can't find image catalog\n");
    exit (1);
  }
  fseek (f, header.size, SEEK_SET); 

  fits_scan (&header, "NIMAGES", "%d", 1, &Ntimage);
  ALLOCATE (timage, Image, Ntimage);
  ntimage = Fread (timage, sizeof(Image), Ntimage, f, "image");
  if (Ntimage != ntimage) {
    fprintf (stderr, "failed to read in entire image file %s\n", ImageCat);
    exit (1);
  }

  /* need to delete on basis of both image time & photcode */
  /* first, mark the deleted images with a flag (NX = 0) */
  for (i = 0; i < Ntimage; i++) {
    for (j = 0; j < Nimages; j++) {
      tstart = timage[i].tzero;
      tend = timage[i].tzero + timage[i].trate * timage[i].NY;
      start = image[j].tzero;
      end = image[j].tzero + image[j].trate * image[j].NY;
      if ((tstart <= end) && (tend >= start) && (timage[i].source == image[j].source)) {
	fprintf (stderr, "deleting %s\n", timage[i].name);
	timage[i].NX = 0;
      }
    }
  }

  /* delete the marked images */
  for (i = 0, j = 0; j < Ntimage; j++) {
    if (timage[j].NX) {
      if (i != j) {
	timage[i] = timage[j];
      }
      i++;
    }
  }
  Ntimage = i;
  REALLOCATE (timage, Image, Ntimage);
  fits_modify (&header, "NIMAGES", "%d", 1, Ntimage);

  /* should make a backup copy of the ImageCat file */
  fseek (f, 0, SEEK_SET);
  Fwrite (header.buffer, 1, header.size, f, "char");
  Fwrite (timage, sizeof(Image), Ntimage, f, "image");

}
