# include "dvoshell.h"

int imstats (int argc, char **argv) {
  
  int i, Nimage, N;
  int Mcal, AutoLimits, Ngraph;
  double r, d;
  Image *image;
  Vector Xvec, Yvec;  
  Graphdata graphmode;

  Ngraph = -1;
  if ((N = get_argument (argc, argv, "-n"))) {
    remove_argument (N, &argc, argv);
    Ngraph = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if (!GetGraph (&graphmode, NULL, &Ngraph)) return (FALSE);

  Mcal = TRUE;
  if ((N = get_argument (argc, argv, "-dM"))) {
    remove_argument (N, &argc, argv);
    Mcal = FALSE;
  }

  AutoLimits = FALSE;
  if ((N = get_argument (argc, argv, "-l"))) {
    remove_argument (N, &argc, argv);
    AutoLimits = TRUE;
  }

  if (argc != 1) {
    gprint (GP_ERR, "USAGE: imstats [-dM] [-l]\n");
    return (FALSE);
  }

  if ((image = LoadImages (&Nimage)) == NULL) return (FALSE);
  BuildChipMatch (image, Nimage);

  /* assign vector values */
  Xvec.Nelements = Nimage;
  Yvec.Nelements = Nimage;
  ALLOCATE (Xvec.elements, float, Xvec.Nelements);
  ALLOCATE (Yvec.elements, float, Yvec.Nelements);
  gprint (GP_LOG, "seq  ra (J2000) dec    time (s)   Nstars\n");
  for (i = 0; i < Nimage; i++) {
    Xvec.elements[i] = image[i].secz_PS;
    if (Mcal) 
      Yvec.elements[i] = image[i].Mcal_PS;
    else 
      Yvec.elements[i] = image[i].dMcal_PS;
    if (!FindMosaicForImage (image, Nimage, i)) continue;
    XY_to_RD (&r, &d, 0.5*image[i].NX, 0.5*image[i].NY, &image[i].coords);
    gprint (GP_ERR, "%d %8.4f %8.4f %10d %6d  %5.3f %6.3f %6.3f\n", 
	     i, r, d, image[i].tzero, image[i].nstar, Xvec.elements[i], 
	     image[i].Mcal_PS, image[i].dMcal_PS);
  } 
  if (AutoLimits) SetLimits (&Xvec, &Yvec, &graphmode);

  graphmode.style = 2;
  graphmode.etype = 0;
  PrepPlotting (Nimage, &graphmode);
  PlotVector (Nimage, Xvec.elements);
  PlotVector (Nimage, Yvec.elements);
  
  free (Xvec.elements);
  free (Yvec.elements);
  return (TRUE);
}

