# include "delstar.h"

Image *gtimes (FILE *f, char **argv, int *NIMAGE, int *START, int *END) {
 
  int i, npimage, NPIMAGE, ntimage, Ntimage, NTIMAGE, Nimage;
  int start, end, range, tstart, tend;
  double Ra, Dec;
  Image *pimage, *timage;
  Header header;

  start = atof(argv[1]);
  range = atof(argv[2]);
  if (range < 2) {
    start = start - 1;
    range = 2;
  }
  end = start + range;
  *START = start;
  *END = end;

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

  Nimage = 0;
  fits_scan (&header, "NIMAGES", "%d", 1, &Nimage);

  NTIMAGE = 100;
  ALLOCATE (timage, Image, NTIMAGE);

  npimage = 0;
  NPIMAGE = 20;
  ALLOCATE (pimage, Image, NPIMAGE);

  for (Ntimage = 0; Ntimage < Nimage; Ntimage += ntimage) {
    ntimage = Fread (timage, sizeof(Image), NTIMAGE, f, "image");
    for (i = 0; i < ntimage; i++) {
      tstart = timage[i].tzero;
      tend = timage[i].tzero + 1e-4*timage[i].trate*timage[i].NY;
      if ((tstart <= end) && (tend >= start)) {
	pimage[npimage] = timage[i];
	npimage ++;
	if (npimage == NPIMAGE) {
	  NPIMAGE += 20;
	  REALLOCATE (pimage, Image, NPIMAGE);
	}
      }
    }
  }
  free (timage);

  fprintf (stderr, "found the following images:\n");
  for (i = 0; i < npimage; i++) {
    XY_to_RD (&Ra, &Dec, 0.5*pimage[i].NX, 0.5*pimage[i].NY, &pimage[i].coords);
    fprintf (stderr, "%3d %s %8.4f %8.4f %d %d\n", i, pimage[i].name, Ra, Dec,
	     pimage[i].tzero, pimage[i].nstar);
  }

  *NIMAGE = npimage;
  return (pimage);

}
