From 794d69dcfe3c832df39496ecc9a9beb137e0a732 Mon Sep 17 00:00:00 2001
From: fvogel <fvogelnew1@free.fr>
Date: Sat, 21 Jul 2018 13:37:42 +0000
Subject: [PATCH 256/693] Fix [fbaed1f66b]: [image create photo] errors out on
 a sane animated gif

---
 generic/tkImgGIF.c | 46 +++++++++++++++++++++-------------------------
 1 file changed, 21 insertions(+), 25 deletions(-)

diff --git a/generic/tkImgGIF.c b/generic/tkImgGIF.c
index be90f0684..7c4872bef 100644
--- a/generic/tkImgGIF.c
+++ b/generic/tkImgGIF.c
@@ -1141,9 +1141,9 @@ ReadImage(
 		     * Last pass reset the decoder, so the first code we see
 		     * must be a singleton. Seed the stack with it, and set up
 		     * the old/first code pointers for insertion into the
-		     * string table. We can't just roll this into the
-		     * clearCode test above, because at that point we have not
-		     * yet read the next code.
+		     * codes table. We can't just roll this into the clearCode
+		     * test above, because at that point we have not yet read
+		     * the next code.
 		     */
 
 		    *top++ = append[code];
@@ -1154,11 +1154,11 @@ ReadImage(
 
 		inCode = code;
 
-		if (code == maxCode) {
+		if ((code == maxCode) && (maxCode < (1 << MAX_LWZ_BITS))) {
 		    /*
 		     * maxCode is always one bigger than our highest assigned
 		     * code. If the code we see is equal to maxCode, then we
-		     * are about to add a new string to the table. ???
+		     * are about to add a new entry to the codes table.
 		     */
 
 		    *top++ = firstCode;
@@ -1167,7 +1167,7 @@ ReadImage(
 
 		while (code > clearCode) {
 		    /*
-		     * Populate the stack by tracing the string in the string
+		     * Populate the stack by tracing the code in the codes
 		     * table from its tail to its head
 		     */
 
@@ -1176,28 +1176,24 @@ ReadImage(
 		}
 		firstCode = append[code];
 
-		/*
-		 * If there's no more room in our string table, quit.
-		 * Otherwise, add a new string to the table
-		 */
-
-		if (maxCode >= (1 << MAX_LWZ_BITS)) {
-		    return TCL_OK;
-		}
-
-		/*
-		 * Push the head of the string onto the stack.
-		 */
+	        /*
+	         * Push the head of the code onto the stack.
+	         */
 
-		*top++ = firstCode;
+	        *top++ = firstCode;
 
-		/*
-		 * Add a new string to the string table
-		 */
+                if (maxCode < (1 << MAX_LWZ_BITS)) {
+		    /*
+		     * If there's still room in our codes table, add a new entry.
+		     * Otherwise don't, and keep using the current table.
+                     * See DEFERRED CLEAR CODE IN LZW COMPRESSION in the GIF89a
+                     * specification.
+		     */
 
-		prefix[maxCode] = oldCode;
-		append[maxCode] = firstCode;
-		maxCode++;
+		    prefix[maxCode] = oldCode;
+		    append[maxCode] = firstCode;
+		    maxCode++;
+                }
 
 		/*
 		 * maxCode tells us the maximum code value we can accept. If
-- 
2.19.1

