Description: <short summary of the patch>
 TODO: Put a short summary on the line above and replace this paragraph
 with a longer explanation of this change. Complete the meta-information
 with other relevant fields (see below for details). To make it easier, the
 information below has been extracted from the changelog. Adjust it or drop
 it.
 .
 djview4 (4.9-4) unstable; urgency=low
 .
   * bump policy version (no changes needed)
   * clean some icons generated during build (closes: #679921)
   * update debian packaging repo urls to current naming scheme
   * the upstream changelog is called NEWS
Author: Barak A. Pearlmutter <bap@debian.org>
Bug-Debian: http://bugs.debian.org/679921

---
The information above should follow the Patch Tagging Guidelines, please
checkout http://dep.debian.net/deps/dep3/ to learn about the format. Here
are templates for supplementary fields that you might want to add:

Origin: <vendor|upstream|other>, <url of original patch>
Bug: <url in upstream bugtracker>
Bug-Debian: http://bugs.debian.org/<bugnumber>
Bug-Ubuntu: https://launchpad.net/bugs/<bugnumber>
Forwarded: <no|not-needed|url proving that it has been forwarded>
Reviewed-By: <name and email of someone who approved the patch>
Last-Update: <YYYY-MM-DD>

--- djview4-4.9.orig/src/djview.pro
+++ djview4-4.9/src/djview.pro
@@ -18,7 +18,7 @@
 TEMPLATE = app 
 TARGET = djview
 CONFIG += qt thread warn_on 
-QT += network 
+QT += network opengl
 
 # -- find libraries
 CONFIG(autoconf) {
@@ -29,17 +29,13 @@ CONFIG(autoconf) {
     #   QMAKE_CXXFLAGS += ...
     #   QMAKE_CFLAGS += ...
     #   QMAKE_LFLAGS += ...
-} else:unix:!macx {
-    # for use under unix with pkgconfig
-    CONFIG += link_pkgconfig
-    PKGCONFIG += ddjvuapi
 } else {
-    # for use on other platforms
-    # LIBS += -ldjvulibre
-    # QMAKE_CXXFLAGS +=  ... (c++ flags)
-    # QMAKE_CFLAGS += ...    (c flags)
-    # QMAKE_LFLAGS += ...    (link flags)
-    # DEFINES += ...         (definitions)
+    # customize below
+    LIBS += -ldjvulibre
+    #QMAKE_CXXFLAGS += 
+    #QMAKE_CFLAGS += 
+    #QMAKE_LFLAGS += 
+    #DEFINES += 
 }
 
 
--- djview4-4.9.orig/src/qdjviewprefs.cpp
+++ djview4-4.9/src/qdjviewprefs.cpp
@@ -148,6 +148,7 @@ QDjViewPrefs::QDjViewPrefs(void)
     invertLuminance(false),
     mouseWheelZoom(false),
     restrictOverride(false),
+    openGLAccel(false),
     modifiersForLens(Qt::ControlModifier|Qt::ShiftModifier),
     modifiersForSelect(Qt::ControlModifier),
     modifiersForLinks(Qt::ShiftModifier),
@@ -360,6 +361,8 @@ QDjViewPrefs::load()
     languageOverride = s.value("language").toString();
   if (s.contains("restrictOverride"))
     restrictOverride = s.value("restrictOverride").toBool();
+  if (s.contains("openGLAccel"))
+    openGLAccel = s.value("openGLAccel").toBool();
   if (s.contains("modifiersForLens"))
     modifiersForLens 
       = stringToModifiers(s.value("modifiersForLens").toString());
@@ -455,6 +458,7 @@ QDjViewPrefs::save(void)
   s.setValue("modifiersForLinks", modifiersToString(modifiersForLinks));
   s.setValue("language", languageOverride);
   s.setValue("restrictOverride", restrictOverride);
+  s.setValue("openGLAccel", openGLAccel);
 
   s.setValue("thumbnailSize", thumbnailSize);
   s.setValue("thumbnailSmart", thumbnailSmart);
@@ -944,6 +948,7 @@ QDjViewPrefsDialog::load(QDjView *djview
   d->ui.animationCheckBox->setChecked(prefs->enableAnimations);
   d->ui.textLabelCheckBox->setChecked(prefs->showTextLabel);
   d->ui.restrictOverrideCheckBox->setChecked(prefs->restrictOverride);
+  d->ui.openGLCheckBox->setChecked(prefs->openGLAccel);
   d->ui.printerManualCheckBox->setChecked(pgamma > 0);
   d->ui.printerGammaSpinBox->setValue((pgamma > 0) ? pgamma : 2.2);
   // no longer modified
@@ -976,9 +981,10 @@ QDjViewPrefsDialog::loadLanguageComboBox
       {
         QString nlang = languages[i];
         QString xlang = QString::null;
-        QTranslator *trans = new QTranslator();
-        if (app->loadTranslator(trans, "djview", QStringList(nlang)))
-          xlang = trans->translate("Generic", thisLang[0].src);
+        QTranslator *dTrans = new QTranslator();
+        QTranslator *qTrans = new QTranslator();
+        if (app->loadTranslators(QStringList(nlang), dTrans, qTrans))
+          xlang = dTrans->translate("Generic", thisLang[0].src);
         else if (nlang == "en" || nlang.startsWith("en"))
           xlang = "English";
         if (lang == nlang && xlang.size() > 0)
@@ -987,7 +993,8 @@ QDjViewPrefsDialog::loadLanguageComboBox
           index = cb->count();
         if (xlang.size() > 0)
           cb->addItem(xlang, nlang);
-        delete trans;
+        delete dTrans;
+        delete qTrans;
       }
   db->setChecked(index >= 0 && lang.size() > 0);
   cb->setCurrentIndex(index);
@@ -1043,6 +1050,7 @@ QDjViewPrefsDialog::apply()
   prefs->advancedFeatures = d->ui.advancedCheckBox->isChecked();
   prefs->showTextLabel = d->ui.textLabelCheckBox->isChecked();
   prefs->restrictOverride = d->ui.restrictOverrideCheckBox->isChecked();
+  prefs->openGLAccel = d->ui.openGLCheckBox->isChecked();
   prefs->printerGamma = 0;
   if (d->ui.printerManualCheckBox->isChecked())
     prefs->printerGamma = d->ui.printerGammaSpinBox->value();
@@ -1088,14 +1096,16 @@ QDjViewPrefsDialog::reset()
   d->ui.lensSizeSpinBox->setValue(300);
   // 5- network tab
   d->ui.proxyCheckBox->setChecked(false);
-  // 6- advanced tab
   d->ui.pixelCacheSpinBox->setValue(1);
   d->ui.pageCacheSpinBox->setValue(10);
+  // 6- advanced tab
   d->ui.languageCheckBox->setChecked(false);
-  d->ui.printerManualCheckBox->setChecked(false);
-  d->ui.printerGammaSpinBox->setValue(2.2);
+  d->ui.animationCheckBox->setChecked(true);
   d->ui.advancedCheckBox->setChecked(false);
   d->ui.textLabelCheckBox->setChecked(false);
+  d->ui.openGLCheckBox->setChecked(false);
+  d->ui.printerManualCheckBox->setChecked(false);
+  d->ui.printerGammaSpinBox->setValue(2.2);
 }
 
 
--- djview4-4.9.orig/src/qdjviewprefs.h
+++ djview4-4.9/src/qdjviewprefs.h
@@ -155,6 +155,7 @@ public:
   bool       mouseWheelZoom;    //!< Mouse wheel zooms instead of scroll.
   QString    languageOverride;  //!< Language settings
   bool       restrictOverride;  //!< Override noprint/nosave
+  bool       openGLAccel;       //!< Use opengl acceleration
   Qt::KeyboardModifiers modifiersForLens;   //!< Keys for the lens. 
   Qt::KeyboardModifiers modifiersForSelect; //!< Keys for selecting.
   Qt::KeyboardModifiers modifiersForLinks;  //!< Keys for showing the links.
--- djview4-4.9.orig/src/qdjvuwidget.h
+++ djview4-4.9/src/qdjvuwidget.h
@@ -165,6 +165,8 @@ public:
 
   QDjVuWidget(QWidget *parent=0);
   QDjVuWidget(QDjVuDocument *doc, QWidget *parent=0);
+  QDjVuWidget(bool opengl, QWidget *parent=0);
+  QDjVuWidget(QDjVuDocument *doc, bool opengl, QWidget *parent=0);
   
   QDjVuDocument *document(void) const;
   int page(void) const;
--- djview4-4.9.orig/src/djview.h
+++ djview4-4.9/src/djview.h
@@ -46,7 +46,7 @@ class QDjViewApplication : public QAppli
   QDjViewApplication(int &argc, char **argv);
   QDjVuContext *djvuContext() { return &context; }
   QDjView *newWindow();
-  bool loadTranslator(QTranslator *trans, QString name, QStringList langs);
+  bool loadTranslators(QStringList langs, QTranslator *dt, QTranslator *qt);
 protected:
   bool event(QEvent *ev);
 #ifdef Q_WS_X11
--- djview4-4.9.orig/src/djview_fr.ts
+++ djview4-4.9/src/djview_fr.ts
@@ -4,7 +4,7 @@
 <context>
     <name>Generic</name>
     <message>
-        <location filename="qdjviewprefs.cpp" line="969"/>
+        <location filename="qdjviewprefs.cpp" line="974"/>
         <source>thisLanguage</source>
         <comment>Name of THIS language</comment>
         <translation>Français</translation>
@@ -850,74 +850,74 @@
     </message>
     <message>
         <location filename="qdjview.cpp" line="2222"/>
-        <location filename="qdjview.cpp" line="2504"/>
+        <location filename="qdjview.cpp" line="2506"/>
         <source>DjView</source>
         <translation>DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2524"/>
+        <location filename="qdjview.cpp" line="2526"/>
         <source>Cannot open file &apos;%1&apos;.</source>
         <translation>Impossible d&apos;ouvrir le fichier «%1».</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2557"/>
+        <location filename="qdjview.cpp" line="2559"/>
         <source>Cannot open URL &apos;%1&apos;.</source>
         <translation>Impossible d&apos;ouvrir l&apos;URL «%1».</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2571"/>
+        <location filename="qdjview.cpp" line="2573"/>
         <source>Certificate validation error - DjView</source>
         <comment>dialog caption</comment>
         <translation>Erreur de validation du certificat - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2572"/>
+        <location filename="qdjview.cpp" line="2574"/>
         <source>&lt;html&gt; %1  Do you want to continue anyway? &lt;/html&gt;</source>
         <translation>&lt;html&gt; %1  Voulez-vous continuer tout-de-même? &lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2650"/>
+        <location filename="qdjview.cpp" line="2652"/>
         <source>Cannot find page numbered: %1</source>
         <translation>Impossible de trouver la page numérotée «%1»</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2682"/>
-        <location filename="qdjview.cpp" line="2712"/>
+        <location filename="qdjview.cpp" line="2684"/>
+        <location filename="qdjview.cpp" line="2714"/>
         <source>Cannot find page named: %1</source>
         <translation>Impossible de trouver la page nommée «%1»</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2925"/>
+        <location filename="qdjview.cpp" line="2927"/>
         <source>Unrecognized sidebar options &apos;%1&apos;.</source>
         <translation>L&apos;option de panneau latéral «%1» n&apos;est pas reconnue.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2987"/>
+        <location filename="qdjview.cpp" line="2989"/>
         <source>&lt;html&gt; This file was served with printing restrictions. Do you want to print it anyway?&lt;/html&gt;</source>
         <oldsource>&lt;html&gt; This file was served with printing restrictions.Do you want to print it anyway?&lt;/html&gt;</oldsource>
         <translation>&lt;html&gt;Ce fichier est servi avec une restriction d&apos;impression. Voulez-vous l&apos;imprimer quand même?&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3003"/>
+        <location filename="qdjview.cpp" line="3005"/>
         <source>&lt;html&gt; This file was served with saving restrictions. Do you want to save it anyway?&lt;/html&gt;</source>
         <oldsource>&lt;html&gt; This file was served with saving restrictions.Do you want to save it anyway?&lt;/html&gt;</oldsource>
         <translation>&lt;html&gt;Ce fichier est servi avec une restriction de sauvegarde. Voulez vous le sauver quand même?&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3400"/>
+        <location filename="qdjview.cpp" line="3402"/>
         <source>Cannot determine file format.
 Filename &apos;%1&apos; has no suffix.</source>
         <translation>Impossible de déterminer le format du fichier.
 Le nom «%1» n&apos;a pas de suffixe.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3413"/>
+        <location filename="qdjview.cpp" line="3415"/>
         <source>Image format %1 not supported.</source>
         <translation>Le format de fichier image «%1» n&apos;est pas supporté.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3355"/>
-        <location filename="qdjview.cpp" line="3420"/>
+        <location filename="qdjview.cpp" line="3357"/>
+        <location filename="qdjview.cpp" line="3422"/>
         <source>Cannot write file &apos;%1&apos;.
 %2.</source>
         <translation>Impossible d&apos;écrire le fichier «%1».
@@ -939,27 +939,27 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Recherche</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3641"/>
+        <location filename="qdjview.cpp" line="3643"/>
         <source>Cannot decode page %1.</source>
         <translation>Impossible de décoder la page «%1».</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3643"/>
+        <location filename="qdjview.cpp" line="3645"/>
         <source>Cannot decode document.</source>
         <translation>Impossible de décoder le document.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3785"/>
+        <location filename="qdjview.cpp" line="3787"/>
         <source> x=%1 y=%2 </source>
         <translation> x=%1 y=%2 </translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3789"/>
+        <location filename="qdjview.cpp" line="3791"/>
         <source> %3x%4+%1+%2 </source>
         <translation> %3x%4+%1+%2 </translation>
     </message>
     <message numerus="yes">
-        <location filename="qdjview.cpp" line="3862"/>
+        <location filename="qdjview.cpp" line="3864"/>
         <source>Go: %n pages forward.</source>
         <translation>
             <numerusform>Avancer de %n page.</numerusform>
@@ -967,7 +967,7 @@ Le nom «%1» n&apos;a pas de suffixe.</
         </translation>
     </message>
     <message numerus="yes">
-        <location filename="qdjview.cpp" line="3865"/>
+        <location filename="qdjview.cpp" line="3867"/>
         <source>Go: %n pages backward.</source>
         <translation>
             <numerusform>Reculer de %n page.</numerusform>
@@ -975,59 +975,59 @@ Le nom «%1» n&apos;a pas de suffixe.</
         </translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3868"/>
         <location filename="qdjview.cpp" line="3870"/>
+        <location filename="qdjview.cpp" line="3872"/>
         <source>Go: page %1.</source>
         <translation>Aller page %1.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3872"/>
+        <location filename="qdjview.cpp" line="3874"/>
         <source>Go: %1</source>
         <oldsource>Link: %1</oldsource>
         <translation>Aller à %1</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3961"/>
+        <location filename="qdjview.cpp" line="3963"/>
         <source>Cannot resolve link &apos;%1&apos;</source>
         <translation>Impossible d&apos;interpréter le lien «%1»</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3989"/>
+        <location filename="qdjview.cpp" line="3991"/>
         <source>Cannot spawn a browser for url &apos;%1&apos;</source>
         <translation>Impossible de lancer un navigateur pour l&apos;URL «%1»</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4009"/>
+        <location filename="qdjview.cpp" line="4011"/>
         <source>Copy text (%1)</source>
         <translation>Copier le texte (%1)</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4010"/>
+        <location filename="qdjview.cpp" line="4012"/>
         <source>Save text as...</source>
         <translation>Enregistrer le texte...</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4016"/>
+        <location filename="qdjview.cpp" line="4018"/>
         <source>Copy image (%1x%2 pixels)</source>
         <translation>Copier l&apos;image (%1x%2)</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4018"/>
+        <location filename="qdjview.cpp" line="4020"/>
         <source>Save image as...</source>
         <translation>Enregistrer l&apos;image...</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4022"/>
+        <location filename="qdjview.cpp" line="4024"/>
         <source>Zoom to rectangle</source>
         <translation>Zoomer sur ce rectangle</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4204"/>
+        <location filename="qdjview.cpp" line="4206"/>
         <source>About DjView</source>
         <translation>À propos de DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4224"/>
+        <location filename="qdjview.cpp" line="4226"/>
         <source>DjVu files</source>
         <translation>Fichiers DjVu</translation>
     </message>
@@ -1042,7 +1042,7 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Montre les informations sur l&apos;encodage du document et sa structure.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3874"/>
+        <location filename="qdjview.cpp" line="3876"/>
         <source> (in other window.)</source>
         <translation> (dans une autre fenêtre.)</translation>
     </message>
@@ -1077,85 +1077,85 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>&lt;html&gt;&lt;b&gt;Méta informations sur le document et la page.&lt;/b&gt;&lt;br&gt; Affiche un panneau montrant les informations supplémentaires qui se rapportent au document ou à une de ses pages.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2525"/>
+        <location filename="qdjview.cpp" line="2527"/>
         <source>Opening DjVu file</source>
         <translation>Ouverture de fichier DjVu</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2558"/>
+        <location filename="qdjview.cpp" line="2560"/>
         <source>Opening DjVu document</source>
         <translation>Ouverture de document DjVu</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="2986"/>
-        <location filename="qdjview.cpp" line="3022"/>
+        <location filename="qdjview.cpp" line="2988"/>
+        <location filename="qdjview.cpp" line="3024"/>
         <source>Print - DjView</source>
         <comment>dialog caption</comment>
         <translation>Imprimer - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3002"/>
-        <location filename="qdjview.cpp" line="3042"/>
+        <location filename="qdjview.cpp" line="3004"/>
+        <location filename="qdjview.cpp" line="3044"/>
         <source>Save - DjView</source>
         <comment>dialog caption</comment>
         <translation>Sauver - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3336"/>
+        <location filename="qdjview.cpp" line="3338"/>
         <source>Text files</source>
         <comment>save filter</comment>
         <translation>Fichiers texte</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3337"/>
-        <location filename="qdjview.cpp" line="3384"/>
+        <location filename="qdjview.cpp" line="3339"/>
+        <location filename="qdjview.cpp" line="3386"/>
         <source>All files</source>
         <comment>save filter</comment>
         <translation>Tous les fichiers</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3338"/>
+        <location filename="qdjview.cpp" line="3340"/>
         <source>Save Text - DjView</source>
         <comment>dialog caption</comment>
         <translation>Sauver le texte - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3354"/>
-        <location filename="qdjview.cpp" line="3399"/>
-        <location filename="qdjview.cpp" line="3419"/>
+        <location filename="qdjview.cpp" line="3356"/>
+        <location filename="qdjview.cpp" line="3401"/>
+        <location filename="qdjview.cpp" line="3421"/>
         <source>Error - DjView</source>
         <comment>dialog caption</comment>
         <translation>Erreur - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3385"/>
+        <location filename="qdjview.cpp" line="3387"/>
         <source>Save Image - DjView</source>
         <comment>dialog caption</comment>
         <translation>Enregistrement de l&apos;image - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3645"/>
+        <location filename="qdjview.cpp" line="3647"/>
         <source>Decoding DjVu document</source>
         <translation>Décodage de document DjVu</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3778"/>
+        <location filename="qdjview.cpp" line="3780"/>
         <source> P%1/%2 %3x%4 %5dpi </source>
         <translation> P%1/%2 %3x%4 %5dpi </translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4184"/>
+        <location filename="qdjview.cpp" line="4186"/>
         <source>&lt;html&gt;&lt;h2&gt;DjVuLibre DjView %1&lt;/h2&gt;%2&lt;p&gt;Viewer for DjVu documents&lt;br&gt;&lt;a href=%3&gt;%3&lt;/a&gt;&lt;br&gt;Copyright © 2006-- Léon Bottou.&lt;/p&gt;&lt;p align=justify&gt;&lt;small&gt;This program is free software. You can redistribute or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. This program is distributed &lt;i&gt;without any warranty&lt;/i&gt;. See the GNU General Public License for more details.&lt;/small&gt;&lt;/p&gt;&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;h2&gt;DjVuLibre DjView %1&lt;/h2&gt;%2&lt;p&gt;Afficheur pour documents DjVu&lt;br&gt;&lt;a href=%3&gt;%3&lt;/a&gt;&lt;br&gt;Copyright © 2006-- Léon Bottou.&lt;/p&gt;&lt;p align=justify&gt;&lt;small&gt;Ce programme est un logiciel libre. Vous pouvez le redistribuer ou le modifier au titre des clauses de la «GNU General Public License», telle que publiée par la Free Software Foundation. Ce programme est distribué &lt;i&gt;sans aucune garantie&lt;/i&gt;.  Voir la «GNU General Public License» pour plus de détails.&lt;/small&gt;&lt;/p&gt;&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4261"/>
+        <location filename="qdjview.cpp" line="4263"/>
         <source>Information - DjView</source>
         <comment>dialog caption</comment>
         <translation>Information - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4276"/>
+        <location filename="qdjview.cpp" line="4278"/>
         <source>Metadata - DjView</source>
         <comment>dialog caption</comment>
         <translation>Meta-information - DjView</translation>
@@ -1172,7 +1172,7 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Exporte la page ou le document DjVu sous un autre format.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3061"/>
+        <location filename="qdjview.cpp" line="3063"/>
         <source>Export - DjView</source>
         <comment>dialog caption</comment>
         <translation>Export - DjView</translation>
@@ -1195,7 +1195,7 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Ouvrir un Fichier &amp;Récent</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4454"/>
+        <location filename="qdjview.cpp" line="4456"/>
         <source>&amp;Clear History</source>
         <translation>&amp;Effacer l&apos;historique</translation>
     </message>
@@ -1253,18 +1253,18 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Ctrl+F5</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4243"/>
+        <location filename="qdjview.cpp" line="4245"/>
         <source>Open Location - DjView</source>
         <comment>dialog caption</comment>
         <translation>Ouverture d&apos;une URL - DjView</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4244"/>
+        <location filename="qdjview.cpp" line="4246"/>
         <source>Enter the URL of a DjVu document:</source>
         <translation>Entrez l&apos;URL d&apos;un document DjVu:</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4226"/>
+        <location filename="qdjview.cpp" line="4228"/>
         <source>Open - DjView</source>
         <comment>dialog caption</comment>
         <translation>Ouverture - DjView</translation>
@@ -1288,13 +1288,13 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Ligne d&apos;é&amp;tat</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3381"/>
+        <location filename="qdjview.cpp" line="3383"/>
         <source>%1 files (*.%2);;</source>
         <comment>save image filter</comment>
         <translation>Fichiers %1 (*.%2)</translation>
     </message>
     <message numerus="yes">
-        <location filename="qdjview.cpp" line="4003"/>
+        <location filename="qdjview.cpp" line="4005"/>
         <source>%n characters</source>
         <translation>
             <numerusform>%n caractère</numerusform>
@@ -1302,12 +1302,12 @@ Le nom «%1» n&apos;a pas de suffixe.</
         </translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3861"/>
+        <location filename="qdjview.cpp" line="3863"/>
         <source>Go: 1 page forward.</source>
         <translation>Avancer de 1 page.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="3864"/>
+        <location filename="qdjview.cpp" line="3866"/>
         <source>Go: 1 page backward.</source>
         <translation>Reculer de 1 page.</translation>
     </message>
@@ -1335,47 +1335,47 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Copie les &amp;Annotations</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4013"/>
+        <location filename="qdjview.cpp" line="4015"/>
         <source>Copy text into the clipboard.</source>
         <translation>Copie le texte correspondant à la sélection.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4014"/>
+        <location filename="qdjview.cpp" line="4016"/>
         <source>Save text into a file.</source>
         <translation>Enregistre le texte correspondant à la sélection dans un fichier.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4019"/>
+        <location filename="qdjview.cpp" line="4021"/>
         <source>Copy image into the clipboard.</source>
         <translation>Copie une image correspondant à la sélection.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4020"/>
+        <location filename="qdjview.cpp" line="4022"/>
         <source>Save image into a file.</source>
         <translation>Enregistre une image correspondant à la sélection dans un fichier.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4023"/>
+        <location filename="qdjview.cpp" line="4025"/>
         <source>Zoom the selection to fit the window.</source>
         <translation>Change le grossissement de façon à maximiser la sélection dans la fenêtre.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4029"/>
+        <location filename="qdjview.cpp" line="4031"/>
         <source>Copy URL</source>
         <translation>Copie l&apos;URL</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4030"/>
+        <location filename="qdjview.cpp" line="4032"/>
         <source>Save into the clipboard an URL that highlights the selection.</source>
         <translation>Copie une URL qui monte la page courante et met en valeur la sélection.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4032"/>
+        <location filename="qdjview.cpp" line="4034"/>
         <source>Copy Maparea</source>
         <translation>Copie la «Maparea»</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4033"/>
+        <location filename="qdjview.cpp" line="4035"/>
         <source>Save into the clipboard a maparea annotation expression for program djvused.</source>
         <translation>Copie une directive d&apos;annotation «maparea» correspondant à la sélection.</translation>
     </message>
@@ -1442,7 +1442,7 @@ Le nom «%1» n&apos;a pas de suffixe.</
         <translation>Affiche les pages de droite à gauche en mode côte-à-côte.</translation>
     </message>
     <message>
-        <location filename="qdjview.cpp" line="4225"/>
+        <location filename="qdjview.cpp" line="4227"/>
         <source>All files</source>
         <translation>Tous les fichiers</translation>
     </message>
@@ -1525,54 +1525,54 @@ Options fréquentes:
 <context>
     <name>QDjViewDjVuExporter</name>
     <message>
-        <location filename="qdjviewexporters.cpp" line="382"/>
+        <location filename="qdjviewexporters.cpp" line="394"/>
         <source>Question - DjView</source>
         <comment>dialog caption</comment>
         <translation>Question - DjView</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="383"/>
+        <location filename="qdjviewexporters.cpp" line="395"/>
         <source>&lt;html&gt; This file belongs to a non empty directory. Saving an indirect document creates many files in this directory. Do you want to continue and risk overwriting files in this directory?&lt;/html&gt;</source>
         <translation>&lt;html&gt; Ce fichier appartient à un répertoire qui n&apos;est pas vide. La sauvegarde d&apos;un document DjVu indirect crée de nombreux fichiers dans ce répertoire. Voulez-vous continuer et prendre le risque de remplacer des fichiers dans ce répertoire?&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="389"/>
+        <location filename="qdjviewexporters.cpp" line="401"/>
         <source>Con&amp;tinue</source>
         <translation>Con&amp;tinuer</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="390"/>
+        <location filename="qdjviewexporters.cpp" line="402"/>
         <source>&amp;Cancel</source>
         <translation>&amp;Annuler</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="434"/>
+        <location filename="qdjviewexporters.cpp" line="446"/>
         <source>Save job creation failed!</source>
         <translation>L&apos;operation d&apos;enregistrement a échoué!</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="417"/>
+        <location filename="qdjviewexporters.cpp" line="429"/>
         <source>Unknown error.</source>
         <translation>Erreur inconnue.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="419"/>
+        <location filename="qdjviewexporters.cpp" line="431"/>
         <source>System error: %1.</source>
         <translation>Erreur système: %1.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="330"/>
+        <location filename="qdjviewexporters.cpp" line="342"/>
         <source>DjVu Bundled Document</source>
         <translation>Document DjVu «bundled»</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="331"/>
-        <location filename="qdjviewexporters.cpp" line="335"/>
+        <location filename="qdjviewexporters.cpp" line="343"/>
+        <location filename="qdjviewexporters.cpp" line="347"/>
         <source>DjVu Files (*.djvu *.djv)</source>
         <translation>Fichiers DjVu (*.djvu *.djv)</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="334"/>
+        <location filename="qdjviewexporters.cpp" line="346"/>
         <source>DjVu Indirect Document</source>
         <translation>Document DjVu «indirect»</translation>
     </message>
@@ -2148,23 +2148,23 @@ Voulez-vous le remplacer?</translation>
 <context>
     <name>QDjViewImgExporter</name>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1913"/>
+        <location filename="qdjviewexporters.cpp" line="1925"/>
         <source>Cannot render page.</source>
         <translation>Impossible de dessiner la page.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1923"/>
+        <location filename="qdjviewexporters.cpp" line="1935"/>
         <source>Image format %1 not supported.</source>
         <translation>Le format de fichier image «%1» n&apos;est pas supporté.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1846"/>
+        <location filename="qdjviewexporters.cpp" line="1858"/>
         <source>%1 Image</source>
         <comment>JPG Image</comment>
         <translation>Images %1</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1847"/>
+        <location filename="qdjviewexporters.cpp" line="1859"/>
         <source>%1 Files (*.%2)</source>
         <comment>JPG Files</comment>
         <translation>Fichiers %1 (*.%2)</translation>
@@ -2449,56 +2449,56 @@ Voulez-vous le remplacer?</translation>
 <context>
     <name>QDjViewPSExporter</name>
     <message>
-        <location filename="qdjviewexporters.cpp" line="593"/>
+        <location filename="qdjviewexporters.cpp" line="606"/>
         <source>PostScript</source>
         <comment>tab caption</comment>
         <translation>PostScript</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="594"/>
+        <location filename="qdjviewexporters.cpp" line="607"/>
         <source>Position</source>
         <comment>tab caption</comment>
         <translation>Position</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="595"/>
+        <location filename="qdjviewexporters.cpp" line="608"/>
         <source>Booklet</source>
         <comment>tab caption</comment>
         <translation>Fascicule</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="620"/>
+        <location filename="qdjviewexporters.cpp" line="633"/>
         <source>&lt;html&gt;&lt;b&gt;Producing booklets.&lt;/b&gt;&lt;br&gt;The booklet mode prints the selected pages as sheets suitable for folding one or several booklets. Several booklets might be produced when a maximum number of sheets per booklet is specified. You can either use a duplex printer or print rectos and versos separately.&lt;p&gt; Shifting rectos and versos is useful with poorly aligned duplex printers. The center margins determine how much space is left between the pages to fold the sheets. This space slowly increases from the inner sheet to the outer sheet.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Production de fascicules.&lt;/b&gt;&lt;br&gt;Le mode fascicule permet d&apos;imprimer des feuillets à plier en un ou plusieurs fascicules. Plusieurs fascicules sont nécessaires lorsqu&apos;un nombre maximum de feuillets est spécifié. Vous pouvez utiliser une imprimante recto-verso ou imprimer séparément les rectos et les versos&lt;p&gt; Décaler les versos est utile pour les imprimantes recto-versos mal alignées. La marge centrale peut être modifiée et augmente lors de la progression du feuillet intérieur vers le feuillet extérieur.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1111"/>
+        <location filename="qdjviewexporters.cpp" line="1123"/>
         <source>Save job creation failed!</source>
         <translation>L&apos;operation d&apos;enregistrement a échoué!</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="605"/>
+        <location filename="qdjviewexporters.cpp" line="618"/>
         <source>&lt;html&gt;&lt;b&gt;PostScript options.&lt;/b&gt;&lt;br&gt;Option &lt;tt&gt;Color&lt;/tt&gt; enables color printing. Document pages can be decorated with frame and crop marks. PostScript language level 1 is only useful with very old printers. Level 2 works with most printers. Level 3 print color document faster on recent printers.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Options PostScript.&lt;/b&gt;&lt;br&gt;L&apos;option &lt;tt&gt;Couleur&lt;/tt&gt; autorise l&apos;impression en couleur. Les pages imprimées peuvent être décorées avec un cadre ou des marques de découpage. Le niveau PostScript 1 est utile pour les très vieilles imprimantes. Le niveau 2 fonctionne avec la plupart des imprimantes en service. Le niveau 3 imprime les documents en couleur plus rapidement sur des imprimantes récentes.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="613"/>
+        <location filename="qdjviewexporters.cpp" line="626"/>
         <source>&lt;html&gt;&lt;b&gt;Position and scaling.&lt;/b&gt;&lt;br&gt;Option &lt;tt&gt;Scale to fit&lt;/tt&gt; accommodates whatever paper size your printer uses. Zoom factor &lt;tt&gt;100%&lt;/tt&gt; reproduces the initial document size. Orientation &lt;tt&gt;Automatic&lt;/tt&gt; chooses portrait or landscape on a page per page basis.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Position and aggrandissement.&lt;/b&gt;&lt;br&gt;L&apos;option &lt;tt&gt;Agrandir à la page&lt;/tt&gt; choisit un grossissement adapté a la taille de papier utilisée par votre imprimante. Le facteur de grossissement &lt;tt&gt;100%&lt;/tt&gt; reproduit la taille originale du document. L&apos;orientation &lt;tt&gt;Automatique&lt;/tt&gt; sélectionne portrait ou paysage en fonction de la taille de chaque page.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="543"/>
+        <location filename="qdjviewexporters.cpp" line="556"/>
         <source>PostScript</source>
         <translation>PostScript</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="544"/>
-        <location filename="qdjviewexporters.cpp" line="548"/>
+        <location filename="qdjviewexporters.cpp" line="557"/>
+        <location filename="qdjviewexporters.cpp" line="561"/>
         <source>PostScript Files (*.ps *.eps)</source>
         <translation>Fichiers PostScript (*.ps *.eps)</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="547"/>
+        <location filename="qdjviewexporters.cpp" line="560"/>
         <source>Encapsulated PostScript</source>
         <translation>PostScript Encapsulé</translation>
     </message>
@@ -2506,54 +2506,54 @@ Voulez-vous le remplacer?</translation>
 <context>
     <name>QDjViewPdfExporter</name>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1689"/>
+        <location filename="qdjviewexporters.cpp" line="1701"/>
         <source>PDF Document</source>
         <translation>Document PDF</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1690"/>
+        <location filename="qdjviewexporters.cpp" line="1702"/>
         <source>PDF Files (*.pdf)</source>
         <translation>Fichiers PDF (*.pdf)</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1699"/>
+        <location filename="qdjviewexporters.cpp" line="1711"/>
         <source>PDF Options</source>
         <comment>tab caption</comment>
         <translation>Options PDF</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1700"/>
+        <location filename="qdjviewexporters.cpp" line="1712"/>
         <source>&lt;html&gt;&lt;b&gt;PDF options.&lt;/b&gt;&lt;br&gt;These options control the characteristics of the images embedded in the exported PDF files. The resolution box limits their maximal resolution. Forcing bitonal G4 compression encodes all pages in black and white using the CCITT Group 4 compression. Allowing JPEG compression uses lossy JPEG for all non bitonal or subsampled images. Otherwise, allowing deflate compression produces more compact files. &lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Options PDF.&lt;/b&gt;&lt;br&gt;Ces options s&apos;appliquent aux images encapsulées dans les fichiers PDF exportés. La boite de résolution spécifie leur résolution maximale. Forcer la compression bitonale G4 encode toutes les pages en noir et blanc avec la compression CCITT Groupe 4. Autoriser la compression JPEG utilise JPEG pour toutes les images en niveaux de gris ou en couleurs. Sinon, autoriser la compression «deflate» produit des fichiers plus compacts.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1744"/>
+        <location filename="qdjviewexporters.cpp" line="1756"/>
         <source>Error while creating pdf file.</source>
         <translation>Erreur pendant la création du fichier PDF.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1768"/>
+        <location filename="qdjviewexporters.cpp" line="1780"/>
         <source>PDF export was not compiled.</source>
         <translation>L&apos;exportation de fichiers PDF n&apos;a pas été compilée.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1748"/>
+        <location filename="qdjviewexporters.cpp" line="1760"/>
         <source>Unable to create output file.</source>
         <translation>Impossible de créer le fichier de sortie.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1750"/>
-        <location filename="qdjviewexporters.cpp" line="1794"/>
+        <location filename="qdjviewexporters.cpp" line="1762"/>
+        <location filename="qdjviewexporters.cpp" line="1806"/>
         <source>System error: %1.</source>
         <translation>Erreur système: %1.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1753"/>
+        <location filename="qdjviewexporters.cpp" line="1765"/>
         <source>Unable to reopen temporary file.</source>
         <translation>Impossible de réouvrir le fichier temporaire.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1792"/>
+        <location filename="qdjviewexporters.cpp" line="1804"/>
         <source>Unable to create temporary file.</source>
         <translation>Impossible de créer le fichier temporaire.</translation>
     </message>
@@ -2841,62 +2841,67 @@ Voulez-vous le remplacer?</translation>
     </message>
     <message>
         <location filename="qdjviewprefsdialog.ui" line="1131"/>
+        <source>Render with openGL when available</source>
+        <translation>Utiliser openGL losrque c&apos;est possible.</translation>
+    </message>
+    <message>
+        <location filename="qdjviewprefsdialog.ui" line="1141"/>
         <source>Override saving and printing restrictions</source>
         <translation>Outrepasse les restrictions d&apos;impression et de sauvegarde</translation>
     </message>
     <message>
-        <location filename="qdjviewprefsdialog.ui" line="1218"/>
+        <location filename="qdjviewprefsdialog.ui" line="1228"/>
         <source>&amp;Defaults</source>
         <translation>&amp;Défaults</translation>
     </message>
     <message>
-        <location filename="qdjviewprefsdialog.ui" line="1244"/>
+        <location filename="qdjviewprefsdialog.ui" line="1254"/>
         <source>&amp;Apply</source>
         <translation>&amp;Appliquer</translation>
     </message>
     <message>
-        <location filename="qdjviewprefsdialog.ui" line="1251"/>
+        <location filename="qdjviewprefsdialog.ui" line="1261"/>
         <source>&amp;Ok</source>
         <translation>&amp;Ok</translation>
     </message>
     <message>
-        <location filename="qdjviewprefsdialog.ui" line="1258"/>
+        <location filename="qdjviewprefsdialog.ui" line="1268"/>
         <source>Cancel</source>
         <translation>Annuler</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="726"/>
+        <location filename="qdjviewprefs.cpp" line="730"/>
         <source>Preferences[*] - DjView</source>
         <translation>Préférences[*] - DjView</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="809"/>
+        <location filename="qdjviewprefs.cpp" line="813"/>
         <source>&lt;html&gt;&lt;b&gt;Initial interface setup.&lt;/b&gt;&lt;br&gt;DjView can run as a standalone viewer, as a full screen viewer, as a full page browser plugin, or as a plugin embedded inside a html page. For each case, check the &lt;tt&gt;Remember&lt;/tt&gt; box to automatically save and restore the interface setup. Otherwise, specify an initial configuration.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Configuration initiale.&lt;/b&gt;&lt;br&gt;DjView peut fonctionner comme application normale, comme application plein-écran, comme plugin pleine-page, ou plugin en ligne dans une page web. Dans chaque cas, sélectionnez l&apos;option &lt;tt&gt;Mémoriser...&lt;/tt&gt; pour retenir la dernière configuration utilisée dans ce mode. Sinon, spécifiez les détails de la configuration initiale desirée.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="819"/>
+        <location filename="qdjviewprefs.cpp" line="823"/>
         <source>&lt;html&gt;&lt;b&gt;Modifiers keys.&lt;/b&gt;&lt;br&gt;Define which combination of modifier keys will show the manifying lens, temporarily enable the selection mode, or highlight the hyperlinks.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Touches spéciales.&lt;/b&gt;&lt;br&gt;Definissez quelles combinaisons de touches spéciales seront affectées à la loupe, à la selection de texte et d;images, et à l&apos;affichage temporaire des liens.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="826"/>
+        <location filename="qdjviewprefs.cpp" line="830"/>
         <source>&lt;html&gt;&lt;b&gt;Magnifying lens.&lt;/b&gt;&lt;br&gt;The magnifying lens appears when you depress the modifier keys specified in tab &lt;tt&gt;Keys&lt;/tt&gt;. This panel lets you choose the power and the size of the magnifying lens.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Loupe.&lt;/b&gt;&lt;br&gt;La loupe apparaît lorsque vous maintenez les touches spéciales définies dans l&apos;onglet &lt;tt&gt;Touches&lt;/tt&gt;. Ce panneau vous permet d&apos;en spécifier la taille et le grossissement.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="834"/>
+        <location filename="qdjviewprefs.cpp" line="838"/>
         <source>&lt;html&gt;&lt;b&gt;Advanced.&lt;/b&gt;&lt;br&gt;You can override the default interface language, disable the page animations, or enable additional menu entries that are useful for authoring DjVu files.You can also disable the printing or saving restrictions dictated by certain web sites. The manual color correction can be useful with old printers.&lt;/html&gt;</source>
         <oldsource>&lt;html&gt;&lt;p&gt;&lt;b&gt;Advanced.&lt;/b&gt;You can override the default interface language, disable the page animations, or enable additional menu entries that are useful for authoring DjVu files.You can also disable the printing or saving restrictions dictated by certain web sites. The manual color correction can be useful with old printers.&lt;/html&gt;</oldsource>
         <translation>&lt;html&gt;&lt;b&gt;Options avancées&lt;/b&gt;&lt;br&gt;Vous pouvez changer la langue de l&apos;interface, supprimer les animations, ou dévoiler des entrées de menus supplémentaires utiles pour la création de documents DjVu. Vous pouvez également ignorer les restrictions d&apos;impression et de sauvegarde spécifiées par le site web. La correction manuelle des couleurs d&apos;impression peut être utile avec certaines vieilles imprimantes.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="844"/>
+        <location filename="qdjviewprefs.cpp" line="848"/>
         <source>&lt;html&gt;&lt;b&gt;Network proxy settings.&lt;/b&gt;&lt;br&gt;These proxy settings are used when the standalone djview viewer accesses a djvu document through a http url. The djview plugin always uses the proxy settings of the web browser.&lt;p&gt;&lt;b&gt;Cache settings.&lt;/b&gt;&lt;br&gt;The &lt;i&gt;pixel cache&lt;/i&gt; stores image data located outside the visible area. This cache makes panning smoother. The &lt;i&gt;decoded page cache&lt;/i&gt; contains partially decoded pages. It provides faster response times when navigating a multipage document or when returning to a previously viewed page. Clearing this cache might be useful to reflect a change in the page data without restarting the DjVu viewer.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Options du réseau.&lt;/b&gt;&lt;br&gt;Ce panneau permet de définir un proxy utilisé pour atteindre un document DjVu distant avec le protocole réseau HTTP. Ces options sont ignorées lorsque le programme fonctionne en mode plugin: les accès réseaux utilisent alors les options du navigateur hôte.&lt;p&gt;&lt;b&gt;Caches.&lt;/b&gt;&lt;br&gt;Le &lt;i&gt;cache de pixels&lt;/i&gt; contient des portions d&apos;images situées en limite de la zone visible. Il permet des défilements plus fluides. Le &lt;i&gt;cache de page décodées&lt;/i&gt; contient des pages partiellement décodées. Il permet de parcourir plus rapidement des documents à pages multiples. Effacer ce cache peut être utile pour prendre en compte un fichier modifié sans redemarrer l&apos;application.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewprefs.cpp" line="796"/>
+        <location filename="qdjviewprefs.cpp" line="800"/>
         <source>&lt;html&gt;&lt;b&gt;Screen gamma correction.&lt;/b&gt;&lt;br&gt;The best color rendition is achieved by adjusting the gamma correction slider and choosing the position that makes the gray square as uniform as possible.&lt;p&gt;&lt;b&gt;Screen resolution.&lt;/b&gt;&lt;br&gt;This option forces a particular resolution instead of using the unreliable resolution advertised by the operating system. Forcing the resolution to 100 dpi matches the behavior of the djvulibre command line tools.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Correction de couleur pour l&apos;écran.&lt;/b&gt;&lt;br&gt;Le meilleur rendu est obtenu en ajustant le potentiomètre de façon à rendre les niveaux de gris de la mire aussi proches que possible.&lt;p&gt;&lt;b&gt;Résolution de l&apos;écran.&lt;/b&gt;&lt;br&gt;Forcer une résolution particulière est utile quand le système donne une résolution qui ne correspond pas à la réalité. Forcer une résolution de 100dpi rend l&apos;affichage compatible avec les programmes utilitaires de DjVuLibre.&lt;/html&gt;</translation>
     </message>
@@ -2926,12 +2931,12 @@ Voulez-vous le remplacer?</translation>
         <translation>Divers</translation>
     </message>
     <message>
-        <location filename="qdjviewprefsdialog.ui" line="1140"/>
+        <location filename="qdjviewprefsdialog.ui" line="1150"/>
         <source>Manual printer color correction</source>
         <translation>Correction manuelle de couleur d&apos;impression</translation>
     </message>
     <message>
-        <location filename="qdjviewprefsdialog.ui" line="1153"/>
+        <location filename="qdjviewprefsdialog.ui" line="1163"/>
         <source>gamma=</source>
         <translation>gamma=</translation>
     </message>
@@ -3017,7 +3022,7 @@ Voulez-vous le remplacer?</translation>
     </message>
     <message>
         <location filename="qdjviewprintdialog.ui" line="280"/>
-        <location filename="qdjviewdialogs.cpp" line="1796"/>
+        <location filename="qdjviewdialogs.cpp" line="1828"/>
         <source>&amp;Cancel</source>
         <translation>&amp;Annuler</translation>
     </message>
@@ -3027,17 +3032,17 @@ Voulez-vous le remplacer?</translation>
         <translation>Stop</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1835"/>
+        <location filename="qdjviewdialogs.cpp" line="1867"/>
         <source>This operation has failed.</source>
         <translation>Cette opération a échoué.</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1839"/>
+        <location filename="qdjviewdialogs.cpp" line="1871"/>
         <source>This operation has been interrupted.</source>
         <translation>Cette opération a été interrompue.</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1581"/>
+        <location filename="qdjviewdialogs.cpp" line="1579"/>
         <source>&lt;html&gt;&lt;b&gt;Printing.&lt;/b&gt;&lt;br/&gt; You can print the whole document or a page range. Use the &lt;tt&gt;Choose&lt;/tt&gt; button to select a print destination and specify printer options. Additional dialog tabs might appear to specify conversion options.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Impression.&lt;/b&gt;&lt;br/&gt; Vous pouvez imprimer le document entier ou un intervalle de pages. Utilisez le bouton &lt;tt&gt;Choisir&lt;/tt&gt; pour selectionner une destination d&apos;impression. Des onglets supplémentaires peuvent apparaître pour spécifier des options de conversion adaptées à l&apos;imprimante.&lt;/html&gt;</translation>
     </message>
@@ -3062,37 +3067,37 @@ Voulez-vous le remplacer?</translation>
         <translation>Choisir</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1707"/>
+        <location filename="qdjviewdialogs.cpp" line="1705"/>
         <source>All files</source>
         <comment>save filter</comment>
         <translation>Tous les fichiers</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1714"/>
+        <location filename="qdjviewdialogs.cpp" line="1712"/>
         <source>Print To File - DjView</source>
         <comment>dialog caption</comment>
         <translation>Imprimer vers un fichier - DjView</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1792"/>
+        <location filename="qdjviewdialogs.cpp" line="1824"/>
         <source>Question - DjView</source>
         <comment>dialog caption</comment>
         <translation>Question - DjView</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1793"/>
+        <location filename="qdjviewdialogs.cpp" line="1825"/>
         <source>A file with this name already exists.
 Do you want to replace it?</source>
         <translation>Ce fichier existe déjà.
 Voulez-vous le remplacer?</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1795"/>
+        <location filename="qdjviewdialogs.cpp" line="1827"/>
         <source>&amp;Replace</source>
         <translation>&amp;Remplacer</translation>
     </message>
     <message>
-        <location filename="qdjviewdialogs.cpp" line="1675"/>
+        <location filename="qdjviewdialogs.cpp" line="1673"/>
         <source>(invalid printer)</source>
         <translation>(imprimante invalide)</translation>
     </message>
@@ -3100,28 +3105,28 @@ Voulez-vous le remplacer?</translation>
 <context>
     <name>QDjViewPrnExporter</name>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1990"/>
+        <location filename="qdjviewexporters.cpp" line="2003"/>
         <source>Printer data</source>
         <translation>Données d&apos;impression</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1991"/>
+        <location filename="qdjviewexporters.cpp" line="2004"/>
         <source>PRN Files (*.prn)</source>
         <translation>Fichiers PRN (*.prn)</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="2011"/>
+        <location filename="qdjviewexporters.cpp" line="2024"/>
         <source>Printing Options</source>
         <comment>tab caption</comment>
         <translation>Options d&apos;impression</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="2013"/>
+        <location filename="qdjviewexporters.cpp" line="2026"/>
         <source>&lt;html&gt;&lt;b&gt;Printing options.&lt;/b&gt;&lt;br&gt;Option &lt;tt&gt;Color&lt;/tt&gt; enables color printing. Document pages can be decorated with a frame. Option &lt;tt&gt;Scale to fit&lt;/tt&gt; accommodates whatever paper size your printer uses. Zoom factor &lt;tt&gt;100%&lt;/tt&gt; reproduces the initial document size. Orientation &lt;tt&gt;Automatic&lt;/tt&gt; chooses portrait or landscape on a page per page basis.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Options d&apos;impression.&lt;/b&gt;&lt;br&gt;L&apos;option &lt;tt&gt;Couleur&lt;/tt&gt; autorise l&apos;impression en couleur. Les pages imprimées peuvent être décorées avec un cadre. L&apos;option &lt;tt&gt;Agrandir à la page&lt;/tt&gt; choisit un grossissement adapté a la taille de papier utilisée par votre imprimante. Le facteur de grossissement &lt;tt&gt;100%&lt;/tt&gt; reproduit la taille originale du document. L&apos;orientation &lt;tt&gt;Automatique&lt;/tt&gt; sélectionne portrait ou paysage en fonction de la taille de chaque page.&lt;/html&gt;</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="2265"/>
+        <location filename="qdjviewexporters.cpp" line="2278"/>
         <source>Cannot render page %1.</source>
         <translation>Impossible de dessiner la page «%1».</translation>
     </message>
@@ -3302,43 +3307,43 @@ Voulez-vous le remplacer?</translation>
 <context>
     <name>QDjViewTiffExporter</name>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1353"/>
+        <location filename="qdjviewexporters.cpp" line="1365"/>
         <source>TIFF Options</source>
         <comment>tab caption</comment>
         <translation>Options TIFF</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1513"/>
+        <location filename="qdjviewexporters.cpp" line="1525"/>
         <source>Cannot open output file.</source>
         <translation>Impossible d&apos;ouvrir le fichier destination.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1625"/>
+        <location filename="qdjviewexporters.cpp" line="1637"/>
         <source>Out of memory.</source>
         <translation>Mémoire pleine.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1639"/>
+        <location filename="qdjviewexporters.cpp" line="1651"/>
         <source>TIFF export has not been compiled.</source>
         <translation>L&apos;exportation de fichier TIFF n&apos;est pas compilée.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1627"/>
+        <location filename="qdjviewexporters.cpp" line="1639"/>
         <source>Internal error.</source>
         <translation>Erreur interne.</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1333"/>
+        <location filename="qdjviewexporters.cpp" line="1345"/>
         <source>TIFF Document</source>
         <translation>Documents TIFF</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1334"/>
+        <location filename="qdjviewexporters.cpp" line="1346"/>
         <source>TIFF Files (*.tiff *.tif)</source>
         <translation>Fichiers TIFF (*.tiff *.tif)</translation>
     </message>
     <message>
-        <location filename="qdjviewexporters.cpp" line="1355"/>
+        <location filename="qdjviewexporters.cpp" line="1367"/>
         <source>&lt;html&gt;&lt;b&gt;TIFF options.&lt;/b&gt;&lt;br&gt;The resolution box specifies an upper limit for the resolution of the TIFF images. Forcing bitonal G4 compression encodes all pages in black and white using the CCITT Group 4 compression. Allowing JPEG compression uses lossy JPEG for all non bitonal or subsampled images. Otherwise, allowing deflate compression produces more compact (but less portable) files than the default packbits compression.&lt;/html&gt;</source>
         <translation>&lt;html&gt;&lt;b&gt;Options TIFF.&lt;/b&gt;&lt;br&gt;La boite de résolution spécifie la résolution maximale de chaque image dans le fichier TIFF. Forcer la compression bitonale G4 encode toutes les pages en noir et blanc avec la compression CCITT Groupe 4. Autoriser la compression JPEG utilise JPEG pour toutes les images en niveaux de gris ou en couleurs. Sinon, autoriser la compression «deflate» produit des fichiers plus compacts (mais moins portables) que la compression par défaut «packbits».&lt;/html&gt;</translation>
     </message>
--- djview4-4.9.orig/src/tiff2pdf.c
+++ djview4-4.9/src/tiff2pdf.c
@@ -14,78 +14,199 @@
 //C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 //C- GNU General Public License for more details.
 //C-  ------------------------------------------------------------------
+//
+// The following code is derived from program "tiff2pdf"
+// whose copyright notice is reproduced below.
+// Changes were made to make it independent from the private
+// include file tiffiop.h.
 */
-/* The following code is derived from program "tiff2pdf"
- * whose copyright notice is reproduced below.
- * Changes were made to make it independent from the private
- * include file tiffiop.h.
+
+/* $Id: tiff2pdf.c,v 1.37.2.7 2009-01-01 00:10:43 bfriesen Exp $
+ *
+ * tiff2pdf - converts a TIFF image to a PDF document
  *
- * +--------------------------------------------------------------------
- * | tiff2pdf - converts a TIFF image to a PDF document
- * |
- * | Copyright (c) 2003 Ross Finlayson
- * |
- * | Permission to use, copy, modify, distribute, and sell this software and 
- * | its documentation for any purpose is hereby granted without fee, provided
- * | that (i) the above copyright notices and this permission notice appear in
- * | all copies of the software and related documentation, and (ii) the name of
- * | Ross Finlayson may not be used in any advertising or
- * | publicity relating to the software without the specific, prior written
- * | permission of Ross Finlayson.
- * | 
- * | THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
- * | EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
- * | WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
- * | 
- * | IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR
- * | ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
- * | OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * | WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
- * | LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
- * | OF THIS SOFTWARE.
- * +--------------------------------------------------------------------
+ * Copyright (c) 2003 Ross Finlayson
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and 
+ * its documentation for any purpose is hereby granted without fee, provided
+ * that (i) the above copyright notices and this permission notice appear in
+ * all copies of the software and related documentation, and (ii) the name of
+ * Ross Finlayson may not be used in any advertising or
+ * publicity relating to the software without the specific, prior written
+ * permission of Ross Finlayson.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
+ * 
+ * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR
+ * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
+ * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
+ * OF THIS SOFTWARE.
  */
 
 #include "tiff2pdf.h"
 
-#if HAVE_TIFF2PDF
+#ifdef HAVE_TIFF2PDF
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <ctype.h>
 #include <time.h>
+
 #if HAVE_UNISTD_H
 # include <unistd.h>
 #endif
-#ifndef NULL
-# define NULL ((void*)0)
+
+#ifdef HAVE_FCNTL_H
+# include <fcntl.h>
 #endif
 
-#ifdef __GNUC__
-# define unused __attribute__((unused))
+#if defined(__GNUC__) || defined(HAVE_LONG_LONG_INT)
+# define uint64 unsigned long long
+#elif defined(_MSC_VER)
+# define uint64 unsigned __int64
 #else
-# define unused /**/
+# define uint64 size_t
+#endif
+
+#ifdef WIN32
+/*
+ * Copyright (c) 1987, 1993, 1994
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+static int   opterr = 1,        /* if error message should be printed */
+             optind = 1,        /* index into parent argv vector */
+             optopt,            /* character checked for validity */
+             optreset;          /* reset getopt */
+static char *optarg;            /* argument associated with option */
+
+#define	BADCH	(int)'?'
+#define	BADARG	(int)':'
+#define	EMSG	""
+
+/*
+ * getopt --
+ *	Parse argc/argv argument vector.
+ */
+static int
+getopt(int argc, char * const argv[], const char *optstring)
+{
+	static char *place = EMSG;		/* option letter processing */
+	char *oli;				/* option letter list index */
+
+	if (optreset || *place == 0) {		/* update scanning pointer */
+		optreset = 0;
+		place = argv[optind];
+		if (optind >= argc || *place++ != '-') {
+			/* Argument is absent or is not an option */
+			place = EMSG;
+			return (-1);
+		}
+		optopt = *place++;
+		if (optopt == '-' && *place == 0) {
+			/* "--" => end of options */
+			++optind;
+			place = EMSG;
+			return (-1);
+		}
+		if (optopt == 0) {
+			/* Solitary '-', treat as a '-' option
+			   if the program (eg su) is looking for it. */
+			place = EMSG;
+			if (strchr(optstring, '-') == NULL)
+				return -1;
+			optopt = '-';
+		}
+	} else
+		optopt = *place++;
+
+	/* See if option letter is one the caller wanted... */
+	if (optopt == ':' || (oli = strchr(optstring, optopt)) == NULL) {
+		if (*place == 0)
+			++optind;
+		if (opterr && *optstring != ':')
+			(void)fprintf(stderr,
+                                      "unknown option -- %c\n", optopt);
+		return (BADCH);
+	}
+
+	/* Does this option need an argument? */
+	if (oli[1] != ':') {
+		/* don't need argument */
+		optarg = NULL;
+		if (*place == 0)
+			++optind;
+	} else {
+		/* Option-argument is either the rest of this argument or the
+		   entire next argument. */
+		if (*place)
+			optarg = place;
+		else if (argc > ++optind)
+			optarg = argv[optind];
+		else {
+			/* option-argument absent */
+			place = EMSG;
+			if (*optstring == ':')
+				return (BADARG);
+			if (opterr)
+				(void)fprintf(stderr,
+                                        "option requires an argument -- %c\n",
+                                        optopt);
+			return (BADCH);
+		}
+		place = EMSG;
+		++optind;
+	}
+	return (optopt);			/* return option letter */
+}
 #endif
 
-/* -------------------------------------------------- *
-   Tiff2Pdf declarations
- * -------------------------------------------------- */
 
 #define TIFF2PDF_MODULE "tiff2pdf"
-#define T2P_VERSION "d"
+
+#define PS_UNIT_SIZE	72.0F
 
 /* This type is of PDF color spaces. */
-typedef enum{
-	T2P_CS_BILEVEL=0x01, /* Bilevel, black and white */
-	T2P_CS_GRAY=0x02, /* Single channel */
-	T2P_CS_RGB=0x04, /* Three channel tristimulus RGB */
-	T2P_CS_CMYK=0x08, /* Four channel CMYK print inkset */
-	T2P_CS_LAB=0x10, /* Three channel L*a*b* color space */
-	T2P_CS_PALETTE=0x1000 /* One of the above with a color map */
-	, T2P_CS_CALGRAY=0x20 /* Calibrated single channel */
-	, T2P_CS_CALRGB=0x40 /* Calibrated three channel tristimulus RGB */
-	, T2P_CS_ICCBASED=0x80 /* ICC profile color specification */
+typedef enum {
+	T2P_CS_BILEVEL = 0x01,	/* Bilevel, black and white */
+	T2P_CS_GRAY = 0x02,	/* Single channel */
+	T2P_CS_RGB = 0x04,	/* Three channel tristimulus RGB */
+	T2P_CS_CMYK = 0x08,	/* Four channel CMYK print inkset */
+	T2P_CS_LAB = 0x10,	/* Three channel L*a*b* color space */
+	T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */
+	T2P_CS_CALGRAY = 0x20,	/* Calibrated single channel */
+	T2P_CS_CALRGB = 0x40,	/* Calibrated three channel tristimulus RGB */
+	T2P_CS_ICCBASED = 0x80	/* ICC profile color specification */
 } t2p_cs_t;
 
 /* This type is of PDF compression types.  */
@@ -181,9 +302,6 @@ typedef struct {
 	uint16 tiff_orientation;
 	toff_t tiff_dataoffset;
 	tsize_t tiff_datasize;
-	TIFFReadWriteProc tiff_readproc;
-	TIFFReadWriteProc tiff_writeproc;
-	TIFFSeekProc tiff_seekproc;
 	uint16 tiff_resunit;
 	uint16 pdf_centimeters;
 	uint16 pdf_overrideres;
@@ -208,13 +326,13 @@ typedef struct {
 	uint32 pdf_palettecs;
 	uint16 pdf_fitwindow;
 	uint32 pdf_startxref;
-	char* pdf_fileid;
-	char* pdf_datetime;
-	char* pdf_creator;
-	char* pdf_author;
-	char* pdf_title;
-	char* pdf_subject;
-	char* pdf_keywords;
+	unsigned char* pdf_fileid;
+	unsigned char* pdf_datetime;
+	unsigned char* pdf_creator;
+	unsigned char* pdf_author;
+	unsigned char* pdf_title;
+	unsigned char* pdf_subject;
+	unsigned char* pdf_keywords;
 	t2p_cs_t pdf_colorspace;
 	uint16 pdf_colorspace_invert;
 	uint16 pdf_switchdecode;
@@ -247,12 +365,10 @@ typedef struct {
 	uint32 tiff_iccprofilelength;
 	tdata_t tiff_iccprofile;
 
-  /* LB additional fields */
-  FILE *outputfile;
-  int outputdisable;
-  tsize_t outputwritten;
-
-
+	/* fields for custom read/write procedures */
+	FILE *outputfile;
+	int outputdisable;
+	tsize_t outputwritten;
 } T2P;
 
 /* These functions are called by main. */
@@ -261,10 +377,19 @@ static int tiff2pdf_match_paper_size(flo
 
 /* These functions are used to generate a PDF from a TIFF. */ 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 static T2P* t2p_init(void);
 static void t2p_validate(T2P*);
 static tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*);
 static void t2p_free(T2P*);
+
+#ifdef __cplusplus
+}
+#endif
+
 static void t2p_read_tiff_init(T2P*, TIFF*);
 static int t2p_cmp_t2p_page(const void*, const void*);
 static void t2p_read_tiff_data(T2P*, TIFF*);
@@ -272,6 +397,8 @@ static void t2p_read_tiff_size(T2P*, TIF
 static void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t);
 static int t2p_tile_is_right_edge(T2P_TILES, ttile_t);
 static int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t);
+/* static int t2p_tile_is_edge(T2P_TILES, ttile_t); */
+/* static int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); */
 static tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*);
 static tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);
 #ifdef OJPEG_SUPPORT
@@ -291,7 +418,8 @@ static tsize_t t2p_sample_lab_signed_to_
 static tsize_t t2p_write_pdf_header(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_obj_start(uint32, TIFF*);
 static tsize_t t2p_write_pdf_obj_end(TIFF*);
-static tsize_t t2p_write_pdf_string(char*, TIFF*);
+/* static tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); */
+static tsize_t t2p_write_pdf_string(unsigned char*, TIFF*);
 static tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*);
 static tsize_t t2p_write_pdf_stream_start(TIFF*);
 static tsize_t t2p_write_pdf_stream_end(TIFF*);
@@ -308,6 +436,8 @@ static tsize_t t2p_write_pdf_page(uint32
 static void t2p_compose_pdf_page(T2P*);
 static void t2p_compose_pdf_page_orient(T2P_BOX*, uint16);
 static void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16);
+/* static tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); */
+static tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); 
 static tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_transfer(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16);
@@ -316,280 +446,142 @@ static tsize_t t2p_write_pdf_xobject_cal
 static tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*);
+/* static tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); */
 static tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*);
 static tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*);
 static tsize_t t2p_write_pdf_trailer(T2P*, TIFF*);
 
-
-
-/* -------------------------------------------------- *
-   Replacement for tiffiop functions
- * -------------------------------------------------- */
-
-
-static unused tsize_t 
-t2pReadFile(TIFF *tif, tdata_t data, tsize_t size)
+static void
+t2p_disable(TIFF *tif)
 {
-  thandle_t client = TIFFClientdata(tif);
-  TIFFReadWriteProc proc =  TIFFGetReadProc(tif);
-  if (proc)
-    return proc(client, data, size);
-  return -1;
+	T2P *t2p = (T2P*) TIFFClientdata(tif);
+	t2p->outputdisable = 1;
 }
 
-static unused tsize_t 
-t2pWriteFile(TIFF *tif, tdata_t data, tsize_t size)
+static void
+t2p_enable(TIFF *tif)
 {
-  thandle_t client = TIFFClientdata(tif);
-  TIFFReadWriteProc proc =  TIFFGetWriteProc(tif);
-  if (proc)
-    return proc(client, data, size);
-  return -1;
+	T2P *t2p = (T2P*) TIFFClientdata(tif);
+	t2p->outputdisable = 0;
 }
 
+/*
+ * Procs for TIFFClientOpen
+ */
 
-static unused toff_t
-t2pSeekFile(TIFF *tif, toff_t offset, int whence)
+static tsize_t 
+t2pReadFile(TIFF *tif, tdata_t data, tsize_t size)
 {
-  thandle_t client = TIFFClientdata(tif);
-  TIFFSeekProc proc =  TIFFGetSeekProc(tif);
-  if (proc)
-    return proc(client, offset, whence);
-  return -1;
+	thandle_t client = TIFFClientdata(tif);
+	TIFFReadWriteProc proc =  TIFFGetReadProc(tif);
+	if (proc)
+		return proc(client, data, size);
+	return -1;
 }
 
-#ifdef TIFFReadFile
-# undef TIFFReadFile
-#endif
-#ifndef TIFFReadFile
-# define TIFFReadFile t2pReadFile
-#endif
-
-#ifdef TIFFWriteFile
-# undef TIFFWriteFile
-#endif
-#ifndef TIFFWriteFile
-# define TIFFWriteFile t2pWriteFile
-#endif
-
-#ifdef TIFFSeekFile
-# undef TIFFSeekFile
-#endif
-#ifndef TIFFSeekFile
-# define TIFFSeekFile t2pSeekFile
-#endif
-
-
-static void
-t2p_disable(TIFF *tif)
+static tsize_t 
+t2pWriteFile(TIFF *tif, tdata_t data, tsize_t size)
 {
-  T2P *t2p = (T2P*) TIFFClientdata(tif);
-  t2p->outputdisable = 1;
+	thandle_t client = TIFFClientdata(tif);
+	TIFFReadWriteProc proc =  TIFFGetWriteProc(tif);
+	if (proc)
+		return proc(client, data, size);
+	return -1;
 }
 
-static void
-t2p_enable(TIFF *tif)
+static toff_t
+t2pSeekFile(TIFF *tif, toff_t offset, int whence)
 {
-  T2P *t2p = (T2P*) TIFFClientdata(tif);
-  t2p->outputdisable = 0;
+	thandle_t client = TIFFClientdata(tif);
+	TIFFSeekProc proc =  TIFFGetSeekProc(tif);
+	if (proc)
+		return proc(client, offset, whence);
+	return -1;
 }
 
-
-
-/* -------------------------------------------------- *
-   Procs for TIFFClientOpen
- * -------------------------------------------------- */
-
 static tsize_t 
-t2p_readproc(thandle_t unused handle, tdata_t unused data , tsize_t unused size) 
-{ 
-  return -1;
+t2p_readproc(thandle_t handle, tdata_t data, tsize_t size) 
+{
+	(void) handle, (void) data, (void) size;
+	return -1;
 }
 
 static tsize_t 
 t2p_writeproc(thandle_t handle, tdata_t data, tsize_t size) 
 {
-  T2P *t2p = (T2P*) handle;
-  if (t2p->outputdisable <= 0 && t2p->outputfile)
-    {
-      tsize_t written = fwrite(data, 1, size, t2p->outputfile);
-      t2p->outputwritten += written;
-      return written;
-    }
-  return size; 
+	T2P *t2p = (T2P*) handle;
+	if (t2p->outputdisable <= 0 && t2p->outputfile) {
+		tsize_t written = fwrite(data, 1, size, t2p->outputfile);
+		t2p->outputwritten += written;
+		return written;
+	}
+	return size; 
 }
 
 static toff_t 
 t2p_seekproc(thandle_t handle, toff_t offset, int whence) 
 { 
-  T2P *t2p = (T2P*) handle;
-  if (t2p->outputdisable <= 0 && t2p->outputfile)
-    return fseek(t2p->outputfile, offset, whence);
-  return offset;
+	T2P *t2p = (T2P*) handle;
+	if (t2p->outputdisable <= 0 && t2p->outputfile)
+		return fseek(t2p->outputfile, offset, whence);
+	return offset;
 }
 
 static int 
-t2p_closeproc(thandle_t unused handle) 
+t2p_closeproc(thandle_t handle)
 { 
-  return 0; 
+	(void) handle;
+	return 0; 
 }
 
 static toff_t 
-t2p_sizeproc(thandle_t unused handle) 
-{ 
-  return -1;
+t2p_sizeproc(thandle_t handle) 
+{
+	(void) handle;
+	return -1;
 }
 
 static int 
-t2p_mapproc(thandle_t unused handle, tdata_t unused *data, toff_t unused *offset) 
+t2p_mapproc(thandle_t handle, tdata_t *data, toff_t *offset) 
 { 
-  return -1; 
+	(void) handle, (void) data, (void) offset;
+	return -1; 
 }
 
 static void 
-t2p_unmapproc(thandle_t unused handle, tdata_t unused data, toff_t unused offset) 
+t2p_unmapproc(thandle_t handle, tdata_t data, toff_t offset)
 { 
+	(void) handle, (void) data, (void) offset;
 }
 
-
-
-/* -------------------------------------------------- *
-   Ports
- * -------------------------------------------------- */
-
-#ifdef WIN32
-/*
- * Copyright (c) 1987, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if 0
-static char sccsid[] = "@(#)getopt.c	8.3 (Berkeley) 4/27/95";
-__RCSID("$NetBSD: getopt.c,v 1.26 2003/08/07 16:43:40 agc Exp $");
-#endif
-
-#include <stdio.h>
-#include <string.h>
-
-int	opterr = 1,		/* if error message should be printed */
-	optind = 1,		/* index into parent argv vector */
-	optopt,			/* character checked for validity */
-	optreset;		/* reset getopt */
-char	*optarg;		/* argument associated with option */
-
-#define	BADCH	(int)'?'
-#define	BADARG	(int)':'
-#define	EMSG	""
-
-/*
- * getopt --
- *	Parse argc/argv argument vector.
- */
-int
-getopt(int argc, char * const argv[], const char *optstring)
+static uint64
+checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p)
 {
-	static char *place = EMSG;		/* option letter processing */
-	char *oli;				/* option letter list index */
-
-	if (optreset || *place == 0) {		/* update scanning pointer */
-		optreset = 0;
-		place = argv[optind];
-		if (optind >= argc || *place++ != '-') {
-			/* Argument is absent or is not an option */
-			place = EMSG;
-			return (-1);
-		}
-		optopt = *place++;
-		if (optopt == '-' && *place == 0) {
-			/* "--" => end of options */
-			++optind;
-			place = EMSG;
-			return (-1);
-		}
-		if (optopt == 0) {
-			/* Solitary '-', treat as a '-' option
-			   if the program (eg su) is looking for it. */
-			place = EMSG;
-			if (strchr(optstring, '-') == NULL)
-				return -1;
-			optopt = '-';
-		}
-	} else
-		optopt = *place++;
+	uint64 bytes = summand1 + summand2;
 
-	/* See if option letter is one the caller wanted... */
-	if (optopt == ':' || (oli = strchr(optstring, optopt)) == NULL) {
-		if (*place == 0)
-			++optind;
-		if (opterr && *optstring != ':')
-			(void)fprintf(stderr,
-                                      "unknown option -- %c\n", optopt);
-		return (BADCH);
+	if (bytes - summand1 != summand2) {
+		TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+		t2p->t2p_error = T2P_ERR_ERROR;
+		bytes = 0;
 	}
 
-	/* Does this option need an argument? */
-	if (oli[1] != ':') {
-		/* don't need argument */
-		optarg = NULL;
-		if (*place == 0)
-			++optind;
-	} else {
-		/* Option-argument is either the rest of this argument or the
-		   entire next argument. */
-		if (*place)
-			optarg = place;
-		else if (argc > ++optind)
-			optarg = argv[optind];
-		else {
-			/* option-argument absent */
-			place = EMSG;
-			if (*optstring == ':')
-				return (BADARG);
-			if (opterr)
-				(void)fprintf(stderr,
-                                        "option requires an argument -- %c\n",
-                                        optopt);
-			return (BADCH);
-		}
-		place = EMSG;
-		++optind;
-	}
-	return (optopt);			/* return option letter */
+	return bytes;
 }
 
-#endif
-
-
+static uint64
+checkMultiply64(uint64 first, uint64 second, T2P* t2p)
+{
+	uint64 bytes = first * second;
 
-/* -------------------------------------------------- *
-   Main function
- * -------------------------------------------------- */
+	if (second && bytes / second != first) {
+		TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+		t2p->t2p_error = T2P_ERR_ERROR;
+		bytes = 0;
+	}
 
+	return bytes;
+}
 
 /*
 
@@ -663,23 +655,21 @@ getopt(int argc, char * const argv[], co
     options:
     -o: output to file name
 
-    -j  compress with JPEG (requires libjpeg configured with libtiff)
-    -z  compress with Zip/Deflate (requires zlib configured with libtiff)
+    -j: compress with JPEG (requires libjpeg configured with libtiff)
+    -z: compress with Zip/Deflate (requires zlib configured with libtiff)
     -q: compression quality
-    -n  no compressed data passthrough
-    -d  do not compress (decompress)
-
-	-i  invert colors
-	
+    -n: no compressed data passthrough
+    -d: do not compress (decompress)
+    -i: invert colors
     -u: set distance unit, 'i' for inch, 'm' for centimeter
     -x: set x resolution default
     -y: set y resolution default
     -w: width in units
     -l: length in units
     -r: 'd' for resolution default, 'o' for resolution override
-    -p: paper size, eg "letter", "legal", "A4"
-    -f  set PDF "Fit Window" user preference
-    -b set PDF "Interpolate" user preference
+    -p: paper size, eg "letter", "legal", "a4"
+    -f: set pdf "fit window" user preference
+    -b:	set PDF "Interpolate" user preference
     -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS
     -c: creator, overrides image software default
     -a: author, overrides image artist default
@@ -687,7 +677,7 @@ getopt(int argc, char * const argv[], co
     -s: subject, overrides image image description default
     -k: keywords
 
-    -h  usage
+    -h: usage
 
     examples:
 
@@ -713,193 +703,253 @@ getopt(int argc, char * const argv[], co
     See also libtiff.3t, tiffcp.
   */
 
-
 int
 tiff2pdf(TIFF *input, FILE *outputfile, int argc, const char **argv)
 {
-  extern char *optarg;
-  const char *outfilename = "<null>";
-  T2P *t2p = NULL;
-  TIFF *output = NULL;
-  int c;
-
-  /* T2P */
-  t2p = t2p_init();
-  if (t2p == NULL){
-    TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
-    goto fail;
-  }
-
-  /* Options */
-  while (argv && 
-         (c = getopt(argc, (char**)argv, 
-                     "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1) {
-    switch (c) {
-    case 'o':
-      outfilename = optarg;
-      break;
+        char *outfilename = "<null>";
+        T2P *t2p = NULL;
+        TIFF *output = NULL;
+	tsize_t written = 0;
+	int c;
+
+        (void)written;
+
+	t2p = t2p_init();
+
+	if (t2p == NULL){
+		TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
+		goto fail;
+	}
+
+	while (argv &&
+	       (c = getopt(argc, (void*)argv,
+			   "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1){
+		switch (c) {
+			case 'o':
+				outfilename = optarg;
+				break;
 #ifdef JPEG_SUPPORT
-    case 'j':  
-      t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG;
-      break;
+			case 'j':  
+				t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG;
+				break;
+#endif
+#ifndef JPEG_SUPPORT
+			case 'j':  
+				TIFFWarning(
+					TIFF2PDF_MODULE, 
+					"JPEG support in libtiff required for JPEG compression, ignoring option");
+				break;
 #endif
 #ifdef ZIP_SUPPORT
-    case 'z':  
-      t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP;
-      break;
-#endif
-    case 'q': 
-      t2p->pdf_defaultcompressionquality=atoi(optarg);
-      break;
-    case 'n': 
-      t2p->pdf_nopassthrough=1;
-      break;
-    case 'd': 
-      t2p->pdf_defaultcompression=T2P_COMPRESS_NONE;
-      break;
-    case 'u': 
-      if(optarg[0]=='m'){
-        t2p->pdf_centimeters=1;
-      }
-      break;
-    case 'x': 
-      t2p->pdf_defaultxres = 
-        (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
-      break;
-    case 'y': 
-      t2p->pdf_defaultyres = 
-        (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
-      break;
-    case 'w': 
-      t2p->pdf_overridepagesize=1;
-      t2p->pdf_defaultpagewidth = 
-        ((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F);
-      break;
-    case 'l': 
-      t2p->pdf_overridepagesize=1;
-      t2p->pdf_defaultpagelength = 
-        ((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F);
-      break;
-    case 'r': 
-      if(optarg[0]=='o'){
-        t2p->pdf_overrideres=1;
-      }
-      break;
-    case 'p': 
-      if(tiff2pdf_match_paper_size(&(t2p->pdf_defaultpagewidth), 
-                                   &(t2p->pdf_defaultpagelength), 
-                                   optarg)){
-        t2p->pdf_overridepagesize=1;
-      } else {
-        TIFFWarning(TIFF2PDF_MODULE, 
-                    "Unknown paper size %s, ignoring option",
-                    optarg);
-      }
-      break;
-    case 'i':
-      t2p->pdf_colorspace_invert=1;
-      break;
-    case 'f': 
-      t2p->pdf_fitwindow=1;
-      break;
-    case 'e':
-      t2p->pdf_datetime = (char*)_TIFFmalloc(17);
-      if(t2p->pdf_datetime){
-        if(strlen(optarg)==0){
-          t2p->pdf_datetime[0]=0;
-        } else {
-          if(strlen(optarg)>14){optarg[14]=0;}
-          t2p->pdf_datetime[0]='D';
-          t2p->pdf_datetime[1]=':';
-          strcpy(&(t2p->pdf_datetime[2]), optarg);
-        }
-      }
-      break;
-    case 'c': 
-      t2p->pdf_creator = (char *)_TIFFmalloc(strlen(optarg) + 1);
-      if(t2p->pdf_creator){
-        strcpy(t2p->pdf_creator, optarg);
-        t2p->pdf_creator[strlen(optarg)]=0;
-      }
-      break;
-    case 'a': 
-      t2p->pdf_author = (char *)_TIFFmalloc(strlen(optarg) + 1);
-      if(t2p->pdf_author){
-        strcpy(t2p->pdf_author, optarg);
-        t2p->pdf_author[strlen(optarg)]=0;
-      }
-      break;
-    case 't': 
-      t2p->pdf_title= (char*)_TIFFmalloc(strlen(optarg)+1);
-      if(t2p->pdf_title){
-        strcpy(t2p->pdf_title, optarg);
-        t2p->pdf_title[strlen(optarg)]=0;
-      }
-      break;
-    case 's': 
-      t2p->pdf_subject= (char*)_TIFFmalloc(strlen(optarg)+1);
-      if(t2p->pdf_subject){
-        strcpy(t2p->pdf_subject, optarg);
-        t2p->pdf_subject[strlen(optarg)]=0;
-      }
-      break;
-    case 'k': 
-      t2p->pdf_keywords= (char*)_TIFFmalloc(strlen(optarg)+1);
-      if(t2p->pdf_keywords){
-        strcpy(t2p->pdf_keywords, optarg);
-        t2p->pdf_keywords[strlen(optarg)]=0;
-      }
-      break;		
-    case 'b':
-      t2p->pdf_image_interpolate = 1;
-      break;
-    }
-  }
-
-  /* Output */
-  t2p->outputdisable = 0;
-  t2p->outputfile = outputfile;
-  output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p,
-                          t2p_readproc, t2p_writeproc, t2p_seekproc, 
-                          t2p_closeproc, t2p_sizeproc, 
-                          t2p_mapproc, t2p_unmapproc );
-  if (output == NULL){
-    TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor");
-    goto fail;
-  }
-  
-  /* Validate */
-  t2p_validate(t2p);
-  TIFFSeekFile(output, (toff_t) 0, SEEK_SET);
-
-  /* Write */
-  t2p_write_pdf(t2p, input, output);
-  if(t2p->t2p_error != 0){
-    TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file");
-    goto fail;
-  }
-
-  if (output != NULL)
-    TIFFClose(output);
-  if (t2p != NULL)
-    t2p_free(t2p);
-  return(EXIT_SUCCESS);
+			case 'z':  
+				t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP;
+				break;
+#endif
+#ifndef ZIP_SUPPORT
+			case 'z':  
+				TIFFWarning(
+					TIFF2PDF_MODULE, 
+					"Zip support in libtiff required for Zip compression, ignoring option");
+				break;
+#endif
+			case 'q': 
+				t2p->pdf_defaultcompressionquality=atoi(optarg);
+				break;
+			case 'n': 
+				t2p->pdf_nopassthrough=1;
+				break;
+			case 'd': 
+				t2p->pdf_defaultcompression=T2P_COMPRESS_NONE;
+				break;
+			case 'u': 
+				if(optarg[0]=='m'){
+					t2p->pdf_centimeters=1;
+				}
+				break;
+			case 'x': 
+				t2p->pdf_defaultxres = 
+					(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
+				break;
+			case 'y': 
+				t2p->pdf_defaultyres = 
+					(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
+				break;
+			case 'w': 
+				t2p->pdf_overridepagesize=1;
+				t2p->pdf_defaultpagewidth = 
+					((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F);
+				break;
+			case 'l': 
+				t2p->pdf_overridepagesize=1;
+				t2p->pdf_defaultpagelength = 
+					((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F);
+				break;
+			case 'r': 
+				if(optarg[0]=='o'){
+					t2p->pdf_overrideres=1;
+				}
+				break;
+			case 'p': 
+				if(tiff2pdf_match_paper_size(
+					&(t2p->pdf_defaultpagewidth), 
+					&(t2p->pdf_defaultpagelength), 
+					optarg)){
+					t2p->pdf_overridepagesize=1;
+				} else {
+					TIFFWarning(TIFF2PDF_MODULE, 
+					"Unknown paper size %s, ignoring option",
+						optarg);
+				}
+				break;
+			case 'i':
+				t2p->pdf_colorspace_invert=1;
+				break;
+			case 'f': 
+				t2p->pdf_fitwindow=1;
+				break;
+			case 'e':
+				t2p->pdf_datetime =
+					(unsigned char*)_TIFFmalloc(17);
+				if(t2p->pdf_datetime==NULL){
+					TIFFError(TIFF2PDF_MODULE, 
+				"Can't allocate %u bytes of memory for main", 
+						17); 
+					goto fail;
+				}
+				if(strlen(optarg)==0){
+					t2p->pdf_datetime[0] = 0;
+				} else {
+					if(strlen(optarg)>14){optarg[14]=0;}
+					t2p->pdf_datetime[0] = 'D';
+					t2p->pdf_datetime[1] = ':';
+					strcpy((char *)t2p->pdf_datetime + 2,
+					       optarg);
+				}
+				break;
+			case 'c': 
+				t2p->pdf_creator = (unsigned char *)
+					_TIFFmalloc(strlen(optarg) + 1);
+				if(t2p->pdf_creator==NULL){
+					TIFFError(TIFF2PDF_MODULE, 
+				"Can't allocate %lu bytes of memory for main", 
+						  (long)strlen(optarg) + 1); 
+					goto fail;
+				}
+				strcpy((char *)t2p->pdf_creator, optarg);
+				t2p->pdf_creator[strlen(optarg)] = 0;
+				break;
+			case 'a': 
+				t2p->pdf_author = (unsigned char *)
+					_TIFFmalloc(strlen(optarg) + 1);
+				if(t2p->pdf_author==NULL){
+					TIFFError(
+						TIFF2PDF_MODULE, 
+				"Can't allocate %lu bytes of memory for main", 
+						(long)strlen(optarg) + 1); 
+					goto fail;
+				}
+				strcpy((char *)t2p->pdf_author, optarg);
+				t2p->pdf_author[strlen(optarg)]=0;
+				break;
+			case 't': 
+				t2p->pdf_title = (unsigned char*)
+					_TIFFmalloc(strlen(optarg)+1);
+				if(t2p->pdf_title==NULL){
+					TIFFError(
+						TIFF2PDF_MODULE, 
+				"Can't allocate %lu bytes of memory for main", 
+						(long)strlen(optarg) + 1); 
+					goto fail;
+				}
+				strcpy((char *)t2p->pdf_title, optarg);
+				t2p->pdf_title[strlen(optarg)] = 0;
+				break;
+			case 's': 
+				t2p->pdf_subject = (unsigned char*)
+					_TIFFmalloc(strlen(optarg) + 1);
+				if(t2p->pdf_subject==NULL){
+					TIFFError(
+						TIFF2PDF_MODULE, 
+				"Can't allocate %lu bytes of memory for main", 
+						(long)strlen(optarg)+1); 
+					goto fail;
+				}
+				strcpy((char *)t2p->pdf_subject, optarg);
+				t2p->pdf_subject[strlen(optarg)]=0;
+				break;
+			case 'k': 
+				t2p->pdf_keywords = (unsigned char*)
+					_TIFFmalloc(strlen(optarg) + 1);
+				if(t2p->pdf_keywords==NULL){
+					TIFFError(
+						TIFF2PDF_MODULE, 
+				"Can't allocate %lu bytes of memory for main", 
+						(long)strlen(optarg) + 1); 
+					goto fail;
+				}
+				strcpy((char *)t2p->pdf_keywords, optarg);
+				t2p->pdf_keywords[strlen(optarg)] = 0;
+				break;		
+			case 'b':
+				t2p->pdf_image_interpolate = 1;
+				break;
+		}
+	}
+
+	/*
+	 * Output
+	 */
+	t2p->outputdisable = 0;
+        t2p->outputfile = outputfile;
+
+	output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p,
+				t2p_readproc, t2p_writeproc, t2p_seekproc, 
+				t2p_closeproc, t2p_sizeproc, 
+				t2p_mapproc, t2p_unmapproc );
+	if (output == NULL) {
+		TIFFError(TIFF2PDF_MODULE,
+			  "Can't initialize output descriptor");
+		goto fail;
+	}
+	
+	/*
+	 * Validate
+	 */
+	t2p_validate(t2p);
+	t2pSeekFile(output, (toff_t) 0, SEEK_SET);
+
+	/*
+	 * Write
+	 */
+	written = t2p_write_pdf(t2p, input, output);
+	if (t2p->t2p_error != 0) {
+		TIFFError(TIFF2PDF_MODULE,
+			  "An error occurred creating output PDF file");
+		goto fail;
+	}
+
+/* success: */
+	if (output != NULL)
+		TIFFClose(output);
+	if (t2p != NULL)
+		t2p_free(t2p);
+	return(EXIT_SUCCESS);
 
 fail:
-  if (output != NULL)
-    TIFFClose(output);
-  if (t2p != NULL)
-    t2p_free(t2p);
-  return(EXIT_FAILURE);
+	if(input != NULL)
+		TIFFClose(input);
+	if (output != NULL)
+		TIFFClose(output);
+	if (t2p != NULL)
+		t2p_free(t2p);
+	return(EXIT_FAILURE);
+  
 }
 
 
-static int 
-tiff2pdf_match_paper_size(float* width, float* length, char* papersize)
-{
+static int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){
 
-	int i=0;
-	int len=0;
+	size_t i, len;
 	const char* sizes[]={
 		"LETTER", "A4", "LEGAL",
 		"EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", 
@@ -957,27 +1007,18 @@ tiff2pdf_match_paper_size(float* width,
 	return(0);
 }
 
-
-
-
-/* -------------------------------------------------- *
-   Tiff2Pdf proper with minor changes
- * -------------------------------------------------- */
-
-
-
 /*
 	This function allocates and initializes a T2P context struct pointer.
 */
 
-static T2P* t2p_init()
-{
+static T2P* t2p_init(){
+
 	T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P));
 	if(t2p==NULL){
 		TIFFError(
 			TIFF2PDF_MODULE, 
-			"Can't allocate %u bytes of memory for t2p_init", 
-			(int)sizeof(T2P));
+			"Can't allocate %lu bytes of memory for t2p_init", 
+			(long)sizeof(T2P));
 		return( (T2P*) NULL );
 	}
 	_TIFFmemset(t2p, 0x00, sizeof(T2P));
@@ -988,9 +1029,7 @@ static T2P* t2p_init()
 	t2p->pdf_defaultpagewidth=612.0;
 	t2p->pdf_defaultpagelength=792.0;
 	t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */
-        t2p->outputfile = NULL;
-        t2p->outputdisable = 0;
-        t2p->outputwritten = 0;
+	
 	return(t2p);
 }
 
@@ -1061,7 +1100,7 @@ static void t2p_validate(T2P* t2p){
 
 #ifdef JPEG_SUPPORT
 	if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
-		if(t2p->pdf_defaultcompressionquality<100 ||
+		if(t2p->pdf_defaultcompressionquality>100 ||
 			t2p->pdf_defaultcompressionquality<1){
 			t2p->pdf_defaultcompressionquality=0;
 		}
@@ -1069,22 +1108,14 @@ static void t2p_validate(T2P* t2p){
 #endif
 #ifdef ZIP_SUPPORT
 	if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){
-		switch (t2p->pdf_defaultcompressionquality){
-			case 1: case 10: case 11: case 12: case 13: case 14: case 15:
-			case 101: case 110: case 111: case 112: case 113: case 114: case 115:
-			case 201: case 210: case 211: case 212: case 213: case 214: case 215:
-			case 301: case 310: case 311: case 312: case 313: case 314: case 315:
-			case 401: case 410: case 411: case 412: case 413: case 414: case 415:
-			case 501: case 510: case 511: case 512: case 513: case 514: case 515:
-			case 601: case 610: case 611: case 612: case 613: case 614: case 615:
-			case 701: case 710: case 711: case 712: case 713: case 714: case 715:
-			case 801: case 810: case 811: case 812: case 813: case 814: case 815:
-			case 901: case 910: case 911: case 912: case 913: case 914: case 915:
-				break;
-			default:
-				t2p->pdf_defaultcompressionquality=0;
+ 		uint16 m=t2p->pdf_defaultcompressionquality%100;
+ 		if(t2p->pdf_defaultcompressionquality/100 > 9 ||
+ 			(m>1 && m<10) || m>15){
+ 			t2p->pdf_defaultcompressionquality=0;
 		}
 		if(t2p->pdf_defaultcompressionquality%100 !=0){
+ 			t2p->pdf_defaultcompressionquality/=100;
+ 			t2p->pdf_defaultcompressionquality*=100;
 			TIFFError(
 				TIFF2PDF_MODULE, 
 				"PNG Group predictor differencing not implemented, assuming compression quality %u", 
@@ -1120,8 +1151,8 @@ static void t2p_read_tiff_init(T2P* t2p,
 	if(t2p->tiff_pages==NULL){
 		TIFFError(
 			TIFF2PDF_MODULE, 
-			"Can't allocate %u bytes of memory for tiff_pages array, %s", 
-			directorycount * (int)sizeof(T2P_PAGE), 
+			"Can't allocate %lu bytes of memory for tiff_pages array, %s", 
+			directorycount * (long)sizeof(T2P_PAGE), 
 			TIFFFileName(input));
 		t2p->t2p_error = T2P_ERR_ERROR;
 		return;
@@ -1131,8 +1162,8 @@ static void t2p_read_tiff_init(T2P* t2p,
 	if(t2p->tiff_tiles==NULL){
 		TIFFError(
 			TIFF2PDF_MODULE, 
-			"Can't allocate %u bytes of memory for tiff_tiles array, %s", 
-			directorycount * (int)sizeof(T2P_TILES), 
+			"Can't allocate %lu bytes of memory for tiff_tiles array, %s", 
+			directorycount * (long)sizeof(T2P_TILES), 
 			TIFFFileName(input));
 		t2p->t2p_error = T2P_ERR_ERROR;
 		return;
@@ -1147,6 +1178,7 @@ static void t2p_read_tiff_init(T2P* t2p,
 				"Can't set directory %u of input file %s", 
 				i,
 				TIFFFileName(input));
+			t2p->t2p_error = T2P_ERR_ERROR;
 			return;
 		}
 		if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){
@@ -1263,8 +1295,8 @@ static void t2p_read_tiff_init(T2P* t2p,
 			if( t2p->tiff_tiles[i].tiles_tiles == NULL){
 				TIFFError(
 					TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_read_tiff_init, %s", 
-					t2p->tiff_tiles[i].tiles_tilecount * (int)sizeof(T2P_TILE), 
+					"Can't allocate %lu bytes of memory for t2p_read_tiff_init, %s", 
+					t2p->tiff_tiles[i].tiles_tilecount * (long)sizeof(T2P_TILE), 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return;
@@ -1276,8 +1308,9 @@ static void t2p_read_tiff_init(T2P* t2p,
 }
 
 /*
-	This function is used by qsort to sort a T2P_PAGE* array of page structures by page number.
-*/
+ * This function is used by qsort to sort a T2P_PAGE* array of page structures
+ * by page number.
+ */
 
 static int t2p_cmp_t2p_page(const void* e1, const void* e2){
 
@@ -1503,7 +1536,7 @@ static void t2p_read_tiff_data(T2P* t2p,
 				TIFFError(
 					TIFF2PDF_MODULE, 
 					"No support for palettized image %s with not one sample per pixel", 
-					TIFFFileName(input) );
+					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return;
 			}
@@ -1572,7 +1605,7 @@ static void t2p_read_tiff_data(T2P* t2p,
 				TIFFError(
 					TIFF2PDF_MODULE, 
 					"No support for palettized CMYK image %s with not one sample per pixel", 
-					TIFFFileName(input) );
+					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return;
 			}
@@ -1605,7 +1638,7 @@ static void t2p_read_tiff_data(T2P* t2p,
 				t2p->pdf_palette[(i*4)]  = (unsigned char) (r[i]>>8);
 				t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8);
 				t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8);
-				t2p->pdf_palette[(i*4)+2]= (unsigned char) (a[i]>>8);
+				t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8);
 			}
 			t2p->pdf_palettesize *= 4;
 			break;
@@ -1712,13 +1745,15 @@ static void t2p_read_tiff_data(T2P* t2p,
         if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){
                 t2p->tiff_yres=0.0;
         }
-	TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit) );
-	if(t2p->tiff_resunit==RESUNIT_CENTIMETER){
-		t2p->tiff_xres*=2.54F;
-		t2p->tiff_yres*=2.54F;
-	} else if (t2p->tiff_resunit!=RESUNIT_INCH && t2p->pdf_centimeters!=0){
-		t2p->tiff_xres*=2.54F;
-		t2p->tiff_yres*=2.54F;
+	TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT,
+			      &(t2p->tiff_resunit));
+	if(t2p->tiff_resunit == RESUNIT_CENTIMETER) {
+		t2p->tiff_xres *= 2.54F;
+		t2p->tiff_yres *= 2.54F;
+	} else if (t2p->tiff_resunit != RESUNIT_INCH
+		   && t2p->pdf_centimeters != 0) {
+		t2p->tiff_xres *= 2.54F;
+		t2p->tiff_yres *= 2.54F;
 	}
 
 	t2p_compose_pdf_page(t2p);
@@ -1879,13 +1914,11 @@ static void t2p_read_tiff_size(T2P* t2p,
 	uint32* sbc=NULL;
 #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT)
 	unsigned char* jpt=NULL;
-	uint32 xuint32=0;
 	tstrip_t i=0;
 	tstrip_t stripcount=0;
 #endif
-#ifdef OJPEG_SUPPORT
-        tsize_t k = 0;
-#endif
+        uint64 k = 0;
+
 	if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
 #ifdef CCITT_SUPPORT
 		if(t2p->pdf_compression == T2P_COMPRESS_G4 ){
@@ -1912,19 +1945,25 @@ static void t2p_read_tiff_size(T2P* t2p,
 			}
 			stripcount=TIFFNumberOfStrips(input);
 			for(i=0;i<stripcount;i++){
-				k += sbc[i];
+				k = checkAdd64(k, sbc[i], t2p);
 			}
 			if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){
 				if(t2p->tiff_dataoffset != 0){
 					if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){
-						if(t2p->tiff_datasize < k) {
-							t2p->pdf_ojpegiflength=t2p->tiff_datasize;
-							t2p->tiff_datasize+=k;
-							t2p->tiff_datasize+=6;
-							t2p->tiff_datasize+=2*stripcount;
+                                          if((uint64)t2p->tiff_datasize < k) {
 							TIFFWarning(TIFF2PDF_MODULE, 
 								"Input file %s has short JPEG interchange file byte count", 
 								TIFFFileName(input));
+							t2p->pdf_ojpegiflength=t2p->tiff_datasize;
+							k = checkAdd64(k, t2p->tiff_datasize, t2p);
+							k = checkAdd64(k, 6, t2p);
+							k = checkAdd64(k, stripcount, t2p);
+							k = checkAdd64(k, stripcount, t2p);
+							t2p->tiff_datasize = (tsize_t) k;
+							if ((uint64) t2p->tiff_datasize != k) {
+								TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+								t2p->t2p_error = T2P_ERR_ERROR;
+							}
 							return;
 						}
 						return;
@@ -1937,22 +1976,27 @@ static void t2p_read_tiff_size(T2P* t2p,
 					}
 				}
 			}
-			t2p->tiff_datasize+=k;
-			t2p->tiff_datasize+=2*stripcount;
-			t2p->tiff_datasize+=2048;
+			k = checkAdd64(k, stripcount, t2p);
+			k = checkAdd64(k, stripcount, t2p);
+			k = checkAdd64(k, 2048, t2p);
+			t2p->tiff_datasize = (tsize_t) k;
+			if ((uint64) t2p->tiff_datasize != k) {
+				TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+				t2p->t2p_error = T2P_ERR_ERROR;
+			}
 			return;
 		}
 #endif
 #ifdef JPEG_SUPPORT
-		if(t2p->tiff_compression == COMPRESSION_JPEG){
-			t2p->tiff_datasize = 2048; /* safety margin (actually used!) */
-			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0 ){
-				if(xuint32>4){
-                                        t2p->tiff_datasize+= xuint32;
-					t2p->tiff_datasize -=2; /* don't use EOI of header */
+		if(t2p->tiff_compression == COMPRESSION_JPEG) {
+			uint32 count = 0;
+			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){
+				if(count > 4){
+					k += count;
+					k -= 2; /* don't use EOI of header */
 				}
 			} else {
-				t2p->tiff_datasize=2; /* SOI for first strip */
+				k = 2; /* SOI for first strip */
 			}
 			stripcount=TIFFNumberOfStrips(input);
 			if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
@@ -1963,18 +2007,32 @@ static void t2p_read_tiff_size(T2P* t2p,
 				return;
 			}
 			for(i=0;i<stripcount;i++){
-				t2p->tiff_datasize += sbc[i];
-				t2p->tiff_datasize -=4; /* don't use SOI or EOI of strip */
+				k = checkAdd64(k, sbc[i], t2p);
+				k -=4; /* don't use SOI or EOI of strip */
+			}
+			k = checkAdd64(k, 2, t2p); /* use EOI of last strip */
+			t2p->tiff_datasize = (tsize_t) k;
+			if ((uint64) t2p->tiff_datasize != k) {
+				TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+				t2p->t2p_error = T2P_ERR_ERROR;
 			}
-			t2p->tiff_datasize +=2; /* use EOI of last strip */
-                        return;
 		}
 #endif
 		(void) 0;
 	}
-	t2p->tiff_datasize=TIFFScanlineSize(input) * t2p->tiff_length;
+	k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p);
 	if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
-		t2p->tiff_datasize*= t2p->tiff_samplesperpixel;
+		k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
+	}
+	if (k == 0) {
+		/* Assume we had overflow inside TIFFScanlineSize */
+		t2p->t2p_error = T2P_ERR_ERROR;
+	}
+
+	t2p->tiff_datasize = (tsize_t) k;
+	if ((uint64) t2p->tiff_datasize != k) {
+		TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+		t2p->t2p_error = T2P_ERR_ERROR;
 	}
 
 	return;
@@ -1990,10 +2048,10 @@ static void t2p_read_tiff_size_tile(T2P*
 	uint32* tbc = NULL;
 	uint16 edge=0;
 #ifdef JPEG_SUPPORT
-	uint32 xuint32=0;
 	unsigned char* jpt;
 #endif
-        
+        uint64 k;
+
 	edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
 	edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
 	
@@ -2004,41 +2062,62 @@ static void t2p_read_tiff_size_tile(T2P*
 #endif
 		){
 			t2p->tiff_datasize=TIFFTileSize(input);
+			if (t2p->tiff_datasize == 0) {
+				/* Assume we had overflow inside TIFFTileSize */
+				t2p->t2p_error = T2P_ERR_ERROR;
+			}
 			return;
 		} else {
 			TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc);
-			t2p->tiff_datasize=tbc[tile];
+			k=tbc[tile];
 #ifdef OJPEG_SUPPORT
 			if(t2p->tiff_compression==COMPRESSION_OJPEG){
-				t2p->tiff_datasize+=2048;
-				return;
+			  	k = checkAdd64(k, 2048, t2p);
 			}
 #endif
 #ifdef JPEG_SUPPORT
-			if(t2p->tiff_compression==COMPRESSION_JPEG){
-				if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt)!=0){
-					if(xuint32>4){
-						t2p->tiff_datasize+=xuint32;
-						t2p->tiff_datasize-=4; /* don't use EOI of header or SOI of tile */
+			if(t2p->tiff_compression==COMPRESSION_JPEG) {
+				uint32 count = 0;
+				if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){
+					if(count > 4){
+						k = checkAdd64(k, count, t2p);
+						k -= 4; /* don't use EOI of header or SOI of tile */
+
+
 					}
 				}
 			}
 #endif
+			t2p->tiff_datasize = (tsize_t) k;
+			if ((uint64) t2p->tiff_datasize != k) {
+				TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+				t2p->t2p_error = T2P_ERR_ERROR;
+			}
 			return;
 		}
 	}
-	t2p->tiff_datasize=TIFFTileSize(input);
+	k = TIFFTileSize(input);
 	if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
-		t2p->tiff_datasize*= t2p->tiff_samplesperpixel;
+		k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
+	}
+	if (k == 0) {
+		/* Assume we had overflow inside TIFFTileSize */
+		t2p->t2p_error = T2P_ERR_ERROR;
+	}
+
+	t2p->tiff_datasize = (tsize_t) k;
+	if ((uint64) t2p->tiff_datasize != k) {
+		TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+		t2p->t2p_error = T2P_ERR_ERROR;
 	}
 
 	return;
 }
 
 /*
-	This functions returns a non-zero value when the tile is on the right edge 
-	and does not have full imaged tile width.
-*/
+ * This functions returns a non-zero value when the tile is on the right edge
+ * and does not have full imaged tile width.
+ */
 
 static int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){
 
@@ -2048,15 +2127,12 @@ static int t2p_tile_is_right_edge(T2P_TI
 	} else {
 		return(0);
 	}
-	
-	return(0);
-	
 }
 
 /*
-	This functions returns a non-zero value when the tile is on the bottom edge 
-	and does not have full imaged tile length.
-*/
+ * This functions returns a non-zero value when the tile is on the bottom edge
+ * and does not have full imaged tile length.
+ */
 
 static int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){
 
@@ -2066,8 +2142,6 @@ static int t2p_tile_is_bottom_edge(T2P_T
 	} else {
 		return(0);
 	}
-	
-	return(0);
 }
 
 /*
@@ -2099,9 +2173,6 @@ static tsize_t t2p_readwrite_pdf_image(T
 #endif
 #ifdef JPEG_SUPPORT
 	unsigned char* jpt;
-        uint32 xuint32=0;
-	uint16 xuint16_1=0;
-	uint16 xuint16_2=0;
 	float* xfloatp;
 	uint32* sbc;
 	unsigned char* stripbuffer;
@@ -2109,78 +2180,108 @@ static tsize_t t2p_readwrite_pdf_image(T
 	uint32 max_striplength=0;
 #endif
 
+	/* Fail if prior error (in particular, can't trust tiff_datasize) */
+	if (t2p->t2p_error != T2P_ERR_OK)
+		return(0);
+
 	if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
 #ifdef CCITT_SUPPORT
 		if(t2p->pdf_compression == T2P_COMPRESS_G4){
-			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
-			if(buffer==NULL){
+			buffer = (unsigned char*)
+				_TIFFmalloc(t2p->tiff_datasize);
+			if (buffer == NULL) {
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return(0);
 			}
-			TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize);
+			TIFFReadRawStrip(input, 0, (tdata_t) buffer,
+					 t2p->tiff_datasize);
 			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
-					/* make sure is lsb-to-msb bit-endianness fill order */
-					TIFFReverseBits(buffer, t2p->tiff_datasize);
+					/*
+					 * make sure is lsb-to-msb
+					 * bit-endianness fill order
+					 */
+					TIFFReverseBits(buffer,
+							t2p->tiff_datasize);
 			}
-			TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
+			t2pWriteFile(output, (tdata_t) buffer,
+				      t2p->tiff_datasize);
 			_TIFFfree(buffer);
 			return(t2p->tiff_datasize);
 		}
 #endif
 #ifdef ZIP_SUPPORT
-		if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
-			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
+		if (t2p->pdf_compression == T2P_COMPRESS_ZIP) {
+			buffer = (unsigned char*)
+				_TIFFmalloc(t2p->tiff_datasize);
                         memset(buffer, 0, t2p->tiff_datasize);
-			if(buffer==NULL){
+			if(buffer == NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return(0);
 			}
-			TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize);
-			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
-					TIFFReverseBits(buffer, t2p->tiff_datasize);
+			TIFFReadRawStrip(input, 0, (tdata_t) buffer,
+					 t2p->tiff_datasize);
+			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) {
+					TIFFReverseBits(buffer,
+							t2p->tiff_datasize);
 			}
-			TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
+			t2pWriteFile(output, (tdata_t) buffer,
+				      t2p->tiff_datasize);
 			_TIFFfree(buffer);
 			return(t2p->tiff_datasize);
 		}
 #endif
 #ifdef OJPEG_SUPPORT
-		if(t2p->tiff_compression == COMPRESSION_OJPEG){
+		if(t2p->tiff_compression == COMPRESSION_OJPEG) {
 
-			if(t2p->tiff_dataoffset != 0){
-				buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
+			if(t2p->tiff_dataoffset != 0) {
+				buffer = (unsigned char*)
+					_TIFFmalloc(t2p->tiff_datasize);
                                 memset(buffer, 0, t2p->tiff_datasize);
-				if(buffer==NULL){
+				if(buffer == NULL) {
 					TIFFError(TIFF2PDF_MODULE, 
-						"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 						t2p->tiff_datasize, 
 						TIFFFileName(input));
 					t2p->t2p_error = T2P_ERR_ERROR;
 					return(0);
 				}
 				if(t2p->pdf_ojpegiflength==0){
-					inputoffset=TIFFSeekFile(input, 0, SEEK_CUR);
-					TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
-					TIFFReadFile(input, (tdata_t) buffer, t2p->tiff_datasize);
-					TIFFSeekFile(input, inputoffset, SEEK_SET);
-					TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
+					inputoffset=t2pSeekFile(input, 0,
+								 SEEK_CUR);
+					t2pSeekFile(input,
+						     t2p->tiff_dataoffset,
+						     SEEK_SET);
+					t2pReadFile(input, (tdata_t) buffer,
+						     t2p->tiff_datasize);
+					t2pSeekFile(input, inputoffset,
+						     SEEK_SET);
+					t2pWriteFile(output, (tdata_t) buffer,
+						      t2p->tiff_datasize);
 					_TIFFfree(buffer);
 					return(t2p->tiff_datasize);
 				} else {
-					inputoffset=TIFFSeekFile(input, 0, SEEK_CUR);
-					TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
-					bufferoffset=TIFFReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength);
-					t2p->pdf_ojpegiflength=0;
-					TIFFSeekFile(input, inputoffset, SEEK_SET);
-					TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp);
+					inputoffset=t2pSeekFile(input, 0,
+								 SEEK_CUR);
+					t2pSeekFile(input,
+						     t2p->tiff_dataoffset,
+						     SEEK_SET);
+					bufferoffset = t2pReadFile(input,
+						(tdata_t) buffer,
+						t2p->pdf_ojpegiflength);
+					t2p->pdf_ojpegiflength = 0;
+					t2pSeekFile(input, inputoffset,
+						     SEEK_SET);
+					TIFFGetField(input,
+						     TIFFTAG_YCBCRSUBSAMPLING,
+						     &h_samp, &v_samp);
 					buffer[bufferoffset++]= 0xff;
 					buffer[bufferoffset++]= 0xdd;
 					buffer[bufferoffset++]= 0x00;
@@ -2188,7 +2289,9 @@ static tsize_t t2p_readwrite_pdf_image(T
 					h_samp*=8;
 					v_samp*=8;
 					ri=(t2p->tiff_width+h_samp-1) / h_samp;
-					TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
+					TIFFGetField(input,
+						     TIFFTAG_ROWSPERSTRIP,
+						     &rows);
 					ri*=(rows+v_samp-1)/v_samp;
 					buffer[bufferoffset++]= (ri>>8) & 0xff;
 					buffer[bufferoffset++]= ri & 0xff;
@@ -2203,23 +2306,24 @@ static tsize_t t2p_readwrite_pdf_image(T
 							(tdata_t) &(((unsigned char*)buffer)[bufferoffset]), 
 							-1);
 					}
-					TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
+					t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
 					_TIFFfree(buffer);
 					return(bufferoffset);
 				}
 			} else {
 				if(! t2p->pdf_ojpegdata){
 					TIFFError(TIFF2PDF_MODULE, 
-						"No support for OJPEG image %s with bad tables", 
+				"No support for OJPEG image %s with bad tables", 
 						TIFFFileName(input));
 					t2p->t2p_error = T2P_ERR_ERROR;
 					return(0);
 				}
-				buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
+				buffer = (unsigned char*)
+					_TIFFmalloc(t2p->tiff_datasize);
                                 memset(buffer, 0, t2p->tiff_datasize);
 				if(buffer==NULL){
 					TIFFError(TIFF2PDF_MODULE, 
-						"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 						t2p->tiff_datasize, 
 						TIFFFileName(input));
 					t2p->t2p_error = T2P_ERR_ERROR;
@@ -2242,11 +2346,11 @@ static tsize_t t2p_readwrite_pdf_image(T
 						buffer[bufferoffset++]=0xff;
 						buffer[bufferoffset++]=0xd9;
 				}
-				TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
+				t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
 				_TIFFfree(buffer);
 				return(bufferoffset);
 				TIFFError(TIFF2PDF_MODULE, 
-					"No support for OJPEG image %s with no JPEG File Interchange offset", 
+	"No support for OJPEG image %s with no JPEG File Interchange offset", 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return(0);
@@ -2255,21 +2359,23 @@ static tsize_t t2p_readwrite_pdf_image(T
 		}
 #endif
 #ifdef JPEG_SUPPORT
-		if(t2p->tiff_compression == COMPRESSION_JPEG){
-			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
+		if(t2p->tiff_compression == COMPRESSION_JPEG) {
+			uint32 count = 0;
+			buffer = (unsigned char*)
+				_TIFFmalloc(t2p->tiff_datasize);
                         memset(buffer, 0, t2p->tiff_datasize);
 			if(buffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return(0);
 			}
-			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0){
-				if(xuint32>4){
-					_TIFFmemcpy(buffer, jpt, xuint32);
-					bufferoffset+=xuint32-2;
+			if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
+				if(count > 4) {
+					_TIFFmemcpy(buffer, jpt, count);
+					bufferoffset += count - 2;
 				}
 			}
 			stripcount=TIFFNumberOfStrips(input);
@@ -2277,10 +2383,11 @@ static tsize_t t2p_readwrite_pdf_image(T
 			for(i=0;i<stripcount;i++){
 				if(sbc[i]>max_striplength) max_striplength=sbc[i];
 			}
-			stripbuffer=(unsigned char*) _TIFFmalloc(max_striplength);
+			stripbuffer = (unsigned char*)
+				_TIFFmalloc(max_striplength);
 			if(stripbuffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					max_striplength, 
 					TIFFFileName(input));
 				_TIFFfree(buffer);
@@ -2297,9 +2404,9 @@ static tsize_t t2p_readwrite_pdf_image(T
 					i, 
 					t2p->tiff_length)){
 						TIFFError(TIFF2PDF_MODULE, 
-							"Can't process JPEG data in input file %s", 
+				"Can't process JPEG data in input file %s", 
 							TIFFFileName(input));
-						_TIFFfree(stripbuffer);
+						_TIFFfree(samplebuffer);
 						_TIFFfree(buffer);
 						t2p->t2p_error = T2P_ERR_ERROR;
 						return(0);
@@ -2307,7 +2414,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 			}
 			buffer[bufferoffset++]=0xff; 
 			buffer[bufferoffset++]=0xd9;
-			TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
+			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
 			_TIFFfree(stripbuffer);
 			_TIFFfree(buffer);
 			return(bufferoffset);
@@ -2321,7 +2428,7 @@ static tsize_t t2p_readwrite_pdf_image(T
                 memset(buffer, 0, t2p->tiff_datasize);
 		if(buffer==NULL){
 			TIFFError(TIFF2PDF_MODULE, 
-				"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 				t2p->tiff_datasize, 
 				TIFFFileName(input));
 			t2p->t2p_error = T2P_ERR_ERROR;
@@ -2359,7 +2466,7 @@ static tsize_t t2p_readwrite_pdf_image(T
                         memset(buffer, 0, t2p->tiff_datasize);
 			if(buffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
@@ -2368,7 +2475,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 			samplebuffer = (unsigned char*) _TIFFmalloc(stripsize);
 			if(samplebuffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
@@ -2384,7 +2491,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 							sepstripsize);
 					if(read==-1){
 						TIFFError(TIFF2PDF_MODULE, 
-							"Error on decoding strip %u of %s", 
+					"Error on decoding strip %u of %s", 
 							i + j*stripcount, 
 							TIFFFileName(input));
 							_TIFFfree(buffer);
@@ -2408,7 +2515,7 @@ static tsize_t t2p_readwrite_pdf_image(T
                 memset(buffer, 0, t2p->tiff_datasize);
 		if(buffer==NULL){
 			TIFFError(TIFF2PDF_MODULE, 
-				"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 				t2p->tiff_datasize, 
 				TIFFFileName(input));
 			t2p->t2p_error = T2P_ERR_ERROR;
@@ -2441,7 +2548,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 				t2p->tiff_datasize * t2p->tiff_samplesperpixel);
 			if(samplebuffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
@@ -2471,7 +2578,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 				t2p->tiff_width*t2p->tiff_length*4);
 			if(samplebuffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
+	"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", 
 					t2p->tiff_datasize, 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
@@ -2488,7 +2595,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 				ORIENTATION_TOPLEFT,
 				0)){
 				TIFFError(TIFF2PDF_MODULE, 
-					"Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", 
+	"Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", 
 					TIFFFileName(input));
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return(0);
@@ -2506,8 +2613,9 @@ static tsize_t t2p_readwrite_pdf_image(T
 		}
 	}
 
-	dataready:
-        t2p_disable(output);
+dataready:
+
+	t2p_disable(output);
 	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
 	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
 	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
@@ -2528,10 +2636,11 @@ static tsize_t t2p_readwrite_pdf_image(T
 #endif
 #ifdef JPEG_SUPPORT
 	case T2P_COMPRESS_JPEG:
-		if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
-			if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){
-				if(xuint16_1 != 0 && xuint16_2 != 0){
-					TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2);
+		if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
+			uint16 hor = 0, ver = 0;
+			if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) {
+				if(hor != 0 && ver != 0){
+					TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
 				}
 			}
 			if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
@@ -2540,7 +2649,7 @@ static tsize_t t2p_readwrite_pdf_image(T
 		}
 		if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){
 			TIFFError(TIFF2PDF_MODULE, 
-				"Unable to use JPEG compression for input %s and output %s", 
+		"Unable to use JPEG compression for input %s and output %s", 
 				TIFFFileName(input),
 				TIFFFileName(output));
 			_TIFFfree(buffer);
@@ -2589,37 +2698,44 @@ static tsize_t t2p_readwrite_pdf_image(T
 	default:
 		break;
 	}
-	
-        t2p_enable(output);
-        t2p->outputwritten = 0;
+
+	t2p_enable(output);
+	t2p->outputwritten = 0;
 #ifdef JPEG_SUPPORT
-	if(t2p->pdf_compression==T2P_COMPRESS_JPEG && t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
-		bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,stripsize*stripcount); 
+	if(t2p->pdf_compression == T2P_COMPRESS_JPEG
+	   && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){
+		bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0,
+						     buffer,
+						     stripsize * stripcount); 
 	} else
 #endif
-	bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); 
-	if(buffer != NULL){
+	{
+		bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0,
+						     buffer,
+						     t2p->tiff_datasize); 
+	}
+	if (buffer != NULL) {
 		_TIFFfree(buffer);
 		buffer=NULL;
 	}
 
-	if(bufferoffset==(tsize_t)-1){
+	if (bufferoffset == (tsize_t)-1) {
 		TIFFError(TIFF2PDF_MODULE, 
-			"Error writing encoded strip to output PDF %s", 
-			TIFFFileName(output));
+			  "Error writing encoded strip to output PDF %s", 
+			  TIFFFileName(output));
 		t2p->t2p_error = T2P_ERR_ERROR;
 		return(0);
 	}
 	
-        written= t2p->outputwritten;
+	written = t2p->outputwritten;
 	return(written);
 }
 
 /*
-	This function reads the raster image data from the input TIFF for an image tile and writes 
-	the data to the output PDF XObject image dictionary stream for the tile.  It returns the 
-	amount written or zero on error.
-*/
+ * This function reads the raster image data from the input TIFF for an image
+ * tile and writes the data to the output PDF XObject image dictionary stream
+ * for the tile.  It returns the amount written or zero on error.
+ */
 
 static tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
 
@@ -2632,15 +2748,19 @@ static tsize_t t2p_readwrite_pdf_image_t
 	tsize_t read=0;
 	uint16 i=0;
 	ttile_t tilecount=0;
+	tsize_t tilesize=0;
 	ttile_t septilecount=0;
 	tsize_t septilesize=0;
 #ifdef JPEG_SUPPORT
 	unsigned char* jpt;
-	uint16 xuint16_1=0;
-	uint16 xuint16_2=0;
 	float* xfloatp;
 	uint32 xuint32=0;
 #endif
+        (void)tilesize;
+
+	/* Fail if prior error (in particular, can't trust tiff_datasize) */
+	if (t2p->t2p_error != T2P_ERR_OK)
+		return(0);
 
 	edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
 	edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
@@ -2667,7 +2787,7 @@ static tsize_t t2p_readwrite_pdf_image_t
 			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
 					TIFFReverseBits(buffer, t2p->tiff_datasize);
 			}
-			TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
+			t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
 			_TIFFfree(buffer);
 			return(t2p->tiff_datasize);
 		}
@@ -2688,7 +2808,7 @@ static tsize_t t2p_readwrite_pdf_image_t
 			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
 					TIFFReverseBits(buffer, t2p->tiff_datasize);
 			}
-			TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
+			t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
 			_TIFFfree(buffer);
 			return(t2p->tiff_datasize);
 		}
@@ -2735,7 +2855,7 @@ static tsize_t t2p_readwrite_pdf_image_t
 					-1);
 			((unsigned char*)buffer)[bufferoffset++]=0xff;
 			((unsigned char*)buffer)[bufferoffset++]=0xd9;
-			TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
+			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
 			_TIFFfree(buffer);
 			return(bufferoffset);
 		}
@@ -2743,6 +2863,7 @@ static tsize_t t2p_readwrite_pdf_image_t
 #ifdef JPEG_SUPPORT
 		if(t2p->tiff_compression == COMPRESSION_JPEG){
 			unsigned char table_end[2];
+			uint32 count = 0;
 			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
 			if(buffer==NULL){
 				TIFFError(TIFF2PDF_MODULE, 
@@ -2753,14 +2874,14 @@ static tsize_t t2p_readwrite_pdf_image_t
 				t2p->t2p_error = T2P_ERR_ERROR;
 				return(0);
 			}
-			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint16_1, &jpt) != 0) {
-				if(xuint16_1 > 0){
-					_TIFFmemcpy(buffer, jpt, xuint16_1);
-					bufferoffset += xuint16_1 - 2;
+			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
+				if (count > 0) {
+					_TIFFmemcpy(buffer, jpt, count);
+					bufferoffset += count - 2;
 					table_end[0] = buffer[bufferoffset-2];
 					table_end[1] = buffer[bufferoffset-1];
 				}
-				if(xuint16_1 > 0) {
+				if (count > 0) {
 					xuint32 = bufferoffset;
 					bufferoffset += TIFFReadRawTile(
 						input, 
@@ -2777,7 +2898,7 @@ static tsize_t t2p_readwrite_pdf_image_t
 						-1);
 				}
 			}
-			TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
+			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
 			_TIFFfree(buffer);
 			return(bufferoffset);
 		}
@@ -2817,6 +2938,7 @@ static tsize_t t2p_readwrite_pdf_image_t
 		if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
 			septilesize=TIFFTileSize(input);
 			septilecount=TIFFNumberOfTiles(input);
+			tilesize=septilesize*t2p->tiff_samplesperpixel;
 			tilecount=septilecount/t2p->tiff_samplesperpixel;
 			buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
 			if(buffer==NULL){
@@ -2933,7 +3055,8 @@ static tsize_t t2p_readwrite_pdf_image_t
 			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
 	}
 
-        t2p_disable(output);
+
+	t2p_disable(output);
 	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
 	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
 	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
@@ -2981,10 +3104,11 @@ static tsize_t t2p_readwrite_pdf_image_t
 #endif
 #ifdef JPEG_SUPPORT
 	case T2P_COMPRESS_JPEG:
-		if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
-			if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){
-				if(xuint16_1 != 0 && xuint16_2 != 0){
-					TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2);
+		if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
+			uint16 hor = 0, ver = 0;
+			if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
+				if (hor != 0 && ver != 0) {
+					TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
 				}
 			}
 			if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
@@ -3034,20 +3158,23 @@ static tsize_t t2p_readwrite_pdf_image_t
 	}
 
 	t2p_enable(output);
-        t2p->outputwritten = 0;
-	bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); 
-	if(buffer != NULL){
+	t2p->outputwritten = 0;
+	bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
+					     TIFFStripSize(output)); 
+	if (buffer != NULL) {
 		_TIFFfree(buffer);
-		buffer=NULL;
+		buffer = NULL;
 	}
-	if(bufferoffset==-1){
+	if (bufferoffset == -1) {
 		TIFFError(TIFF2PDF_MODULE, 
-			"Error writing encoded tile to output PDF %s", 
-			TIFFFileName(output));
+			  "Error writing encoded tile to output PDF %s", 
+			  TIFFFileName(output));
 		t2p->t2p_error = T2P_ERR_ERROR;
 		return(0);
 	}
-        written= t2p->outputwritten;
+	
+	written = t2p->outputwritten;
+	
 	return(written);
 }
 
@@ -3412,13 +3539,15 @@ static void t2p_tile_collapse_left(
 
 
 /*
-	This function calls TIFFWriteDirectory on the output after blanking its output by replacing the 
-	read, write, and seek procedures with empty implementations, then it replaces the original 
-	implementations.
-*/
+ * This function calls TIFFWriteDirectory on the output after blanking its
+ * output by replacing the read, write, and seek procedures with empty
+ * implementations, then it replaces the original implementations.
+ */
 
-static void t2p_write_advance_directory(T2P* t2p, TIFF* output){
-  	t2p_disable(output);
+static void
+t2p_write_advance_directory(T2P* t2p, TIFF* output)
+{
+	t2p_disable(output);
 	if(!TIFFWriteDirectory(output)){
 		TIFFError(TIFF2PDF_MODULE, 
 			"Error writing virtual directory to output PDF %s", 
@@ -3426,14 +3555,14 @@ static void t2p_write_advance_directory(
 		t2p->t2p_error = T2P_ERR_ERROR;
 		return;
 	}
-  	t2p_enable(output);
+	t2p_enable(output);
 	return;
 }
 
 static tsize_t t2p_sample_planar_separate_to_contig(T2P* t2p, 
-                                             unsigned char* buffer, 
-                                             unsigned char* samplebuffer, 
-                                             tsize_t samplebuffersize){
+                                                    unsigned char* buffer, 
+                                                    unsigned char* samplebuffer, 
+                                                    tsize_t samplebuffersize){
 
 	tsize_t stride=0;
 	tsize_t i=0;
@@ -3569,8 +3698,8 @@ static tsize_t t2p_write_pdf_header(T2P*
 	int buflen=0;
 	
 	buflen=sprintf(buffer, "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t)"\r%\342\343\317\323\r\n", 8);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7);
 
 	return(written);
 }
@@ -3586,8 +3715,8 @@ static tsize_t t2p_write_pdf_obj_start(u
 	int buflen=0;
 
 	buflen=sprintf(buffer, "%lu", (unsigned long)number);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen );
-	written += TIFFWriteFile(output, (tdata_t) " 0 obj\r", 7);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen );
+	written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7);
 
 	return(written);
 }
@@ -3600,61 +3729,61 @@ static tsize_t t2p_write_pdf_obj_end(TIF
 
 	tsize_t written=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "endobj\r", 7);
+	written += t2pWriteFile(output, (tdata_t) "endobj\n", 7);
 
 	return(written);
 }
 
-
 /*
 	This function writes a PDF string object to output.
 */
 	
-static tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output){
+static tsize_t t2p_write_pdf_string(unsigned char* pdfstr, TIFF* output){
 
-	tsize_t written=0;
-	uint32 i=0;
-	char buffer[5];
-	uint32 len=0;
+	tsize_t written = 0;
+	uint32 i = 0;
+	char buffer[64];
+	uint32 len = 0;
 	
-	len=strlen(pdfstr);
-	written += TIFFWriteFile(output, (tdata_t) "(", 1);
-	for (i=0;i<len;i++){
+	len = strlen((char *)pdfstr);
+	written += t2pWriteFile(output, (tdata_t) "(", 1);
+	for (i=0; i<len; i++) {
 		if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){
-			sprintf(buffer, "\\%.3o", pdfstr[i]);
-			written += TIFFWriteFile(output, (tdata_t) buffer, 4);
+			sprintf(buffer, "\\%.3hho", pdfstr[i]);
+			buffer[sizeof(buffer) - 1] = '\0';
+			written += t2pWriteFile(output, (tdata_t) buffer, 4);
 		} else {
 			switch (pdfstr[i]){
 				case 0x08:
-					written += TIFFWriteFile(output, (tdata_t) "\\b", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\b", 2);
 					break;
 				case 0x09:
-					written += TIFFWriteFile(output, (tdata_t) "\\t", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\t", 2);
 					break;
 				case 0x0A:
-					written += TIFFWriteFile(output, (tdata_t) "\\n", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\n", 2);
 					break;
 				case 0x0C:
-					written += TIFFWriteFile(output, (tdata_t) "\\f", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\f", 2);
 					break;
 				case 0x0D:
-					written += TIFFWriteFile(output, (tdata_t) "\\r", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\r", 2);
 					break;
 				case 0x28:
-					written += TIFFWriteFile(output, (tdata_t) "\\(", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\(", 2);
 					break;
 				case 0x29:
-					written += TIFFWriteFile(output, (tdata_t) "\\)", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\)", 2);
 					break;
 				case 0x5C:
-					written += TIFFWriteFile(output, (tdata_t) "\\\\", 2);
+					written += t2pWriteFile(output, (tdata_t) "\\\\", 2);
 					break;
 				default:
-					written += TIFFWriteFile(output, (tdata_t) &pdfstr[i], 1);
+					written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1);
 			}
 		}
 	}
-	written += TIFFWriteFile(output, (tdata_t) ") ", 1);
+	written += t2pWriteFile(output, (tdata_t) ") ", 1);
 
 	return(written);
 }
@@ -3668,7 +3797,7 @@ static tsize_t t2p_write_pdf_stream(tdat
 
 	tsize_t written=0;
 
-	written += TIFFWriteFile(output, (tdata_t) buffer, len);
+	written += t2pWriteFile(output, (tdata_t) buffer, len);
 
 	return(written);
 }
@@ -3681,7 +3810,7 @@ static tsize_t t2p_write_pdf_stream_star
 
 	tsize_t written=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "stream\r\n", 8);
+	written += t2pWriteFile(output, (tdata_t) "stream\n", 7);
 
 	return(written);
 }
@@ -3694,7 +3823,7 @@ static tsize_t t2p_write_pdf_stream_end(
 
 	tsize_t written=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "\rendstream\r", 11);
+	written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11);
 
 	return(written);
 }
@@ -3709,13 +3838,13 @@ static tsize_t t2p_write_pdf_stream_dict
 	char buffer[16];
 	int buflen=0;
 	
-	written += TIFFWriteFile(output, (tdata_t) "/Length ", 8);
+	written += t2pWriteFile(output, (tdata_t) "/Length ", 8);
 	if(len!=0){
 		written += t2p_write_pdf_stream_length(len, output);
 	} else {
 		buflen=sprintf(buffer, "%lu", (unsigned long)number);
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
 	}
 	
 	return(written);
@@ -3729,7 +3858,7 @@ static tsize_t t2p_write_pdf_stream_dict
 
 	tsize_t written=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "<< \r", 4);
+	written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
 
 	return(written);
 }
@@ -3742,7 +3871,7 @@ static tsize_t t2p_write_pdf_stream_dict
 
 	tsize_t written=0;
 
-	written += TIFFWriteFile(output, (tdata_t) " >>\r", 4);
+	written += t2pWriteFile(output, (tdata_t) " >>\n", 4);
 
 	return(written);
 }
@@ -3758,8 +3887,8 @@ static tsize_t t2p_write_pdf_stream_leng
 	int buflen=0;
 
 	buflen=sprintf(buffer, "%lu", (unsigned long)len);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "\n", 1);
 
 	return(written);
 }
@@ -3774,18 +3903,18 @@ static tsize_t t2p_write_pdf_catalog(T2P
 	char buffer[16];
 	int buflen=0;
 
-	written += TIFFWriteFile(output, 
-		(tdata_t)"<< \r/Type /Catalog \r/Pages ", 
+	written += t2pWriteFile(output, 
+		(tdata_t)"<< \n/Type /Catalog \n/Pages ", 
 		27);
 	buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen );
-	written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen );
+	written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
 	if(t2p->pdf_fitwindow){
-		written += TIFFWriteFile(output, 
-			(tdata_t) "/ViewerPreferences <</FitWindow true>>\r", 
+		written += t2pWriteFile(output, 
+			(tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 
 			39);
 	}
-	written += TIFFWriteFile(output, (tdata_t)">>\r", 3);
+	written += t2pWriteFile(output, (tdata_t)">>\n", 3);
 
 	return(written);
 }
@@ -3796,116 +3925,139 @@ static tsize_t t2p_write_pdf_catalog(T2P
 
 static tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output){
 
-	tsize_t written=0;
-	char* info;
+	tsize_t written = 0;
+	unsigned char* info;
 	char buffer[512];
-	
+	int buflen = 0;
+
+        (void) buflen;
+
 	if(t2p->pdf_datetime==NULL){
 		t2p_pdf_tifftime(t2p, input);
 	}
-	if(strlen(t2p->pdf_datetime) > 0){
-		written += TIFFWriteFile(output, (tdata_t) "<< \r/CreationDate ", 18);
+	if(strlen((char *)t2p->pdf_datetime) > 0){
+		written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18);
 		written += t2p_write_pdf_string(t2p->pdf_datetime, output);
-		written += TIFFWriteFile(output, (tdata_t) "\r/ModDate ", 10);
+		written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10);
 		written += t2p_write_pdf_string(t2p->pdf_datetime, output);
 	}
-	written += TIFFWriteFile(output, (tdata_t) "\r/Producer ", 11);
-	_TIFFmemset((tdata_t)buffer, 0x00, 512);
-	sprintf(buffer, "libtiff / tiff2pdf - %d / %s", 
-                TIFFLIB_VERSION, T2P_VERSION);
-	written += t2p_write_pdf_string(buffer, output);
-	written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+	written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11);
+	_TIFFmemset((tdata_t)buffer, 0x00, sizeof(buffer));
+	buflen = sprintf(buffer, "libtiff / tiff2pdf - %d", TIFFLIB_VERSION);
+	written += t2p_write_pdf_string((unsigned char*)buffer, output);
+	written += t2pWriteFile(output, (tdata_t) "\n", 1);
 	if(t2p->pdf_creator != NULL){ 
-		if(strlen(t2p->pdf_creator)>0){
-			if(strlen(t2p->pdf_creator)>511){t2p->pdf_creator[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9);
+		if(strlen((char *)t2p->pdf_creator)>0){
+			if(strlen((char *)t2p->pdf_creator) > 511) {
+				t2p->pdf_creator[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
 			written += t2p_write_pdf_string(t2p->pdf_creator, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	} else{
 		if( TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0){
-			if(strlen(info)>511){info[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9);
+			if(strlen((char *)info) > 511) {
+				info[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
 			written += t2p_write_pdf_string(info, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	}
-	if(t2p->pdf_author != NULL){ 
-		if(strlen(t2p->pdf_author)>0){
-			if(strlen(t2p->pdf_author)>511){t2p->pdf_author[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
+	if(t2p->pdf_author != NULL) { 
+		if(strlen((char *)t2p->pdf_author) > 0) {
+			if(strlen((char *)t2p->pdf_author) > 511) {
+				t2p->pdf_author[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
 			written += t2p_write_pdf_string(t2p->pdf_author, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	} else{
 		if( TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0){
-			if(strlen(info)>511){info[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
+			if(strlen((char *)info) > 511) {
+				info[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
 			written += t2p_write_pdf_string(info, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		} else if ( TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0){
-			if(strlen(info)>511){info[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
+			if(strlen((char *)info) > 511) {
+				info[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
 			written += t2p_write_pdf_string(info, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		} 
 	}
-	if(t2p->pdf_title != NULL){
-		if(strlen(t2p->pdf_title)>0){
-			if(strlen(t2p->pdf_title)>511){t2p->pdf_title[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Title ", 7);
+	if(t2p->pdf_title != NULL) {
+		if(strlen((char *)t2p->pdf_title) > 0) {
+			if(strlen((char *)t2p->pdf_title) > 511) {
+				t2p->pdf_title[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
 			written += t2p_write_pdf_string(t2p->pdf_title, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	} else{
 		if( TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){
-			if(strlen(info)>511){info[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Title ", 7);
+			if(strlen((char *)info) > 511) {
+				info[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
 			written += t2p_write_pdf_string(info, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	}
-	if(t2p->pdf_subject != NULL){
-		if(strlen(t2p->pdf_subject)>0){
-			if(strlen(t2p->pdf_subject)>511){t2p->pdf_subject[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9);
+	if(t2p->pdf_subject != NULL) {
+		if(strlen((char *)t2p->pdf_subject) > 0) {
+			if(strlen((char *)t2p->pdf_subject) > 511) {
+				t2p->pdf_subject[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
 			written += t2p_write_pdf_string(t2p->pdf_subject, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
-	} else{
-		if( TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0){
-			if(strlen(info)>511){info[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9);
+	} else {
+		if(TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0) {
+			if(strlen((char *)info) > 511) {
+				info[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
 			written += t2p_write_pdf_string(info, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	}
-	if(t2p->pdf_keywords != NULL){ 
-		if(strlen(t2p->pdf_keywords)>0){
-			if(strlen(t2p->pdf_keywords)>511){t2p->pdf_keywords[512]=(char)0;}
-			written += TIFFWriteFile(output, (tdata_t) "/Keywords ", 10);
+	if(t2p->pdf_keywords != NULL) { 
+		if(strlen((char *)t2p->pdf_keywords) > 0) {
+			if(strlen((char *)t2p->pdf_keywords) > 511) {
+				t2p->pdf_keywords[512] = '\0';
+			}
+			written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10);
 			written += t2p_write_pdf_string(t2p->pdf_keywords, output);
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 	}
-	written += TIFFWriteFile(output, (tdata_t) ">> \r", 4);	
+	written += t2pWriteFile(output, (tdata_t) ">> \n", 4);	
 
 	return(written);
 }
 
 /*
-	This function fills a string of a T2P struct with the current time as a PDF date string, 
-	it is called by t2p_pdf_tifftime.
-*/
+ * This function fills a string of a T2P struct with the current time as a PDF
+ * date string, it is called by t2p_pdf_tifftime.
+ */
 
-static void t2p_pdf_currenttime(T2P* t2p){
+static void t2p_pdf_currenttime(T2P* t2p)
+{
 
 	struct tm* currenttime;
 	time_t timenow;
 
 	timenow=time(0);
 	currenttime=localtime(&timenow);
-	sprintf(t2p->pdf_datetime, "D:%.4d%.2d%.2d%.2d%.2d%.2d",
+	sprintf((char *)t2p->pdf_datetime, "D:%.4d%.2d%.2d%.2d%.2d%.2d",
 		(currenttime->tm_year+1900) % 65536, 
 		(currenttime->tm_mon+1) % 256, 
 		(currenttime->tm_mday) % 256, 
@@ -3917,25 +4069,24 @@ static void t2p_pdf_currenttime(T2P* t2p
 }
 
 /*
-	This function fills a string of a T2P struct with the date and time of a TIFF file if it 
-	exists or the current time as a PDF date string.
-*/
+ * This function fills a string of a T2P struct with the date and time of a
+ * TIFF file if it exists or the current time as a PDF date string.
+ */
 
 static void t2p_pdf_tifftime(T2P* t2p, TIFF* input){
 
 	char* datetime;
 
-	t2p->pdf_datetime= (char*) _TIFFmalloc(19);
-	if(t2p->pdf_datetime==NULL){
+	t2p->pdf_datetime = (unsigned char*) _TIFFmalloc(19);
+	if(t2p->pdf_datetime == NULL){
 		TIFFError(TIFF2PDF_MODULE, 
-			"Can't allocate %u bytes of memory for t2p_pdf_tiff_time", 
-			17); 
+		"Can't allocate %u bytes of memory for t2p_pdf_tiff_time", 17); 
 		t2p->t2p_error = T2P_ERR_ERROR;
 		return;
 	}
-	t2p->pdf_datetime[16]=0;
+	t2p->pdf_datetime[16] = '\0';
 	if( TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 
-	&& (strlen(datetime) >= 19) ){
+	    && (strlen(datetime) >= 19) ){
 		t2p->pdf_datetime[0]='D';
 		t2p->pdf_datetime[1]=':';
 		t2p->pdf_datetime[2]=datetime[0];
@@ -3960,28 +4111,26 @@ static void t2p_pdf_tifftime(T2P* t2p, T
 }
 
 /*
-	This function writes a PDF Pages Tree structure to output.
-*/
-
-static tsize_t t2p_write_pdf_pages(T2P* t2p, 
-                                   TIFF* output){
+ * This function writes a PDF Pages Tree structure to output.
+ */
 
+static tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output)
+{
 	tsize_t written=0;
 	tdir_t i=0;
 	char buffer[16];
 	int buflen=0;
 
 	int page=0;
-	written += TIFFWriteFile(output, 
-		(tdata_t) "<< \r/Type /Pages \r/Kids [ ", 
-		26);
+	written += t2pWriteFile(output, 
+		(tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26);
 	page = t2p->pdf_pages+1;
 	for (i=0;i<t2p->tiff_pagecount;i++){
 		buflen=sprintf(buffer, "%d", page);
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
 		if ( ((i+1)%8)==0 ) {
-			written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+			written += t2pWriteFile(output, (tdata_t) "\n", 1);
 		}
 		page +=3;
 		page += t2p->tiff_pages[i].page_extra;
@@ -3991,11 +4140,11 @@ static tsize_t t2p_write_pdf_pages(T2P*
 			page +=2;
 		}
 	}
-	written += TIFFWriteFile(output, (tdata_t) "] \r/Count ", 10);
+	written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10);
 	_TIFFmemset(buffer, 0x00, 16);
 	buflen=sprintf(buffer, "%d", t2p->tiff_pagecount);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " \r>> \r", 6);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6);
 
 	return(written);
 }
@@ -4011,86 +4160,86 @@ static tsize_t t2p_write_pdf_page(uint32
 	char buffer[16];
 	int buflen=0;
 	
-	written += TIFFWriteFile(output, (tdata_t) "<<\r/Type /Page \r/Parent ", 24);
+	written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24);
 	buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
-	written += TIFFWriteFile(output, (tdata_t) "/MediaBox [", 11); 
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
+	written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); 
 	buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x1);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " ", 1); 
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " ", 1); 
 	buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y1);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " ", 1); 
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " ", 1); 
 	buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x2);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " ", 1); 
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " ", 1); 
 	buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y2);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "] \r", 3); 
-	written += TIFFWriteFile(output, (tdata_t) "/Contents ", 10);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "] \n", 3); 
+	written += t2pWriteFile(output, (tdata_t) "/Contents ", 10);
 	buflen=sprintf(buffer, "%lu", (unsigned long)(object + 1));
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
-	written += TIFFWriteFile(output, (tdata_t) "/Resources << \r", 15);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
+	written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15);
 	if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){
-		written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12);
+		written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
 		for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){
-			written += TIFFWriteFile(output, (tdata_t) "/Im", 3);
+			written += t2pWriteFile(output, (tdata_t) "/Im", 3);
 			buflen = sprintf(buffer, "%u", t2p->pdf_page+1);
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) "_", 1);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) "_", 1);
 			buflen = sprintf(buffer, "%u", i+1);
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) " ", 1);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) " ", 1);
 			buflen = sprintf(
 				buffer, 
 				"%lu", 
 				(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); 
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
 			if(i%4==3){
-				written += TIFFWriteFile(output, (tdata_t) "\r", 1);
+				written += t2pWriteFile(output, (tdata_t) "\n", 1);
 			}
 		}
-		written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
+		written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
 	} else {
-			written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12);
-			written += TIFFWriteFile(output, (tdata_t) "/Im", 3);
+			written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
+			written += t2pWriteFile(output, (tdata_t) "/Im", 3);
 			buflen = sprintf(buffer, "%u", t2p->pdf_page+1);
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) " ", 1);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) " ", 1);
 			buflen = sprintf(
 				buffer, 
 				"%lu", 
 				(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); 
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
-		written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
 	}
 	if(t2p->tiff_transferfunctioncount != 0) {
-		written += TIFFWriteFile(output, (tdata_t) "/ExtGState <<", 13);
-		TIFFWriteFile(output, (tdata_t) "/GS1 ", 5);
+		written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13);
+		t2pWriteFile(output, (tdata_t) "/GS1 ", 5);
 		buflen = sprintf(
 			buffer, 
 			"%lu", 
 			(unsigned long)(object + 3)); 
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
-		written += TIFFWriteFile(output, (tdata_t) ">> \r", 4);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
 	}
-	written += TIFFWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
+	written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
 	if(t2p->pdf_colorspace == T2P_CS_BILEVEL 
 		|| t2p->pdf_colorspace == T2P_CS_GRAY
 		){
-		written += TIFFWriteFile(output, (tdata_t) "/ImageB ", 8);
+		written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8);
 	} else {
-		written += TIFFWriteFile(output, (tdata_t) "/ImageC ", 8);
+		written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8);
 		if(t2p->pdf_colorspace & T2P_CS_PALETTE){
-			written += TIFFWriteFile(output, (tdata_t) "/ImageI ", 8);
+			written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8);
 		}
 	}
-	written += TIFFWriteFile(output, (tdata_t) "]\r>>\r>>\r", 8);
+	written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8);
 
 	return(written);
 }
@@ -4114,19 +4263,25 @@ static void t2p_compose_pdf_page(T2P* t2
 	
 	t2p->pdf_xres = t2p->tiff_xres;
 	t2p->pdf_yres = t2p->tiff_yres;
-	if(t2p->pdf_overrideres){
+	if(t2p->pdf_overrideres) {
 		t2p->pdf_xres = t2p->pdf_defaultxres;
 		t2p->pdf_yres = t2p->pdf_defaultyres;
 	}
-	if(t2p->pdf_xres==0.0){
+	if(t2p->pdf_xres == 0.0)
 		t2p->pdf_xres = t2p->pdf_defaultxres;
-	}
-	if(t2p->pdf_yres==0.0){
+	if(t2p->pdf_yres == 0.0)
 		t2p->pdf_yres = t2p->pdf_defaultyres;
+	if (t2p->tiff_resunit != RESUNIT_CENTIMETER	/* RESUNIT_NONE and */
+	    && t2p->tiff_resunit != RESUNIT_INCH) {	/* other cases */
+		t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres;
+		t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres;
+	} else {
+		t2p->pdf_imagewidth = 
+			((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres;
+		t2p->pdf_imagelength = 
+			((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres;
 	}
-	t2p->pdf_imagewidth=((float)(t2p->tiff_width)) *72.0F / t2p->pdf_xres;
-	t2p->pdf_imagelength=((float)(t2p->tiff_length)) *72.0F / t2p->pdf_yres;
-	if(t2p->pdf_overridepagesize != 0){
+	if(t2p->pdf_overridepagesize != 0) {
 		t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth;
 		t2p->pdf_pagelength = t2p->pdf_defaultpagelength;
 	} else {
@@ -4429,7 +4584,7 @@ static tsize_t t2p_write_pdf_page_conten
 		for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){
 			box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box;
 			buflen=sprintf(buffer, 
-				"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\r", 
+				"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", 
 				t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
 				box.mat[0],
 				box.mat[1],
@@ -4444,7 +4599,7 @@ static tsize_t t2p_write_pdf_page_conten
 	} else {
 		box=t2p->pdf_imagebox;
 		buflen=sprintf(buffer, 
-			"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\r", 
+			"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", 
 			t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
 			box.mat[0],
 			box.mat[1],
@@ -4472,17 +4627,17 @@ static tsize_t t2p_write_pdf_xobject_str
 	int buflen=0;
 
 	written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); 
-	written += TIFFWriteFile(output, 
-		(tdata_t) "/Type /XObject \r/Subtype /Image \r/Name /Im", 
+	written += t2pWriteFile(output, 
+		(tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 
 		42);
 	buflen=sprintf(buffer, "%u", t2p->pdf_page+1);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 	if(tile != 0){
-		written += TIFFWriteFile(output, (tdata_t) "_", 1);
+		written += t2pWriteFile(output, (tdata_t) "_", 1);
 		buflen=sprintf(buffer, "%lu", (unsigned long)tile);
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 	}
-	written += TIFFWriteFile(output, (tdata_t) "\r/Width ", 8);
+	written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8);
 	_TIFFmemset((tdata_t)buffer, 0x00, 16);
 	if(tile==0){
 		buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width);
@@ -4499,8 +4654,8 @@ static tsize_t t2p_write_pdf_xobject_str
 				(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
 		}
 	}
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "\r/Height ", 9);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9);
 	_TIFFmemset((tdata_t)buffer, 0x00, 16);
 	if(tile==0){
 		buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length);
@@ -4517,16 +4672,16 @@ static tsize_t t2p_write_pdf_xobject_str
 				(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
 		}
 	}
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "\r/BitsPerComponent ", 19);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19);
 	_TIFFmemset((tdata_t)buffer, 0x00, 16);
 	buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "\r/ColorSpace ", 13);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13);
 	written += t2p_write_pdf_xobject_cs(t2p, output);
 	if (t2p->pdf_image_interpolate)
-		written += TIFFWriteFile(output,
-					 (tdata_t) "\r/Interpolate true", 18);
+		written += t2pWriteFile(output,
+					 (tdata_t) "\n/Interpolate true", 18);
 	if( (t2p->pdf_switchdecode != 0)
 #ifdef CCITT_SUPPORT
 		&& ! (t2p->pdf_colorspace == T2P_CS_BILEVEL 
@@ -4560,66 +4715,66 @@ static tsize_t t2p_write_pdf_xobject_cs(
 		return(written);
 	}
 	if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
-		written += TIFFWriteFile(output, (tdata_t) "[ /Indexed ", 11);
+		written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11);
 		t2p->pdf_colorspace ^= T2P_CS_PALETTE;
 		written += t2p_write_pdf_xobject_cs(t2p, output);
 		t2p->pdf_colorspace |= T2P_CS_PALETTE;
 		buflen=sprintf(buffer, "%u", (0x0001 << t2p->tiff_bitspersample)-1 );
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " ", 1);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " ", 1);
 		_TIFFmemset(buffer, 0x00, 16);
 		buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_palettecs ); 
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ]\r", 7);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7);
 		return(written);
 	}
 	if(t2p->pdf_colorspace & T2P_CS_BILEVEL){
-			written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13);
+			written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
 	}
 	if(t2p->pdf_colorspace & T2P_CS_GRAY){
 			if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
 				written += t2p_write_pdf_xobject_calcs(t2p, output);
 			} else {
-				written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13);
+				written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
 			}
 	}
 	if(t2p->pdf_colorspace & T2P_CS_RGB){
 			if(t2p->pdf_colorspace & T2P_CS_CALRGB){
 				written += t2p_write_pdf_xobject_calcs(t2p, output);
 			} else {
-				written += TIFFWriteFile(output, (tdata_t) "/DeviceRGB \r", 12);
+				written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12);
 			}
 	}
 	if(t2p->pdf_colorspace & T2P_CS_CMYK){
-			written += TIFFWriteFile(output, (tdata_t) "/DeviceCMYK \r", 13);
+			written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13);
 	}
 	if(t2p->pdf_colorspace & T2P_CS_LAB){
-			written += TIFFWriteFile(output, (tdata_t) "[/Lab << \r", 10);
-			written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
+			written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10);
+			written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
 			X_W = t2p->tiff_whitechromaticities[0];
 			Y_W = t2p->tiff_whitechromaticities[1];
 			Z_W = 1.0F - (X_W + Y_W);
 			X_W /= Y_W;
 			Z_W /= Y_W;
 			Y_W = 1.0F;
-			buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+			buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 			X_W = 0.3457F; /* 0.3127F; */ /* D50, commented D65 */
 			Y_W = 0.3585F; /* 0.3290F; */
 			Z_W = 1.0F - (X_W + Y_W);
 			X_W /= Y_W;
 			Z_W /= Y_W;
 			Y_W = 1.0F;
-			buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) "/Range ", 7);
-			buflen=sprintf(buffer, "[%d %d %d %d] \r", 
+			buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) "/Range ", 7);
+			buflen=sprintf(buffer, "[%d %d %d %d] \n", 
 				t2p->pdf_labrange[0], 
 				t2p->pdf_labrange[1], 
 				t2p->pdf_labrange[2], 
 				t2p->pdf_labrange[3]);
-			written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-			written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5);
+			written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+			written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
 			
 	}
 	
@@ -4632,30 +4787,30 @@ static tsize_t t2p_write_pdf_transfer(T2
 	char buffer[16];
 	int buflen=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "<< /Type /ExtGState \r/TR ", 25);
+	written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25);
 	if(t2p->tiff_transferfunctioncount == 1){
 		buflen=sprintf(buffer, "%lu",
 			       (unsigned long)(t2p->pdf_xrefcount + 1));
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
 	} else {
-		written += TIFFWriteFile(output, (tdata_t) "[ ", 2);
+		written += t2pWriteFile(output, (tdata_t) "[ ", 2);
 		buflen=sprintf(buffer, "%lu",
 			       (unsigned long)(t2p->pdf_xrefcount + 1));
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
 		buflen=sprintf(buffer, "%lu",
 			       (unsigned long)(t2p->pdf_xrefcount + 2));
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
 		buflen=sprintf(buffer, "%lu",
 			       (unsigned long)(t2p->pdf_xrefcount + 3));
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
-		written += TIFFWriteFile(output, (tdata_t) "/Identity ] ", 12);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+		written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12);
 	}
 
-	written += TIFFWriteFile(output, (tdata_t) " >> \r", 5);
+	written += t2pWriteFile(output, (tdata_t) " >> \n", 5);
 
 	return(written);
 }
@@ -4667,12 +4822,12 @@ static tsize_t t2p_write_pdf_transfer_di
 	int buflen=0;
 	(void)i; // XXX
 
-	written += TIFFWriteFile(output, (tdata_t) "/FunctionType 0 \r", 17);
-	written += TIFFWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \r", 19);
-	written += TIFFWriteFile(output, (tdata_t) "/Range [0.0 1.0] \r", 18);
-	buflen=sprintf(buffer, "/Size [%u] \r", (1<<t2p->tiff_bitspersample));
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "/BitsPerSample 16 \r", 19);
+	written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17);
+	written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19);
+	written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18);
+	buflen=sprintf(buffer, "/Size [%u] \n", (1<<t2p->tiff_bitspersample));
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19);
 	written += t2p_write_pdf_stream_dict(1<<(t2p->tiff_bitspersample+1), 0, output);
 
 	return(written);
@@ -4725,9 +4880,9 @@ static tsize_t t2p_write_pdf_xobject_cal
 	float G=1.0;
 	float B=1.0;
 	
-	written += TIFFWriteFile(output, (tdata_t) "[", 1);
+	written += t2pWriteFile(output, (tdata_t) "[", 1);
 	if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
-		written += TIFFWriteFile(output, (tdata_t) "/CalGray ", 9);
+		written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9);
 		X_W = t2p->tiff_whitechromaticities[0];
 		Y_W = t2p->tiff_whitechromaticities[1];
 		Z_W = 1.0F - (X_W + Y_W);
@@ -4736,7 +4891,7 @@ static tsize_t t2p_write_pdf_xobject_cal
 		Y_W = 1.0F;
 	}
 	if(t2p->pdf_colorspace & T2P_CS_CALRGB){
-		written += TIFFWriteFile(output, (tdata_t) "/CalRGB ", 8);
+		written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8);
 		x_w = t2p->tiff_whitechromaticities[0];
 		y_w = t2p->tiff_whitechromaticities[1];
 		x_r = t2p->tiff_primarychromaticities[0];
@@ -4762,26 +4917,26 @@ static tsize_t t2p_write_pdf_xobject_cal
 		Z_W /= Y_W;
 		Y_W = 1.0;
 	}
-	written += TIFFWriteFile(output, (tdata_t) "<< \r", 4);
+	written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
 	if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
-		written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
-		buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) "/Gamma 2.2 \r", 12);
+		written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
+		buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12);
 	}
 	if(t2p->pdf_colorspace & T2P_CS_CALRGB){
-		written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
-		buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) "/Matrix ", 8);
-		buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \r", 
+		written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
+		buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8);
+		buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", 
 			X_R, Y_R, Z_R, 
 			X_G, Y_G, Z_G, 
 			X_B, Y_B, Z_B); 
-		written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-		written += TIFFWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \r", 22);
+		written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+		written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22);
 	}
-	written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5);
+	written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
 
 	return(written);
 }
@@ -4796,10 +4951,10 @@ static tsize_t t2p_write_pdf_xobject_icc
 	char buffer[16];
 	int buflen=0;
 	
-	written += TIFFWriteFile(output, (tdata_t) "[/ICCBased ", 11);
+	written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11);
 	buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_icccs);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " 0 R] \r", 7);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7);
 
 	return(written);
 }
@@ -4810,10 +4965,10 @@ static tsize_t t2p_write_pdf_xobject_icc
 	char buffer[16];
 	int buflen=0;
 	
-	written += TIFFWriteFile(output, (tdata_t) "/N ", 3);
-	buflen=sprintf(buffer, "%u \r", t2p->tiff_samplesperpixel);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) "/Alternate ", 11);
+	written += t2pWriteFile(output, (tdata_t) "/N ", 3);
+	buflen=sprintf(buffer, "%u \n", t2p->tiff_samplesperpixel);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11);
 	t2p->pdf_colorspace ^= T2P_CS_ICCBASED;
 	written += t2p_write_pdf_xobject_cs(t2p, output);
 	t2p->pdf_colorspace |= T2P_CS_ICCBASED;
@@ -4859,11 +5014,11 @@ static tsize_t t2p_write_pdf_xobject_dec
 	tsize_t written=0;
 	int i=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "/Decode [ ", 10);
+	written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10);
 	for (i=0;i<t2p->tiff_samplesperpixel;i++){
-		written += TIFFWriteFile(output, (tdata_t) "1 0 ", 4);
+		written += t2pWriteFile(output, (tdata_t) "1 0 ", 4);
 	}
-	written += TIFFWriteFile(output, (tdata_t) "]\r", 2);
+	written += t2pWriteFile(output, (tdata_t) "]\n", 2);
 
 	return(written);
 }
@@ -4882,93 +5037,93 @@ static tsize_t t2p_write_pdf_xobject_str
 	if(t2p->pdf_compression==T2P_COMPRESS_NONE){
 		return(written);
 	}
-	written += TIFFWriteFile(output, (tdata_t) "/Filter ", 8);
+	written += t2pWriteFile(output, (tdata_t) "/Filter ", 8);
 	switch(t2p->pdf_compression){
 #ifdef CCITT_SUPPORT
 		case T2P_COMPRESS_G4:
-			written += TIFFWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
-			written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
-			written += TIFFWriteFile(output, (tdata_t) "<< /K -1 ", 9);
+			written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
+			written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
+			written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9);
 			if(tile==0){
-				written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
+				written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
 				buflen=sprintf(buffer, "%lu",
 					       (unsigned long)t2p->tiff_width);
-				written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-				written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
+				written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+				written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
 				buflen=sprintf(buffer, "%lu",
 					       (unsigned long)t2p->tiff_length);
-				written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+				written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 			} else {
 				if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
-					written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
+					written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
 					buflen=sprintf(
 						buffer, 
 						"%lu", 
 						(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
-					written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+					written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 				} else {
-					written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
+					written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
 					buflen=sprintf(
 						buffer, 
 						"%lu", 
 						(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
-					written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+					written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 				}
 				if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
-					written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
+					written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
 					buflen=sprintf(
 						buffer, 
 						"%lu", 
 						(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
-					written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+					written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 				} else {
-					written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
+					written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
 					buflen=sprintf(
 						buffer, 
 						"%lu", 
 						(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
-					written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+					written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 				}
 			}
 			if(t2p->pdf_switchdecode == 0){
-				written += TIFFWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
+				written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
 			}
-			written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
+			written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
 			break;
 #endif
 #ifdef JPEG_SUPPORT
 		case T2P_COMPRESS_JPEG:
-			written += TIFFWriteFile(output, (tdata_t) "/DCTDecode ", 11);
+			written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11);
 
 			if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) {
-				written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
-				written += TIFFWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\r", 24);
+				written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
+				written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\n", 24);
 			}
 			break;
 #endif
 #ifdef ZIP_SUPPORT
 		case T2P_COMPRESS_ZIP:
-			written += TIFFWriteFile(output, (tdata_t) "/FlateDecode ", 13);
+			written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13);
 			if(t2p->pdf_compressionquality%100){
-				written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
-				written += TIFFWriteFile(output, (tdata_t) "<< /Predictor ", 14);
+				written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
+				written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14);
 				_TIFFmemset(buffer, 0x00, 16);
 				buflen=sprintf(buffer, "%u", t2p->pdf_compressionquality%100);
-				written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-				written += TIFFWriteFile(output, (tdata_t) " /Columns ", 10);
+				written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+				written += t2pWriteFile(output, (tdata_t) " /Columns ", 10);
 				_TIFFmemset(buffer, 0x00, 16);
 				buflen = sprintf(buffer, "%lu",
 						 (unsigned long)t2p->tiff_width);
-				written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-				written += TIFFWriteFile(output, (tdata_t) " /Colors ", 9);
+				written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+				written += t2pWriteFile(output, (tdata_t) " /Colors ", 9);
 				_TIFFmemset(buffer, 0x00, 16);
 				buflen=sprintf(buffer, "%u", t2p->tiff_samplesperpixel);
-				written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-				written += TIFFWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
+				written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+				written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
 				_TIFFmemset(buffer, 0x00, 16);
 				buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample);
-				written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-				written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
+				written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+				written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
 			}
 			break;
 #endif
@@ -4990,21 +5145,21 @@ static tsize_t t2p_write_pdf_xreftable(T
 	int buflen=0;
 	uint32 i=0;
 
-	written += TIFFWriteFile(output, (tdata_t) "xref\r0 ", 7);
+	written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7);
 	buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1));
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
-	written += TIFFWriteFile(output, (tdata_t) " \r0000000000 65535 f\r\n", 22);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22);
 	for (i=0;i<t2p->pdf_xrefcount;i++){
-		sprintf(buffer, "%.10lu 00000 n\r\n",
+		sprintf(buffer, "%.10lu 00000 n \n",
 			(unsigned long)t2p->pdf_xrefoffsets[i]);
-		written += TIFFWriteFile(output, (tdata_t) buffer, 20);
+		written += t2pWriteFile(output, (tdata_t) buffer, 20);
 	}
 
 	return(written);
 }
 
 /*
- *	This function writes a PDF trailer to output.
+ * This function writes a PDF trailer to output.
  */
 
 static tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output)
@@ -5013,15 +5168,13 @@ static tsize_t t2p_write_pdf_trailer(T2P
 	tsize_t written = 0;
 	char buffer[32];
 	int buflen = 0;
-        int ifileidbuf[4];
-	char *fileidbuf = (char*)ifileidbuf;
+	char fileidbuf[16];
 	int i = 0;
 
-	ifileidbuf[0] = rand();
-	ifileidbuf[1] = rand();
-	ifileidbuf[2] = rand();
-	ifileidbuf[3] = rand();
-	t2p->pdf_fileid = (char*)_TIFFmalloc(33);
+        for (i=0; i<(int)sizeof(fileidbuf); i++)
+          fileidbuf[i] = (char) rand();
+
+	t2p->pdf_fileid = (unsigned char*)_TIFFmalloc(33);
 	if(t2p->pdf_fileid == NULL) {
 		TIFFError(
 			TIFF2PDF_MODULE, 
@@ -5031,29 +5184,31 @@ static tsize_t t2p_write_pdf_trailer(T2P
 		return(0);
 	}
 	_TIFFmemset(t2p->pdf_fileid, 0x00, 33);
-	for (i=0; i<16; i++)
-		sprintf(&(t2p->pdf_fileid[2*i]), "%.2hhX", fileidbuf[i]);
-	written += TIFFWriteFile(output, (tdata_t) "trailer\r<<\r/Size ", 17);
+	for (i = 0; i < 16; i++) {
+		sprintf((char *)t2p->pdf_fileid + 2 * i,
+			"%.2hhX", fileidbuf[i]);
+	}
+	written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17);
 	buflen = sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount+1));
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 	_TIFFmemset(buffer, 0x00, 32);	
-	written += TIFFWriteFile(output, (tdata_t) "\r/Root ", 7);
+	written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7);
 	buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_catalog);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 	_TIFFmemset(buffer, 0x00, 32);	
-	written += TIFFWriteFile(output, (tdata_t) " 0 R \r/Info ", 12);
+	written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12);
 	buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_info);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 	_TIFFmemset(buffer, 0x00, 32);	
-	written += TIFFWriteFile(output, (tdata_t) " 0 R \r/ID[<", 11);
-	written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
-	written += TIFFWriteFile(output, (tdata_t) "><", 2);
-	written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
-	written += TIFFWriteFile(output, (tdata_t) ">]\r>>\rstartxref\r", 16);
+	written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11);
+	written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
+	written += t2pWriteFile(output, (tdata_t) "><", 2);
+	written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
+	written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16);
 	buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_startxref);
-	written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
+	written += t2pWriteFile(output, (tdata_t) buffer, buflen);
 	_TIFFmemset(buffer, 0x00, 32);	
-	written += TIFFWriteFile(output, (tdata_t) "\r%%EOF\r", 7);
+	written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7);
 
 	return(written);
 }
@@ -5067,7 +5222,7 @@ static tsize_t t2p_write_pdf_trailer(T2P
   library, and TIFFWriteEncodedStrip can be used to write compressed data to 
   the output.  The output is not actually a TIFF file, it is a PDF file.  
 
-  This function uses only TIFFWriteFile and TIFFWriteEncodedStrip to write to 
+  This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to 
   the output TIFF file.  When libtiff would otherwise be writing data to the 
   output file, the write procedure of the TIFF structure is replaced with an 
   empty implementation.
@@ -5088,7 +5243,7 @@ static tsize_t t2p_write_pdf_trailer(T2P
 	assert(output != NULL);
 
 	if(output->tif_seekproc != NULL){
-		TIFFSeekFile(output, (toff_t) 0, SEEK_SET);
+		t2pSeekFile(output, (toff_t) 0, SEEK_SET);
 	}
 
   This function returns the file size of the output PDF file.  On error it 
@@ -5112,7 +5267,7 @@ static tsize_t t2p_write_pdf(T2P* t2p, T
 		TIFFError(
 			TIFF2PDF_MODULE, 
 			"Can't allocate %lu bytes of memory for t2p_write_pdf", 
-			t2p->pdf_xrefcount * sizeof(uint32) );
+			t2p->pdf_xrefcount * (long)sizeof(uint32) );
 		return(written);
 	}
 	t2p->pdf_xrefcount=0;
@@ -5252,13 +5407,14 @@ static tsize_t t2p_write_pdf(T2P* t2p, T
 			written += t2p_write_pdf_obj_end(output);
 		}
 	}
-	t2p->pdf_startxref=written;
+	t2p->pdf_startxref = written;
 	written += t2p_write_pdf_xreftable(t2p, output);
 	written += t2p_write_pdf_trailer(t2p, output);
-        t2p_disable(output);
+	t2p_disable(output);
+
 	return(written);
 }
 
-#endif
-
 /* vim: set ts=8 sts=8 sw=8 noet: */
+
+#endif
--- djview4-4.9.orig/src/qdjviewprefsdialog.ui
+++ djview4-4.9/src/qdjviewprefsdialog.ui
@@ -7,7 +7,7 @@
     <x>0</x>
     <y>0</y>
     <width>509</width>
-    <height>374</height>
+    <height>388</height>
    </rect>
   </property>
   <property name="windowTitle">
@@ -1126,6 +1126,16 @@
          </property>
          <layout class="QVBoxLayout" name="verticalLayout_12">
           <item>
+           <widget class="QCheckBox" name="openGLCheckBox">
+            <property name="text">
+             <string>Render with openGL when available</string>
+            </property>
+            <property name="checked">
+             <bool>true</bool>
+            </property>
+           </widget>
+          </item>
+          <item>
            <widget class="QCheckBox" name="restrictOverrideCheckBox">
             <property name="text">
              <string>Override saving and printing restrictions</string>
@@ -1317,6 +1327,7 @@
   <tabstop>animationCheckBox</tabstop>
   <tabstop>advancedCheckBox</tabstop>
   <tabstop>textLabelCheckBox</tabstop>
+  <tabstop>openGLCheckBox</tabstop>
   <tabstop>restrictOverrideCheckBox</tabstop>
   <tabstop>printerManualCheckBox</tabstop>
   <tabstop>printerGammaSpinBox</tabstop>
--- djview4-4.9.orig/src/djview.cpp
+++ djview4-4.9/src/djview.cpp
@@ -121,13 +121,18 @@ QDjViewApplication::QDjViewApplication(i
   
   // Install translators
   QStringList langs = getTranslationLangs();
-  QTranslator *qtTrans = new QTranslator(this);
-  if (loadTranslator(qtTrans, "qt", langs))
-    installTranslator(qtTrans);
   QTranslator *djviewTrans = new QTranslator(this);
-  if (loadTranslator(djviewTrans, "djview", langs))
-    installTranslator(djviewTrans);
-
+  QTranslator *qtTrans = new QTranslator(this);
+  if (loadTranslators(langs, djviewTrans, qtTrans))
+    {
+      installTranslator(qtTrans);
+      installTranslator(djviewTrans);
+    }
+  else
+    {
+      delete qtTrans;
+      delete djviewTrans;
+    }
   // Application is ready
   appReady = true;
 }
@@ -154,19 +159,6 @@ addDirectory(QStringList &dirs, QString
 }
 
 
-static void
-addLang(QStringList &langs, QString s)
-{
-  if (s.size() <= 0)
-    return;
-  if (! langs.contains(s))
-    langs << s;
-  QString sl = s.toLower();
-  if (sl != s && ! langs.contains(sl))
-    langs << sl;
-}
-
-
 QStringList 
 QDjViewApplication::getTranslationDirs()
 {
@@ -201,6 +193,24 @@ QDjViewApplication::getTranslationDirs()
 }
 
 
+static void
+addLang(QStringList &langs, QString s)
+{
+  if (s.size() > 0)
+    {
+      s = s.replace(QChar('-'), QChar('_'));
+      if (! langs.contains(s))
+        langs << s;
+#ifdef Q_WS_MAC
+      if (s == "zh_Hans" && ! langs.contains("zh_CN"))
+        langs << "zh_CN";
+      if (s == "zh_Hant" && ! langs.contains("zh_TW"))
+        langs << "zh_TW";
+#endif
+    }
+}
+
+
 QStringList 
 QDjViewApplication::getTranslationLangs()
 {
@@ -214,9 +224,7 @@ QDjViewApplication::getTranslationLangs(
 #ifdef LC_MESSAGES
       addLang(langs, QString::fromLocal8Bit(::setlocale(LC_MESSAGES, 0)));
 #endif
-#ifdef LC_ALL
-      addLang(langs, QString::fromLocal8Bit(::setlocale(LC_ALL, 0)));
-#endif
+      addLang(langs, QString::fromLocal8Bit(::getenv("LANG")));
 #ifdef Q_WS_MAC
       QSettings g(".", "globalPreferences");
       foreach (QString lang, g.value("AppleLanguages").toStringList())
@@ -229,26 +237,43 @@ QDjViewApplication::getTranslationLangs(
 }
 
 
-bool
-QDjViewApplication::loadTranslator(QTranslator *trans, 
-                                   QString name, QStringList langs)
+static bool loadOneTranslator(QTranslator *trans, 
+                              QString name, QString lang, QStringList dirs)
 {
-  foreach (QString lang, langs)
+  QString llang = lang.toLower();
+  foreach (QString dir, dirs)
     {
-      foreach (QString dir, getTranslationDirs())
+      dir = dir.replace(QRegExp("\\$LANG(?!\\w)"), lang);
+      QDir qdir(dir);
+      if (qdir.exists())
         {
-          dir = dir.replace(QRegExp("\\$LANG(?!\\w)"), lang);
-          QDir qdir(dir);
-          if (qdir.exists())
-            if (trans->load(name + "_" + lang, dir, "_.-"))
-              return true;
-          if (lang.startsWith("en_") || lang == "en" || lang == "c")
-            break;
+          if (trans->load(name + "_" + lang, dir, "_.-"))
+            return true;
+          if (lang != llang && trans->load(name + "_" + llang, dir, "_.-"))
+            return true;
         }
     }
   return false;
 }
 
+bool
+QDjViewApplication::loadTranslators(QStringList langs, 
+                                    QTranslator *dTrans, QTranslator *qTrans)
+{
+  QStringList dirs = getTranslationDirs();
+  foreach (QString lang, langs)
+    {
+      bool okay = true;
+      if (okay && dTrans && !loadOneTranslator(dTrans, "djview", lang, dirs))
+        okay = false;
+      if (okay && qTrans && !loadOneTranslator(qTrans, "qt", lang, dirs))
+        okay = false;
+      if (okay || lang.startsWith("en_") || lang == "en")
+        return okay;
+    }
+  return false;
+}
+
 
 bool 
 QDjViewApplication::event(QEvent *ev)
@@ -359,6 +384,7 @@ usage()
   exit(10);
 }
 
+
 int 
 main(int argc, char *argv[])
 {
@@ -369,11 +395,21 @@ main(int argc, char *argv[])
   
   // Message handler
   qInstallMsgHandler(qtMessageHandler);
+
+  // Set verbose flag as early as possible
 #ifdef Q_OS_UNIX
   const char *s = ::getenv("DJVIEW_VERBOSE");
   if (s && strcmp(s,"0"))
     verbose = true;
 #endif
+  for (int i=1; i<argc; i++)
+    {
+      char *s = argv[i];
+      while (s && *s=='-') 
+        s++;
+      if (! strcmp(s, "verbose"))
+        verbose = true;
+    }
   
   // Color specification 
   // (cause XRender errors under many versions of Qt/X11)
--- djview4-4.9.orig/src/qdjview.cpp
+++ djview4-4.9/src/qdjview.cpp
@@ -2256,7 +2256,7 @@ QDjView::QDjView(QDjVuContext &context,
   
   // Create djvu widget
   QWidget *central = new QWidget(this);
-  widget = new QDjVuWidget(central);
+  widget = new QDjVuWidget(prefs->openGLAccel, central);
   widget->setFrameShape(QFrame::NoFrame);
   if (viewerMode == STANDALONE)
     widget->setFrameShadow(QFrame::Sunken);
--- djview4-4.9.orig/src/qdjvuwidget.cpp
+++ djview4-4.9/src/qdjvuwidget.cpp
@@ -53,6 +53,8 @@
 #include <QVector>
 #include <QWheelEvent>
 #include <QWidget>
+#include <QGLWidget>
+#include <QGLFormat>
 
 
 #if DDJVUAPI_VERSION < 17
@@ -857,6 +859,7 @@ public:
   QCursor cursHandOpen;
   QCursor cursHandClosed;
 
+  void initWidget(bool noaccel);
   void changeLayout(int change, int delay=0);
   void getAnnotationsAndText(Page *p);
   bool requestPage(Page *p);
@@ -1108,10 +1111,9 @@ QDjVuPrivate::makeLayout()
           for(int i=0; i<numPages; i++)
             if (i < loPage - 2 && i >= hiPage + 2)
               pageData[i].clear();
-          if (continuous || sideBySide)
-            adjustSettings(PRIORITY_ANNO, miniexp_nil);
-          else
-            adjustSettings(PRIORITY_ANNO, pageLayout[0]->annotations);
+          // Display settings are unclear when showing multiple page.
+          // We use the annotations of the first displayed page as a proxy.
+          adjustSettings(PRIORITY_ANNO, pageLayout[0]->annotations);
         }
       // Layout page sizes
       else if (layoutChange & CHANGE_SIZE)
@@ -1627,8 +1629,9 @@ QDjVuPrivate::getAnnotationsAndText(Page
   if (p->annotations == miniexp_dummy)
     {
       p->annotations = doc->getPageAnnotations(p->pageno);
-      if (p->annotations && !continuous && !sideBySide)
-        adjustSettings(PRIORITY_ANNO, p->annotations);
+      if (p->annotations)
+        if (pageLayout.size() > 0 && p == pageLayout[0])
+          adjustSettings(PRIORITY_ANNO, p->annotations);
       if (p->annotations)
         prepareMapAreas(p);
     }
@@ -1979,23 +1982,74 @@ QDjVuWidget::~QDjVuWidget()
   priv = 0;
 }
 
+// This is a helper for the constructors
+void
+QDjVuPrivate::initWidget(bool opengl)
+{
+  // set widget policies
+  widget->setFocusPolicy(Qt::StrongFocus);
+  widget->setSizePolicy(QSizePolicy::MinimumExpanding, 
+                        QSizePolicy::MinimumExpanding);
+  // set opengl acceleration
+#if QT_VERSION >= 0x040400
+  if (opengl)
+    {
+      const char *ge = 0;
+      QGLWidget *gw = 0;
+      if (! QGLFormat::hasOpenGL())
+        ge = "cannot find openGL on this system";
+      if (!ge)
+        gw = new QGLWidget();
+      if (gw && !ge && !gw->isValid())
+        ge = "cannot setup openGL context";
+      if (gw && !ge && !gw->format().directRendering())
+        ge = "cannot setup openGL direct rendering";
+      if (gw && !ge)
+        widget->setViewport(gw);
+      else if (gw)
+        delete gw;
+      if (ge)
+        qWarning("Using default rendering (%s)", ge);
+      else
+        qWarning("Using openGL rendering");
+    }
+#endif
+  // setup viewport
+  QWidget *vp = widget->viewport();
+#if QT_VERSION >= 0x040100
+  vp->setAttribute(Qt::WA_OpaquePaintEvent);
+#endif
+  vp->setAttribute(Qt::WA_NoSystemBackground);
+  vp->setAttribute(Qt::WA_StaticContents);
+  vp->setMouseTracking(true);
+}
+
 /*! Construct a \a QDjVuWidget instance.
-  Argument \a parent is the parent of this widget
-  in the \a QObject hierarchy. */
+  Argument \a parent is the parent of this widget 
+  in the \a QObject hierarchy. Setting argument
+  \a opengl to true enables openGL acceleration */
+
+QDjVuWidget::QDjVuWidget(bool opengl, QWidget *parent)
+  : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
+{
+  priv->initWidget(opengl);
+}
+
+/*! Overloaded constructor */
 
 QDjVuWidget::QDjVuWidget(QWidget *parent)
   : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
 {
-  setFocusPolicy(Qt::StrongFocus);
-  setSizePolicy(QSizePolicy::MinimumExpanding, 
-                QSizePolicy::MinimumExpanding);
-  // setup viewport
-#if QT_VERSION >= 0x040100
-  viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
-#endif
-  viewport()->setAttribute(Qt::WA_NoSystemBackground);
-  viewport()->setAttribute(Qt::WA_StaticContents);
-  viewport()->setMouseTracking(true);
+  priv->initWidget(false);
+}
+
+/*! This overloaded constructor calls \a setDocument. */
+
+QDjVuWidget::QDjVuWidget(QDjVuDocument *doc, bool opengl, QWidget *parent)
+  : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
+{
+  priv->initWidget(opengl);
+  setDocument(doc);
 }
 
 /*! This overloaded constructor calls \a setDocument. */
@@ -2003,15 +2057,7 @@ QDjVuWidget::QDjVuWidget(QWidget *parent
 QDjVuWidget::QDjVuWidget(QDjVuDocument *doc, QWidget *parent)
   : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
 {
-  setFocusPolicy(Qt::StrongFocus);
-  setSizePolicy(QSizePolicy::MinimumExpanding, 
-                QSizePolicy::MinimumExpanding);
-#if QT_VERSION >= 0x040100
-  viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
-#endif
-  viewport()->setAttribute(Qt::WA_NoSystemBackground);
-  viewport()->setAttribute(Qt::WA_StaticContents);
-  viewport()->setMouseTracking(true);
+  priv->initWidget(false);
   setDocument(doc);
 }
 
@@ -3545,8 +3591,7 @@ QDjVuPrivate::prepareMapAreas(Page *p)
     if (p->mapAreas[j].expr)
       p->mapAreas.removeAt(j);
   // parse annotations.
-  if (p->annotations && 
-      p->annotations != miniexp_dummy) 
+  if (p->annotations && p->annotations != miniexp_dummy)
     {
       miniexp_t *annos;
       annos = ddjvu_anno_get_hyperlinks(p->annotations);
--- djview4-4.9.orig/src/qdjvunet.cpp
+++ djview4-4.9/src/qdjvunet.cpp
@@ -355,7 +355,7 @@ QDjVuNetDocument::setUrl(QDjVuContext *c
 void 
 QDjVuNetDocument::newstream(int streamid, QString, QUrl url)
 {
-  // network request
+  QString message = tr("Requesting '%1'").arg(url.toString());
   QNetworkRequest request(url);
   QString agent = "Djview/" + QDjViewPrefs::versionString();
   request.setRawHeader("User-Agent", agent.toAscii());
@@ -368,9 +368,9 @@ QDjVuNetDocument::newstream(int streamid
           p, SLOT(sslErrors(const QList<QSslError>&)) );
   connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), 
           p, SLOT(error(QNetworkReply::NetworkError)) );
-  emit info(tr("Requesting '%1'").arg(url.toString()));
   p->reqid[reply] = streamid;
   p->reqok[reply] = false;
+  emit info(message);
 }
 
 
--- djview4-4.9.orig/nsdejavu/nsdejavu.c
+++ djview4-4.9/nsdejavu/nsdejavu.c
@@ -322,9 +322,11 @@ static int
 WriteStringLen(int fd, const char *str, int length)
 {
   int type = TYPE_STRING;
+  static char zero = 0;
   if ( (Write(fd, &type, sizeof(type)) < 0) ||
        (Write(fd, &length, sizeof(length)) < 0) ||
-       (Write(fd, str, length+1) < 0) )
+       (Write(fd, str, length) < 0) ||
+       (Write(fd, &zero, 1) < 0) )
     return -1;
   return 1;
 }
@@ -1160,8 +1162,8 @@ LoadStatic(void)
  ********************************** Callbacks **********************************
  *******************************************************************************/
 
-static int  Detach(void * id);
-static int  Resize(void * id);
+static int  Detach(void *id);
+static int  Resize(void *id);
 static void CloseConnection(void);
 static int  IsConnectionOK(int);
 static void ProgramDied(void);
@@ -1659,7 +1661,7 @@ CloseConnection(void)
 }
 
 static int
-Resize(void * id)
+Resize(void *id)
 {
   /* Instead of selecting ConfigureEvent in the application I catch
      resizeCallback here and send the appropriate request to the
@@ -1719,7 +1721,7 @@ Detach(void * id)
 }
 
 static int
-Attach(Display * displ, Window window, void * id)
+Attach(Display *displ, NPWindow *npw, void *id)
 {
   char *displ_str;
   Instance *inst;
@@ -1728,6 +1730,7 @@ Attach(Display * displ, Window window, v
   Visual *visual;
   char protocol_str[128]; 
   XWindowAttributes attributes;
+  Window window = (npw) ? (Window)npw->window : 0;
   int width, height;
 #if USE_XT
   XtAppContext app_context = 0;   
@@ -1790,7 +1793,11 @@ Attach(Display * displ, Window window, v
       /* Prepare protocol string */
       protocol_str[0]=0;
       if (inst->xembed_mode)
-        strcpy(protocol_str, "XEMBED");
+        {
+          width = (npw) ? npw->width : width;
+          height = (npw) ? npw->height : height;
+          strcpy(protocol_str, "XEMBED");
+        }
 #if USE_XT
       else
         {
@@ -2432,7 +2439,7 @@ NPP_SetWindow(NPP np_inst, NPWindow * wi
   new_window = (win_str) ? (Window) win_str->window : 0;
   if (cur_window)
     {
-      if (new_window==cur_window)
+      if (new_window == cur_window)
         {
           Resize(id);
           return NPERR_NO_ERROR;
@@ -2450,7 +2457,7 @@ NPP_SetWindow(NPP np_inst, NPWindow * wi
         displ = ((NPSetWindowCallbackStruct *)(win_str->ws_info))->display;
       if (!IsConnectionOK(FALSE)) 
         return NPERR_GENERIC_ERROR;
-      if (Attach(displ, new_window, id) < 0)
+      if (Attach(displ, win_str, id) < 0)
         {
           ProgramDied();
           return NPERR_GENERIC_ERROR;
