# include "Ximage.h"
# define SCAN \
  status = read (layout[0].Ximage, buffer, 16); \
  buffer[16] = 0; \
  sscanf (buffer, "%*s %d", &Nbytes); \
  status = read (layout[0].Ximage, buffer, Nbytes); \
  buffer[status] = 0; /* make the string easy to parse */ \
  (DEBUG) && fprintf (stderr, "buffer: <%s>\n", buffer); \

int NewPicture (Graphic *graphic, Layout *layout) {

  Header header;
  char buffer[1024], *buff;
  int status, bytes_left, Nbytes;
 
  fits_free_matrix (&layout[0].matrix);
  sprintf (buffer, "NCOLOR: %6d ", layout[0].Npixels);
  write (layout[0].Ximage, buffer, 16);

  fcntl (layout[0].Ximage, F_SETFL, !O_NONBLOCK);  

  header.Naxes = 2;
  SCAN;
  sscanf (buffer, "%d %d %d %d %lf %lf",
	  &header.Naxis[0], &header.Naxis[1], &header.bitpix, 
	  &header.unsign,   &header.bzero,    &header.bscale);

  SCAN;
  sscanf (buffer, "%lf %lf %lf %lf %d", &layout[0].zero, &layout[0].range, &layout[0].min,  &layout[0].max, &header.size);

  SCAN;
  sscanf (buffer, "%lf %f %f %f %f", &layout[0].coords.crval1, &layout[0].coords.crpix1, &layout[0].coords.cdelt1, &layout[0].coords.pc1_1, &layout[0].coords.pc1_2);
	  
  SCAN;
  sscanf (buffer, "%lf %f %f %f %f", &layout[0].coords.crval2, &layout[0].coords.crpix2, &layout[0].coords.cdelt2, &layout[0].coords.pc2_1, &layout[0].coords.pc2_2);
	  
  SCAN;
  sscanf (buffer, "%s %s %s", layout[0].coords.ctype, layout[0].file, layout[0].buffer_name);

  fits_create_matrix (&header, &layout[0].matrix);

  fcntl (layout[0].Ximage, F_SETFL, O_NONBLOCK);  

  status = 1;
  buff = layout[0].matrix.buffer;
  bytes_left = header.size;
  layout[0].matrix.size = 0;
  while (bytes_left > 0) {
    status = read (layout[0].Ximage, buff, bytes_left);
    if (status == 0) {  /* No more pipe */
      fprintf (stderr, "error: pipe closed\n");
      return (FALSE);
    }
    if (status != -1) { /* pipe has data */
      layout[0].matrix.size += status;
      bytes_left -= status;
      buff = (char *)(buff + status);
    }
  }

  (DEBUG) && fprintf (stderr, "read %d bytes\n", layout[0].matrix.size);
  /* it it not obvious this condition should kill kii, but ... */
  if (layout[0].matrix.size != header.size) {  
    fprintf (stderr, "error: expected %d bytes, but got only %d\n", header.size, layout[0].matrix.size);
    return (FALSE);
  }

  Remap (graphic, layout, &layout[0].matrix);
  (DEBUG) && fprintf (stderr, "remapped image\n");
  Refresh (graphic, layout, 0);
  
  (DEBUG) && fprintf (stderr, "refreshed\n");
  XFlush (graphic[0].display);

  return (TRUE);

}

/*
   layout[0].X = 0;
   layout[0].Y = 0;
   layout[0].expand = 1;
*/
  
