# include "dvo.h"

static int badim_int = FALSE;
void badim_escape () {
  badim_int = TRUE;
}

int badimages (int argc, char **argv) {
  
  FILE *f;
  int i, Nimage, nimage, entry, First, Cross;
  float *ptr;
  double nominal, big, small, value;
  Header header;
  Image *image;
  char ImageCat[256];

  VarConfig ("IMAGE_CATALOG", "%s", ImageCat);
  
  if (argc != 3) {
    fprintf (stderr, "USAGE: badimages entry value\n");
    fprintf (stderr, "   OR: badimages -image N\n");
    return (FALSE);
  }
  
  First = FALSE;
  if (!strcmp (argv[1], "-image")) {
    First = TRUE;
    entry = atof(argv[2]);
  } else {
    entry = atof(argv[1]);
    nominal = atof(argv[2]);
    Cross = FALSE;
    if (!strcasecmp (argv[1], "x")) {
      Cross = TRUE;
    }
  }
  
  /* check if image datafile exists, get header */
  if (!fits_read_header (ImageCat, &header)) {
    fprintf (stderr, "can't open image catalog %s\n", ImageCat);
    return (FALSE);
  }
  
  /* get ready to read data on images */ 
  f = fopen (ImageCat, "r");
  if (f == (FILE *) NULL) {
    fprintf (stderr, "can't open image catalog %s\n", ImageCat);
    return (FALSE);
  }
  fseek (f, header.size, SEEK_SET); 
  
  /* read in image data */
  Nimage = 0;
  fits_scan (&header, "NIMAGES", "%d", 1, &Nimage);
  ALLOCATE (image, Image, Nimage);
  nimage = Fread (image, sizeof(Image), Nimage, f, "image");
  fclose (f);
  if (nimage != Nimage) {
    fprintf (stderr, "error reading all data from image file (%d != %d)\n", nimage, Nimage);
    free (image);
    return (FALSE);
  }
  
  if (First) {
    ptr = &image[entry].coords.crpix1;
    for (i = 0; i < 22; i++) {
      fprintf (GetOutfile(), "%2d: %g\n", i, ptr[i]);
    }
    value = image[entry].coords.pc1_1*image[entry].coords.pc2_2 + image[entry].coords.pc1_2*image[entry].coords.pc2_1;
    fprintf (GetOutfile(), " x: %g\n", value);
    return (TRUE);
  }
  
  big = nominal * 1.05;
  small = nominal / 1.05;
  if (big < small) {
    double tmp;
    tmp = big; big = small; small = tmp;
  }
  
  badim_int = FALSE;
  if (Cross) {
    for (i = 0; (i < Nimage) && !badim_int; i++) {
      value = image[i].coords.pc1_1*image[i].coords.pc2_2 + image[i].coords.pc1_2*image[i].coords.pc2_1;
      if ((value > big) || (value < small)) {
	fprintf (GetOutfile(), "%5d %s: %d %g\n", i, image[i].name, image[i].tzero, value);
      }
    }
  } else {
    for (i = 0; (i < Nimage) && !badim_int; i++) {
      ptr = &image[i].coords.crpix1;
      if ((ptr[entry] > big) || (ptr[entry] < small)) {
	fprintf (GetOutfile(), "%5d %s: %d %g\n", i, image[i].name, image[i].tzero, ptr[entry]);
      }
    }
  }
  
  return (TRUE);

}
  
