/* write_jpg_file.c   color jpg */

static void write_jpg_file(char filename[])
{
  XImage * my_image;
  int this_bit;
  long int my_pixel;
  unsigned char my_buffer[3600]; /* one scan line in RGB */
  JSAMPLE * image_buffer=(JSAMPLE *)my_buffer;
  int image_width=frame_xmax-frame_xmin-1;  /* Number of columns in image */
  int image_height=frame_ymax-frame_ymin-1; /* Number of rows in image */
  int input_components=3;             /* RGB = 3 */
  int in_color_space=JCS_RGB;         /* color */
  int quality=95;
  int i, j;
  struct jpeg_compress_struct cinfo;
  struct jpeg_error_mgr jerr;
  FILE * outfile;		/* target file */
  JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */

  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_compress(&cinfo);

  if ((outfile = fopen(filename, "wb")) == NULL)
  {
    fprintf(stderr, "can't open %s\n", filename );
    XtManageChild(f_dialog);
    return;
  }

  my_image = XGetImage(XtDisplay(draw_a), XtWindow(draw_a),
		       frame_xmin+1, frame_ymin+1,
                       frame_xmax-frame_xmin-1, frame_ymax-frame_ymin-1,
                       0xFFFFFF, XYPixmap);
  if(my_image == NULL)
  {
    printf("can't get my_image\n");
    XtManageChild(f_dialog);
    return;
  }
  jpeg_stdio_dest(&cinfo, outfile);
  cinfo.image_width = image_width; 	     /* image width and height, in pixels */
  cinfo.image_height = image_height;
  cinfo.input_components = input_components; /* # of color components per pixel */
  cinfo.in_color_space = in_color_space;     /* colorspace of input image */

  jpeg_set_defaults(&cinfo);
  jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
  jpeg_start_compress(&cinfo, TRUE);
  row_pointer[0] = & my_buffer[0]; /* keep refilling */
  i=0;
  while (cinfo.next_scanline < cinfo.image_height) {
      for(j=0; j<image_width; j++)
      {
        my_pixel = XGetPixel(my_image, j, i);
#ifdef XBITS
        my_buffer[3*j]=  (my_pixel>>11)<<3;        /* R */
        my_buffer[3*j+1]=((my_pixel>>4)&0x3F)<<2 ; /* G */
        my_buffer[3*j+2]=((my_pixel)&0x1F)<<3 ;    /* B */
        printf("16bit i=%d, j=%d, R=%X G=%X B=%X \n", i, j,
	       my_buffer[3*j], my_buffer[3*j+1], my_buffer[3*j+2]);

#else
        my_buffer[3*j]=  my_pixel>>16;        /* R */
        my_buffer[3*j+1]=(my_pixel>>8)&0xFF ; /* G */
        my_buffer[3*j+2]=(my_pixel)&0xFF ;    /* B */
#endif
      }
      (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
      i++;
  }
  jpeg_finish_compress(&cinfo);
  fclose(outfile);
  jpeg_destroy_compress(&cinfo);
} /* end write_jpg_file */


