# include "dvo.h"

int pcat (int argc, char **argv) {
  
  double Radius;
  int i, j, N, Nregions, ShowAll, NPTS, Npts;
  RegionFile *regions;
  char filename[128];
  struct stat filestat;
  Vector Xvec, Yvec;
  Graphdata graphmode;
  double X[4], Y[4];
  char catdir[256];
  int Ngraph;

  VarConfig ("CATDIR", "%s", catdir);

  ShowAll = FALSE;
  if (N = get_argument (argc, argv, "-all")) {
    remove_argument (N, &argc, argv);
    ShowAll = TRUE;
  }
  if (argc != 1) {
    fprintf (stderr, "USAGE: pcat [-all]\n");
    return (FALSE);
  }
  Ngraph = 0;
  if (!GetGraph (&graphmode, NULL, &Ngraph)) return (FALSE);
  
  Radius = MAX (fabs(graphmode.xmax), fabs(graphmode.ymax));
  regions = find_regions (graphmode.coords.crval1, graphmode.coords.crval2, Radius, &Nregions);

  NPTS = 200;
  ALLOCATE (Xvec.elements, float, NPTS);
  ALLOCATE (Yvec.elements, float, NPTS);
  Npts = 0;
   
  for (i = 0; i < Nregions; i++) {
    sprintf (filename, "%s/%s", catdir, regions[i].name);
    if (ShowAll || (stat (filename, &filestat) != -1)) {
      fprintf (stderr, "%3d %s\n", i, regions[i].name);
      RD_to_XY (&X[0], &Y[0], regions[i].RA0, regions[i].DEC0, &graphmode.coords);
      RD_to_XY (&X[1], &Y[1], regions[i].RA0, regions[i].DEC1, &graphmode.coords);
      RD_to_XY (&X[2], &Y[2], regions[i].RA1, regions[i].DEC1, &graphmode.coords);
      RD_to_XY (&X[3], &Y[3], regions[i].RA1, regions[i].DEC0, &graphmode.coords);
      for (j = 0; j < 4; j++) {
	Xvec.elements[Npts + j*2] = X[j];
	Yvec.elements[Npts + j*2] = Y[j];
	if (j > 0) {
	  Xvec.elements[Npts+2*j - 1] = Xvec.elements[Npts+2*j];
	  Yvec.elements[Npts+2*j - 1] = Yvec.elements[Npts+2*j];
	}
      }
      Xvec.elements[Npts+7] = Xvec.elements[Npts];
      Yvec.elements[Npts+7] = Yvec.elements[Npts];
      Npts += 8;
      if (Npts > NPTS - 1) {  /* this is OK because NPTS is made always a multiple of 8 */
	NPTS += 200;
	REALLOCATE (Xvec.elements, float, NPTS);
	REALLOCATE (Yvec.elements, float, NPTS);
      }
    }
  }

  fprintf (stderr, "plotting %d catalogs\n", Npts/8);
  Xvec.Nelements = Xvec.Nelements = Npts;
  if (Npts > 0) {
    graphmode.style = 2; /* points */
    graphmode.ptype = 100; /* connect pairs of points */
    graphmode.etype = 0;
    PrepPlotting (Npts, &graphmode);
    PlotVector (Npts, Xvec.elements);
    PlotVector (Npts, Yvec.elements);
  }

  free (Xvec.elements);
  free (Yvec.elements);
  free (regions);

  return (TRUE);

}
