libtiff: Try to avoid writing out a full readbuffer of tile data when writing the

From b29a8609993c25c4e249e788f931c09990e5dd55 Mon Sep 17 00:00:00 2001
From: Frank Warmerdam <[EMAIL REDACTED]>
Date: Thu, 22 Nov 2007 21:53:41 +0000
Subject: [PATCH] Try to avoid writing out a full readbuffer of tile data when
 writing the directory just because we have BEENWRITING at some point in the
 past.  This was causing odd junk to be written out in a tile of data when a
 single tile had an interleaving of reading and writing with reading last. 
 (highlighted by gdal autotest/gcore/tif_write.py test 7.

---
 ChangeLog              |  7 +++++++
 libtiff/tif_dirwrite.c | 11 ++++++++---
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index fccf2e7b..29000bd3 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,12 @@
 2007-11-22  Frank Warmerdam  <warmerdam@pobox.com>
 
+	* tif_dirwrite.c: Try to avoid writing out a full readbuffer of tile
+	data when writing the directory just because we have BEENWRITING at
+	some point in the past.  This was causing odd junk to be written out
+	in a tile of data when a single tile had an interleaving of reading 
+	and writing with reading last.  (highlighted by gdal 
+	autotest/gcore/tif_write.py test 7. 
+
 	* tif_predict.c: use working buffer in PredictorEncodeTile to avoid
 	modifying callers buffer. 
 	http://trac.osgeo.org/gdal/ticket/1965
diff --git a/libtiff/tif_dirwrite.c b/libtiff/tif_dirwrite.c
index 27a2056f..b8b9490d 100644
--- a/libtiff/tif_dirwrite.c
+++ b/libtiff/tif_dirwrite.c
@@ -1,4 +1,4 @@
-/* $Id: tif_dirwrite.c,v 1.37.2.2 2007-05-01 15:01:32 dron Exp $ */
+/* $Id: tif_dirwrite.c,v 1.37.2.3 2007-11-22 21:53:42 fwarmerdam Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -100,6 +100,8 @@ _TIFFWriteDirectory(TIFF* tif, int done)
 	 */
 	if (done)
 	{
+                tsize_t orig_rawcc = tif->tif_rawcc;
+
 		if (tif->tif_flags & TIFF_POSTENCODE) {
 			tif->tif_flags &= ~TIFF_POSTENCODE;
 			if (!(*tif->tif_postencode)(tif)) {
@@ -112,9 +114,12 @@ _TIFFWriteDirectory(TIFF* tif, int done)
 		(*tif->tif_close)(tif);		/* shutdown encoder */
 		/*
 		 * Flush any data that might have been written
-		 * by the compression close+cleanup routines.
+ 		 * by the compression close+cleanup routines.  But
+                 * be careful not to write stuff if we didn't add data
+                 * in the previous steps as the "rawcc" data may well be
+                 * a previously read tile/strip in mixed read/write mode.
 		 */
-		if (tif->tif_rawcc > 0 
+		if (tif->tif_rawcc > 0 && tif->tif_rawcc != orig_rawcc
                     && (tif->tif_flags & TIFF_BEENWRITING) != 0
                     && !TIFFFlushData1(tif)) {
 			TIFFErrorExt(tif->tif_clientdata, tif->tif_name,