]> git.imager.perl.org - imager.git/blobdiff - tiff.c
Changes to GIF support:
[imager.git] / tiff.c
diff --git a/tiff.c b/tiff.c
index bd6d8cd024e2eb8554c841b595e1f8bdb50808e5..48f48702c23debd5886d47300b0b60b2f81590c5 100644 (file)
--- a/tiff.c
+++ b/tiff.c
@@ -1,7 +1,7 @@
-#include "image.h"
+#include "imager.h"
 #include "tiffio.h"
 #include "iolayer.h"
-#include "imagei.h"
+#include "imageri.h"
 
 /*
 =head1 NAME
@@ -31,7 +31,6 @@ Some of these functions are internal.
 =cut
 */
 
-
 #define byteswap_macro(x) \
      ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >>  8) |     \
       (((x) & 0x0000ff00) <<  8) | (((x) & 0x000000ff) << 24))
@@ -61,10 +60,47 @@ static void error_handler(char const *module, char const *fmt, va_list ap) {
   i_push_errorvf(0, fmt, ap);
 }
 
+#define WARN_BUFFER_LIMIT 10000
+static char *warn_buffer = NULL;
+static int warn_buffer_size = 0;
+
+static void warn_handler(char const *module, char const *fmt, va_list ap) {
+  char buf[1000];
+
+  buf[0] = '\0';
+#ifdef HAVE_SNPRINTF
+  vsnprintf(buf, sizeof(buf), fmt, ap);
+#else
+  vsprintf(buf, fmt, ap);
+#endif
+  if (!warn_buffer || strlen(warn_buffer)+strlen(buf)+2 > warn_buffer_size) {
+    int new_size = warn_buffer_size + strlen(buf) + 2;
+    char *old_buffer = warn_buffer;
+    if (new_size > WARN_BUFFER_LIMIT) {
+      new_size = WARN_BUFFER_LIMIT;
+    }
+    warn_buffer = myrealloc(warn_buffer, new_size);
+    if (!old_buffer) *warn_buffer = '\0';
+    warn_buffer_size = new_size;
+  }
+  if (strlen(warn_buffer)+strlen(buf)+2 <= warn_buffer_size) {
+    strcat(warn_buffer, buf);
+    strcat(warn_buffer, "\n");
+  }
+}
+
 static int save_tiff_tags(TIFF *tif, i_img *im);
 
 static void expand_4bit_hl(unsigned char *buf, int count);
 
+static void pack_4bit_hl(unsigned char *buf, int count);
+
+
+static toff_t sizeproc(thandle_t x) {
+       return 0;
+}
+
+
 /*
 =item comp_seek(h, o, w)
 
@@ -84,26 +120,43 @@ comp_seek(thandle_t h, toff_t o, int w) {
   return (toff_t) ig->seekcb(ig, o, w);
 }
 
+/*
+=item comp_mmap(thandle_t, tdata_t*, toff_t*)
+
+Dummy mmap stub.
+
+This shouldn't ever be called but newer tifflibs want it anyway.
+
+=cut
+*/
+
+static 
+int
+comp_mmap(thandle_t h, tdata_t*p, toff_t*off) {
+  return -1;
+}
 
 /*
-=item i_readtiff_wiol(ig, length)
+=item comp_munmap(thandle_t h, tdata_t p, toff_t off)
 
-Retrieve an image and stores in the iolayer object. Returns NULL on fatal error.
+Dummy munmap stub.
 
-   ig     - io_glue object
-   length - maximum length to read from data source, before closing it
+This shouldn't ever be called but newer tifflibs want it anyway.
 
 =cut
 */
 
-i_img*
-i_readtiff_wiol(io_glue *ig, int length) {
+static void
+comp_munmap(thandle_t h, tdata_t p, toff_t off) {
+  /* do nothing */
+}
+
+static i_img *read_one_tiff(TIFF *tif) {
   i_img *im;
   uint32 width, height;
   uint16 channels;
   uint32* raster = NULL;
   int tiled, error;
-  TIFF* tif;
   float xres, yres;
   uint16 resunit;
   int gotXres, gotYres;
@@ -111,37 +164,9 @@ i_readtiff_wiol(io_glue *ig, int length) {
   uint16 bits_per_sample;
   int i;
   int ch;
-  TIFFErrorHandler old_handler;
-
-  i_clear_error();
-  old_handler = TIFFSetErrorHandler(error_handler);
 
   error = 0;
 
-  /* Add code to get the filename info from the iolayer */
-  /* Also add code to check for mmapped code */
-
-  io_glue_commit_types(ig);
-  mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig, length));
-  
-  tif = TIFFClientOpen("(Iolayer)", 
-                      "rm", 
-                      (thandle_t) ig,
-                      (TIFFReadWriteProc) ig->readcb,
-                      (TIFFReadWriteProc) ig->writecb,
-                      (TIFFSeekProc) comp_seek,
-                      (TIFFCloseProc) ig->closecb,
-                      (TIFFSizeProc) ig->sizecb,
-                      (TIFFMapFileProc) NULL,
-                      (TIFFUnmapFileProc) NULL);
-  
-  if (!tif) {
-    mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
-    i_push_error(0, "opening file");
-    TIFFSetErrorHandler(old_handler);
-    return NULL;
-  }
-
   TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
   TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
   TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &channels);
@@ -153,6 +178,26 @@ i_readtiff_wiol(io_glue *ig, int length) {
   mm_log((1, "i_readtiff_wiol: %stiled\n", tiled?"":"not "));
   mm_log((1, "i_readtiff_wiol: %sbyte swapped\n", TIFFIsByteSwapped(tif)?"":"not "));
 
+  /* separated defaults to CMYK, but if the user is using some strange
+     ink system we can't work out the color anyway */
+  if (photometric == PHOTOMETRIC_SEPARATED && channels >= 4) {
+    /* TIFF can have more than one alpha channel on an image,
+       but Imager can't, only store the first one */
+    
+    channels = channels == 4 ? 3 : 4;
+
+    /* unfortunately the RGBA functions don't try to deal with the alpha
+       channel on CMYK images, at some point I'm planning on expanding
+       TIFF support to handle 16-bit/sample images and I'll deal with
+       it then */
+  }
+
+  /* TIFF images can have more than one alpha channel, but Imager can't
+     this ignores the possibility of 2 channel images with 2 alpha,
+     but there's not much I can do about that */
+  if (channels > 4)
+    channels = 4;
+
   if (photometric == PHOTOMETRIC_PALETTE && bits_per_sample <= 8) {
     channels = 3;
     im = i_img_pal_new(width, height, channels, 256);
@@ -160,6 +205,13 @@ i_readtiff_wiol(io_glue *ig, int length) {
   else {
     im = i_img_empty_ch(NULL, width, height, channels);
   }
+
+  if (!im)
+    return NULL;
+
+  /* general metadata */
+  i_tags_addn(&im->tags, "tiff_bitspersample", 0, bits_per_sample);
+  i_tags_addn(&im->tags, "tiff_photometric", 0, photometric);
     
   /* resolution tags */
   TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &resunit);
@@ -170,16 +222,28 @@ i_readtiff_wiol(io_glue *ig, int length) {
       xres = yres;
     else if (!gotYres)
       yres = xres;
+    i_tags_addn(&im->tags, "tiff_resolutionunit", 0, resunit);
     if (resunit == RESUNIT_CENTIMETER) {
       /* from dots per cm to dpi */
       xres *= 2.54;
       yres *= 2.54;
+      i_tags_add(&im->tags, "tiff_resolutionunit_name", 0, "centimeter", -1, 0);
     }
-    i_tags_addn(&im->tags, "tiff_resolutionunit", 0, resunit);
-    if (resunit == RESUNIT_NONE)
+    else if (resunit == RESUNIT_NONE) {
       i_tags_addn(&im->tags, "i_aspect_only", 0, 1);
-    i_tags_set_float(&im->tags, "i_xres", 0, xres);
-    i_tags_set_float(&im->tags, "i_yres", 0, yres);
+      i_tags_add(&im->tags, "tiff_resolutionunit_name", 0, "none", -1, 0);
+    }
+    else if (resunit == RESUNIT_INCH) {
+      i_tags_add(&im->tags, "tiff_resolutionunit_name", 0, "inch", -1, 0);
+    }
+    else {
+      i_tags_add(&im->tags, "tiff_resolutionunit_name", 0, "unknown", -1, 0);
+    }
+    /* tifflib doesn't seem to provide a way to get to the original rational
+       value of these, which would let me provide a more reasonable
+       precision. So make up a number. */
+    i_tags_set_float2(&im->tags, "i_xres", 0, xres, 6);
+    i_tags_set_float2(&im->tags, "i_yres", 0, yres, 6);
   }
 
   /* Text tags */
@@ -192,6 +256,12 @@ i_readtiff_wiol(io_glue *ig, int length) {
                 strlen(data), 0);
     }
   }
+
+  i_tags_add(&im->tags, "i_format", 0, "tiff", -1, 0);
+  if (warn_buffer && *warn_buffer) {
+    i_tags_add(&im->tags, "i_warning", 0, warn_buffer, -1, 0);
+    *warn_buffer = '\0';
+  }
   
   /*   TIFFPrintDirectory(tif, stdout, 0); good for debugging */
 
@@ -205,17 +275,13 @@ i_readtiff_wiol(io_glue *ig, int length) {
 
     if (!TIFFGetField(tif, TIFFTAG_COLORMAP, maps+0, maps+1, maps+2)) {
       i_push_error(0, "Cannot get colormap for paletted image");
-      TIFFSetErrorHandler(old_handler);
       i_img_destroy(im);
-      TIFFClose(tif);
       return NULL;
     }
     buffer = (unsigned char *)_TIFFmalloc(width+2);
     if (!buffer) {
       i_push_error(0, "out of memory");
-      TIFFSetErrorHandler(old_handler);
       i_img_destroy(im);
-      TIFFClose(tif);
       return NULL;
     }
     row = 0;
@@ -268,8 +334,6 @@ i_readtiff_wiol(io_glue *ig, int length) {
       if (!raster) {
         i_img_destroy(im);
         i_push_error(0, "No space for raster buffer");
-        TIFFSetErrorHandler(old_handler);
-        TIFFClose(tif);
         return NULL;
       }
       
@@ -300,15 +364,17 @@ i_readtiff_wiol(io_glue *ig, int length) {
       }
     } else {
       uint32 rowsperstrip, row;
-      TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
-      mm_log((1, "i_readtiff_wiol: rowsperstrip=%d\n", rowsperstrip));
-      
+      int rc = TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+      mm_log((1, "i_readtiff_wiol: rowsperstrip=%d rc = %d\n", rowsperstrip, rc));
+  
+                       if (rc != 1 || rowsperstrip==-1) {
+                               rowsperstrip = height;
+                       }
+    
       raster = (uint32*)_TIFFmalloc(width * rowsperstrip * sizeof (uint32));
       if (!raster) {
         i_img_destroy(im);
         i_push_error(0, "No space for raster buffer");
-        TIFFSetErrorHandler(old_handler);
-        TIFFClose(tif);
         return NULL;
       }
       
@@ -344,141 +410,426 @@ i_readtiff_wiol(io_glue *ig, int length) {
   }
   if (raster)
     _TIFFfree( raster );
+
+  return im;
+}
+
+/*
+=item i_readtiff_wiol(im, ig)
+
+=cut
+*/
+i_img*
+i_readtiff_wiol(io_glue *ig, int length, int page) {
+  TIFF* tif;
+  TIFFErrorHandler old_handler;
+  TIFFErrorHandler old_warn_handler;
+  i_img *im;
+
+  i_clear_error();
+  old_handler = TIFFSetErrorHandler(error_handler);
+  old_warn_handler = TIFFSetWarningHandler(warn_handler);
+  if (warn_buffer)
+    *warn_buffer = '\0';
+
+  /* Add code to get the filename info from the iolayer */
+  /* Also add code to check for mmapped code */
+
+  io_glue_commit_types(ig);
+  mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig, length));
+  
+  tif = TIFFClientOpen("(Iolayer)", 
+                      "rm", 
+                      (thandle_t) ig,
+                      (TIFFReadWriteProc) ig->readcb,
+                      (TIFFReadWriteProc) ig->writecb,
+                      (TIFFSeekProc) comp_seek,
+                      (TIFFCloseProc) ig->closecb,
+                      ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
+                      (TIFFMapFileProc) comp_mmap,
+                      (TIFFUnmapFileProc) comp_munmap);
+  
+  if (!tif) {
+    mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
+    i_push_error(0, "Error opening file");
+    TIFFSetErrorHandler(old_handler);
+    TIFFSetWarningHandler(old_warn_handler);
+    return NULL;
+  }
+
+  if (page != 0) {
+    if (!TIFFSetDirectory(tif, page)) {
+      mm_log((1, "i_readtiff_wiol: Unable to switch to directory %d\n", page));
+      i_push_errorf(0, "could not switch to page %d", page);
+      TIFFSetErrorHandler(old_handler);
+      TIFFSetWarningHandler(old_warn_handler);
+      TIFFClose(tif);
+      return NULL;
+    }
+  }
+
+  im = read_one_tiff(tif);
+
   if (TIFFLastDirectory(tif)) mm_log((1, "Last directory of tiff file\n"));
   TIFFSetErrorHandler(old_handler);
+  TIFFSetWarningHandler(old_warn_handler);
   TIFFClose(tif);
   return im;
 }
 
+/*
+=item i_readtiff_multi_wiol(ig, length, *count)
 
+Reads multiple images from a TIFF.
 
-/*
-=item i_writetif_wiol(im, ig)
+=cut
+*/
+i_img**
+i_readtiff_multi_wiol(io_glue *ig, int length, int *count) {
+  TIFF* tif;
+  TIFFErrorHandler old_handler;
+  TIFFErrorHandler old_warn_handler;
+  i_img **results = NULL;
+  int result_alloc = 0;
+  int dirnum = 0;
 
-Stores an image in the iolayer object.
+  i_clear_error();
+  old_handler = TIFFSetErrorHandler(error_handler);
+  old_warn_handler = TIFFSetWarningHandler(warn_handler);
+  if (warn_buffer)
+    *warn_buffer = '\0';
 
-   im - image object to write out
-   ig - io_object that defines source to write to 
+  /* Add code to get the filename info from the iolayer */
+  /* Also add code to check for mmapped code */
 
-=cut 
-*/
+  io_glue_commit_types(ig);
+  mm_log((1, "i_readtiff_wiol(ig %p, length %d)\n", ig, length));
+  
+  tif = TIFFClientOpen("(Iolayer)", 
+                      "rm", 
+                      (thandle_t) ig,
+                      (TIFFReadWriteProc) ig->readcb,
+                      (TIFFReadWriteProc) ig->writecb,
+                      (TIFFSeekProc) comp_seek,
+                      (TIFFCloseProc) ig->closecb,
+                      ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
+                      (TIFFMapFileProc) comp_mmap,
+                      (TIFFUnmapFileProc) comp_munmap);
+  
+  if (!tif) {
+    mm_log((1, "i_readtiff_wiol: Unable to open tif file\n"));
+    i_push_error(0, "Error opening file");
+    TIFFSetErrorHandler(old_handler);
+    TIFFSetWarningHandler(old_warn_handler);
+    return NULL;
+  }
+
+  *count = 0;
+  do {
+    i_img *im = read_one_tiff(tif);
+    if (!im)
+      break;
+    if (++*count > result_alloc) {
+      if (result_alloc == 0) {
+        result_alloc = 5;
+        results = mymalloc(result_alloc * sizeof(i_img *));
+      }
+      else {
+        i_img **newresults;
+        result_alloc *= 2;
+        newresults = myrealloc(results, result_alloc * sizeof(i_img *));
+       if (!newresults) {
+         i_img_destroy(im); /* don't leak it */
+         break;
+       }
+       results = newresults;
+      }
+    }
+    results[*count-1] = im;
+  } while (TIFFSetDirectory(tif, ++dirnum));
 
-/* FIXME: Add an options array in here soonish */
+  TIFFSetWarningHandler(old_warn_handler);
+  TIFFSetErrorHandler(old_handler);
+  TIFFClose(tif);
+  return results;
+}
 
 undef_int
-i_writetiff_wiol(i_img *im, io_glue *ig) {
+i_writetiff_low_faxable(TIFF *tif, i_img *im, int fine) {
   uint32 width, height;
-  uint16 channels;
-  uint16 predictor = 0;
-  int quality = 75;
-  int jpegcolormode = JPEGCOLORMODE_RGB;
-  uint16 compression = COMPRESSION_PACKBITS;
-  i_color val;
-  uint16 photometric;
-  uint32 rowsperstrip = (uint32) -1;  /* Let library pick default */
   unsigned char *linebuf = NULL;
   uint32 y;
-  tsize_t linebytes;
-  int ch, ci, rc;
+  int rc;
   uint32 x;
-  TIFF* tif;
-  int got_xres, got_yres, got_aspectonly, aspect_only, resunit;
-  double xres, yres;
-
-  char *cc = mymalloc( 123 );
-  myfree(cc);
-
+  uint32 rowsperstrip;
+  float vres = fine ? 196 : 98;
+  int luma_chan;
 
   width    = im->xsize;
   height   = im->ysize;
-  channels = im->channels;
 
-  switch (channels) {
+  switch (im->channels) {
   case 1:
-    photometric = PHOTOMETRIC_MINISBLACK;
+  case 2:
+    luma_chan = 0;
     break;
   case 3:
-    photometric = PHOTOMETRIC_RGB;
-    if (compression == COMPRESSION_JPEG && jpegcolormode == JPEGCOLORMODE_RGB) photometric = PHOTOMETRIC_YCBCR;
+  case 4:
+    luma_chan = 1;
     break;
   default:
     /* This means a colorspace we don't handle yet */
-    mm_log((1, "i_writetiff_wiol: don't handle %d channel images.\n", channels));
+    mm_log((1, "i_writetiff_wiol_faxable: don't handle %d channel images.\n", im->channels));
     return 0;
   }
 
   /* Add code to get the filename info from the iolayer */
   /* Also add code to check for mmapped code */
 
-  io_glue_commit_types(ig);
-  mm_log((1, "i_writetiff_wiol(im 0x%p, ig 0x%p)\n", im, ig));
 
-  /* FIXME: Enable the mmap interface */
+  mm_log((1, "i_writetiff_wiol_faxable: width=%d, height=%d, channels=%d\n", width, height, im->channels));
   
-  tif = TIFFClientOpen("No name", 
-                      "wm",
-                      (thandle_t) ig, 
-                      (TIFFReadWriteProc) ig->readcb,
-                      (TIFFReadWriteProc) ig->writecb,
-                      (TIFFSeekProc)      comp_seek,
-                      (TIFFCloseProc)     ig->closecb, 
-                      (TIFFSizeProc)      ig->sizecb,
-                      (TIFFMapFileProc)   NULL,
-                      (TIFFUnmapFileProc) NULL);
+  if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH,      width)   )
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField width=%d failed\n", width)); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH,     height)  )
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField length=%d failed\n", height)); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField samplesperpixel=1 failed\n")); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_ORIENTATION,  ORIENTATION_TOPLEFT))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Orientation=topleft\n")); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE,   1)        )
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField bitpersample=1\n")); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField planarconfig\n")); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField photometric=%d\n", PHOTOMETRIC_MINISBLACK)); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, 3))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField compression=3\n")); return 0; }
+
+  linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) );
   
+  if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
+    mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField rowsperstrip=-1\n")); return 0; }
 
+  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
 
-  if (!tif) {
-    mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
-    return 0;
-  }
+  mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
+  mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField scanlinesize=%d\n", TIFFScanlineSize(tif) ));
+  mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField planarconfig=%d == %d\n", rc, PLANARCONFIG_CONTIG));
 
-  mm_log((1, "i_writetiff_wiol: width=%d, height=%d, channels=%d\n", width, height, channels));
-  
-  if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH,      width)   ) { mm_log((1, "i_writetiff_wiol: TIFFSetField width=%d failed\n", width)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH,     height)  ) { mm_log((1, "i_writetiff_wiol: TIFFSetField length=%d failed\n", height)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, channels)) { mm_log((1, "i_writetiff_wiol: TIFFSetField samplesperpixel=%d failed\n", channels)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_ORIENTATION,  ORIENTATION_TOPLEFT)) { mm_log((1, "i_writetiff_wiol: TIFFSetField Orientation=topleft\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE,   8)        ) { mm_log((1, "i_writetiff_wiol: TIFFSetField bitpersample=8\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) { mm_log((1, "i_writetiff_wiol: TIFFSetField planarconfig\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC,   photometric)) { mm_log((1, "i_writetiff_wiol: TIFFSetField photometric=%d\n", photometric)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_COMPRESSION,   compression)) { mm_log((1, "i_writetiff_wiol: TIFFSetField compression=%d\n", compression)); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)204))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Xresolution=204\n")); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, vres))
+    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Yresolution=196\n")); return 0; }
+  if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH)) {
+    mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField ResolutionUnit=%d\n", RESUNIT_INCH)); return 0; 
+  }
 
-  switch (compression) {
-  case COMPRESSION_JPEG:
-    mm_log((1, "i_writetiff_wiol: jpeg compression\n"));
-    if (!TIFFSetField(tif, TIFFTAG_JPEGQUALITY, quality)        ) { mm_log((1, "i_writetiff_wiol: TIFFSetField jpegquality=%d\n", quality)); return 0; }
-    if (!TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, jpegcolormode)) { mm_log((1, "i_writetiff_wiol: TIFFSetField jpegcolormode=%d\n", jpegcolormode)); return 0; }
-    break;
-  case COMPRESSION_LZW:
-    mm_log((1, "i_writetiff_wiol: lzw compression\n"));
-    break;
-  case COMPRESSION_DEFLATE:
-    mm_log((1, "i_writetiff_wiol: deflate compression\n"));
-    if (predictor != 0) 
-      if (!TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor)) { mm_log((1, "i_writetiff_wiol: TIFFSetField predictor=%d\n", predictor)); return 0; }
-    break;
-  case COMPRESSION_PACKBITS:
-    mm_log((1, "i_writetiff_wiol: packbits compression\n"));
-    break;
-  default:
-    mm_log((1, "i_writetiff_wiol: unknown compression %d\n", compression));
+  if (!save_tiff_tags(tif, im)) {
     return 0;
   }
-  
-  linebytes = channels * width;
-  linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) > linebytes ?
-                                         linebytes : TIFFScanlineSize(tif) );
-  
-  if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, rowsperstrip))) {
-    mm_log((1, "i_writetiff_wiol: TIFFSetField rowsperstrip=%d\n", rowsperstrip)); return 0; }
 
-  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
-  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
-
-  mm_log((1, "i_writetiff_wiol: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
+  for (y=0; y<height; y++) {
+    int linebufpos=0;
+    for(x=0; x<width; x+=8) { 
+      int bits;
+      int bitpos;
+      i_sample_t luma[8];
+      uint8 bitval = 128;
+      linebuf[linebufpos]=0;
+      bits = width-x; if(bits>8) bits=8;
+      i_gsamp(im, x, x+8, y, luma, &luma_chan, 1);
+      for(bitpos=0;bitpos<bits;bitpos++) {
+       linebuf[linebufpos] |= ((luma[bitpos] < 128) ? bitval : 0);
+       bitval >>= 1;
+      }
+      linebufpos++;
+    }
+    if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
+      mm_log((1, "i_writetiff_wiol_faxable: TIFFWriteScanline failed.\n"));
+      break;
+    }
+  }
+  if (linebuf) _TIFFfree(linebuf);
+
+  return 1;
+}
+
+undef_int
+i_writetiff_low(TIFF *tif, i_img *im) {
+  uint32 width, height;
+  uint16 channels;
+  uint16 predictor = 0;
+  int quality = 75;
+  int jpegcolormode = JPEGCOLORMODE_RGB;
+  uint16 compression = COMPRESSION_PACKBITS;
+  i_color val;
+  uint16 photometric;
+  uint32 rowsperstrip = (uint32) -1;  /* Let library pick default */
+  unsigned char *linebuf = NULL;
+  uint32 y;
+  tsize_t linebytes;
+  int ch, ci, rc;
+  uint32 x;
+  int got_xres, got_yres, aspect_only, resunit;
+  double xres, yres;
+  uint16 bitspersample = 8;
+  uint16 samplesperpixel;
+  uint16 *colors = NULL;
+
+  width    = im->xsize;
+  height   = im->ysize;
+  channels = im->channels;
+
+  switch (channels) {
+  case 1:
+    photometric = PHOTOMETRIC_MINISBLACK;
+    break;
+  case 3:
+    photometric = PHOTOMETRIC_RGB;
+    if (compression == COMPRESSION_JPEG && jpegcolormode == JPEGCOLORMODE_RGB) photometric = PHOTOMETRIC_YCBCR;
+    else if (im->type == i_palette_type) {
+      photometric = PHOTOMETRIC_PALETTE;
+    }
+    break;
+  default:
+    /* This means a colorspace we don't handle yet */
+    mm_log((1, "i_writetiff_wiol: don't handle %d channel images.\n", channels));
+    return 0;
+  }
+
+  /* Add code to get the filename info from the iolayer */
+  /* Also add code to check for mmapped code */
+
+  /*io_glue_commit_types(ig);*/
+  /*mm_log((1, "i_writetiff_wiol(im 0x%p, ig 0x%p)\n", im, ig));*/
+
+  mm_log((1, "i_writetiff_low: width=%d, height=%d, channels=%d\n", width, height, channels));
+  
+  if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH,      width)   ) { 
+    mm_log((1, "i_writetiff_wiol: TIFFSetField width=%d failed\n", width)); 
+    return 0; 
+  }
+  if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH,     height)  ) { 
+    mm_log((1, "i_writetiff_wiol: TIFFSetField length=%d failed\n", height)); 
+    return 0; 
+  }
+  if (!TIFFSetField(tif, TIFFTAG_ORIENTATION,  ORIENTATION_TOPLEFT)) {
+    mm_log((1, "i_writetiff_wiol: TIFFSetField Orientation=topleft\n")); 
+    return 0; 
+  }
+  if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) { 
+    mm_log((1, "i_writetiff_wiol: TIFFSetField planarconfig\n")); 
+    return 0; 
+  }
+  if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC,   photometric)) { 
+    mm_log((1, "i_writetiff_wiol: TIFFSetField photometric=%d\n", photometric)); 
+    return 0; 
+  }
+  if (!TIFFSetField(tif, TIFFTAG_COMPRESSION,   compression)) { 
+    mm_log((1, "i_writetiff_wiol: TIFFSetField compression=%d\n", compression)); 
+    return 0; 
+  }
+  samplesperpixel = channels;
+  if (photometric == PHOTOMETRIC_PALETTE) {
+    uint16 *out[3];
+    i_color c;
+    int count = i_colorcount(im);
+    int size;
+    int ch, i;
+    
+    samplesperpixel = 1;
+    if (count > 16)
+      bitspersample = 8;
+    else
+      bitspersample = 4;
+    size = 1 << bitspersample;
+    colors = (uint16 *)_TIFFmalloc(sizeof(uint16) * 3 * size);
+    out[0] = colors;
+    out[1] = colors + size;
+    out[2] = colors + 2 * size;
+    
+    for (i = 0; i < count; ++i) {
+      i_getcolors(im, i, &c, 1);
+      for (ch = 0; ch < 3; ++ch)
+        out[ch][i] = c.channel[ch] * 257;
+    }
+    for (; i < size; ++i) {
+      for (ch = 0; ch < 3; ++ch)
+        out[ch][i] = 0;
+    }
+    if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bitspersample)) { 
+      mm_log((1, "i_writetiff_wiol: TIFFSetField bitpersample=%d\n", 
+              bitspersample)); 
+      return 0;
+    }
+    if (!TIFFSetField(tif, TIFFTAG_COLORMAP, out[0], out[1], out[2])) {
+      mm_log((1, "i_writetiff_wiol: TIFFSetField colormap\n")); 
+      return 0;
+    }
+  }
+  else {
+    if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bitspersample)) { 
+      mm_log((1, "i_writetiff_wiol: TIFFSetField bitpersample=%d\n", 
+              bitspersample)); 
+      return 0;
+    }
+  }
+  if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel)) { 
+    mm_log((1, "i_writetiff_wiol: TIFFSetField samplesperpixel=%d failed\n", samplesperpixel)); 
+    return 0;
+  }
+
+  switch (compression) {
+  case COMPRESSION_JPEG:
+    mm_log((1, "i_writetiff_wiol: jpeg compression\n"));
+    if (!TIFFSetField(tif, TIFFTAG_JPEGQUALITY, quality)        ) { 
+      mm_log((1, "i_writetiff_wiol: TIFFSetField jpegquality=%d\n", quality));
+      return 0; 
+    }
+    if (!TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, jpegcolormode)) { 
+      mm_log((1, "i_writetiff_wiol: TIFFSetField jpegcolormode=%d\n", jpegcolormode)); 
+      return 0; 
+    }
+    break;
+  case COMPRESSION_LZW:
+    mm_log((1, "i_writetiff_wiol: lzw compression\n"));
+    break;
+  case COMPRESSION_DEFLATE:
+    mm_log((1, "i_writetiff_wiol: deflate compression\n"));
+    if (predictor != 0) 
+      if (!TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor)) { 
+        mm_log((1, "i_writetiff_wiol: TIFFSetField predictor=%d\n", predictor)); 
+        return 0; 
+      }
+    break;
+  case COMPRESSION_PACKBITS:
+    mm_log((1, "i_writetiff_wiol: packbits compression\n"));
+    break;
+  default:
+    mm_log((1, "i_writetiff_wiol: unknown compression %d\n", compression));
+    return 0;
+  }
+  
+  linebytes = channels * width;
+  linebytes = TIFFScanlineSize(tif) > linebytes ? linebytes 
+    : TIFFScanlineSize(tif);
+  /* working space for the scanlines - we go from 8-bit/pixel to 4 */
+  if (photometric == PHOTOMETRIC_PALETTE && bitspersample == 4)
+    linebytes += linebytes + 1;
+  linebuf = (unsigned char *)_TIFFmalloc(linebytes);
+  
+  if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, rowsperstrip))) {
+    mm_log((1, "i_writetiff_wiol: TIFFSetField rowsperstrip=%d\n", rowsperstrip)); return 0; }
+
+  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
+
+  mm_log((1, "i_writetiff_wiol: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
   mm_log((1, "i_writetiff_wiol: TIFFGetField scanlinesize=%d\n", TIFFScanlineSize(tif) ));
   mm_log((1, "i_writetiff_wiol: TIFFGetField planarconfig=%d == %d\n", rc, PLANARCONFIG_CONTIG));
+  mm_log((1, "i_writetiff_wiol: bitspersample = %d\n", bitspersample));
 
   got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
   got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
@@ -504,97 +855,149 @@ i_writetiff_wiol(i_img *im, io_glue *ig) {
       }
     }
     if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres)) {
-      TIFFClose(tif);
-      i_img_destroy(im);
       i_push_error(0, "cannot set TIFFTAG_XRESOLUTION tag");
       return 0;
     }
     if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres)) {
-      TIFFClose(tif);
-      i_img_destroy(im);
       i_push_error(0, "cannot set TIFFTAG_YRESOLUTION tag");
       return 0;
     }
     if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, (uint16)resunit)) {
-      TIFFClose(tif);
-      i_img_destroy(im);
       i_push_error(0, "cannot set TIFFTAG_RESOLUTIONUNIT tag");
       return 0;
     }
   }
 
   if (!save_tiff_tags(tif, im)) {
-    TIFFClose(tif);
     return 0;
   }
 
-  for (y=0; y<height; y++) {
-    ci = 0;
-    for(x=0; x<width; x++) { 
-      (void) i_gpix(im, x, y,&val);
-      for(ch=0; ch<channels; ch++) linebuf[ci++] = val.channel[ch];
+  if (photometric == PHOTOMETRIC_PALETTE) {
+    for (y = 0; y < height; ++y) {
+      i_gpal(im, 0, width, y, linebuf);
+      if (bitspersample == 4)
+        pack_4bit_hl(linebuf, width);
+      if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
+        mm_log((1, "i_writetiff_wiol: TIFFWriteScanline failed.\n"));
+        if (linebuf) _TIFFfree(linebuf);
+        if (colors) _TIFFfree(colors);
+        return 0;
+      }
     }
-    if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
-      mm_log((1, "i_writetiff_wiol: TIFFWriteScanline failed.\n"));
-      break;
+  }
+  else {
+    for (y=0; y<height; y++) {
+      ci = 0;
+      for(x=0; x<width; x++) { 
+        (void) i_gpix(im, x, y,&val);
+        for(ch=0; ch<channels; ch++) 
+          linebuf[ci++] = val.channel[ch];
+      }
+      if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
+        mm_log((1, "i_writetiff_wiol: TIFFWriteScanline failed.\n"));
+        if (linebuf) _TIFFfree(linebuf);
+        if (colors) _TIFFfree(colors);
+        return 0;
+      }
     }
   }
-  (void) TIFFClose(tif);
   if (linebuf) _TIFFfree(linebuf);
+  if (colors) _TIFFfree(colors);
   return 1;
 }
 
 /*
-=item i_writetiff_wiol_faxable(i_img *, io_glue *)
+=item i_writetiff_multi_wiol(ig, imgs, count, fine_mode)
 
-Stores an image in the iolayer object in faxable tiff format.
+Stores an image in the iolayer object.
 
-   im - image object to write out
    ig - io_object that defines source to write to 
+   imgs,count - the images to write
 
-Note, this may be rewritten to use to simply be a call to a
-lower-level function that gives more options for writing tiff at some
-point.
-
-=cut
+=cut 
 */
 
 undef_int
-i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
-  uint32 width, height;
-  unsigned char *linebuf = NULL;
-  uint32 y;
-  int rc;
-  uint32 x;
+i_writetiff_multi_wiol(io_glue *ig, i_img **imgs, int count) {
   TIFF* tif;
-  int luma_mask;
-  uint32 rowsperstrip;
-  float vres = fine ? 196 : 98;
-  int luma_chan;
+  TIFFErrorHandler old_handler;
+  int i;
 
-  width    = im->xsize;
-  height   = im->ysize;
+  old_handler = TIFFSetErrorHandler(error_handler);
 
-  switch (im->channels) {
-  case 1:
-  case 2:
-    luma_chan = 0;
-    break;
-  case 3:
-  case 4:
-    luma_chan = 1;
-    break;
-  default:
-    /* This means a colorspace we don't handle yet */
-    mm_log((1, "i_writetiff_wiol_faxable: don't handle %d channel images.\n", im->channels));
+  io_glue_commit_types(ig);
+  i_clear_error();
+  mm_log((1, "i_writetiff_multi_wiol(ig 0x%p, imgs 0x%p, count %d)\n", 
+          ig, imgs, count));
+
+  /* FIXME: Enable the mmap interface */
+  
+  tif = TIFFClientOpen("No name", 
+                      "wm",
+                      (thandle_t) ig, 
+                      (TIFFReadWriteProc) ig->readcb,
+                      (TIFFReadWriteProc) ig->writecb,
+                      (TIFFSeekProc)      comp_seek,
+                      (TIFFCloseProc)     ig->closecb, 
+                      ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
+                      (TIFFMapFileProc)   comp_mmap,
+                      (TIFFUnmapFileProc) comp_munmap);
+  
+
+
+  if (!tif) {
+    mm_log((1, "i_writetiff_multi_wiol: Unable to open tif file for writing\n"));
+    i_push_error(0, "Could not create TIFF object");
+    TIFFSetErrorHandler(old_handler);
     return 0;
   }
 
-  /* Add code to get the filename info from the iolayer */
-  /* Also add code to check for mmapped code */
+  for (i = 0; i < count; ++i) {
+    if (!i_writetiff_low(tif, imgs[i])) {
+      TIFFClose(tif);
+      TIFFSetErrorHandler(old_handler);
+      return 0;
+    }
+
+    if (!TIFFWriteDirectory(tif)) {
+      i_push_error(0, "Cannot write TIFF directory");
+      TIFFClose(tif);
+      TIFFSetErrorHandler(old_handler);
+      return 0;
+    }
+  }
+
+  TIFFSetErrorHandler(old_handler);
+  (void) TIFFClose(tif);
+
+  return 1;
+}
+
+/*
+=item i_writetiff_multi_wiol_faxable(ig, imgs, count, fine_mode)
+
+Stores an image in the iolayer object.
+
+   ig - io_object that defines source to write to 
+   imgs,count - the images to write
+   fine_mode - select fine or normal mode fax images
+
+=cut 
+*/
+
+
+undef_int
+i_writetiff_multi_wiol_faxable(io_glue *ig, i_img **imgs, int count, int fine) {
+  TIFF* tif;
+  int i;
+  TIFFErrorHandler old_handler;
+
+  old_handler = TIFFSetErrorHandler(error_handler);
 
   io_glue_commit_types(ig);
-  mm_log((1, "i_writetiff_wiol_faxable(im 0x%p, ig 0x%p)\n", im, ig));
+  i_clear_error();
+  mm_log((1, "i_writetiff_multi_wiol(ig 0x%p, imgs 0x%p, count %d)\n", 
+          ig, imgs, count));
 
   /* FIXME: Enable the mmap interface */
   
@@ -605,102 +1008,175 @@ i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
                       (TIFFReadWriteProc) ig->writecb,
                       (TIFFSeekProc)      comp_seek,
                       (TIFFCloseProc)     ig->closecb, 
-                      (TIFFSizeProc)      ig->sizecb,
-                      (TIFFMapFileProc)   NULL,
-                      (TIFFUnmapFileProc) NULL);
+                      ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
+                      (TIFFMapFileProc)   comp_mmap,
+                      (TIFFUnmapFileProc) comp_munmap);
+  
+
 
   if (!tif) {
-    mm_log((1, "i_writetiff_wiol_faxable: Unable to open tif file for writing\n"));
+    mm_log((1, "i_writetiff_mulit_wiol: Unable to open tif file for writing\n"));
+    i_push_error(0, "Could not create TIFF object");
+    TIFFSetErrorHandler(old_handler);
     return 0;
   }
 
-  mm_log((1, "i_writetiff_wiol_faxable: width=%d, height=%d, channels=%d\n", width, height, im->channels));
-  
-  if (!TIFFSetField(tif, TIFFTAG_IMAGEWIDTH,      width)   )
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField width=%d failed\n", width)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_IMAGELENGTH,     height)  )
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField length=%d failed\n", height)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField samplesperpixel=1 failed\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_ORIENTATION,  ORIENTATION_TOPLEFT))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Orientation=topleft\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE,   1)        )
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField bitpersample=1\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField planarconfig\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField photometric=%d\n", PHOTOMETRIC_MINISBLACK)); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, 3))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField compression=3\n")); return 0; }
+  for (i = 0; i < count; ++i) {
+    if (!i_writetiff_low_faxable(tif, imgs[i], fine)) {
+      TIFFClose(tif);
+      TIFFSetErrorHandler(old_handler);
+      return 0;
+    }
 
-  linebuf = (unsigned char *)_TIFFmalloc( TIFFScanlineSize(tif) );
-  
-  if (!TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, -1))) {
-    mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField rowsperstrip=-1\n")); return 0; }
+    if (!TIFFWriteDirectory(tif)) {
+      i_push_error(0, "Cannot write TIFF directory");
+      TIFFClose(tif);
+      TIFFSetErrorHandler(old_handler);
+      return 0;
+    }
+  }
 
-  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
-  TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rc);
+  (void) TIFFClose(tif);
+  TIFFSetErrorHandler(old_handler);
 
-  mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField rowsperstrip=%d\n", rowsperstrip));
-  mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField scanlinesize=%d\n", TIFFScanlineSize(tif) ));
-  mm_log((1, "i_writetiff_wiol_faxable: TIFFGetField planarconfig=%d == %d\n", rc, PLANARCONFIG_CONTIG));
+  return 1;
+}
 
-  if (!TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)204))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Xresolution=204\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_YRESOLUTION, vres))
-    { mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField Yresolution=196\n")); return 0; }
-  if (!TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH)) {
-    mm_log((1, "i_writetiff_wiol_faxable: TIFFSetField ResolutionUnit=%d\n", RESUNIT_INCH)); return 0; 
+/*
+=item i_writetiff_wiol(im, ig)
+
+Stores an image in the iolayer object.
+
+   im - image object to write out
+   ig - io_object that defines source to write to 
+
+=cut 
+*/
+undef_int
+i_writetiff_wiol(i_img *img, io_glue *ig) {
+  TIFF* tif;
+  TIFFErrorHandler old_handler;
+
+  old_handler = TIFFSetErrorHandler(error_handler);
+
+  io_glue_commit_types(ig);
+  i_clear_error();
+  mm_log((1, "i_writetiff_wiol(img %p, ig 0x%p)\n", img, ig));
+
+  /* FIXME: Enable the mmap interface */
+
+  tif = TIFFClientOpen("No name", 
+                      "wm",
+                      (thandle_t) ig, 
+                      (TIFFReadWriteProc) ig->readcb,
+                      (TIFFReadWriteProc) ig->writecb,
+                      (TIFFSeekProc)      comp_seek,
+                      (TIFFCloseProc)     ig->closecb, 
+                      ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
+                      (TIFFMapFileProc)   comp_mmap,
+                      (TIFFUnmapFileProc) comp_munmap);
+  
+
+
+  if (!tif) {
+    mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
+    i_push_error(0, "Could not create TIFF object");
+    TIFFSetErrorHandler(old_handler);
+    return 0;
   }
 
-  if (!save_tiff_tags(tif, im)) {
+  if (!i_writetiff_low(tif, img)) {
     TIFFClose(tif);
+    TIFFSetErrorHandler(old_handler);
     return 0;
   }
 
-  for (y=0; y<height; y++) {
-    int linebufpos=0;
-    for(x=0; x<width; x+=8) { 
-      int bits;
-      int bitpos;
-      i_sample_t luma[8];
-      uint8 bitval = 128;
-      linebuf[linebufpos]=0;
-      bits = width-x; if(bits>8) bits=8;
-      i_gsamp(im, x, x+8, y, luma, &luma_chan, 1);
-      for(bitpos=0;bitpos<bits;bitpos++) {
-       linebuf[linebufpos] |= ((luma[bitpos]>=128)?bitval:0);
-       bitval >>= 1;
-      }
-      linebufpos++;
-    }
-    if (TIFFWriteScanline(tif, linebuf, y, 0) < 0) {
-      mm_log((1, "i_writetiff_wiol_faxable: TIFFWriteScanline failed.\n"));
-      break;
-    }
+  (void) TIFFClose(tif);
+  TIFFSetErrorHandler(old_handler);
+
+  return 1;
+}
+
+
+
+/*
+=item i_writetiff_wiol_faxable(i_img *, io_glue *)
+
+Stores an image in the iolayer object in faxable tiff format.
+
+   im - image object to write out
+   ig - io_object that defines source to write to 
+
+Note, this may be rewritten to use to simply be a call to a
+lower-level function that gives more options for writing tiff at some
+point.
+
+=cut
+*/
+
+undef_int
+i_writetiff_wiol_faxable(i_img *im, io_glue *ig, int fine) {
+  TIFF* tif;
+  TIFFErrorHandler old_handler;
+
+  old_handler = TIFFSetErrorHandler(error_handler);
+
+  io_glue_commit_types(ig);
+  i_clear_error();
+  mm_log((1, "i_writetiff_wiol(img %p, ig 0x%p)\n", im, ig));
+
+  /* FIXME: Enable the mmap interface */
+  
+  tif = TIFFClientOpen("No name", 
+                      "wm",
+                      (thandle_t) ig, 
+                      (TIFFReadWriteProc) ig->readcb,
+                      (TIFFReadWriteProc) ig->writecb,
+                      (TIFFSeekProc)      comp_seek,
+                      (TIFFCloseProc)     ig->closecb, 
+                      ig->sizecb ? (TIFFSizeProc) ig->sizecb : (TIFFSizeProc) sizeproc,
+                      (TIFFMapFileProc)   comp_mmap,
+                      (TIFFUnmapFileProc) comp_munmap);
+  
+
+
+  if (!tif) {
+    mm_log((1, "i_writetiff_wiol: Unable to open tif file for writing\n"));
+    i_push_error(0, "Could not create TIFF object");
+    TIFFSetErrorHandler(old_handler);
+    return 0;
+  }
+
+  if (!i_writetiff_low_faxable(tif, im, fine)) {
+    TIFFClose(tif);
+    TIFFSetErrorHandler(old_handler);
+    return 0;
   }
+
   (void) TIFFClose(tif);
-  if (linebuf) _TIFFfree(linebuf);
+  TIFFSetErrorHandler(old_handler);
+
   return 1;
 }
 
 static int save_tiff_tags(TIFF *tif, i_img *im) {
   int i;
-
   for (i = 0; i < text_tag_count; ++i) {
     int entry;
     if (i_tags_find(&im->tags, text_tag_names[i].name, 0, &entry)) {
       if (!TIFFSetField(tif, text_tag_names[i].tag, 
-                       im->tags.tags[entry].data)) {
-       i_push_errorf(0, "cannot save %s to TIFF", text_tag_names[i].name);
-       return 0;
+                       im->tags.tags[entry].data)) {
+       i_push_errorf(0, "cannot save %s to TIFF", text_tag_names[i].name);
+       return 0;
       }
     }
   }
-
   return 1;
 }
 
+
 /*
 =item expand_4bit_hl(buf, count)
 
@@ -721,6 +1197,13 @@ static void expand_4bit_hl(unsigned char *buf, int count) {
   }
 }
 
+static void pack_4bit_hl(unsigned char *buf, int count) {
+  int i = 0;
+  while (i < count) {
+    buf[i/2] = (buf[i] << 4) + buf[i+1];
+    i += 2;
+  }
+}
 
 /*
 =back