# include "dvoshell.h"
extern double drand48();

int imdense (int argc, char **argv) {
  
  long A, B;
  int i, kapa, N, Nimage, status, NPTS;
  double r, d, x, y, Rmin, Rmax;
  Vector Xvec, Yvec;
  Image *image;
  Graphdata graphmode;

  if (!style_args (&graphmode, &argc, argv, &kapa)) return FALSE;

  /* need options to list only images in region and only images in a time range */
  /* also, option to list and not plot or plot and not list images */
  if (argc != 1) {
    gprint (GP_ERR, "USAGE: image\n");
    return (FALSE);
  }

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

  Rmin = graphmode.coords.crval1 - 182.0;
  Rmax = graphmode.coords.crval1 + 182.0;
  
  A = time(NULL);
  for (B = 0; A == time(NULL); B++);
  srand48(B);

  NPTS = 200;
  ALLOCATE (Xvec.elements, float, NPTS);
  ALLOCATE (Yvec.elements, float, NPTS);
  N = 0;
  for (i = 0; i < Nimage; i++) {
    /* choose a position for point within image box */
    x = (0.1 + 0.9*drand48()) * image[i].NX;
    y = (0.1 + 0.9*drand48()) * image[i].NY;
    /* project this image to screen display coords */
    status = FALSE;
    if (!FindMosaicForImage (image, Nimage, i)) continue;
    XY_to_RD (&r, &d, x, y, &image[i].coords);
    r = ohana_normalize_angle (r);
    while (r < Rmin) r += 360.0; 
    while (r > Rmax) r -= 360.0; 
    status |= fRD_to_XY (&Xvec.elements[N], &Yvec.elements[N], r, d, &graphmode.coords);
    if ((Xvec.elements[N] >= graphmode.xmin) && 
	(Xvec.elements[N] <= graphmode.xmax) && 
	(Yvec.elements[N] >= graphmode.ymin) && 
	(Yvec.elements[N] <= graphmode.ymax) && status) {
      N++;
      if (N > NPTS - 1) { 
	NPTS += 200;
	REALLOCATE (Xvec.elements, float, NPTS);
	REALLOCATE (Yvec.elements, float, NPTS);
      }
    }
  }

  Xvec.Nelements = Xvec.Nelements = N;
  if (N > 0) {
    graphmode.style = 2; /* points */
    graphmode.etype = 0;
    PlotVectorPair (kapa, N, Xvec.elements, Yvec.elements, &graphmode);
  }

  free (Xvec.elements);
  free (Yvec.elements);
  free (image);
  return (TRUE);

}


