/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	Adresse mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)

	E-mail address:
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/
#include "dumpToPsAndPdf.h"

#include "dumpToGif.h"

#define _XOPEN_SOURCE_EXTENDED
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
/* #include <unistd.h> */
#include <sys/types.h>

#include <visu_tools.h>

#include <glib.h>

/**
 * SECTION:dumpToPsAndPdf
 * @short_description: add an export capability into PS and PDF files
 * (encapsulating bitmaps).
 *
 * This provides a write routine to export V_Sim views into bitmaps
 * encapsulated into PS or PDF files. The PostScript file can be
 * either in 256 colours or in full True Color. For a vectorial
 * export, see #dumpToSVG.
 */

static void PrintByte(unsigned long lcode);
static void OutputCode(int code);

static unsigned long accumulator;
static int cnt, code_width, bits;

static FILE *out;
static unsigned char *image;
static Image *img;
static int PSwidth, PSheight;

static gpointer waitData;
static ToolVoidDataFunc waitFunc;


static gboolean writeViewInPsFormat(ToolFileFormat *format, const char* filename,
                                    VisuGlNodeScene *scene, guint width, guint height,
                                    GError **error, ToolVoidDataFunc functionWait,
                                    gpointer data);
static gboolean writeViewInPs256Format(const char* filename,
				       int width, int height,
				       guchar* imageData, GError **error,
				       ToolVoidDataFunc functionWait, gpointer data);
static gboolean writePsTrueColor(const char* filename,
				 int width, int height,
				 guchar* imageData, GError **error,
				 ToolVoidDataFunc functionWait, gpointer data);
static gboolean writeViewInPdfFormat(ToolFileFormat *format, const char* filename,
                                     VisuGlNodeScene *scene, guint width, guint height,
                                     GError **error, ToolVoidDataFunc functionWait,
                                     gpointer data);

static VisuDump *ps;
const VisuDump* visu_dump_bitmap_ps_getStatic()
{
  const gchar *typePS[] = {"*.ps", (char*)0};
  #define descrPS _("Bitmap in a postscript (v3.0) file")

  if (ps)
    return ps;

  ps = VISU_DUMP(visu_dump_scene_new(descrPS, typePS, writeViewInPsFormat, FALSE));

  waitFunc = (ToolVoidDataFunc)0;
  waitData = (gpointer)0;

  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ps), "reduced_colormap",
                                      _("Use a reduced colormap (256 colors)"), FALSE);
  
  return ps;
}
static VisuDump *pdf;
const VisuDump* visu_dump_bitmap_pdf_getStatic()
{
  const gchar *typePDF[] = {"*.pdf", (char*)0};
#define descrPDF _("Bitmap in a PDF (v. 1.2)")

  if (pdf)
    return pdf;

  pdf = VISU_DUMP(visu_dump_scene_new(descrPDF, typePDF, writeViewInPdfFormat, FALSE));

  waitFunc = (ToolVoidDataFunc)0;
  waitData = (gpointer)0;

  return pdf;
}

/******************************************************************************/

static void PrintByte(unsigned long lcode) {

         
    int ii;
         
    ii = lcode%256ul;
    
    (void)fprintf(out, "%02x", ii);     
    cnt = cnt + 2;
    if(cnt == 78) {
       (void)fprintf(out, "\n");
       cnt = 0;
    }
      
}

/******************************************************************************/

static void OutputCode(int code) {
         
   unsigned long lcode;
         
   lcode = code;
      
   accumulator = accumulator + (lcode << (32 - code_width - bits));
   bits = bits + code_width;
   for(;;) {
      if(bits < 8) {
         break;
       }
       PrintByte(accumulator >> 24);
       accumulator = accumulator << 8;
       bits = bits - 8;
   }
      
}

/******************************************************************************/

static void OutputData() {
         
#define LZWClr 256
#define LZWEod 257
   int prefix[4096], suffix[4096], next[4096];
   int idx, next_idx, last_code;
   int i;
         
   accumulator = 0ul;
   cnt = 0;
   code_width = 9;
   bits = 0; 
   OutputCode(LZWClr);
         
   for(idx = 0; idx < 256; idx++) {
      prefix[idx] = -1;
      suffix[idx] = idx;
      next[idx] = -1;
   }
  
   next_idx = LZWEod + 1;
   code_width = 9;
   last_code = image[0];
   
   for(i = 1; i<3*PSwidth*PSheight; i++) {

     if (waitFunc && i % (3*PSwidth*PSheight / 100) == 0)
       waitFunc(waitData);

      idx = last_code;
      for(;;) {
         if(idx == -1) {
            break;
         }
         if ( (prefix[idx] != last_code) ||
              (suffix[idx] != image[i]) ) {
            idx = next[idx];
         }
         else { 
            last_code = idx;
            break;
         }
      }
      if ( last_code != idx ) {
         OutputCode(last_code);
         prefix[next_idx] = last_code;
         suffix[next_idx] = image[i];
         next[next_idx] = next[last_code];
         next[last_code] = next_idx;
         next_idx = next_idx + 1;
         if ( (next_idx >> code_width) != 0 ) {
            code_width = code_width + 1;
            if ( code_width > 12 ) {
               code_width = code_width - 1;
               OutputCode(LZWClr);
               for(idx = 0; idx < 256; idx++) {
                  prefix[idx] = -1;
                  suffix[idx] = idx;
                  next[idx] = -1;
               }
               next_idx = LZWEod + 1;
               code_width = 9;
            }
         }
         last_code = image[i];
      }
   }
         
   OutputCode(last_code);
   OutputCode(LZWEod);
   if ( bits != 0 ) {
      PrintByte(accumulator >> 24);
   }
}

/******************************************************************************/

static void OutputDataPS256() {
         
#define LZWClr 256
#define LZWEod 257
   int prefix[4096], suffix[4096], next[4096];
   int idx, next_idx, last_code;
   guint i;
         
   accumulator = 0ul;
   cnt = 0;
   code_width = 9;
   bits = 0; 
   OutputCode(LZWClr);
         
   for(idx = 0; idx < 256; idx++) {
      prefix[idx] = -1;
      suffix[idx] = idx;
      next[idx] = -1;
   }
  
   next_idx = LZWEod + 1;
   code_width = 9;
   last_code = (img->pixels[0]).index;
   
   for(i = 1; i<img->columns*img->rows; i++) {

     if (waitFunc && i % (img->columns*img->rows / 100) == 0)
       waitFunc(waitData);

      idx = last_code;
      for(;;) {
         if(idx == -1) {
            break;
         }
         if ( (prefix[idx] != last_code) ||
              (suffix[idx] != (img->pixels[i]).index) ) {
            idx = next[idx];
         }
         else { 
            last_code = idx;
            break;
         }
      }
      if ( last_code != idx ) {
         OutputCode(last_code);
         prefix[next_idx] = last_code;
         suffix[next_idx] = (img->pixels[i]).index;
         next[next_idx] = next[last_code];
         next[last_code] = next_idx;
         next_idx = next_idx + 1;
         if ( (next_idx >> code_width) != 0 ) {
            code_width = code_width + 1;
            if ( code_width > 12 ) {
               code_width = code_width - 1;
               OutputCode(LZWClr);
               for(idx = 0; idx < 256; idx++) {
                  prefix[idx] = -1;
                  suffix[idx] = idx;
                  next[idx] = -1;
               }
               next_idx = LZWEod + 1;
               code_width = 9;
            }
         }
         last_code = (img->pixels[i]).index;
      }
   }
         
   OutputCode(last_code);
   OutputCode(LZWEod);
   if ( bits != 0 ) {
      PrintByte(accumulator >> 24);
   }
}

/******************************************************************************/

static gboolean writeViewInPsFormat(ToolFileFormat *format, const char* filename,
                                    VisuGlNodeScene *scene, guint width, guint height,
                                    GError **error, ToolVoidDataFunc functionWait _U_,
                                    gpointer data _U_)
{
  GArray *imageData;

  imageData = visu_gl_ext_set_getPixmapData(VISU_GL_EXT_SET(scene),
                                            width, height, FALSE);
  if (!imageData)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_OPENGL,
                           _("Can't dump OpenGL area to data.\n"));
      return FALSE;
    }

  if (tool_file_format_getPropertyBoolean(format, "reduced_colormap"))
    return writeViewInPs256Format(filename, width, height,
                                  (unsigned char*)imageData->data, error, functionWait, data);
  else
    return writePsTrueColor(filename, width, height,
                            (unsigned char*)imageData->data, error, functionWait, data);

  g_array_free(imageData, TRUE);
}

/******************************************************************************/

static gboolean writePsTrueColor(const char* filename,
				 int width, int height,
				 guchar* imageData, GError **error,
				 ToolVoidDataFunc functionWait _U_, gpointer data _U_)
{
  static int x = 10, y = 10;
  time_t timer;
  float facx, facy, fac;
  int wu, hu;
         
  g_return_val_if_fail(error && !*error, FALSE);
  g_return_val_if_fail(imageData, FALSE);

  image    = imageData;
  PSwidth  = width;
  PSheight = height;

  DBG_fprintf(stderr, "Dump PS & PDF : begin PS True ToolColor export in %dx%d : %s.\n",
	      width, height, filename);

  out = fopen(filename, "w");
  if(!out)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_FILE,
			   _("Cannot open file (to write in)."));
      return FALSE;
    }                  
   
   facx = (552.0f - x - 5)/PSwidth;
   facy = (796.0f - y - 5)/PSheight;
   if(facx < facy) {
      fac = facx;
   }
   else {
      fac = facy;
   }
   if(fac < 1.0f) {
      wu = PSwidth*fac + 1;
      hu = PSheight*fac + 1;
   }
   else {
      wu = PSwidth;
      hu = PSheight;
   }
         
   (void)fprintf(out, "%%!PS-Adobe-3.0\n");
   (void)fprintf(out, "%%%%Title: %s\n", filename);
   (void)fprintf(out, "%%%%Creator: v_sim (L. BILLARD)\n");
   timer = time((time_t *) NULL);
   (void)localtime(&timer);
   (void)fprintf(out, "%%%%CreationDate: %s",ctime(&timer));
   (void)fprintf(out, "%%%%For: %s\n", g_get_user_name());
   (void)fprintf(out, "%%%%LanguageLevel: 2\n");
   (void)fprintf(out, "%%%%DocumentData: Clean7Bit\n");
   (void)fprintf(out, "%%%%Orientation: Portrait\n");
   (void)fprintf(out, "%%%%BoundingBox: %d %d %d %d\n",
            x - 1, y - 1, x + wu + 1, y + hu + 1);
   (void)fprintf(out, "%%%%Pages: 1\n");
   (void)fprintf(out, "%%%%EndComments\n");
   (void)fprintf(out, "%%%%BeginProlog\n");
   (void)fprintf(out, "/ASCLZW {\n");
   (void)fprintf(out, "   /DeviceRGB setcolorspace\n");
   (void)fprintf(out, "   <</ImageType 1 /Width %d /Height %d "
                          "/BitsPerComponent 8\n", 
            PSwidth, PSheight);
   (void)fprintf(out, "     /Decode [0 1 0 1 0 1] "
                            "/ImageMatrix [%d 0 0 %d 0 %d]\n",
            PSwidth, -PSheight, PSheight);
   (void)fprintf(out, "     /DataSource currentfile /ASCIIHexDecode filter "
                            "/LZWDecode filter\n");
   (void)fprintf(out, "   >>image\n");
   (void)fprintf(out, "} bind def\n");
   (void)fprintf(out, "%%%%EndProlog\n");
   (void)fprintf(out, "%%%%Page: un 1\n");
   (void)fprintf(out, "gsave\n");
   (void)fprintf(out, "%d %d translate\n", x, y);
   (void)fprintf(out, "%f %f scale\n", 
            1.0*PSwidth, 1.0*PSheight);
   if(fac < 1.0f) {
      (void)fprintf(out, "%%Supplementary scaling to remain A4\n");
      (void)fprintf(out, "%f %f scale\n", fac, fac);
   }
   (void)fprintf(out, "ASCLZW\n");
   
   OutputData();
  
   (void)fprintf(out, ">\n");
   (void)fprintf(out, "grestore\n");
   (void)fprintf(out, "showpage\n");
   (void)fprintf(out, "%%%%PageTrailer\n");
   (void)fprintf(out, "%%%%Trailer\n");
   (void)fprintf(out, "%%%%EOF\n");
    
   (void)fclose(out);
  return TRUE;
}

/******************************************************************************/

static gboolean writeViewInPdfFormat(ToolFileFormat *format _U_, const char* filename,
				      VisuGlNodeScene *scene, guint width, guint height,
				      GError **error, ToolVoidDataFunc functionWait _U_,
                                      gpointer data _U_)
{
  GArray *imageData;
  time_t timer;
   
  struct tm *ltm;
  long int longueur;
  long int sz[10];
  int i;    
         
  g_return_val_if_fail(error && !*error, FALSE);

  imageData = visu_gl_ext_set_getPixmapData(VISU_GL_EXT_SET(scene),
                                            width, height, FALSE);
  if (!imageData)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_OPENGL,
                           _("Can't dump OpenGL area to data.\n"));
      return FALSE;
    }

  image      = (unsigned char*)imageData->data;
  PSwidth  = width;
  PSheight = height;

  DBG_fprintf(stderr, "Dump PS & PDF : begin PDF export in %dx%d : %s.\n",
	      width, height, filename);

  out = fopen(filename, "w");
  if(!out)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_FILE,
			   _("Cannot open file (to write in)."));
      return FALSE;
    }
                  
  timer = time((time_t *) NULL);
  ltm = localtime(&timer);
  (void)fprintf(out, "%%PDF-1.2\n");
  (void)fprintf(out, "%c%c%c%c\n", 202, 203, 204, 205);
   
  sz[1] = ftell(out);
  (void)fprintf(out, "1 0 obj\n");
  (void)fprintf(out, "<<\n");
  (void)fprintf(out, "/CreationDate (D:%04d%02d%02d%02d%02d%02d)\n",
		ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, 
		ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
  (void)fprintf(out, "/Producer (v_sim \\(L. BILLARD\\))\n");
  (void)fprintf(out, "/Author (%s)\n", g_get_real_name());
  (void)fprintf(out, "/Title (%s)\n", filename);
  (void)fprintf(out, ">>\n");
  (void)fprintf(out, "endobj\n");
   
  sz[2] = ftell(out);
  (void)fprintf(out, "2 0 obj\n");
  (void)fprintf(out, "<</Type/Catalog/Pages 3 0 R>>\n");
  (void)fprintf(out, "endobj\n");
   
  sz[3] = ftell(out);
  (void)fprintf(out, "3 0 obj\n");
  (void)fprintf(out, "<</Type/Pages/Kids[4 0 R]/Count 1>>\n");
  (void)fprintf(out, "endobj\n");
   
  sz[4] = ftell(out);
  (void)fprintf(out, "4 0 obj\n");
  (void)fprintf(out, "<<\n");
  (void)fprintf(out, "/Type/Page/MediaBox[0 0 %d %d]/Parent 3 0 R/Contents 5 0 R\n",
		PSwidth, PSheight);
  (void)fprintf(out, "/Resources<</ProcSet[/PDF/ImageC]/XObject<</IMG 7 0 R>>>>\n");
  (void)fprintf(out, ">>\n");
  (void)fprintf(out, "endobj\n");
   
  sz[5] = ftell(out);
  (void)fprintf(out, "5 0 obj\n");
  (void)fprintf(out, "<</Length 6 0 R>>\n");
  (void)fprintf(out, "stream\n");
  longueur = ftell(out);
  (void)fprintf(out, "q\n");
  (void)fprintf(out, "%4d 0 0 %4d 0 0 cm\n", PSwidth, PSheight);
  (void)fprintf(out, "/IMG Do\n");
  (void)fprintf(out, "Q\n");
  longueur = ftell(out) - longueur;
  (void)fprintf(out, "endstream\n");
  (void)fprintf(out, "endobj\n");
   
  sz[6] = ftell(out);
  (void)fprintf(out, "6 0 obj\n");
  (void)fprintf(out, "%ld\n", longueur);
  (void)fprintf(out, "endobj\n");
   
  sz[7] = ftell(out);
  (void)fprintf(out, "7 0 obj\n");
  (void)fprintf(out, "<<\n");
  (void)fprintf(out, "/Type/XObject/Subtype/Image/Name/IMG/Length"
                " 8 0 R/ToolColorSpace /DeviceRGB\n");
  (void)fprintf(out, "/Width %d/Height %d/BitsPerComponent"
                " 8/Filter[/ASCIIHexDecode/LZWDecode]\n",
		PSwidth, PSheight);
  (void)fprintf(out, ">>\n");
  (void)fprintf(out, "stream\n");
  longueur = ftell(out);
   
  OutputData();
  
  (void)fprintf(out, ">\n");
  longueur = ftell(out) - longueur;
  (void)fprintf(out, "endstream\n");
  (void)fprintf(out, "endobj\n");

  
  sz[8] = ftell(out);
  (void)fprintf(out, "8 0 obj\n");
  (void)fprintf(out, "%ld\n", longueur);
  (void)fprintf(out, "endobj\n");
  
  sz[9] = ftell(out);
  (void)fprintf(out, "xref\n");
  (void)fprintf(out, "0 9\n");
  (void)fprintf(out, "%010d %05d f \n", 0, 65535);
  for(i=1; i<= 8; i++)
    (void)fprintf(out, "%010ld %05d n \n", sz[i], 0);
  (void)fprintf(out, "trailer\n");
  (void)fprintf(out, "<</Size 9/Root 2 0 R/Info 1 0 R>>\n");
  (void)fprintf(out, "startxref\n");
  (void)fprintf(out, "%ld\n", sz[9]);
  (void)fprintf(out, "%%%%EOF\n");
    
  (void)fclose(out);

  g_array_free(imageData, TRUE);

  return TRUE;
}

/******************************************************************************/

static gboolean writeViewInPs256Format(const char* filename,
				       int width, int height,
				       guchar* imageData, GError **error,
				       ToolVoidDataFunc functionWait, gpointer data)
{
  static int x = 10, y = 10;
  time_t timer;
  float facx, facy, fac;
  int wu, hu;
  register guint i;
  register ColorPacket *q;
  register unsigned char *p;
         
  g_return_val_if_fail(error && !*error, FALSE);
  g_return_val_if_fail(imageData, FALSE);

  image    = imageData;
  PSwidth  = width;
  PSheight = height;

  DBG_fprintf(stderr, "Dump PS & PDF : begin PS 256c. export in %dx%d : %s.\n",
	      width, height, filename);

  img=g_malloc(sizeof(Image));
  img->colormap = (ColorPacket*)0;

  img->columns = PSwidth;
  img->rows = PSheight;
  img->packets=img->columns*img->rows;
  img->pixels=g_malloc(img->packets*sizeof(ColorPacket));
  q=img->pixels;
  p=image;
  for (i=0; i < img->packets; i++) {
    q->red=(*p++);
    q->green=(*p++);
    q->blue=(*p++);
    q->index=0;
    q++;
  }
  dumpToGif_setImage(img);
  
  if(dumpToGif_quantizeImage(256, error, functionWait, data))
    {
      g_free(img->pixels);
      if (img->colormap)
	g_free(img->colormap);
      g_free(img);
      return FALSE;
    }
  dumpToGif_syncImage();

  out = fopen(filename, "w");
  if(!out)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_FILE,
			   _("Cannot open file (to write in)."));
      g_free(img->pixels);
      g_free(img->colormap);
      g_free(img);
      return FALSE;
    }
   
   facx = (552.0f - x - 5)/img->columns;
   facy = (796.0f - y - 5)/img->rows;
   if(facx < facy) {
      fac = facx;
   }
   else {
      fac = facy;
   }
   if(fac < 1.0f) {
      wu = img->columns*fac + 1;
      hu = img->rows*fac + 1;
   }
   else {
      wu = img->columns;
      hu = img->rows;
   }
         
   (void)fprintf(out, "%%!PS-Adobe-3.0\n");
   (void)fprintf(out, "%%%%Title: %s\n", filename);
   (void)fprintf(out, "%%%%Creator: v_sim (L. BILLARD)\n");
   timer = time((time_t *) NULL);
   (void)localtime(&timer);
   (void)fprintf(out, "%%%%CreationDate: %s",ctime(&timer));
   (void)fprintf(out, "%%%%For: %s\n", g_get_user_name());
   (void)fprintf(out, "%%%%LanguageLevel: 2\n");
   (void)fprintf(out, "%%%%DocumentData: Clean7Bit\n");
   (void)fprintf(out, "%%%%Orientation: Portrait\n");
   (void)fprintf(out, "%%%%BoundingBox: %d %d %d %d\n",
            x - 1, y - 1, x + wu + 1, y + hu + 1);
   (void)fprintf(out, "%%%%Pages: 1\n");
   (void)fprintf(out, "%%%%EndComments\n");
   (void)fprintf(out, "%%%%BeginProlog\n");
   (void)fprintf(out, "/ASCLZWI {\n");
   (void)fprintf(out, "   /table currentfile %d string readhexstring pop "
                       "def\n",
         3 * img->colors);
   (void)fprintf(out, "   [/Indexed /DeviceRGB %d table] setcolorspace\n", 
         img->colors - 1);
   (void)fprintf(out, "   <</ImageType 1 /Width %d /Height %d "
                          "/BitsPerComponent 8\n", 
            img->columns, img->rows);
   (void)fprintf(out, "     /Decode [0 255] "
                            "/ImageMatrix [%d 0 0 %d 0 %d]\n",
            img->columns, -img->rows, img->rows);
   (void)fprintf(out, "     /DataSource currentfile /ASCIIHexDecode filter "
                            "/LZWDecode filter\n");
   (void)fprintf(out, "   >>image\n");
   (void)fprintf(out, "} bind def\n");
   (void)fprintf(out, "%%%%EndProlog\n");
   (void)fprintf(out, "%%%%Page: un 1\n");
   (void)fprintf(out, "gsave\n");
   (void)fprintf(out, "%d %d translate\n", x, y);
   (void)fprintf(out, "%f %f scale\n", 
            1.0*img->columns, 1.0*img->rows);
   if(fac < 1.0f) {
      (void)fprintf(out, "%%Supplementary scaling to remain A4\n");
      (void)fprintf(out, "%f %f scale\n", fac, fac);
   }
   (void)fprintf(out, "ASCLZWI\n");
   for ( i = 0; i < img->colors; i++ )
      (void)fprintf(out, "%02x%02x%02x\n", 
          (unsigned char) img->colormap[i].red, 
          (unsigned char) img->colormap[i].green, 
          (unsigned char) img->colormap[i].blue); 
   
  OutputDataPS256();
  
   (void)fprintf(out, ">\n");
   (void)fprintf(out, "grestore\n");
   (void)fprintf(out, "showpage\n");
   (void)fprintf(out, "%%%%PageTrailer\n");
   (void)fprintf(out, "%%%%Trailer\n");
   (void)fprintf(out, "%%%%EOF\n");

  (void)fclose(out);

  g_free(img->pixels);
  g_free(img->colormap);
  g_free(img);

  return TRUE;
}
