/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)
  
	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-2006)

	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 <opengl.h>

#include <glib.h>

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 voidDataFunc waitFunc;


int writeViewInPsFormat(FileFormat *format, GString *buffer,
			char* filename, int width, int height,
			VisuData *dataObj,
			voidDataFunc functionWait, gpointer data);
int writeViewInPs256Format(GString *buffer, char* filename,
			   int width, int height,
			   VisuData *dataObj,
			   voidDataFunc functionWait, gpointer data);
int writeViewInPdfFormat(FileFormat *format, GString *buffer,
			 char* filename, int width, int height,
			 VisuData *dataObj,
			 voidDataFunc functionWait, gpointer data);
int writeViewInPsTrueColorFormat(GString *buffer, char* filename,
				 int width, int height,
				 VisuData *dataObj,
				 voidDataFunc functionWait, gpointer data);

DumpType* initDumpToPs()
{
  DumpType *ps;
  char *typePS[] = {"*.ps", (char*)0};
  #define descrPS _("Postscript (v3.0) file")
  FileFormat* fmt;

  ps = malloc(sizeof(DumpType));
  if (!ps)
    {
      allocationProblems();
      exit(1);
    }
  fmt = fileFormatNew(descrPS, typePS);
  if (!fmt)
    g_error("Can't initialize the PS dump module, aborting.\n");

  ps->fileType = fmt;
  ps->writeFunc = writeViewInPsFormat;

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

  fileFormatAdd_propertyBoolean(fmt, "reduced_colormap",
				_("Use a reduced colormap (256 colors)"), FALSE);
  
  return ps;
}
DumpType* initDumpToPdf()
{
  DumpType *pdf;
  char *typePDF[] = {"*.pdf", (char*)0};
#define descrPDF _("PDF file (v. 1.2)")
  FileFormat* fmt;

  pdf = malloc(sizeof(DumpType));
  if (!pdf)
    {
      allocationProblems();
      exit(1);
    }
  fmt = fileFormatNew(descrPDF, typePDF);
  if (!fmt)
    g_error("Can't initialize the PS dump module, aborting.\n");

  pdf->fileType = fmt;
  pdf->writeFunc = writeViewInPdfFormat;
  
  waitFunc = (voidDataFunc)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;
   unsigned 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 = (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);
   }
}

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

int writeViewInPsFormat(FileFormat *format, GString *buffer,
			char* filename, int width, int height,
			VisuData *dataObj,
			voidDataFunc functionWait, gpointer data)
{
  GList *prop;
  gchar* name;

  prop = fileFormatGet_propertiesList(format);
  while (prop)
    {
      name = fileFormatGet_propertyName((FileFormatProperty*)(prop->data));
      if (strcmp(name, "reduced_colormap") == 0)
	{
	  if (fileFormatGet_propertyBoolean((FileFormatProperty*)(prop->data)))
	    return writeViewInPs256Format(buffer, filename, width,
					  height, dataObj, functionWait, data);
	  else
	    return writeViewInPsTrueColorFormat(buffer, filename, width,
						height, dataObj, functionWait, data);
	}
      prop = g_list_next(prop);
    }
  return writeViewInPsTrueColorFormat(buffer, filename, width,
				      height, dataObj, functionWait, data);
}

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

int writeViewInPsTrueColorFormat(GString *buffer,
				 char* filename, int width, int height,
				 VisuData *dataObj,
				 voidDataFunc functionWait, gpointer data)
{
  static int x = 10, y = 10;
  time_t timer;
  float facx, facy, fac;
  int wu, hu;
         
  image = dumpViewToImage(dataObj, buffer, &width, &height);
  if(!image)
    {
      g_string_append(buffer, _("Internal dumpImageToPS error :\n"
				"image is not allocated"));
      return 1;
    }

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

  out = fopen(filename, "w");
  if(!out)
    {
      g_string_append(buffer, _("Cannot open file (to write in)\n"));
      free(image);
      return 1;
    }
                  
   
   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);
  free(image);
  return 0;
}

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

int writeViewInPdfFormat(FileFormat *format, GString *buffer,
			 char* filename, int width, int height,
			 VisuData *dataObj,
			 voidDataFunc functionWait, gpointer data)
{
  time_t timer;
   
  struct tm *ltm;
  long int longueur;
  long int sz[10];
  int i;    
         
  image = dumpViewToImage(dataObj, buffer, &width, &height);
  if(!image)
    {
      g_string_append(buffer, _("Internal dumpImageToPS error :\n"
				"image is not allocated"));
      return 1;
    }

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

  out = fopen(filename, "w");
  if(!out)
    {
      g_string_append(buffer, _("Cannot open file (to write in)\n"));
      free(image);
      return 1;
    }
                  
  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/ColorSpace /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);
  free(image);
  return 0;
}

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

int writeViewInPs256Format(GString *buffer,
			   char* filename, int width, int height,
			   VisuData *dataObj,
			   voidDataFunc functionWait, gpointer data)
{
  static int x = 10, y = 10;
  time_t timer;
  float facx, facy, fac;
  int wu, hu;
  register unsigned int i;
  register ColorPacket *q;
  register unsigned char *p;
         
  image = dumpViewToImage(dataObj, buffer, &width, &height);
  if(!image)
    {
      g_string_append(buffer, _("Internal dumpImageToPS error :\n"
				"image is not allocated"));
      return 1;
    }

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

  img=g_malloc(sizeof(Image));

  img->columns = PSwidth;
  img->rows = PSheight;
  img->packets=img->columns*img->rows;
  img->pixels=(ColorPacket *)
    malloc((unsigned int) img->packets*sizeof(ColorPacket));
  if (!img->pixels)
    {
      g_string_append(buffer, _("Memory allocation error for img->packets\n"));
      return 1;
    }
  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++;
  }
  setImage(img);
  
  if(QuantizeImage(256, buffer, functionWait, data))
    return 1;
  SyncImage();

  out = fopen(filename, "w");
  if(!out)
    {
      g_string_append(buffer, _("Cannot open file (to write in)\n"));
      free(image);
      return 1;
    }
   
   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);
  free(image);
  return 0;
}
