# include "Ximage.h"
# define NPALETTE 9

int PPMit () {

  FILE *f;
  int pixval[NPALETTE], red[NPALETTE], blue[NPALETTE], green[NPALETTE];
  XColor color;
  int dx, dy;
  int i, j, k, m, found;
  XImage *tmpimage;
  unsigned long pixel;
  char filename[1024];
  int Nbytes, status;
  char *buffer;

  XWindowAttributes WindowAttributes;
  Pixmap tmp_pixmap;
  Window tmp_window;
  
  dx = graphic.dx;
  dy = graphic.dy;
  
  /* expect a line telling the number of bytes and a filename */
  status = read (sock, filename, 16);
  filename[16] = 0;
  sscanf (filename, "%*s %d", &Nbytes);
  status = read (sock, filename, Nbytes);
  filename[status] = 0; /* make the string easy to parse */

  ALLOCATE (buffer, char, 3*dx*dy);

  /* define the palette */
  for (i = 0; i < NPALETTE; i++) {
    color.pixel = graphic.color[i];
    XQueryColor (graphic.display, graphic.colormap, &color);
    red[i]     = (color.red >> 8);
    green[i]   = (color.green >> 8);
    blue[i]    = (color.blue >> 8);
    pixval[i]  = color.pixel;
  }

  f = fopen (filename, "w");
  if (f == (FILE *) NULL) {
    fprintf (stderr, "can't open output file %s\n", filename);
    return (TRUE);  /* true because otherwise it quits kapa! */
  }
  
  fprintf (f, "P6\n");
  fprintf (f, "%d %d\n", dx, dy);
  fprintf (f, "255\n");

  XGetWindowAttributes (graphic.display, graphic.window, &WindowAttributes);
  
  tmp_pixmap = XCreatePixmap (graphic.display, graphic.window, dx, dy, WindowAttributes.depth);
  
  tmp_window = graphic.window;
  graphic.window = tmp_pixmap;
  
  Refresh (1);
  
  tmpimage = XGetImage (graphic.display, graphic.window, 0, 0, dx, dy, 0xffffffff, ZPixmap);
  for (m = j = 0; j < dy; j++) {
    for (i = 0; i < dx; i++, m+=3) {
      pixel = XGetPixel (tmpimage, i, j);
      for (found = k = 0; (k < NPALETTE) && !found; k++) {
	if (pixel == pixval[k]) {
	  found = TRUE;
	  buffer[m+0] = red[k];
	  buffer[m+1] = green[k];
	  buffer[m+2] = blue[k];
	}
      }
    }
  }
  graphic.window = tmp_window;
  XFreePixmap (graphic.display, tmp_pixmap);

  fwrite (buffer, 3, dx*dy, f);

  XDestroyImage (tmpimage);

  fclose (f);
  return (TRUE);

}
