# include "Ximage.h"

int LoadPicture (int sock) {

  Header header;
  char *buff;
  int status, bytes_left;
  Section *section;
  KapaImageWidget *image;
  Graphic *graphic;

  graphic = GetGraphic ();
  section = GetActiveSection();
  if (section->image == NULL) {
    section->image = InitImage ();
    SetSectionSizes (section);
  }
  image = section->image;
  
  KiiSendMessage (sock, "%d", graphic->Npixels);

  header.Naxes = 2;
  KiiScanMessage (sock, "%d %d %d %d %lf %lf", &header.Naxis[0], &header.Naxis[1]);
  KiiScanMessage (sock, "%d %d %d %d %lf %lf", &header.bitpix, &header.unsign, &header.bzero, &header.bscale);
  KiiScanMessage (sock, "%lf %lf %s",  &image[0].zero, &image[0].range, image[0].name, image[0].file);
  KiiScanMessage (sock, "%lf %lf %d", &image[0].min,  &image[0].max, &header.size);
  KiiScanMessage (sock, "%lf %f %f %f %f", &image[0].coords.crval1, &image[0].coords.crpix1, &image[0].coords.cdelt1, &image[0].coords.pc1_1, &image[0].coords.pc1_2);
  KiiScanMessage (sock, "%lf %f %f %f %f", &image[0].coords.crval2, &image[0].coords.crpix2, &image[0].coords.cdelt2, &image[0].coords.pc2_1, &image[0].coords.pc2_2);
  KiiScanMessage (sock, "%s", image[0].coords.ctype);

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

  fcntl (sock, F_SETFL, O_NONBLOCK);  

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

  fcntl (sock, F_SETFL, !O_NONBLOCK);  

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

  if (!USE_XWINDOW) return (TRUE);

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

  return (TRUE);
}
