# include "Ximage.h"

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

  Header header;
  char *buff;
  int status, bytes_left, socket;
 
  socket = layout[0].Ximage;

  KiiSendMessage (socket, "%d", layout[0].Npixels);

  fcntl (socket, F_SETFL, !O_NONBLOCK);  

  header.Naxes = 2;

  KiiScanMessage (socket, "%d %d %d %d %lf %lf", &header.Naxis[0], &header.Naxis[1]);
  KiiScanMessage (socket, "%d %d %d %d %lf %lf", &header.bitpix, &header.unsign, &header.bzero, &header.bscale);
  KiiScanMessage (socket, "%lf %lf",  &layout[0].zero, &layout[0].range);
  KiiScanMessage (socket, "%lf %lf %d", &layout[0].min,  &layout[0].max, &header.size);
  KiiScanMessage (socket, "%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);
  KiiScanMessage (socket, "%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);
	  
  KiiScanMessage (socket, "%s %s %s", layout[0].coords.ctype, layout[0].file, layout[0].buffer_name);

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

  fcntl (socket, 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 (socket, 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);
    }
  }

  if (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);
  }

  if (!USE_XWINDOW) return (TRUE);

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

  return (TRUE);

}

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