]> granicus.if.org Git - imagemagick/blobdiff - coders/tiff.c
(no commit message)
[imagemagick] / coders / tiff.c
index 0638faac606c18945ea949ad38adca83daf42966..229639dd06fcc360c613c4344a5607899ca50781 100644 (file)
@@ -17,7 +17,7 @@
 %                                 July 1992                                   %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2009 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2010 ImageMagick Studio LLC, a non-profit organization      %
 %  dedicated to making software imaging solutions freely available.           %
 %                                                                             %
 %  You may not use this file except in compliance with the License.  You may  %
   Include declarations.
 */
 #include "magick/studio.h"
+#include "magick/attribute.h"
 #include "magick/blob.h"
 #include "magick/blob-private.h"
 #include "magick/cache.h"
 #include "magick/color.h"
 #include "magick/color-private.h"
+#include "magick/colormap.h"
 #include "magick/colorspace.h"
 #include "magick/constitute.h"
 #include "magick/enhance.h"
@@ -72,9 +74,9 @@
 #include "magick/static.h"
 #include "magick/statistic.h"
 #include "magick/string_.h"
+#include "magick/string-private.h"
 #include "magick/thread_.h"
 #include "magick/utility.h"
-#include "magick/module.h"
 #if defined(MAGICKCORE_TIFF_DELEGATE)
 # if defined(MAGICKCORE_HAVE_TIFFCONF_H)
 #  include "tiffconf.h"
@@ -105,7 +107,7 @@ static const ExifInfo
     { EXIFTAG_FNUMBER, TIFF_RATIONAL, "exif:FNumber" },
     { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, "exif:ExposureProgram" },
     { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, "exif:SpectralSensitivity" },
-    { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, "exif:ISOSpeedRatings" }, 
+    { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, "exif:ISOSpeedRatings" },
     { EXIFTAG_OECF, TIFF_UNDEFINED, "exif:OptoelectricConversionFactor" },
     { EXIFTAG_EXIFVERSION, TIFF_UNDEFINED, "exif:ExifVersion" },
     { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, "exif:DateTimeOriginal" },
@@ -261,7 +263,7 @@ static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
 %
 */
 
-static inline size_t WriteLSBLong(FILE *file,const unsigned int value)
+static inline size_t WriteLSBLong(FILE *file,const size_t value)
 {
   unsigned char
     buffer[4];
@@ -339,25 +341,25 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
   length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
   length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
   strip_offset=10+(12*14)+4+8;
-  length=WriteLSBLong(file,(unsigned long) strip_offset);
+  length=WriteLSBLong(file,(size_t) strip_offset);
   length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
-  length=WriteLSBLong(file,(unsigned long) image_info->orientation);
+  length=WriteLSBLong(file,(size_t) image_info->orientation);
   length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
   length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
-  length=WriteLSBLong(file,image->columns);
+  length=WriteLSBLong(file,image->rows);
   length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
   offset=(ssize_t) ftell(file)-4;
   length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
-  length=WriteLSBLong(file,(unsigned long) (strip_offset-8));
+  length=WriteLSBLong(file,(size_t) (strip_offset-8));
   length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
-  length=WriteLSBLong(file,(unsigned long) (strip_offset-8));
+  length=WriteLSBLong(file,(size_t) (strip_offset-8));
   length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
   length=fwrite("\000\000\000\000",1,4,file);
   length=WriteLSBLong(file,image->x_resolution);
   length=WriteLSBLong(file,1);
   for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
     (void) fputc(c,file);
-  offset=(ssize_t) fseek(file,(long) offset,SEEK_SET);
+  offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
   length=WriteLSBLong(file,(unsigned int) length);
   (void) fclose(file);
   (void) CloseBlob(image);
@@ -365,7 +367,7 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
   /*
     Read TIFF image.
   */
-  read_info=CloneImageInfo((Image *) NULL);
+  read_info=CloneImageInfo((ImageInfo *) NULL);
   (void) FormatMagickString(read_info->filename,MaxTextExtent,"%.1024s",
     filename);
   image=ReadTIFFImage(read_info,exception);
@@ -419,7 +421,7 @@ static inline size_t MagickMax(const size_t x,const size_t y)
   return(y);
 }
 
-static inline long MagickMin(const long x,const long y)
+static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
 {
   if (x < y)
     return(x);
@@ -427,12 +429,12 @@ static inline long MagickMin(const long x,const long y)
 }
 
 static MagickBooleanType ReadProfile(Image *image,const char *name,
-  unsigned char *datum,long length)
+  unsigned char *datum,ssize_t length)
 {
   MagickBooleanType
     status;
 
-  register long
+  register ssize_t
     i;
 
   StringInfo
@@ -489,8 +491,8 @@ static void TIFFErrors(const char *module,const char *format,va_list error)
   (void) ConcatenateMagickString(message,".",MaxTextExtent);
   exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
   if (exception != (ExceptionInfo *) NULL)
-    (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
-      message,"`%s'",module);
+    (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
+      "`%s'",module);
 }
 
 static void TIFFGetProfiles(TIFF *tiff,Image *image)
@@ -504,30 +506,30 @@ static void TIFFGetProfiles(TIFF *tiff,Image *image)
 #if defined(TIFFTAG_ICCPROFILE)
   length=0;
   if (TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1)
-    (void) ReadProfile(image,"icc",profile,(long) length);
+    (void) ReadProfile(image,"icc",profile,(ssize_t) length);
 #endif
 #if defined(TIFFTAG_PHOTOSHOP)
   length=0;
   if (TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1)
-    (void) ReadProfile(image,"8bim",profile,(long) length);
+    (void) ReadProfile(image,"8bim",profile,(ssize_t) length);
 #endif
 #if defined(TIFFTAG_RICHTIFFIPTC)
   length=0;
   if (TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1)
     {
       if (TIFFIsByteSwapped(tiff) != 0)
-        TIFFSwabArrayOfLong((uint32 *) profile,(unsigned long) length);
+        TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
       (void) ReadProfile(image,"iptc",profile,4L*length);
     }
 #endif
 #if defined(TIFFTAG_XMLPACKET)
   length=0;
   if (TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1)
-    (void) ReadProfile(image,"xmp",profile,(long) length);
+    (void) ReadProfile(image,"xmp",profile,(ssize_t) length);
 #endif
   length=0;
   if (TIFFGetField(tiff,37724,&length,&profile) == 1)
-    (void) ReadProfile(image,"tiff:37724",profile,(long) length);
+    (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length);
 }
 
 static void TIFFGetProperties(TIFF *tiff,Image *image)
@@ -563,7 +565,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
   char
     value[MaxTextExtent];
 
-  register long
+  register ssize_t
     i;
 
   tdir_t
@@ -606,10 +608,10 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
       case TIFF_LONG:
       {
         uint32
-          longy;
+          ssize_ty;
 
-        if (TIFFGetField(tiff,exif_info[i].tag,&longy) != 0)
-          (void) FormatMagickString(value,MaxTextExtent,"%d",longy);
+        if (TIFFGetField(tiff,exif_info[i].tag,&ssize_ty) != 0)
+          (void) FormatMagickString(value,MaxTextExtent,"%d",ssize_ty);
         break;
       }
       case TIFF_RATIONAL:
@@ -655,8 +657,8 @@ static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
   return(count);
 }
 
-static int32 TIFFReadPixels(TIFF *tiff,unsigned long bits_per_sample,
-  tsample_t sample,long row,tdata_t scanline)
+static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
+  tsample_t sample,ssize_t row,tdata_t scanline)
 {
   int32
     status;
@@ -743,7 +745,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
   Image
     *image;
 
-  long
+  ssize_t
     y;
 
   MagickBooleanType
@@ -760,7 +762,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
   QuantumType
     quantum_type;
 
-  register long
+  register ssize_t
     i;
 
   size_t
@@ -802,7 +804,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
   unsigned char
     *pixels;
 
-  unsigned long
+  size_t
     lsb_first;
 
   /*
@@ -841,7 +843,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       /*
         Generate blank images for subimage specification (e.g. image.tif[4].
       */
-      for (i=0; i < (long) image_info->scene; i++)
+      for (i=0; i < (ssize_t) image_info->scene; i++)
       {
         (void) TIFFReadDirectory(tiff);
         AcquireNextImage(image_info,image);
@@ -857,6 +859,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
   {
     if (0 && (image_info->verbose != MagickFalse))
       TIFFPrintDirectory(tiff,stdout,MagickFalse);
+    (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
+      "lsb" : "msb");
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGEWIDTH,&width);
@@ -900,6 +904,11 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
         (void) SetImageProperty(image,"tiff:photometric","separated");
         break;
       }
+      case PHOTOMETRIC_YCBCR:
+      {
+        (void) SetImageProperty(image,"tiff:photometric","YCBCR");
+        break;
+      }
       default:
       {
         (void) SetImageProperty(image,"tiff:photometric","unknown");
@@ -921,12 +930,12 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
         (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
           "interpretation: %s",GetImageProperty(image,"tiff:photometric"));
       }
-    image->columns=(unsigned long) width;
-    image->rows=(unsigned long) height;
-    image->depth=(unsigned long) bits_per_sample;
+    image->columns=(size_t) width;
+    image->rows=(size_t) height;
+    image->depth=(size_t) bits_per_sample;
     if (image->debug != MagickFalse)
-      (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %lu",
-        image->depth);
+      (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
+        (double) image->depth);
     lsb_first=1;
     image->endian=MSBEndian;
     if ((int) (*(char *) &lsb_first) != 0)
@@ -948,8 +957,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     y_position=(float) image->page.y/y_resolution;
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
-    image->page.x=(long) (x_position*x_resolution+0.5);
-    image->page.y=(long) (y_position*y_resolution+0.5);
+    image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
+    image->page.y=(ssize_t) ceil(y_position*y_resolution-0.5);
     image->orientation=(OrientationType) orientation;
     chromaticity=(float *) NULL;
     (void) TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity);
@@ -1029,7 +1038,10 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     }
     quantum_info=AcquireQuantumInfo(image_info,image);
     if (quantum_info == (QuantumInfo *) NULL)
-      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      {
+        TIFFClose(tiff);
+        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      }
     if (sample_format == SAMPLEFORMAT_UINT)
       status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
     if (sample_format == SAMPLEFORMAT_INT)
@@ -1037,7 +1049,10 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     if (sample_format == SAMPLEFORMAT_IEEEFP)
       status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
     if (status == MagickFalse)
-      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      {
+        TIFFClose(tiff);
+        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      }
     status=MagickTrue;
     switch (photometric)
     {
@@ -1064,23 +1079,11 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
           image->matte=MagickTrue;
       }
     else
+      for (i=0; i < extra_samples; i++)
       {
-        if (samples_per_pixel > 3)
-          {
-            image->matte=MagickTrue;
-            associated_alpha=MagickFalse;
-          }
-        if (sample_info[0] == EXTRASAMPLE_UNASSALPHA)
-          {
-            image->matte=MagickTrue;
-            associated_alpha=MagickFalse;
-          }
-        if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
-          {
-            image->matte=MagickTrue;
-            associated_alpha=MagickTrue;
-            SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
-          }
+        image->matte=MagickTrue;
+        if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
+          SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
       }
     option=GetImageOption(image_info,"tiff:alpha");
     if (option != (const char *) NULL)
@@ -1092,10 +1095,10 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     if ((photometric == PHOTOMETRIC_PALETTE) &&
         (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
       {
-        unsigned long
+        size_t
           colors;
 
-        colors=(unsigned long) GetQuantumRange(bits_per_sample)+1;
+        colors=(size_t) GetQuantumRange(bits_per_sample)+1;
         if (AcquireImageColormap(image,colors) == MagickFalse)
           {
             TIFFClose(tiff);
@@ -1143,6 +1146,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     if ((photometric != PHOTOMETRIC_SEPARATED) &&
         (interlace == PLANARCONFIG_SEPARATE))
       method=ReadGenericMethod;
+    if (image->compression == JPEGCompression)
+      method=ReadGenericMethod;
     if (TIFFIsTiled(tiff) != MagickFalse)
       method=ReadTileMethod;
     quantum_type=RGBQuantum;
@@ -1157,7 +1162,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
         if ((image->storage_class == PseudoClass) &&
             (photometric == PHOTOMETRIC_PALETTE))
           {
-            unsigned long
+            size_t
               range;
 
             uint16
@@ -1171,20 +1176,20 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             (void) TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
               &green_colormap,&blue_colormap);
             range=255;  /* might be old style 8-bit colormap */
-            for (i=0; i < (long) image->colors; i++)
+            for (i=0; i < (ssize_t) image->colors; i++)
               if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
                   (blue_colormap[i] >= 256))
                 {
                   range=65535;
                   break;
                 }
-            for (i=0; i < (long) image->colors; i++)
+            for (i=0; i < (ssize_t) image->colors; i++)
             {
-              image->colormap[i].red=RoundToQuantum(((double) QuantumRange*
+              image->colormap[i].red=ClampToQuantum(((double) QuantumRange*
                 red_colormap[i])/range);
-              image->colormap[i].green=RoundToQuantum(((double) QuantumRange*
+              image->colormap[i].green=ClampToQuantum(((double) QuantumRange*
                 green_colormap[i])/range);
-              image->colormap[i].blue=RoundToQuantum(((double) QuantumRange*
+              image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*
                 blue_colormap[i])/range);
             }
           }
@@ -1212,15 +1217,18 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             }
         status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
         if (status == MagickFalse)
-          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+          {
+            TIFFClose(tiff);
+            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+          }
         pixels=GetQuantumPixels(quantum_info);
-        for (y=0; y < (long) image->rows; y++)
+        for (y=0; y < (ssize_t) image->rows; y++)
         {
           int
             status;
 
           register PixelPacket
-            *__restrict q;
+            *restrict q;
 
           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
           if (status == -1)
@@ -1234,7 +1242,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,LoadImageTag,y,image->rows);
+              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -1265,15 +1274,18 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
           }
         status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
         if (status == MagickFalse)
-          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+          {
+            TIFFClose(tiff);
+            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+          }
         pixels=GetQuantumPixels(quantum_info);
-        for (y=0; y < (long) image->rows; y++)
+        for (y=0; y < (ssize_t) image->rows; y++)
         {
           int
             status;
 
           register PixelPacket
-            *__restrict q;
+            *restrict q;
 
           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
           if (status == -1)
@@ -1287,7 +1299,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,LoadImageTag,y,image->rows);
+              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -1299,13 +1312,13 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
         /*
           Convert TIFF image to DirectClass MIFF image.
         */
-        for (y=0; y < (long) image->rows; y++)
+        for (i=0; i < (ssize_t) samples_per_pixel; i++)
         {
-          register PixelPacket
-            *__restrict q;
-
-          for (i=0; i < (long) samples_per_pixel; i++)
+          for (y=0; y < (ssize_t) image->rows; y++)
           {
+            register PixelPacket
+              *restrict q;
+
             int
               status;
 
@@ -1325,7 +1338,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
                 case 3: quantum_type=AlphaQuantum; break;
                 default: quantum_type=UndefinedQuantum; break;
               }
-           else
+            else
               switch (i)
               {
                 case 0: quantum_type=CyanQuantum; break;
@@ -1342,7 +1355,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
           }
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,LoadImageTag,y,image->rows);
+              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -1359,13 +1373,13 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
         */
         i=0;
         p=(unsigned char *) NULL;
-        for (y=0; y < (long) image->rows; y++)
+        for (y=0; y < (ssize_t) image->rows; y++)
         {
-          register long
+          register ssize_t
             x;
 
           register PixelPacket
-            *__restrict q;
+            *restrict q;
 
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (PixelPacket *) NULL)
@@ -1374,11 +1388,12 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             {
               if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
                 break;
-              i=(long) MagickMin((long) rows_per_strip,(long) image->rows-y);
+              i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
+                image->rows-y);
             }
           i--;
           p=pixels+image->columns*i;
-          for (x=0; x < (long) image->columns; x++)
+          for (x=0; x < (ssize_t) image->columns; x++)
           {
             q->red=ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)));
             q->green=ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)));
@@ -1392,7 +1407,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,LoadImageTag,y,image->rows);
+              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -1409,7 +1425,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
           columns,
           rows;
 
-        unsigned long
+        size_t
           number_pixels;
 
         /*
@@ -1430,38 +1446,38 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             TIFFClose(tiff);
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
           }
-        for (y=0; y < (long) image->rows; y+=rows)
+        for (y=0; y < (ssize_t) image->rows; y+=rows)
         {
           PixelPacket
             *tile;
 
-          register long
+          register ssize_t
             x;
 
           register PixelPacket
-            *__restrict q;
+            *restrict q;
 
-          unsigned long
+          size_t
             columns_remaining,
             rows_remaining;
 
           rows_remaining=image->rows-y;
-          if ((long) (y+rows) < (long) image->rows)
+          if ((ssize_t) (y+rows) < (ssize_t) image->rows)
             rows_remaining=rows;
           tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
             exception);
           if (tile == (PixelPacket *) NULL)
             break;
-          for (x=0; x < (long) image->columns; x+=columns)
+          for (x=0; x < (ssize_t) image->columns; x+=columns)
           {
-            unsigned long
+            size_t
               column,
               row;
 
             if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
               break;
             columns_remaining=image->columns-x;
-            if ((long) (x+columns) < (long) image->columns)
+            if ((ssize_t) (x+columns) < (ssize_t) image->columns)
               columns_remaining=columns;
             p=tile_pixels+(rows-rows_remaining)*columns;
             q=tile+(image->columns*(rows_remaining-1)+x);
@@ -1495,7 +1511,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,LoadImageTag,y,image->rows);
+              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -1535,25 +1552,26 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
           Convert image to DirectClass pixel packets.
         */
         p=pixels+number_pixels-1;
-        for (y=0; y < (long) image->rows; y++)
+        for (y=0; y < (ssize_t) image->rows; y++)
         {
-          register long
+          register ssize_t
             x;
 
           register PixelPacket
-            *__restrict q;
+            *restrict q;
 
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (PixelPacket *) NULL)
             break;
           q+=image->columns-1;
-          for (x=0; x < (long) image->columns; x++)
+          for (x=0; x < (ssize_t) image->columns; x++)
           {
             q->red=ScaleCharToQuantum((unsigned char) TIFFGetR(*p));
             q->green=ScaleCharToQuantum((unsigned char) TIFFGetG(*p));
             q->blue=ScaleCharToQuantum((unsigned char) TIFFGetB(*p));
             if (image->matte != MagickFalse)
-              q->opacity=ScaleCharToQuantum((unsigned char) TIFFGetA(*p));
+              q->opacity=(Quantum) (QuantumRange-
+                ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));
             p--;
             q--;
           }
@@ -1561,7 +1579,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,LoadImageTag,y,image->rows);
+              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -1646,10 +1665,10 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
 %
 %  The format of the RegisterTIFFImage method is:
 %
-%      unsigned long RegisterTIFFImage(void)
+%      size_t RegisterTIFFImage(void)
 %
 */
-ModuleExport unsigned long RegisterTIFFImage(void)
+ModuleExport size_t RegisterTIFFImage(void)
 {
 #define TIFFDescription  "Tagged Image File Format"
 
@@ -1659,14 +1678,16 @@ ModuleExport unsigned long RegisterTIFFImage(void)
   MagickInfo
     *entry;
 
-  AcquireSemaphoreInfo(&tiff_semaphore);
+  if (tiff_semaphore == (SemaphoreInfo *) NULL)
+    tiff_semaphore=AllocateSemaphoreInfo();
+  LockSemaphoreInfo(tiff_semaphore);
   if (instantiate_key == MagickFalse)
     {
       if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
       instantiate_key=MagickTrue;
     }
-  RelinquishSemaphoreInfo(tiff_semaphore);
+  UnlockSemaphoreInfo(tiff_semaphore);
   *version='\0';
 #if defined(TIFF_VERSION)
   (void) FormatMagickString(version,MaxTextExtent,"%d",TIFF_VERSION);
@@ -1676,7 +1697,7 @@ ModuleExport unsigned long RegisterTIFFImage(void)
     const char
       *p;
 
-    register long int
+    register ssize_t
       i;
 
     p=TIFFGetVersion();
@@ -1694,6 +1715,7 @@ ModuleExport unsigned long RegisterTIFFImage(void)
   entry->raw=MagickTrue;
   entry->endian_support=MagickTrue;
   entry->adjoin=MagickFalse;
+  entry->format_type=ImplicitFormatType;
   entry->seekable_stream=MagickTrue;
   entry->thread_support=NoThreadSupport;
   entry->description=ConstantString("Raw CCITT Group4");
@@ -1781,12 +1803,14 @@ ModuleExport void UnregisterTIFFImage(void)
   (void) UnregisterMagickInfo("TIF");
   (void) UnregisterMagickInfo("TIFF");
   (void) UnregisterMagickInfo("TIFF64");
-  AcquireSemaphoreInfo(&tiff_semaphore);
+  if (tiff_semaphore == (SemaphoreInfo *) NULL)
+    tiff_semaphore=AllocateSemaphoreInfo();
+  LockSemaphoreInfo(tiff_semaphore);
   if (instantiate_key != MagickFalse)
     if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
       ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
   instantiate_key=MagickFalse;
-  RelinquishSemaphoreInfo(tiff_semaphore);
+  UnlockSemaphoreInfo(tiff_semaphore);
   DestroySemaphoreInfo(&tiff_semaphore);
 }
 \f
@@ -1837,7 +1861,7 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
   MagickBooleanType
     status;
 
-  register long
+  register ssize_t
     i;
 
   ssize_t
@@ -1846,10 +1870,7 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
   TIFF
     *tiff;
 
-  uint16
-    fillorder;
-
-  uint32
+  toff_t
     *byte_count,
     strip_size;
 
@@ -1874,10 +1895,11 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
       (void) CloseBlob(image);
       return(MagickFalse);
     }
+  huffman_image->endian=MSBEndian;
   file=(FILE *) NULL;
   unique_file=AcquireUniqueFileResource(filename);
   if (unique_file != -1)
-    file=fdopen(unique_file,"wb"); 
+    file=fdopen(unique_file,"wb");
   if ((unique_file == -1) || (file == (FILE *) NULL))
     {
       ThrowFileException(&image->exception,FileOpenError,
@@ -1887,7 +1909,7 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
   (void) FormatMagickString(huffman_image->filename,MaxTextExtent,"tiff:%s",
     filename);
   (void) SetImageType(huffman_image,BilevelType);
-  write_info=CloneImageInfo((Image *) NULL);
+  write_info=CloneImageInfo((ImageInfo *) NULL);
   SetImageInfoFile(write_info,file);
   write_info->compression=Group4Compression;
   write_info->type=BilevelType;
@@ -1916,10 +1938,16 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
   /*
     Allocate raw strip buffer.
   */
-  byte_count=0;
-  (void) TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count);
+  if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
+    {
+      TIFFClose(tiff);
+      huffman_image=DestroyImage(huffman_image);
+      (void) fclose(file);
+      (void) RelinquishUniqueFileResource(filename);
+      return(MagickFalse);
+    }
   strip_size=byte_count[0];
-  for (i=1; i < (long) TIFFNumberOfStrips(tiff); i++)
+  for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
     if (byte_count[i] > strip_size)
       strip_size=byte_count[i];
   buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
@@ -1936,14 +1964,9 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
   /*
     Compress runlength encoded to 2D Huffman pixels.
   */
-  fillorder=FILLORDER_LSB2MSB;
-  (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&fillorder);
-  for (i=0; i < (long) TIFFNumberOfStrips(tiff); i++)
+  for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
   {
-    count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,(long)
-      byte_count[i]);
-    if (fillorder == FILLORDER_LSB2MSB)
-      TIFFReverseBits(buffer,(unsigned long) count);
+    count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
     if (WriteBlob(image,(size_t) count,buffer) != count)
       status=MagickFalse;
   }
@@ -1998,7 +2021,7 @@ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
   MagickBooleanType
     status;
 
-  unsigned long
+  size_t
     columns,
     rows;
 
@@ -2091,6 +2114,10 @@ static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
   MagickStatusType
     flags;
 
+  uint32
+    tile_columns,
+    tile_rows;
+
   assert(tiff_info != (TIFFInfo *) NULL);
   (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
   option=GetImageOption(image_info,"tiff:tile-geometry");
@@ -2099,15 +2126,17 @@ static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
   flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
   if ((flags & HeightValue) == 0)
     tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
-  (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,(uint32)
-    tiff_info->tile_geometry.width);
-  (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,(uint32)
-    tiff_info->tile_geometry.height);
+  tile_columns=(uint32) tiff_info->tile_geometry.width;
+  tile_rows=(uint32) tiff_info->tile_geometry.height;
+  TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
+  (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
+  (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
+  tiff_info->tile_geometry.width=tile_columns;
+  tiff_info->tile_geometry.height=tile_rows;
   tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
-    tiff_info->tile_geometry.height*TIFFScanlineSize(tiff),
-    sizeof(*tiff_info->scanlines));
+    tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
   tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
-    TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
+    tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
   if ((tiff_info->scanlines == (unsigned char *) NULL) ||
       (tiff_info->pixels == (unsigned char *) NULL))
     {
@@ -2117,26 +2146,26 @@ static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
   return(MagickTrue);
 }
 
-static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,long row,
+static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
   tsample_t sample,Image *image)
 {
   int32
     status;
 
-  long
+  ssize_t
     bytes_per_pixel,
     j,
     k,
     l;
 
-  register long
+  register ssize_t
     i;
 
   register unsigned char
     *p,
     *q;
 
-  unsigned long
+  size_t
     number_tiles,
     tile_width;
 
@@ -2145,26 +2174,26 @@ static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,long row,
   /*
     Fill scanlines to tile height.
   */
-  i=(long) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
+  i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
   (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
     (size_t) TIFFScanlineSize(tiff));
-  if (((unsigned long) (row % tiff_info->tile_geometry.height) !=
-      (tiff_info->tile_geometry.height-1)) && (row != (long) (image->rows-1)))
+  if (((size_t) (row % tiff_info->tile_geometry.height) !=
+      (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1)))
     return(0);
   /*
     Write tile to TIFF image.
   */
   status=0;
-  bytes_per_pixel=TIFFTileSize(tiff)/(long) (tiff_info->tile_geometry.height*
+  bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
     tiff_info->tile_geometry.width);
   number_tiles=(image->columns+tiff_info->tile_geometry.width)/
     tiff_info->tile_geometry.width;
-  for (i=0; i < (long) number_tiles; i++)
+  for (i=0; i < (ssize_t) number_tiles; i++)
   {
-    tile_width=(i == (long) (number_tiles-1)) ? image->columns-(i*
+    tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
       tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
-    for (j=0; j < (long) ((row % tiff_info->tile_geometry.height)+1); j++)
-      for (k=0; k < (long) tile_width; k++)
+    for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
+      for (k=0; k < (ssize_t) tile_width; k++)
       {
         if (bytes_per_pixel == 0)
           {
@@ -2180,10 +2209,11 @@ static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,long row,
         for (l=0; l < bytes_per_pixel; l++)
           *q++=(*p++);
       }
-    status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
-      tiff_info->tile_geometry.width),(uint32) ((row/
-      tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
-      sample);
+    if ((i*tiff_info->tile_geometry.width) != image->columns)
+      status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
+        tiff_info->tile_geometry.width),(uint32) ((row/
+        tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
+        sample);
     if (status < 0)
       break;
   }
@@ -2250,6 +2280,7 @@ static void TIFFSetProperties(TIFF *tiff,Image *image)
   const char
     *value;
 
+  (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
   value=GetImageProperty(image,"tiff:hostcomputer");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
@@ -2265,9 +2296,9 @@ static void TIFFSetProperties(TIFF *tiff,Image *image)
   value=GetImageProperty(image,"tiff:model");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
-  (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,
-    GetMagickVersion((unsigned long *) NULL));
-  (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
+  value=GetImageProperty(image,"tiff:software");
+  if (value != (const char *) NULL)
+    (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
   value=GetImageProperty(image,"tiff:copyright");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,33432,value);
@@ -2291,7 +2322,7 @@ static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
   const char
     *value;
 
-  register long
+  register ssize_t
     i;
 
   uint32
@@ -2319,17 +2350,17 @@ static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
         uint16
           shorty;
 
-        shorty=(uint16) atoi(value);
+        shorty=(uint16) StringToLong(value);
         (void) TIFFSetField(tiff,exif_info[i].tag,shorty);
         break;
       }
       case TIFF_LONG:
       {
         uint16
-          longy;
+          ssize_ty;
 
-        longy=(uint16) atol(value);
-        (void) TIFFSetField(tiff,exif_info[i].tag,longy);
+        ssize_ty=(uint16) StringToLong(value);
+        (void) TIFFSetField(tiff,exif_info[i].tag,ssize_ty);
         break;
       }
       case TIFF_RATIONAL:
@@ -2338,7 +2369,7 @@ static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
         float
           rational;
 
-        rational=atof(value);
+        rational=StringToDouble(value);
         (void) TIFFSetField(tiff,exif_info[i].tag,rational);
         break;
       }
@@ -2364,13 +2395,13 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
     *mode,
     *option;
 
-  const char
-    *value;
-
   CompressionType
     compression;
 
-  long
+  EndianType
+    endian_type;
+
+  ssize_t
     y;
 
   MagickBooleanType
@@ -2386,7 +2417,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   QuantumType
     quantum_type;
 
-  register long
+  register ssize_t
     i;
 
   size_t
@@ -2414,7 +2445,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   unsigned char
     *pixels;
 
-  unsigned long
+  size_t
     lsb_first;
 
   /*
@@ -2432,7 +2463,16 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   (void) MagickSetThreadValue(tiff_exception,&image->exception);
   error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
   warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
-  switch (image_info->endian)
+  endian_type=UndefinedEndian;
+  option=GetImageOption(image_info,"tiff:endian");
+  if (option != (const char *) NULL)
+    {
+      if (LocaleNCompare(option,"msb",3) == 0)
+        endian_type=MSBEndian;
+      if (LocaleNCompare(option,"lsb",3) == 0)
+        endian_type=LSBEndian;;
+    }
+  switch (endian_type)
   {
     case LSBEndian: mode="wl"; break;
     case MSBEndian: mode="wb"; break;
@@ -2440,7 +2480,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   }
 #if defined(TIFF_VERSION_BIG)
   if (LocaleCompare(image_info->magick,"TIFF64") == 0)
-    switch (image_info->endian)
+    switch (endian_type)
     {
       case LSBEndian: mode="wl8"; break;
       case MSBEndian: mode="wb8"; break;
@@ -2529,27 +2569,15 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         break;
       }
     }
-#if defined(MAGICKCORE_HAVE_TIFFGETCONFIGUREDCODECS) || (TIFFLIB_VERSION > 20040919)
-    if (compress_tag != COMPRESSION_NONE)
+#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
+    if ((compress_tag != COMPRESSION_NONE) &&
+        (TIFFIsCODECConfigured(compress_tag) == 0))
       {
-        TIFFCodec
-          *codec;
-
-        codec=TIFFGetConfiguredCODECs();
-        while ((codec != (TIFFCodec *) NULL) && (codec->name != (char *) NULL))
-        {
-          if (codec->scheme == compress_tag)
-            break;
-          codec++;
-        }
-        if (((codec == (TIFFCodec *) NULL)) || (codec->scheme != compress_tag))
-          {
-            (void) ThrowMagickException(&image->exception,GetMagickModule(),
-              CoderError,"CompressionNotSupported","`%s'",
-              MagickOptionToMnemonic(MagickCompressOptions,(long) compression));
-            compress_tag=COMPRESSION_NONE;
-            compression=NoCompression;
-          }
+        (void) ThrowMagickException(&image->exception,GetMagickModule(),
+          CoderError,"CompressionNotSupported","`%s'",MagickOptionToMnemonic(
+          MagickCompressOptions,(ssize_t) compression));
+        compress_tag=COMPRESSION_NONE;
+        compression=NoCompression;
       }
 #else
       switch (compress_tag)
@@ -2576,7 +2604,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         {
           (void) ThrowMagickException(&image->exception,GetMagickModule(),
             CoderError,"CompressionNotSupported","`%s'",MagickOptionToMnemonic(
-              MagickCompressOptions,(long) compression));
+              MagickCompressOptions,(ssize_t) compression));
           compress_tag=COMPRESSION_NONE;
           compression=NoCompression;
           break;
@@ -2600,7 +2628,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       default:
         break;
     }
-    (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
     if (image->colorspace == CMYKColorspace)
       {
         photometric=PHOTOMETRIC_SEPARATED;
@@ -2619,6 +2646,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
             {
               photometric=PHOTOMETRIC_YCBCR;
               (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
+              (void) SetImageStorageClass(image,DirectClass);
               (void) SetImageDepth(image,8);
             }
           else
@@ -2631,43 +2659,89 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         if ((image_info->type != TrueColorType) &&
             (image_info->type != TrueColorMatteType))
           {
-            if (image->storage_class == PseudoClass)
+            if ((image_info->type != PaletteType) &&
+                (IsGrayImage(image,&image->exception) != MagickFalse))
               {
-                unsigned long
-                  depth;
-
-                /*
-                  Colormapped TIFF raster.
-                */
+                photometric=(uint16) (quantum_info->min_is_white !=
+                  MagickFalse ? PHOTOMETRIC_MINISWHITE :
+                  PHOTOMETRIC_MINISBLACK);
                 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
-                photometric=PHOTOMETRIC_PALETTE;
-                depth=1;
-                while ((GetQuantumRange(depth)+1) < image->colors)
-                  depth<<=1;
-                status=SetQuantumDepth(image,quantum_info,depth);
-                if (status == MagickFalse)
-                  ThrowWriterException(ResourceLimitError,
-                    "MemoryAllocationFailed");
+                if ((image_info->depth == 0) && (image->matte == MagickFalse) &&
+                    (IsMonochromeImage(image,&image->exception) != MagickFalse))
+                  {
+                    status=SetQuantumDepth(image,quantum_info,1);
+                    if (status == MagickFalse)
+                      ThrowWriterException(ResourceLimitError,
+                        "MemoryAllocationFailed");
+                  }
               }
             else
-              if ((image_info->type != PaletteType) &&
-                  (IsGrayImage(image,&image->exception) != MagickFalse))
+              if (image->storage_class == PseudoClass)
                 {
-                  photometric=(uint16) (quantum_info->min_is_white !=
-                    MagickFalse ? PHOTOMETRIC_MINISWHITE :
-                    PHOTOMETRIC_MINISBLACK);
+                  size_t
+                    depth;
+
+                  /*
+                    Colormapped TIFF raster.
+                  */
                   (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
-                  if ((image_info->depth == 0) &&
-                      (IsMonochromeImage(image,&image->exception) != MagickFalse))
-                    {
-                      status=SetQuantumDepth(image,quantum_info,1);
-                      if (status == MagickFalse)
-                        ThrowWriterException(ResourceLimitError,
-                          "MemoryAllocationFailed");
-                    }
+                  photometric=PHOTOMETRIC_PALETTE;
+                  depth=1;
+                  while ((GetQuantumRange(depth)+1) < image->colors)
+                    depth<<=1;
+                  status=SetQuantumDepth(image,quantum_info,depth);
+                  if (status == MagickFalse)
+                    ThrowWriterException(ResourceLimitError,
+                      "MemoryAllocationFailed");
                 }
           }
       }
+    switch (image->endian)
+    {
+      case LSBEndian:
+      {
+        endian=FILLORDER_LSB2MSB;
+        break;
+      }
+      case MSBEndian:
+      {
+        endian=FILLORDER_MSB2LSB;
+        break;
+      }
+      case UndefinedEndian:
+      default:
+      {
+        (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
+        break;
+      }
+    }
+    lsb_first=1;
+    image->endian=MSBEndian;
+    if ((int) (*(char *) &lsb_first) != 0)
+      image->endian=LSBEndian;
+    if ((compress_tag == COMPRESSION_CCITTFAX3) &&
+        (photometric != PHOTOMETRIC_MINISWHITE))
+      {
+        compress_tag=COMPRESSION_NONE;
+        endian=FILLORDER_MSB2LSB;
+      }
+    else
+      if ((compress_tag == COMPRESSION_CCITTFAX4) &&
+         (photometric != PHOTOMETRIC_MINISWHITE))
+       {
+         compress_tag=COMPRESSION_NONE;
+         endian=FILLORDER_MSB2LSB;
+       }
+    option=GetImageProperty(image,"tiff:fill-order");
+    if (option != (const char *) NULL)
+      {
+        if (LocaleNCompare(option,"msb",3) == 0)
+          endian=FILLORDER_MSB2LSB;
+        if (LocaleNCompare(option,"lsb",3) == 0)
+          endian=FILLORDER_LSB2MSB;
+      }
+    (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
+    (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
     (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
     if (image->matte != MagickFalse)
       {
@@ -2716,30 +2790,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       default:
         break;
     }
-    switch (image->endian)
-    {
-      case LSBEndian:
-      {
-        endian=FILLORDER_LSB2MSB;
-        break;
-      }
-      case MSBEndian:
-      {
-        endian=FILLORDER_MSB2LSB;
-        break;
-      }
-      case UndefinedEndian:
-      default:
-      {
-        (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
-        break;
-      }
-    }
-    lsb_first=1;
-    image->endian=MSBEndian;
-    if ((int) (*(char *) &lsb_first) != 0)
-      image->endian=LSBEndian;
-    (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
     (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
     (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
     if (photometric == PHOTOMETRIC_RGB)
@@ -2748,11 +2798,11 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
     rows_per_strip=1;
     if (TIFFScanlineSize(tiff) != 0)
-      rows_per_strip=(unsigned long) MagickMax((size_t)
-        TIFFDefaultStripSize(tiff,-1),1);
+      rows_per_strip=(uint32) MagickMax((size_t) TIFFDefaultStripSize(tiff,0),
+        1);
     option=GetImageOption(image_info,"tiff:rows-per-strip");
     if (option != (const char *) NULL)
-      rows_per_strip=(unsigned long) strtol(option,(char **) NULL,10);
+      rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
     switch (compress_tag)
     {
       case COMPRESSION_JPEG:
@@ -2775,6 +2825,9 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
         if (image->colorspace == RGBColorspace)
           {
+            const char
+              *value;
+
             (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
             sampling_factor=(const char *) NULL;
             value=GetImageProperty(image,"jpeg:sampling-factor");
@@ -2792,8 +2845,9 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                 flags=ParseGeometry(sampling_factor,&geometry_info);
                 if ((flags & SigmaValue) == 0)
                   geometry_info.sigma=geometry_info.rho;
-                (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
-                  geometry_info.rho,(uint16) geometry_info.sigma);
+                if (image->colorspace == YCbCrColorspace)
+                  (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
+                    geometry_info.rho,(uint16) geometry_info.sigma);
               }
           }
         if (bits_per_sample == 12)
@@ -2803,16 +2857,16 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       }
       case COMPRESSION_ADOBE_DEFLATE:
       {
-        rows_per_strip=image->rows;
+        rows_per_strip=(uint32) image->rows;
         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
           &bits_per_sample);
         if (((photometric == PHOTOMETRIC_RGB) ||
              (photometric == PHOTOMETRIC_MINISBLACK)) &&
             ((bits_per_sample == 8) || (bits_per_sample == 16)))
           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,2);
-        (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,image_info->quality ==
-          UndefinedCompressionQuality ? 7 : MagickMin(1L*image_info->quality/10,
-          9));
+        (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
+          image_info->quality == UndefinedCompressionQuality ? 7 :
+          MagickMin((ssize_t) image_info->quality/10,9)));
         break;
       }
       case COMPRESSION_CCITTFAX3:
@@ -2820,13 +2874,13 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         /*
           Byte-aligned EOL.
         */
-        rows_per_strip=image->rows;
+        rows_per_strip=(uint32) image->rows;
         (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
         break;
       }
       case COMPRESSION_CCITTFAX4:
       {
-        rows_per_strip=image->rows;
+        rows_per_strip=(uint32) image->rows;
         break;
       }
       case COMPRESSION_LZW:
@@ -2842,7 +2896,9 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       default:
         break;
     }
-    (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
+    option=GetImageOption(image_info,"tiff:tile-geometry");
+    if (option == (const char *) NULL)
+      (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
     if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
       {
         unsigned short
@@ -2905,7 +2961,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         pages;
 
       page=(uint16) scene;
-      pages=GetImageListLength(image);
+      pages=(uint16) GetImageListLength(image);
       if ((image_info->adjoin != MagickFalse) && (pages > 1))
         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
       (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
@@ -2937,10 +2993,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
             quantum_type=RGBQuantum;
             if (image->matte != MagickFalse)
               quantum_type=RGBAQuantum;
-            for (y=0; y < (long) image->rows; y++)
+            for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const PixelPacket
-                *__restrict p;
+                *restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,
                 &image->exception);
@@ -2952,7 +3008,8 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                 break;
               if (image->previous == (Image *) NULL)
                 {
-                  status=SetImageProgress(image,SaveImageTag,y,image->rows);
+                  status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
+                    y,image->rows);
                   if (status == MagickFalse)
                     break;
                 }
@@ -2965,10 +3022,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
             /*
               Plane interlacing:  RRRRRR...GGGGGG...BBBBBB...
             */
-            for (y=0; y < (long) image->rows; y++)
+            for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const PixelPacket
-                *__restrict p;
+                *restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,
                 &image->exception);
@@ -2985,10 +3042,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                 if (status == MagickFalse)
                   break;
               }
-            for (y=0; y < (long) image->rows; y++)
+            for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const PixelPacket
-                *__restrict p;
+                *restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,
                 &image->exception);
@@ -3005,10 +3062,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                 if (status == MagickFalse)
                   break;
               }
-            for (y=0; y < (long) image->rows; y++)
+            for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const PixelPacket
-                *__restrict p;
+                *restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,
                 &image->exception);
@@ -3026,10 +3083,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                   break;
               }
             if (image->matte != MagickFalse)
-              for (y=0; y < (long) image->rows; y++)
+              for (y=0; y < (ssize_t) image->rows; y++)
               {
                 register const PixelPacket
-                  *__restrict p;
+                  *restrict p;
 
                 p=GetVirtualPixels(image,0,y,image->columns,1,
                   &image->exception);
@@ -3061,10 +3118,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
           quantum_type=CMYKAQuantum;
         if (image->colorspace != CMYKColorspace)
           (void) TransformImageColorspace(image,CMYKColorspace);
-        for (y=0; y < (long) image->rows; y++)
+        for (y=0; y < (ssize_t) image->rows; y++)
         {
           register const PixelPacket
-            *__restrict p;
+            *restrict p;
 
           p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
           if (p == (const PixelPacket *) NULL)
@@ -3075,7 +3132,8 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,SaveImageTag,y,image->rows);
+              status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }
@@ -3104,7 +3162,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         (void) ResetMagickMemory(red,0,65536*sizeof(*red));
         (void) ResetMagickMemory(green,0,65536*sizeof(*green));
         (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
-        for (i=0; i < (long) image->colors; i++)
+        for (i=0; i < (ssize_t) image->colors; i++)
         {
           red[i]=ScaleQuantumToShort(image->colormap[i].red);
           green[i]=ScaleQuantumToShort(image->colormap[i].green);
@@ -3131,10 +3189,10 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
          else
            if (photometric != PHOTOMETRIC_PALETTE)
              quantum_type=GrayQuantum;
-        for (y=0; y < (long) image->rows; y++)
+        for (y=0; y < (ssize_t) image->rows; y++)
         {
           register const PixelPacket
-            *__restrict p;
+            *restrict p;
 
           p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
           if (p == (const PixelPacket *) NULL)
@@ -3145,7 +3203,8 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
             break;
           if (image->previous == (Image *) NULL)
             {
-              status=SetImageProgress(image,SaveImageTag,y,image->rows);
+              status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
+                image->rows);
               if (status == MagickFalse)
                 break;
             }