File GraphicsMagick-mat.c-update.patch of Package GraphicsMagick.7727

Index: GraphicsMagick-1.3.25/coders/mat.c
===================================================================
--- GraphicsMagick-1.3.25.orig/coders/mat.c	2018-01-08 13:32:01.394340606 +0100
+++ GraphicsMagick-1.3.25/coders/mat.c	2018-01-08 13:33:02.951348262 +0100
@@ -1,5 +1,5 @@
 /*
-% Copyright (C) 2003 - 2016 GraphicsMagick Group
+% Copyright (C) 2003 - 2017 GraphicsMagick Group
 % Copyright (C) 2002 ImageMagick Studio
 %
 % This program is covered by multiple licenses, which are described in
@@ -67,7 +67,7 @@ typedef struct
   unsigned short Version;
   char EndianIndicator[2];
   unsigned long DataType;
-  unsigned long ObjectSize;
+  magick_uint32_t ObjectSize;
   unsigned long unknown1;
   unsigned long unknown2;
 
@@ -100,43 +100,43 @@ static const char *OsDesc=
 
 typedef enum
   {
-    miINT8 = 1,			/* 8 bit signed */
-    miUINT8,			/* 8 bit unsigned */
-    miINT16,			/* 16 bit signed */
-    miUINT16,			/* 16 bit unsigned */
-    miINT32,			/* 32 bit signed */
-    miUINT32,			/* 32 bit unsigned */
-    miSINGLE,			/* IEEE 754 single precision float */
+    miINT8 = 1,                 /* 8 bit signed */
+    miUINT8,                    /* 8 bit unsigned */
+    miINT16,                    /* 16 bit signed */
+    miUINT16,                   /* 16 bit unsigned */
+    miINT32,                    /* 32 bit signed */
+    miUINT32,                   /* 32 bit unsigned */
+    miSINGLE,                   /* IEEE 754 single precision float */
     miRESERVE1,
-    miDOUBLE,			/* IEEE 754 double precision float */
+    miDOUBLE,                   /* IEEE 754 double precision float */
     miRESERVE2,
     miRESERVE3,
-    miINT64,			/* 64 bit signed */
-    miUINT64,			/* 64 bit unsigned */
-    miMATRIX,		        /* MATLAB array */
-    miCOMPRESSED,	        /* Compressed Data */
-    miUTF8,		        /* Unicode UTF-8 Encoded Character Data */
-    miUTF16,		        /* Unicode UTF-16 Encoded Character Data */
-    miUTF32			/* Unicode UTF-32 Encoded Character Data */
+    miINT64,                    /* 64 bit signed */
+    miUINT64,                   /* 64 bit unsigned */
+    miMATRIX,                   /* MATLAB array */
+    miCOMPRESSED,               /* Compressed Data */
+    miUTF8,                     /* Unicode UTF-8 Encoded Character Data */
+    miUTF16,                    /* Unicode UTF-16 Encoded Character Data */
+    miUTF32                     /* Unicode UTF-32 Encoded Character Data */
   } mat5_data_type;
 
 typedef enum
   {
-    mxCELL_CLASS=1,		/* cell array */
-    mxSTRUCT_CLASS,		/* structure */
-    mxOBJECT_CLASS,		/* object */
-    mxCHAR_CLASS,		/* character array */
-    mxSPARSE_CLASS,		/* sparse array */
-    mxDOUBLE_CLASS,		/* double precision array */
-    mxSINGLE_CLASS,		/* single precision floating point */
-    mxINT8_CLASS,		/* 8 bit signed integer */
-    mxUINT8_CLASS,		/* 8 bit unsigned integer */
-    mxINT16_CLASS,		/* 16 bit signed integer */
-    mxUINT16_CLASS,		/* 16 bit unsigned integer */
-    mxINT32_CLASS,		/* 32 bit signed integer */
-    mxUINT32_CLASS,		/* 32 bit unsigned integer */
-    mxINT64_CLASS,		/* 64 bit signed integer */
-    mxUINT64_CLASS,		/* 64 bit unsigned integer */
+    mxCELL_CLASS=1,             /* cell array */
+    mxSTRUCT_CLASS,             /* structure */
+    mxOBJECT_CLASS,             /* object */
+    mxCHAR_CLASS,               /* character array */
+    mxSPARSE_CLASS,             /* sparse array */
+    mxDOUBLE_CLASS,             /* double precision array */
+    mxSINGLE_CLASS,             /* single precision floating point */
+    mxINT8_CLASS,               /* 8 bit signed integer */
+    mxUINT8_CLASS,              /* 8 bit unsigned integer */
+    mxINT16_CLASS,              /* 16 bit signed integer */
+    mxUINT16_CLASS,             /* 16 bit unsigned integer */
+    mxINT32_CLASS,              /* 32 bit signed integer */
+    mxUINT32_CLASS,             /* 32 bit unsigned integer */
+    mxINT64_CLASS,              /* 64 bit signed integer */
+    mxUINT64_CLASS,             /* 64 bit unsigned integer */
     mxFUNCTION_CLASS            /* Function handle */
   } arrayclasstype;
 
@@ -262,8 +262,8 @@ static void FixSignedValues(PixelPacket
   while(y-->0)
   {
      /* Please note that negative values will overflow
-        Q=8; MaxRGB=255: <0;127> + 127+1 = <128; 255> 
-		       <-1;-128> + 127+1 = <0; 127> */
+        Q=8; MaxRGB=255: <0;127> + 127+1 = <128; 255>
+                       <-1;-128> + 127+1 = <0; 127> */
     q->red += MaxRGB/2 + 1;
     q->green += MaxRGB/ + 1;
     q->blue += MaxRGB/ + 1;
@@ -282,7 +282,7 @@ unsigned char val = 0;
   while(ldblk-->0)
   {
     if(*Buff++ != 0)
-      val |= mask;    
+      val |= mask;
 
     mask >>= 1;
     if(mask==0)
@@ -290,8 +290,8 @@ unsigned char val = 0;
       *BuffL++ = val;
       val = 0;
       mask = 128;
-    }   
-      
+    }
+
   }
   *BuffL = val;
 }
@@ -309,7 +309,7 @@ static void ZLIBFreeFunc(voidpf opaque,
 }
 
 /** This procedure decompreses an image block for a new MATLAB format. */
-static Image *DecompressBlock(Image *orig, magick_off_t Size, ImageInfo *clone_info, ExceptionInfo *exception)
+static Image *DecompressBlock(Image *orig, magick_uint32_t *Size, ImageInfo *clone_info, ExceptionInfo *exception)
 {
 Image *image2;
 void *cache_block, *decompress_block;
@@ -317,22 +317,23 @@ z_stream zip_info;
 FILE *mat_file;
 size_t magick_size;
 int status;
- int zip_status;
+int zip_status;
+magick_off_t TotalSize = 0;
 
   if(clone_info==NULL) return NULL;
-  if(clone_info->file)		/* Close file opened from previous transaction. */
+  if(clone_info->file)          /* Close file opened from previous transaction. */
   {
     fclose(clone_info->file);
     clone_info->file = NULL;
     (void) unlink(clone_info->filename);
   }
 
-  cache_block = MagickAllocateMemory(unsigned char *,(size_t)((Size<16384)?Size:16384));
+  cache_block = MagickAllocateMemory(unsigned char *,(size_t)((*Size<16384) ? *Size : 16384));
   if(cache_block==NULL) return NULL;
   decompress_block = MagickAllocateMemory(unsigned char *,(size_t)(4096));
-  if(decompress_block==NULL) 
+  if(decompress_block==NULL)
   {
-    MagickFreeMemory(cache_block);    
+    MagickFreeMemory(cache_block);
     return NULL;
   }
 
@@ -363,54 +364,58 @@ int status;
 
   zip_info.avail_in = 0;
   zip_info.total_out = 0;
-  while(Size>0 && !EOFBlob(orig))
-  {    
-    magick_size = ReadBlob(orig, (Size<16384)?Size:16384, cache_block);
+  while(*Size>0 && !EOFBlob(orig))
+  {
+    magick_size = ReadBlob(orig, (*Size<16384)?*Size:16384, cache_block);
     zip_info.next_in = cache_block;
-    zip_info.avail_in = (uInt) magick_size;    
+    zip_info.avail_in = (uInt) magick_size;
 
     while(zip_info.avail_in>0)
     {
-      zip_info.avail_out = 4096;    
+      zip_info.avail_out = 4096;
       zip_info.next_out = decompress_block;
       zip_status = inflate(&zip_info,Z_NO_FLUSH);
       if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
         {
           (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Corrupt inflate stream");
-          ThrowException(exception,CorruptImageError, UnableToUncompressImage, orig->filename);
+          inflateEnd(&zip_info);
           MagickFreeMemory(cache_block);
           MagickFreeMemory(decompress_block);
-          inflateEnd(&zip_info);
           (void)fclose(mat_file);
           LiberateTemporaryFile(clone_info->filename);
+          ThrowException(exception,CorruptImageError, UnableToUncompressImage, orig->filename);
           return NULL;
         }
       fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file);
+      TotalSize += 4096-zip_info.avail_out;
 
       if(zip_status == Z_STREAM_END) goto DblBreak;
     }
-
-    Size -= magick_size;
+        if (*Size >= magick_size)
+                *Size -= (magick_uint32_t) magick_size;
+        else
+                *Size = 0U;
   }
 DblBreak:
- 
-  inflateEnd(&zip_info);			/* Release all caches used by zip. */
+
+  inflateEnd(&zip_info);                        /* Release all caches used by zip. */
   (void)fclose(mat_file);
   MagickFreeMemory(cache_block);
   MagickFreeMemory(decompress_block);
+  *Size = TotalSize;
 
   if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
-  if( (image2 = AllocateImage(clone_info))==NULL ) goto EraseFile;  
+  if((image2 = AllocateImage(clone_info))==NULL) goto EraseFile;
   status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
   if (status == False)
   {
-    DeleteImageFromList(&image2);    
+    DeleteImageFromList(&image2);
 EraseFile:
     fclose(clone_info->file);
     clone_info->file = NULL;
 UnlinkFile:
     LiberateTemporaryFile(clone_info->filename);
-    return NULL; 
+    return NULL;
   }
 
   return image2;
@@ -426,13 +431,27 @@ UnlinkFile:
 }
 
 
+#define ThrowImg2MATReaderException(code_,reason_,image_) \
+{ \
+   if(image2!=NULL && image2!=image)    /* Does shadow temporary decompressed image exist? */ \
+   { \
+     CloseBlob(image2); \
+     DeleteImageFromList(&image2); \
+  } \
+  if(clone_info) \
+    DestroyImageInfo(clone_info);    \
+  ThrowReaderException(code_,reason_,image_); \
+}
+
+
+
 
 typedef struct {
-	unsigned char Type[4];
-	magick_uint32_t nRows;
-	magick_uint32_t nCols;
-	magick_uint32_t imagf;
-	magick_uint32_t nameLen;
+        unsigned char Type[4];
+        magick_uint32_t nRows;
+        magick_uint32_t nCols;
+        magick_uint32_t imagf;
+        magick_uint32_t nameLen;
 } MAT4_HDR;
 
 
@@ -453,208 +472,225 @@ size_t (*ReadBlobXXXDoubles)(Image *imag
 size_t (*ReadBlobXXXFloats)(Image *image, size_t len, float *data);
 
   (void)SeekBlob(image,0,SEEK_SET);
-
-  ldblk = ReadBlobLSBLong(image);
-  if(ldblk>9999 || ldblk<0) return 0;
-  HDR.Type[3] = ldblk % 10;	ldblk /= 10;	/* T digit */
-  HDR.Type[2] = ldblk % 10;	ldblk /= 10;	/* P digit */
-  HDR.Type[1] = ldblk % 10;	ldblk /= 10;	/* O digit */
-  HDR.Type[0] = ldblk;				/* M digit */
-
-  if(HDR.Type[3]!=0) return 0;		/* Data format */
-  if(HDR.Type[2]!=0) return 0;		/* Always 0 */
-
-  ImportPixelAreaOptionsInit(import_options);
-
-  switch(HDR.Type[0])
-  {
-    case 0: ReadBlobXXXLong = ReadBlobLSBLong;            
-            ReadBlobXXXDoubles = ReadBlobLSBDoubles;
-            ReadBlobXXXFloats = ReadBlobLSBFloats;
-            import_options->endian = LSBEndian;
-            break;
-    case 1: ReadBlobXXXLong = ReadBlobMSBLong;            
-            ReadBlobXXXDoubles = ReadBlobMSBDoubles;
-            ReadBlobXXXFloats = ReadBlobMSBFloats;
-            import_options->endian = MSBEndian;
-            break;
-    default: return 0;		/* Unsupported endian */
-  }
-
-  HDR.nRows = ReadBlobXXXLong(image);  
-  HDR.nCols = ReadBlobXXXLong(image);
-
-  HDR.imagf = ReadBlobXXXLong(image);
-  if(HDR.imagf!=0 && HDR.imagf!=1) return NULL;
-
-  HDR.nameLen = ReadBlobXXXLong(image);
-  if(HDR.nameLen>0xFFFF) return NULL;
-  (void)SeekBlob(image,HDR.nameLen,SEEK_CUR);	/* Skip a matrix name. */
-
-  switch(HDR.Type[1])
+  while(!EOFBlob(image)) /* object parser loop */
   {
-    case 0: sample_size = 64;				/* double-precision (64-bit) floating point numbers */             
-            image->depth = Min(QuantumDepth,32);        /* double type cell */
-            import_options->sample_type = FloatQuantumSampleType;
-            if(sizeof(double) != 8) return NULL;	/* incompatible double size */          
-            ldblk = (long) (8 * HDR.nRows);
-            break;
-
-    case 1: sample_size = 32;				/* single-precision (32-bit) floating point numbers */            
-            image->depth = Min(QuantumDepth,32);        /* double type cell */
-            import_options->sample_type = FloatQuantumSampleType;
+    ldblk = ReadBlobLSBLong(image);
+    if(EOFBlob(image)) break;
+    if(ldblk>9999 || ldblk<0) return 0;
+    HDR.Type[3] = ldblk % 10;   ldblk /= 10;    /* T digit */
+    HDR.Type[2] = ldblk % 10;   ldblk /= 10;    /* P digit */
+    HDR.Type[1] = ldblk % 10;   ldblk /= 10;    /* O digit */
+    HDR.Type[0] = ldblk;                                /* M digit */
+
+    if(HDR.Type[3]!=0) return 0;                /* Data format */
+    if(HDR.Type[2]!=0) return 0;                /* Always 0 */
+
+    ImportPixelAreaOptionsInit(import_options);
+
+    switch(HDR.Type[0])
+    {
+      case 0: ReadBlobXXXLong = ReadBlobLSBLong;
+              ReadBlobXXXDoubles = ReadBlobLSBDoubles;
+              ReadBlobXXXFloats = ReadBlobLSBFloats;
+              import_options->endian = LSBEndian;
+              break;
+      case 1: ReadBlobXXXLong = ReadBlobMSBLong;
+              ReadBlobXXXDoubles = ReadBlobMSBDoubles;
+              ReadBlobXXXFloats = ReadBlobMSBFloats;
+              import_options->endian = MSBEndian;
+              break;
+      default: return 0;                /* Unsupported endian */
+    }
+
+    HDR.nRows = ReadBlobXXXLong(image);
+    HDR.nCols = ReadBlobXXXLong(image);
+
+    HDR.imagf = ReadBlobXXXLong(image);
+    if(HDR.imagf!=0 && HDR.imagf!=1) return NULL;
+
+    HDR.nameLen = ReadBlobXXXLong(image);
+    if(HDR.nameLen>0xFFFF) return NULL;
+    (void)SeekBlob(image,HDR.nameLen,SEEK_CUR); /* Skip a matrix name. */
+
+    switch(HDR.Type[1])
+    {
+      case 0: sample_size = 64;                         /* double-precision (64-bit) floating point numbers */
+              image->depth = Min(QuantumDepth,32);        /* double type cell */
+              import_options->sample_type = FloatQuantumSampleType;
+              if(sizeof(double) != 8) return NULL;      /* incompatible double size */
+              ldblk = (long) (8 * HDR.nRows);
+              break;
+
+      case 1: sample_size = 32;                         /* single-precision (32-bit) floating point numbers */
+              image->depth = Min(QuantumDepth,32);        /* double type cell */
+              import_options->sample_type = FloatQuantumSampleType;
 #if 0
-            if(sizeof(float) != 4)
-              ThrowMATReaderException(CoderError, IncompatibleSizeOfFloat, image);
-#endif        
-            ldblk = (long) (4 * HDR.nRows);
-            break;
+              if(sizeof(float) != 4)
+                ThrowMATReaderException(CoderError, IncompatibleSizeOfFloat, image);
+#endif
+              ldblk = (long) (4 * HDR.nRows);
+              break;
 
-    case 2: sample_size = 32;				/* 32-bit signed integers */            
-            image->depth = Min(QuantumDepth,32);        /* Dword type cell */
-            ldblk = (long) (4 * HDR.nRows);      
-            import_options->sample_type = UnsignedQuantumSampleType;
-            break;
+      case 2: sample_size = 32;                         /* 32-bit signed integers */
+              image->depth = Min(QuantumDepth,32);        /* Dword type cell */
+              ldblk = (long) (4 * HDR.nRows);
+              import_options->sample_type = UnsignedQuantumSampleType;
+              break;
+
+      case 3:                           /* 16-bit signed integers */
+      case 4:                           /* 16-bit unsigned integers */
+              sample_size = 16;
+              image->depth = Min(QuantumDepth,16);        /* Word type cell */
+              ldblk = (long) (2 * HDR.nRows);
+             import_options->sample_type = UnsignedQuantumSampleType;
+              break;
+
+      case 5: sample_size = 8;          /* 8-bit unsigned integers */
+              image->depth = Min(QuantumDepth,8);         /* Byte type cell */
+              import_options->sample_type = UnsignedQuantumSampleType;
+              ldblk = (long) HDR.nRows;
+              break;
 
-    case 3:				/* 16-bit signed integers */
-    case 4:				/* 16-bit unsigned integers */
-            sample_size = 16;
-            image->depth = Min(QuantumDepth,16);        /* Word type cell */
-            ldblk = (long) (2 * HDR.nRows);
-            import_options->sample_type = UnsignedQuantumSampleType;       
-            break;
+      default: return NULL;
+    }
 
-    case 5: sample_size = 8;		/* 8-bit unsigned integers */
-            image->depth = Min(QuantumDepth,8);         /* Byte type cell */
-            import_options->sample_type = UnsignedQuantumSampleType;
-            ldblk = (long) HDR.nRows;
-            break;
-	
-    default: return NULL;
-  }     
-
-  image->columns = HDR.nRows;
-  image->rows = HDR.nCols;
-  image->colors = 1l << image->depth;
-  if(image->columns == 0 || image->rows == 0) return NULL;
-  if(CheckImagePixelLimits(image, exception) != MagickPass)
-  {
-    return NULL;
-    /* ThrowReaderException(ResourceLimitError,ImagePixelLimitExceeded,image); */
-  }
+    image->columns = HDR.nRows;
+    image->rows = HDR.nCols;
+    image->colors = 1l << image->depth;
+    if(image->columns == 0 || image->rows == 0) return NULL;
+    if(CheckImagePixelLimits(image, exception) != MagickPass)
+    {
+      return NULL;
+      /* ThrowReaderException(ResourceLimitError,ImagePixelLimitExceeded,image); */
+    }
 
-  /* If ping is true, then only set image size and colors without reading any image data. */
-  if(image_info->ping)
-  {
-    unsigned long temp = image->columns;  /* The true image is rotater 90 degs. Do rotation without data. */
-    image->columns = image->rows;
-    image->rows = temp;
-    goto done_reading; /* !!!!!! BAD  !!!! */
-    }  
+    /* If ping is true, then only set image size and colors without reading any image data. */
+    if(image_info->ping)
+    {
+      unsigned long temp = image->columns;  /* The true image is rotater 90 degs. Do rotation without data. */
+      image->columns = image->rows;
+      image->rows = temp;
+      if(HDR.imagf==1) ldblk *= 2;
+      SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);
+      goto skip_reading_current;
+    }
 
- /* ----- Load raster data ----- */
-  BImgBuff = MagickAllocateMemory(unsigned char *,(size_t) (ldblk));    /* Ldblk was set in the check phase */
-  if(BImgBuff == NULL) return 0;
-   
-  if(HDR.Type[1]==0)		/* Find Min and Max Values for doubles */
-  {
-    (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
+        /* ----- Load raster data ----- */
+    BImgBuff = MagickAllocateMemory(unsigned char *,(size_t) (ldblk));    /* Ldblk was set in the check phase */
+    if(BImgBuff == NULL) return 0;
+
+    if(HDR.Type[1]==0)          /* Find Min and Max Values for doubles */
+    {
+      (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
                                       HDR.nCols, DoublePixel, ldblk, BImgBuff,
-                                      &import_options->double_minvalue, 
+                                      &import_options->double_minvalue,
                                       &import_options->double_maxvalue);
-  }
-  if(HDR.Type[1]==1)		/* Find Min and Max Values for floats */
-  {
-    (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
-                                      HDR.nCols, FloatPixel, ldblk, BImgBuff, 
-                                      &import_options->double_minvalue, 
-                                      &import_options->double_maxvalue);
-  }
-
- 
-	/* Main reader loop. */
-  for(i=0; i<(long)HDR.nCols; i++)
-  {
-    q = SetImagePixels(image, 0, HDR.nCols-i-1, image->columns, 1);
-    if(q == (PixelPacket *)NULL)
+    }
+    if(HDR.Type[1]==1)          /* Find Min and Max Values for floats */
     {
-      /* if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), */
-      /*        "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); */
-      goto done_reading;		/* Skip image rotation, when cannot set image pixels */	  
+      (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
+                                      HDR.nCols, FloatPixel, ldblk, BImgBuff,
+                                      &import_options->double_minvalue,
+                                      &import_options->double_maxvalue);
     }
 
-    if(ReadBlob(image,ldblk,(char *)BImgBuff) != (size_t)ldblk)
+        /* Main reader loop. */
+    for(i=0; i<(long)HDR.nCols; i++)
     {
-      /* if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), */
-      /*         "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); */
-      goto ExitLoop;
-    }
+      q = SetImagePixels(image, 0, HDR.nCols-i-1, image->columns, 1);
+      if(q == (PixelPacket *)NULL)
+      {
+        /* if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), */
+        /*        "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); */
+        goto skip_reading_current;              /* Skip image rotation, when cannot set image pixels */
+      }
+
+      if(ReadBlob(image,ldblk,(char *)BImgBuff) != (size_t)ldblk)
+      {
+        /* if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), */
+        /*         "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); */
+        goto ExitLoop;
+      }
 
-    if(ImportImagePixelArea(image,GrayQuantum,sample_size,BImgBuff,import_options,0) == MagickFail)
-	    goto ImportImagePixelAreaFailed;
+      if(ImportImagePixelArea(image,GrayQuantum,sample_size,BImgBuff,import_options,0) == MagickFail)
+            goto ImportImagePixelAreaFailed;
 
-    if(HDR.Type[1]==2 || HDR.Type[1]==3)	        
-	FixSignedValues(q,HDR.nRows);
+      if(HDR.Type[1]==2 || HDR.Type[1]==3)
+          FixSignedValues(q,HDR.nRows);
 
-    if(!SyncImagePixels(image))
-    {
-	/* if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), */
+      if(!SyncImagePixels(image))
+      {
+        /* if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), */
         /*     "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); */
-	goto ExitLoop;
+        goto ExitLoop;
+      }
     }
-  }
 
-	/* Read complex part of data. */
-  if(HDR.imagf==1)
-  {
-    MinVal_c = MaxVal_c = 0;
-    if(HDR.Type[1]==0)		/* Find Min and Max Values for doubles */
+        /* Read complex part of data. */
+    if(HDR.imagf==1)
     {
-      (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
+      MinVal_c = MaxVal_c = 0;
+      if(HDR.Type[1]==0)                /* Find Min and Max Values for doubles */
+      {
+        (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
                                         HDR.nCols, DoublePixel, ldblk, BImgBuff,
                                         &MinVal_c, &MaxVal_c);
-      for(i=0; i<(long)HDR.nCols; i++)
-      {
-        ReadBlobXXXDoubles(image, ldblk, (double *)BImgBuff);
-        InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal_c, MaxVal_c);      	
+        for(i=0; i<(long)HDR.nCols; i++)
+        {
+          ReadBlobXXXDoubles(image, ldblk, (double *)BImgBuff);
+          InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal_c, MaxVal_c);
+        }
       }
-    }
 
-    if(HDR.Type[1]==1)		/* Find Min and Max Values for floats */
-    {
-      (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
+      if(HDR.Type[1]==1)                /* Find Min and Max Values for floats */
+      {
+        (void)MagickFindRawImageMinMax(image, import_options->endian, HDR.nRows,
                                       HDR.nCols, FloatPixel, ldblk, BImgBuff,
                                       &MinVal_c, &MaxVal_c);
-      for(i=0; i<(long)HDR.nCols; i++)
-      {
-        ReadBlobXXXFloats(image, ldblk, (float *)BImgBuff);
-        InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal_c, MaxVal_c);
-      }    
+        for(i=0; i<(long)HDR.nCols; i++)
+        {
+          ReadBlobXXXFloats(image, ldblk, (float *)BImgBuff);
+          InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal_c, MaxVal_c);
+        }
+      }
     }
-  }
 
-	/*  Rotate image. */
-  rotated_image = RotateImage(image, 90.0, exception);
-  if(rotated_image != (Image *) NULL)
-  {
+        /*  Rotate image. */
+    rotated_image = RotateImage(image, 90.0, exception);
+    if(rotated_image != (Image *) NULL)
+    {
         /* Remove page offsets added by RotateImage */
-    rotated_image->page.x=0;
-    rotated_image->page.y=0;
+      rotated_image->page.x=0;
+      rotated_image->page.y=0;
+
+      blob = rotated_image->blob;
+      rotated_image->blob = image->blob;
+      rotated_image->colors = image->colors;
+      image->blob = blob;
+      AppendImageToList(&image,rotated_image);
+      DeleteImageFromList(&image);
+      image = rotated_image;
+    }
+
+skip_reading_current:
+        /* Allocate next image structure. */
+    AllocateNextImage(image_info,image);
+    if (image->next == (Image *) NULL) break;
+    image=SyncNextImageInList(image);
+    image->columns = image->rows = 0;
+    image->colors=0;
+
+      /* row scan buffer is no longer needed */
+    MagickFreeMemory(BImgBuff);
+    BImgBuff = NULL;
 
-    blob = rotated_image->blob;
-    rotated_image->blob = image->blob;
-    rotated_image->colors = image->colors;
-    image->blob = blob;      
-    AppendImageToList(&image,rotated_image);
-    DeleteImageFromList(&image);
-    image = rotated_image;
   }
-    
+
 ImportImagePixelAreaFailed:
 ExitLoop:
-done_reading:
 
-  MagickFreeMemory(BImgBuff);
+  if(BImgBuff!=NULL) MagickFreeMemory(BImgBuff);
+
   return image;
 }
 
@@ -697,7 +733,7 @@ static Image *ReadMATImage(const ImageIn
   PixelPacket *q;
   unsigned int status;
   MATHeader MATLAB_HDR;
-  unsigned long size;  
+  unsigned long size;
   magick_uint32_t CellType;
   ImportPixelAreaOptions import_options;
   int i;
@@ -711,7 +747,7 @@ static Image *ReadMATImage(const ImageIn
   magick_off_t filepos=0x80;
   BlobInfo *blob;
   ImageInfo *clone_info = NULL;
-  
+
   magick_uint32_t (*ReadBlobXXXLong)(Image *image);
   magick_uint16_t (*ReadBlobXXXShort)(Image *image);
   size_t (*ReadBlobXXXDoubles)(Image *image, size_t len, double *data);
@@ -721,7 +757,7 @@ static Image *ReadMATImage(const ImageIn
   assert(image_info->signature == MagickSignature);
   assert(exception != (ExceptionInfo *) NULL);
   assert(exception->signature == MagickSignature);
-  logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); 
+  logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
 
   /*
      Open image file.
@@ -730,25 +766,31 @@ static Image *ReadMATImage(const ImageIn
 
   status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
   if (status == False)
+  {
     ThrowMATReaderException(FileOpenError, UnableToOpenFile, image);
+  }
 
   /*
      Read MATLAB image.
    */
   if(ReadBlob(image,124,&MATLAB_HDR.identific) != 124)
+  {
     ThrowMATReaderException(CorruptImageError,ImproperImageHeader,image);
+  }
 
   if(strncmp(MATLAB_HDR.identific, "MATLAB", 6))
   {
     image2 = ReadMATImageV4(image_info,image,&import_options,exception);
     if(image2==NULL) goto MATLAB_KO;
     image = image2;
-    goto END_OF_READING;    
+    goto END_OF_READING;
   }
 
   MATLAB_HDR.Version = ReadBlobLSBShort(image);
   if(ReadBlob(image,2,&MATLAB_HDR.EndianIndicator) != 2)
+  {
     ThrowMATReaderException(CorruptImageError,ImproperImageHeader,image);
+  }
 
   ImportPixelAreaOptionsInit(&import_options);
 
@@ -761,7 +803,7 @@ static Image *ReadMATImage(const ImageIn
     ReadBlobXXXDoubles = ReadBlobLSBDoubles;
     ReadBlobXXXFloats = ReadBlobLSBFloats;
     import_options.endian = LSBEndian;
-  } 
+  }
   else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
   {
     ReadBlobXXXLong = ReadBlobMSBLong;
@@ -770,14 +812,16 @@ static Image *ReadMATImage(const ImageIn
     ReadBlobXXXFloats = ReadBlobMSBFloats;
     import_options.endian = MSBEndian;
   }
-  else			/* unsupported endian */
+  else                  /* unsupported endian */
   {
-MATLAB_KO: ThrowMATReaderException(CorruptImageError,ImproperImageHeader,image);  
+MATLAB_KO: ThrowMATReaderException(CorruptImageError,ImproperImageHeader,image);
   }
 
   filepos = TellBlob(image);
   if(filepos < 0)
-      ThrowMATReaderException(BlobError,UnableToObtainOffset,image);
+  {
+    ThrowMATReaderException(BlobError,UnableToObtainOffset,image);
+  }
   while(!EOFBlob(image)) /* object parser loop */
   {
     Frames = 1;
@@ -788,7 +832,18 @@ MATLAB_KO: ThrowMATReaderException(Corru
     if(EOFBlob(image)) break;
     MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
     if(EOFBlob(image)) break;
-    filepos += MATLAB_HDR.ObjectSize + 4 + 4;
+
+    if(BlobIsSeekable(image))
+    {
+      if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))   /* Safety check for forged and or corrupted data. */
+      {
+        if(logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
+             "  MAT Object with size %u overflows file with size %u.", (unsigned)MATLAB_HDR.ObjectSize, (unsigned)(GetBlobSize(image)));
+        goto MATLAB_KO;
+      }
+    }
+
+    filepos += MATLAB_HDR.ObjectSize + 4 + 4;   /* Position of a next object, when exists. */
 
     image2 = image;
 #if defined(HasZLIB)
@@ -796,13 +851,13 @@ MATLAB_KO: ThrowMATReaderException(Corru
     {
       if(clone_info==NULL)
         if((clone_info=CloneImageInfo(image_info)) == NULL)
-		{
-		  if(logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
+                {
+                  if(logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
                                    "CloneImageInfo failed");
-		  continue;
-		}
-      image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
-      if(image2==NULL) 
+                  continue;
+                }
+      image2 = DecompressBlock(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
+      if(image2==NULL)
       {
         if(logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
                                    "Decompression failed");
@@ -810,67 +865,66 @@ MATLAB_KO: ThrowMATReaderException(Corru
       }
       MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
     }
-#endif    
+#endif
 
     if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */
- 
+
     MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
-    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);  
+    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
 
     MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
     MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
-    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;  
+    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
 
     MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
     if(image!=image2)
-      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);	/* ??? don't understand why ?? */
+      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);    /* ??? don't understand why ?? */
     MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
     MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
     MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
-    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);  
-   
+    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
+
 
     switch(MATLAB_HDR.DimFlag)
-    {     
-      case  8: z2=z=1; break;			/* 2D matrix*/
-      case 12: z2=z = ReadBlobXXXLong(image2);	/* 3D matrix RGB*/
-	       (void) ReadBlobXXXLong(image2);  /* Unknown6 */
-	       if(z!=3) ThrowMATReaderException(CoderError, MultidimensionalMatricesAreNotSupported,
+    {
+      case  8: z2=z=1; break;                   /* 2D matrix*/
+      case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/
+               (void) ReadBlobXXXLong(image2);  /* Unknown6 */
+               if(z!=3) ThrowImg2MATReaderException(CoderError, MultidimensionalMatricesAreNotSupported,
                          image);
-	       break;
-      case 16: z2=z = ReadBlobXXXLong(image2);	/* 4D matrix animation */
-	       if(z!=3 && z!=1)
-		 ThrowMATReaderException(CoderError, MultidimensionalMatricesAreNotSupported, image);
+               break;
+      case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */
+               if(z!=3 && z!=1)
+                 ThrowImg2MATReaderException(CoderError, MultidimensionalMatricesAreNotSupported, image);
                Frames = ReadBlobXXXLong(image2);
                if (Frames == 0)
-                 ThrowMATReaderException(CorruptImageError,ImproperImageHeader,image2);
-	       break;
-      default: ThrowMATReaderException(CoderError, MultidimensionalMatricesAreNotSupported,
-                         image);
-    }  
+                 ThrowImg2MATReaderException(CorruptImageError,ImproperImageHeader,image2);
+               break;
+      default: ThrowImg2MATReaderException(CoderError, MultidimensionalMatricesAreNotSupported, image);
+    }
 
     MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
     MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
 
     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
           "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
-    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && 
-        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&		/* float + complex float */
-        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&		/* double + complex double */
+    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
+        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&          /* float + complex float */
+        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&          /* double + complex double */
         MATLAB_HDR.StructureClass != mxINT8_CLASS &&
-        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&		/* uint8 + uint8 3D */
+        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&           /* uint8 + uint8 3D */
         MATLAB_HDR.StructureClass != mxINT16_CLASS &&
-        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&		/* uint16 + uint16 3D */
+        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&          /* uint16 + uint16 3D */
         MATLAB_HDR.StructureClass != mxINT32_CLASS &&
-        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&		/* uint32 + uint32 3D */
+        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&          /* uint32 + uint32 3D */
         MATLAB_HDR.StructureClass != mxINT64_CLASS &&
-        MATLAB_HDR.StructureClass != mxUINT64_CLASS)		/* uint64 + uint64 3D */
-      ThrowMATReaderException(CoderError,UnsupportedCellTypeInTheMatrix,image);
+        MATLAB_HDR.StructureClass != mxUINT64_CLASS)            /* uint64 + uint64 3D */
+      ThrowImg2MATReaderException(CoderError,UnsupportedCellTypeInTheMatrix,image);
 
     switch (MATLAB_HDR.NameFlag)
     {
       case 0:
-        size = ReadBlobXXXLong(image2);	/* Object name string size */
+        size = ReadBlobXXXLong(image2); /* Object name string size */
         size = 4 * (long) ((size + 3 + 1) / 4);
         (void) SeekBlob(image2, size, SEEK_CUR);
         break;
@@ -887,12 +941,12 @@ MATLAB_KO: ThrowMATReaderException(Corru
     CellType = ReadBlobXXXLong(image2);    /* Additional object type */
     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
           "MATLAB_HDR.CellType: %d",CellType);
-  
+
     (void) ReadBlob(image2, 4, &size);     /* data size */
 
 NEXT_FRAME:
       /* Image is gray when no complex flag is set and 2D Matrix */
-    image->is_grayscale = (MATLAB_HDR.DimFlag==8) && 
+    image->is_grayscale = (MATLAB_HDR.DimFlag==8) &&
            ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0);
 
     switch (CellType)
@@ -900,70 +954,75 @@ NEXT_FRAME:
       case miINT8:
       case miUINT8:
         sample_size = 8;
-        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) 
+        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
           image->depth = 1;
         else
           image->depth = Min(QuantumDepth,8);         /* Byte type cell */
         import_options.sample_type = UnsignedQuantumSampleType;
-        ldblk = (long) MATLAB_HDR.SizeX;      
+        ldblk = (long) MATLAB_HDR.SizeX;
         break;
       case miINT16:
       case miUINT16:
         sample_size = 16;
         image->depth = Min(QuantumDepth,16);        /* Word type cell */
         ldblk = (long) (2 * MATLAB_HDR.SizeX);
-        import_options.sample_type = UnsignedQuantumSampleType;       
+        import_options.sample_type = UnsignedQuantumSampleType;
         break;
       case miINT32:
       case miUINT32:
         sample_size = 32;
         image->depth = Min(QuantumDepth,32);        /* Dword type cell */
-        ldblk = (long) (4 * MATLAB_HDR.SizeX);      
-        import_options.sample_type = UnsignedQuantumSampleType;      
+        ldblk = (long) (4 * MATLAB_HDR.SizeX);
+        import_options.sample_type = UnsignedQuantumSampleType;
         break;
       case miINT64:
       case miUINT64:
         sample_size = 64;
         image->depth = Min(QuantumDepth,32);        /* Qword type cell */
-        ldblk = (long) (8 * MATLAB_HDR.SizeX);      
-        import_options.sample_type = UnsignedQuantumSampleType;      
-        break;   
+        ldblk = (long) (8 * MATLAB_HDR.SizeX);
+        import_options.sample_type = UnsignedQuantumSampleType;
+        break;
       case miSINGLE:
         sample_size = 32;
         image->depth = Min(QuantumDepth,32);        /* double type cell */
         import_options.sample_type = FloatQuantumSampleType;
 #if 0
       if (sizeof(float) != 4)
-        ThrowMATReaderException(CoderError, IncompatibleSizeOfFloat, image);
+        ThrowImg2MATReaderException(CoderError, IncompatibleSizeOfFloat, image);
 #endif
         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
-	{					    /* complex float type cell */
-	}
+        {                                           /* complex float type cell */
+        }
         ldblk = (long) (4 * MATLAB_HDR.SizeX);
         break;
       case miDOUBLE:
-        sample_size = 64; 
+        sample_size = 64;
         image->depth = Min(QuantumDepth,32);        /* double type cell */
         import_options.sample_type = FloatQuantumSampleType;
         if (sizeof(double) != 8)
-          ThrowMATReaderException(CoderError, IncompatibleSizeOfDouble, image);
+        {
+          ThrowImg2MATReaderException(CoderError, IncompatibleSizeOfDouble, image);  /* this causes immediate return. */
+        }
         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
-	{                         /* complex double type cell */        
-	}
+        {                         /* complex double type cell */
+        }
         ldblk = (long) (8 * MATLAB_HDR.SizeX);
         break;
       default:
-        ThrowMATReaderException(CoderError, UnsupportedCellTypeInTheMatrix, image)
+        ThrowImg2MATReaderException(CoderError, UnsupportedCellTypeInTheMatrix, image)
     }
 
     image->columns = MATLAB_HDR.SizeX;
-    image->rows = MATLAB_HDR.SizeY;    
+    image->rows = MATLAB_HDR.SizeY;
     image->colors = 1l << image->depth;
     if(image->columns == 0 || image->rows == 0)
       goto MATLAB_KO;
+    if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)  /* Safety check for forged and or corrupted data. */
+      goto MATLAB_KO;
+
     if(CheckImagePixelLimits(image, exception) != MagickPass)
     {
-      ThrowReaderException(ResourceLimitError,ImagePixelLimitExceeded,image);
+      ThrowImg2MATReaderException(ResourceLimitError,ImagePixelLimitExceeded,image);
     }
 
     /* ----- Create gray palette ----- */
@@ -972,10 +1031,12 @@ NEXT_FRAME:
     {
       if(image->colors>256) image->colors = 256;
 
-      if (!AllocateImageColormap(image, image->colors))
+      if(AllocateImageColormap(image, image->colors) != MagickPass)
       {
-NoMemory: ThrowMATReaderException(ResourceLimitError, MemoryAllocationFailed,
-                           image)}
+         if(logging)
+           (void)LogMagickEvent(CoderEvent,GetMagickModule(), "Cannot allocate colormap with %d colors.", image->colors);
+NoMemory: ThrowImg2MATReaderException(ResourceLimitError, MemoryAllocationFailed, image)
+      }
     }
 
     /*
@@ -987,11 +1048,11 @@ NoMemory: ThrowMATReaderException(Resour
       unsigned long temp = image->columns;  /* The true image is rotater 90 degs. Do rotation without data. */
       image->columns = image->rows;
       image->rows = temp;
-      goto done_reading; /* !!!!!! BAD  !!!! */
-    }  
+      goto skip_reading_current;
+    }
 
   /* ----- Load raster data ----- */
-    BImgBuff = MagickAllocateMemory(unsigned char *,(size_t) (MagickArraySize(ldblk,sizeof(double))));    /* Ldblk was set in the check phase */
+    BImgBuff = MagickAllocateArray(unsigned char *,(size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */
     if (BImgBuff == NULL)
       goto NoMemory;
     (void) memset(BImgBuff,0,ldblk*sizeof(double));
@@ -1000,64 +1061,64 @@ NoMemory: ThrowMATReaderException(Resour
     {
       (void) MagickFindRawImageMinMax(image2, import_options.endian,MATLAB_HDR.SizeX,
                                       MATLAB_HDR.SizeY,DoublePixel, ldblk, BImgBuff,
-                                      &import_options.double_minvalue, 
+                                      &import_options.double_minvalue,
                                       &import_options.double_maxvalue);
     }
     if (CellType==miSINGLE)        /* Find Min and Max Values for floats */
     {
       (void) MagickFindRawImageMinMax(image2, import_options.endian,MATLAB_HDR.SizeX,
-                                      MATLAB_HDR.SizeY,FloatPixel, ldblk, BImgBuff, 
-                                      &import_options.double_minvalue, 
+                                      MATLAB_HDR.SizeY,FloatPixel, ldblk, BImgBuff,
+                                      &import_options.double_minvalue,
                                       &import_options.double_maxvalue);
     }
 
     /* Main loop for reading all scanlines */
     if(z==1) z=0; /* read grey scanlines */
-		/* else read color scanlines */
+                /* else read color scanlines */
     do
     {
       for(i = 0; i < (long) MATLAB_HDR.SizeY; i++)
       {
         q = SetImagePixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1);
         if (q == (PixelPacket *)NULL)
-	{
-	  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
+        {
+          if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
               "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
-	  goto done_reading;		/* Skip image rotation, when cannot set image pixels */	  
-	}
+          goto skip_reading_current;            /* Skip image rotation, when cannot set image pixels */
+        }
         if(ReadBlob(image2,ldblk,(char *)BImgBuff) != (size_t) ldblk)
-	{
-	  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
+        {
+          if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
              "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
-	  goto ExitLoop;
-	}
+          goto ExitLoop;
+        }
         if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
         {
           FixLogical((unsigned char *)BImgBuff,ldblk);
           if(ImportImagePixelArea(image,z2qtype[z],1,BImgBuff,&import_options,0) == MagickFail)
-	  {
+          {
 ImportImagePixelAreaFailed:
-	    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
+            if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
               "  MAT failed to ImportImagePixelArea for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
-	    break;
-	  }
+            break;
+          }
         }
         else
         {
           if(ImportImagePixelArea(image,z2qtype[z],sample_size,BImgBuff,&import_options,0) == MagickFail)
-	    goto ImportImagePixelAreaFailed;
+            goto ImportImagePixelAreaFailed;
 
-          if (z<=1 &&			 /* fix only during a last pass z==0 || z==1 */
-	        (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
-	    FixSignedValues(q,MATLAB_HDR.SizeX);
+          if (z<=1 &&                    /* fix only during a last pass z==0 || z==1 */
+                (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
+            FixSignedValues(q,MATLAB_HDR.SizeX);
         }
 
         if (!SyncImagePixels(image))
-	{
-	  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
+        {
+          if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
             "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
-	  goto ExitLoop;
-	}
+          goto ExitLoop;
+        }
       }
     } while(z-- >= 2);
 ExitLoop:
@@ -1085,28 +1146,28 @@ ExitLoop:
 
       if (CellType==miDOUBLE)
         for (i = 0; i < (long) MATLAB_HDR.SizeY; i++)
-	{
+        {
           ReadBlobXXXDoubles(image2, ldblk, (double *)BImgBuff);
           InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal_c, MaxVal_c);
-	}
+        }
 
       if (CellType==miSINGLE)
         for (i = 0; i < (long) MATLAB_HDR.SizeY; i++)
-	{
+        {
           ReadBlobXXXFloats(image2, ldblk, (float *)BImgBuff);
           InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal_c, MaxVal_c);
-	}    
+        }
     }
 
       /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
-    image->is_grayscale = (MATLAB_HDR.DimFlag==8) && 
+    image->is_grayscale = (MATLAB_HDR.DimFlag==8) &&
              ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0);
     image->is_monochrome = image->depth==1;
     if(image->is_monochrome)
       image->colorspace=GRAYColorspace;
 
-    if(image2==image)		/* image2 is either native image or decompressed block. */
-        image2 = NULL;		/* Remove shadow copy to an image before rotation. */
+    if(image2==image)           /* image2 is either native image or decompressed block. */
+        image2 = NULL;          /* Remove shadow copy to an image before rotation. */
 
       /*  Rotate image. */
     rotated_image = RotateImage(image, 90.0, exception);
@@ -1119,18 +1180,18 @@ ExitLoop:
       blob = rotated_image->blob;
       rotated_image->blob = image->blob;
       rotated_image->colors = image->colors;
-      image->blob = blob;      
+      image->blob = blob;
       AppendImageToList(&image,rotated_image);
-      DeleteImageFromList(&image);      
+      DeleteImageFromList(&image);
     }
 
-done_reading:
+skip_reading_current:
 
     if(image2==image) image2 = NULL;
 
-      /* Allocate next image structure. */    
+      /* Allocate next image structure. */
     AllocateNextImage(image_info,image);
-    if (image->next == (Image *) NULL) break;                
+    if (image->next == (Image *) NULL) break;
     image=SyncNextImageInList(image);
     image->columns = image->rows = 0;
     image->colors=0;
@@ -1147,19 +1208,19 @@ done_reading:
     }
 
     if(image2!=NULL)
-      if(image2!=image)		/* Does shadow temporary decompressed image exist? */
+      if(image2!=image)         /* Does shadow temporary decompressed image exist? */
       {
-/*	CloseBlob(image2); */
+/*      CloseBlob(image2); */
         DeleteImageFromList(&image2);
-	if(clone_info)
-	{
+        if(clone_info)
+        {
           if(clone_info->file)
-	  {
+          {
             fclose(clone_info->file);
             clone_info->file = NULL;
             (void) unlink(clone_info->filename);
-	  }
-        }    
+          }
+        }
       }
 
   }
@@ -1169,9 +1230,9 @@ END_OF_READING:
   CloseBlob(image);
 
   {
-    Image *p;    
+    Image *p;
     long scene=0;
-    
+
     /*
       Rewind list, removing any empty images while rewinding.
     */
@@ -1188,7 +1249,7 @@ END_OF_READING:
           p=p->previous;
         }
       }
-    
+
     /*
       Fix scene numbers
     */
@@ -1196,7 +1257,7 @@ END_OF_READING:
       p->scene=scene++;
   }
 
-  if(clone_info != NULL)	/* cleanup garbage file from compression */
+  if(clone_info != NULL)        /* cleanup garbage file from compression */
   {
     if(clone_info->file)
     {
@@ -1224,7 +1285,7 @@ END_OF_READING:
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  Function WriteMATLABImage writes an Matlab matrix to a file.  
+%  Function WriteMATLABImage writes an Matlab matrix to a file.
 %
 %  The format of the WriteMATLABImage method is:
 %
@@ -1255,7 +1316,7 @@ static unsigned int WriteMATLABImage(con
   unsigned char *pixels;
   int is_gray;
   unsigned char ImageName = 'A';
-  
+
   current_time = time((time_t *)NULL);
   t = localtime(&current_time);
 
@@ -1269,7 +1330,7 @@ static unsigned int WriteMATLABImage(con
   logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
   if (status == False)
-    ThrowWriterException(FileOpenError,UnableToOpenFile,image);  
+    ThrowWriterException(FileOpenError,UnableToOpenFile,image);
 
   /*
     Store MAT header.
@@ -1285,7 +1346,7 @@ static unsigned int WriteMATLABImage(con
   MATLAB_HDR[0x7C]=0;
   MATLAB_HDR[0x7D]=1;
   MATLAB_HDR[0x7E]='I';
-  MATLAB_HDR[0x7F]='M';  
+  MATLAB_HDR[0x7F]='M';
   (void) WriteBlob(image,sizeof(MATLAB_HDR),MATLAB_HDR);
 
   pixels=(unsigned char *) NULL;
@@ -1293,7 +1354,7 @@ static unsigned int WriteMATLABImage(con
   {
     pixels=MagickAllocateMemory(unsigned char *,image->rows);
     if (pixels == (unsigned char *) NULL)
-      ThrowWriterException(ResourceLimitError,MemoryAllocationFailed,image);  
+      ThrowWriterException(ResourceLimitError,MemoryAllocationFailed,image);
 
     is_gray = IsGrayImage(image,&image->exception);
     z = is_gray ? 0 : 3;
@@ -1306,21 +1367,21 @@ static unsigned int WriteMATLABImage(con
     (void) WriteBlobLSBLong(image, DataSize + padding + (is_gray?48l:56l)); /* 0x84 */
     (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
     (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
-    (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */  
-    (void) WriteBlobLSBLong(image, 0);   
+    (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
+    (void) WriteBlobLSBLong(image, 0);
     (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
     (void) WriteBlobLSBLong(image, is_gray?0x8:0xC); /* 0x9C - DimFlag */
-    (void) WriteBlobLSBLong(image, image->rows);    /* x: 0xA0 */  
-    (void) WriteBlobLSBLong(image, image->columns); /* y: 0xA4 */  
+    (void) WriteBlobLSBLong(image, image->rows);    /* x: 0xA0 */
+    (void) WriteBlobLSBLong(image, image->columns); /* y: 0xA4 */
     if(!is_gray)
     {
-      (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */  
+      (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
       (void) WriteBlobLSBLong(image, 0);
     }
-    (void) WriteBlobLSBShort(image, 1);  /* 0xB0 */  
+    (void) WriteBlobLSBShort(image, 1);  /* 0xB0 */
     (void) WriteBlobLSBShort(image, 1);  /* 0xB2 */
     (void) WriteBlobLSBLong(image, ImageName++); /* 0xB4  - here is a small bug only 'A' .. 'Z images could be generated properly */
-    (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */  
+    (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
     (void) WriteBlobLSBLong(image, DataSize); /* 0xBC */
 
     /*
@@ -1340,7 +1401,7 @@ static unsigned int WriteMATLABImage(con
       do
       {
         for (y=0; y<(long)image->columns; y++)
-	{
+        {
           progress_quantum++;
           (void) AcquireImagePixels(image,y,0,1,image->rows,&image->exception);
           (void) ExportImagePixelArea(image,z2qtype[z],8,pixels,0,0);
@@ -1348,9 +1409,9 @@ static unsigned int WriteMATLABImage(con
           if (QuantumTick(progress_quantum,progress_span))
             if (!MagickMonitorFormatted(progress_quantum,progress_span,&image->exception,
                                         SaveImageText,image->filename,
-					image->columns,image->rows))
+                                        image->columns,image->rows))
               goto BreakAll;
-	}    
+        }
       } while(z-- >= 2);
     }
 BreakAll:
@@ -1359,7 +1420,7 @@ BreakAll:
 
     status=True;
 
-    if(pixels) 
+    if(pixels)
      {MagickFreeMemory(pixels);pixels=NULL;}
     if(image->next==NULL) break;
     image=SyncNextImageInList(image);
@@ -1370,7 +1431,7 @@ BreakAll:
 
   if (logging)
     (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return MAT");
-  
+
   return(status);
 }
 
@@ -1409,7 +1470,7 @@ ModuleExport void RegisterMATImage(void)
 #if defined(HasZLIB)
                         "MATLAB Level 4.0-7.0 image formats";
 #else
-			"MATLAB Level 4.0-6.0 image formats";
+                        "MATLAB Level 4.0-6.0 image formats";
 #endif
   entry->module = "MAT";
   entry->blob_support=False;
openSUSE Build Service is sponsored by