# include "delstar.h"

int *find_images_name (FITS_DB *db, char *filename, int *nlist) {

  int i, Nimage, Nlist, NLIST;
  int *list;
  char *p, *name;
  Image *image;

  /* strip off all but the filename */
  p = strrchr (filename, '/');
  if (p == NULL) {
    name = filename;
  } else {
    name = p + 1;
  }

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

  Nlist = 0;
  NLIST = 100;
  ALLOCATE (list, int, NLIST);

  for (i = 0; i < Nimage; i++) {
    if (strcmp (image[i].name, name)) continue;
    list[Nlist] = i;
    Nlist ++;
    CHECK_REALLOCATE (list, int, NLIST, Nlist, 100);
  }

  *nlist = Nlist;
  return (list);
}

/* find images in db by image data (time/photcode) */
int *find_images_data (FITS_DB *db, Image *timage, int *nlist) {

  int i, Nimage, Nlist, NLIST; 
  int *list;
  Image *image;
  time_t start, stop;
  int code;

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

  start = timage[0].tzero - MAX(0.05*timage[0].trate*timage[0].NY, 1);
  stop  = timage[0].tzero + MAX(1.05*timage[0].trate*timage[0].NY, 1);
  code  = timage[0].source;

  Nlist = 0;
  NLIST = 100;
  ALLOCATE (list, int, NLIST);

  for (i = 0; i < Nimage; i++) {
    if (image[i].tzero < start) continue;
    if (image[i].tzero > stop) continue;
    if (image[i].source != code) continue;
    list[Nlist] = i;
    Nlist ++;
    CHECK_REALLOCATE (list, int, NLIST, Nlist, 100);
  }

  *nlist = Nlist;
  return (list);
}

/* find images in db by image data (time/photcode) */
int *find_images_time (FITS_DB *db, time_t start, time_t end, PhotCode *code, int *nlist) {

  int i, Nimage, Nlist, NLIST;
  int *list;
  Image *image;

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

  Nlist = 0;
  NLIST = 100;
  ALLOCATE (list, int, NLIST);

  for (i = 0; i < Nimage; i++) {
    if (image[i].tzero < START) continue;
    if (image[i].tzero > END) continue;
    if (code != NULL) {
      if (image[i].source != code[0].code) continue;
    }
    list[Nlist] = i;
    Nlist ++;
    CHECK_REALLOCATE (list, int, NLIST, Nlist, 100);
  }

  *nlist = Nlist;
  return (list);
}

