]> granicus.if.org Git - imagemagick/blob - coders/mat.c
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=7017
[imagemagick] / coders / mat.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                  M   M   AAA   TTTTT  L       AAA   BBBB                    %
6 %                  MM MM  A   A    T    L      A   A  B   B                   %
7 %                  M M M  AAAAA    T    L      AAAAA  BBBB                    %
8 %                  M   M  A   A    T    L      A   A  B   B                   %
9 %                  M   M  A   A    T    LLLLL  A   A  BBBB                    %
10 %                                                                             %
11 %                                                                             %
12 %                        Read MATLAB Image Format                             %
13 %                                                                             %
14 %                              Software Design                                %
15 %                              Jaroslav Fojtik                                %
16 %                                2001-2008                                    %
17 %                                                                             %
18 %                                                                             %
19 %  Permission is hereby granted, free of charge, to any person obtaining a    %
20 %  copy of this software and associated documentation files ("ImageMagick"),  %
21 %  to deal in ImageMagick without restriction, including without limitation   %
22 %  the rights to use, copy, modify, merge, publish, distribute, sublicense,   %
23 %  and/or sell copies of ImageMagick, and to permit persons to whom the       %
24 %  ImageMagick is furnished to do so, subject to the following conditions:    %
25 %                                                                             %
26 %  The above copyright notice and this permission notice shall be included in %
27 %  all copies or substantial portions of ImageMagick.                         %
28 %                                                                             %
29 %  The software is provided "as is", without warranty of any kind, express or %
30 %  implied, including but not limited to the warranties of merchantability,   %
31 %  fitness for a particular purpose and noninfringement.  In no event shall   %
32 %  ImageMagick Studio be liable for any claim, damages or other liability,    %
33 %  whether in an action of contract, tort or otherwise, arising from, out of  %
34 %  or in connection with ImageMagick or the use or other dealings in          %
35 %  ImageMagick.                                                               %
36 %                                                                             %
37 %  Except as contained in this notice, the name of the ImageMagick Studio     %
38 %  shall not be used in advertising or otherwise to promote the sale, use or  %
39 %  other dealings in ImageMagick without prior written authorization from the %
40 %  ImageMagick Studio.                                                        %
41 %                                                                             %
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
43 %
44 %
45 */
46 \f
47 /*
48   Include declarations.
49 */
50 #include "MagickCore/studio.h"
51 #include "MagickCore/attribute.h"
52 #include "MagickCore/blob.h"
53 #include "MagickCore/blob-private.h"
54 #include "MagickCore/cache.h"
55 #include "MagickCore/color-private.h"
56 #include "MagickCore/colormap.h"
57 #include "MagickCore/colorspace-private.h"
58 #include "MagickCore/distort.h"
59 #include "MagickCore/exception.h"
60 #include "MagickCore/exception-private.h"
61 #include "MagickCore/image.h"
62 #include "MagickCore/image-private.h"
63 #include "MagickCore/list.h"
64 #include "MagickCore/magick.h"
65 #include "MagickCore/memory_.h"
66 #include "MagickCore/monitor.h"
67 #include "MagickCore/monitor-private.h"
68 #include "MagickCore/pixel-accessor.h"
69 #include "MagickCore/quantum.h"
70 #include "MagickCore/quantum-private.h"
71 #include "MagickCore/option.h"
72 #include "MagickCore/pixel.h"
73 #include "MagickCore/resource_.h"
74 #include "MagickCore/static.h"
75 #include "MagickCore/string_.h"
76 #include "MagickCore/module.h"
77 #include "MagickCore/transform.h"
78 #include "MagickCore/utility-private.h"
79 #if defined(MAGICKCORE_ZLIB_DELEGATE)
80  #include "zlib.h"
81 #endif
82 \f
83 /*
84   Forward declaration.
85 */
86 static MagickBooleanType
87   WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);
88
89
90 /* Auto coloring method, sorry this creates some artefact inside data
91 MinReal+j*MaxComplex = red  MaxReal+j*MaxComplex = black
92 MinReal+j*0 = white          MaxReal+j*0 = black
93 MinReal+j*MinComplex = blue  MaxReal+j*MinComplex = black
94 */
95
96 typedef struct
97 {
98   char identific[124];
99   unsigned short Version;
100   char EndianIndicator[2];
101   unsigned long DataType;
102   unsigned int ObjectSize;
103   unsigned long unknown1;
104   unsigned long unknown2;
105
106   unsigned short unknown5;
107   unsigned char StructureFlag;
108   unsigned char StructureClass;
109   unsigned long unknown3;
110   unsigned long unknown4;
111   unsigned long DimFlag;
112
113   unsigned long SizeX;
114   unsigned long SizeY;
115   unsigned short Flag1;
116   unsigned short NameFlag;
117 }
118 MATHeader;
119
120 static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
121 static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
122 static const char *OsDesc=
123 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
124     "PCWIN";
125 #else
126  #ifdef __APPLE__
127     "MAC";
128  #else
129     "LNX86";
130  #endif
131 #endif
132
133 typedef enum
134   {
135     miINT8 = 1,      /* 8 bit signed */
136     miUINT8,      /* 8 bit unsigned */
137     miINT16,      /* 16 bit signed */
138     miUINT16,      /* 16 bit unsigned */
139     miINT32,      /* 32 bit signed */
140     miUINT32,      /* 32 bit unsigned */
141     miSINGLE,      /* IEEE 754 single precision float */
142     miRESERVE1,
143     miDOUBLE,      /* IEEE 754 double precision float */
144     miRESERVE2,
145     miRESERVE3,
146     miINT64,      /* 64 bit signed */
147     miUINT64,      /* 64 bit unsigned */
148     miMATRIX,            /* MATLAB array */
149     miCOMPRESSED,          /* Compressed Data */
150     miUTF8,            /* Unicode UTF-8 Encoded Character Data */
151     miUTF16,            /* Unicode UTF-16 Encoded Character Data */
152     miUTF32      /* Unicode UTF-32 Encoded Character Data */
153   } mat5_data_type;
154
155 typedef enum
156   {
157     mxCELL_CLASS=1,    /* cell array */
158     mxSTRUCT_CLASS,    /* structure */
159     mxOBJECT_CLASS,    /* object */
160     mxCHAR_CLASS,    /* character array */
161     mxSPARSE_CLASS,    /* sparse array */
162     mxDOUBLE_CLASS,    /* double precision array */
163     mxSINGLE_CLASS,    /* single precision floating point */
164     mxINT8_CLASS,    /* 8 bit signed integer */
165     mxUINT8_CLASS,    /* 8 bit unsigned integer */
166     mxINT16_CLASS,    /* 16 bit signed integer */
167     mxUINT16_CLASS,    /* 16 bit unsigned integer */
168     mxINT32_CLASS,    /* 32 bit signed integer */
169     mxUINT32_CLASS,    /* 32 bit unsigned integer */
170     mxINT64_CLASS,    /* 64 bit signed integer */
171     mxUINT64_CLASS,    /* 64 bit unsigned integer */
172     mxFUNCTION_CLASS            /* Function handle */
173   } arrayclasstype;
174
175 #define FLAG_COMPLEX 0x8
176 #define FLAG_GLOBAL  0x4
177 #define FLAG_LOGICAL 0x2
178
179 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
180
181
182 static void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal,
183   double MaxVal,ExceptionInfo *exception)
184 {
185
186   double f;
187   int x;
188   register Quantum *q;
189
190   if (MinVal == 0)
191     MinVal = -1;
192   if (MaxVal == 0)
193     MaxVal = 1;
194
195   q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
196   if (q == (Quantum *) NULL)
197     return;
198   for (x = 0; x < (ssize_t) image->columns; x++)
199   {
200     if (*p > 0)
201     {
202       f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
203       if (f + GetPixelRed(image,q) > QuantumRange)
204         SetPixelRed(image,QuantumRange,q);
205       else
206         SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
207       if ((int) f / 2.0 > GetPixelGreen(image,q))
208         {
209           SetPixelGreen(image,0,q);
210           SetPixelBlue(image,0,q);
211         }
212       else
213         {
214           SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
215           SetPixelGreen(image,GetPixelBlue(image,q),q);
216         }
217     }
218     if (*p < 0)
219     {
220       f = (*p / MinVal) * (QuantumRange-GetPixelBlue(image,q));
221       if (f+GetPixelBlue(image,q) > QuantumRange)
222         SetPixelBlue(image,QuantumRange,q);
223       else
224         SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);
225       if ((int) f / 2.0 > GetPixelGreen(image,q))
226         {
227           SetPixelRed(image,0,q);
228           SetPixelGreen(image,0,q);
229         }
230       else
231         {
232           SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
233           SetPixelGreen(image,GetPixelRed(image,q),q);
234         }
235     }
236     p++;
237     q+=GetPixelChannels(image);
238   }
239   if (!SyncAuthenticPixels(image,exception))
240     return;
241   return;
242 }
243
244
245 static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,
246   double MaxVal,ExceptionInfo *exception)
247 {
248   double f;
249   int x;
250   register Quantum *q;
251
252   if (MinVal == 0)
253     MinVal = -1;
254   if (MaxVal == 0)
255     MaxVal = 1;
256
257   q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
258   if (q == (Quantum *) NULL)
259     return;
260   for (x = 0; x < (ssize_t) image->columns; x++)
261   {
262     if (*p > 0)
263     {
264       f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
265       if (f+GetPixelRed(image,q) > QuantumRange)
266         SetPixelRed(image,QuantumRange,q);
267       else
268         SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
269       if ((int) f / 2.0 > GetPixelGreen(image,q))
270         {
271           SetPixelGreen(image,0,q);
272           SetPixelBlue(image,0,q);
273         }
274       else
275         {
276           SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
277           SetPixelGreen(image,GetPixelBlue(image,q),q);
278         }
279     }
280     if (*p < 0)
281     {
282       f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));
283       if (f + GetPixelBlue(image,q) > QuantumRange)
284         SetPixelBlue(image,QuantumRange,q);
285       else
286         SetPixelBlue(image,GetPixelBlue(image,q)+
287           (int) f,q);
288       if ((int) f / 2.0 > GetPixelGreen(image,q))
289         {
290           SetPixelGreen(image,0,q);
291           SetPixelRed(image,0,q);
292         }
293       else
294         {
295           SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
296           SetPixelGreen(image,GetPixelRed(image,q),q);
297         }
298     }
299     p++;
300     q++;
301   }
302   if (!SyncAuthenticPixels(image,exception))
303     return;
304   return;
305 }
306
307
308 /************** READERS ******************/
309
310 /* This function reads one block of floats*/
311 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
312 {
313   while (len >= 4)
314   {
315     *data++ = ReadBlobFloat(image);
316     len -= sizeof(float);
317   }
318   if (len > 0)
319     (void) SeekBlob(image, len, SEEK_CUR);
320 }
321
322 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
323 {
324   while (len >= 4)
325   {
326     *data++ = ReadBlobFloat(image);
327     len -= sizeof(float);
328   }
329   if (len > 0)
330     (void) SeekBlob(image, len, SEEK_CUR);
331 }
332
333 /* This function reads one block of doubles*/
334 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
335 {
336   while (len >= 8)
337   {
338     *data++ = ReadBlobDouble(image);
339     len -= sizeof(double);
340   }
341   if (len > 0)
342     (void) SeekBlob(image, len, SEEK_CUR);
343 }
344
345 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
346 {
347   while (len >= 8)
348   {
349     *data++ = ReadBlobDouble(image);
350     len -= sizeof(double);
351   }
352   if (len > 0)
353     (void) SeekBlob(image, len, SEEK_CUR);
354 }
355
356 /* Calculate minimum and maximum from a given block of data */
357 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
358 {
359 MagickOffsetType filepos;
360 int i, x;
361 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
362 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
363 double *dblrow;
364 float *fltrow;
365
366   if (endian_indicator == LSBEndian)
367   {
368     ReadBlobDoublesXXX = ReadBlobDoublesLSB;
369     ReadBlobFloatsXXX = ReadBlobFloatsLSB;
370   }
371   else    /* MI */
372   {
373     ReadBlobDoublesXXX = ReadBlobDoublesMSB;
374     ReadBlobFloatsXXX = ReadBlobFloatsMSB;
375   }
376
377   filepos = TellBlob(image);     /* Please note that file seeking occurs only in the case of doubles */
378   for (i = 0; i < SizeY; i++)
379   {
380     if (CellType==miDOUBLE)
381     {
382       ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
383       dblrow = (double *)BImgBuff;
384       if (i == 0)
385       {
386         *Min = *Max = *dblrow;
387       }
388       for (x = 0; x < SizeX; x++)
389       {
390         if (*Min > *dblrow)
391           *Min = *dblrow;
392         if (*Max < *dblrow)
393           *Max = *dblrow;
394         dblrow++;
395       }
396     }
397     if (CellType==miSINGLE)
398     {
399       ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
400       fltrow = (float *)BImgBuff;
401       if (i == 0)
402       {
403         *Min = *Max = *fltrow;
404       }
405     for (x = 0; x < (ssize_t) SizeX; x++)
406       {
407         if (*Min > *fltrow)
408           *Min = *fltrow;
409         if (*Max < *fltrow)
410           *Max = *fltrow;
411         fltrow++;
412       }
413     }
414   }
415   (void) SeekBlob(image, filepos, SEEK_SET);
416 }
417
418
419 static void FixSignedValues(const Image *image,Quantum *q, int y)
420 {
421   while(y-->0)
422   {
423      /* Please note that negative values will overflow
424         Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
425            <-1;-128> + 127+1 = <0; 127> */
426     SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
427     SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
428     SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
429     q++;
430   }
431 }
432
433
434 /** Fix whole row of logical/binary data. It means pack it. */
435 static void FixLogical(unsigned char *Buff,int ldblk)
436 {
437 unsigned char mask=128;
438 unsigned char *BuffL = Buff;
439 unsigned char val = 0;
440
441   while(ldblk-->0)
442   {
443     if(*Buff++ != 0)
444       val |= mask;
445
446     mask >>= 1;
447     if(mask==0)
448     {
449       *BuffL++ = val;
450       val = 0;
451       mask = 128;
452     }
453
454   }
455   *BuffL = val;
456 }
457
458 #if defined(MAGICKCORE_ZLIB_DELEGATE)
459 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
460   unsigned int size)
461 {
462   (void) context;
463   return((voidpf) AcquireQuantumMemory(items,size));
464 }
465
466 static void RelinquishZIPMemory(voidpf context,voidpf memory)
467 {
468   (void) context;
469   memory=RelinquishMagickMemory(memory);
470 }
471 #endif
472
473 #if defined(MAGICKCORE_ZLIB_DELEGATE)
474 /** This procedure decompreses an image block for a new MATLAB format. */
475 static Image *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception)
476 {
477
478 Image *image2;
479 void *cache_block, *decompress_block;
480 z_stream zip_info;
481 FILE *mat_file;
482 size_t magick_size;
483 size_t extent;
484 int file;
485
486 int status;
487 int zip_status;
488 ssize_t TotalSize = 0;
489
490   if(clone_info==NULL) return NULL;
491   if(clone_info->file)    /* Close file opened from previous transaction. */
492   {
493     fclose(clone_info->file);
494     clone_info->file = NULL;
495     (void) remove_utf8(clone_info->filename);
496   }
497
498   cache_block = AcquireQuantumMemory((size_t)(*Size < 16384) ? *Size: 16384,sizeof(unsigned char *));
499   if(cache_block==NULL) return NULL;
500   decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
501   if(decompress_block==NULL)
502   {
503     RelinquishMagickMemory(cache_block);
504     return NULL;
505   }
506
507   mat_file=0;
508   file = AcquireUniqueFileResource(clone_info->filename);
509   if (file != -1)
510     mat_file = fdopen(file,"w");
511   if(!mat_file)
512   {
513     RelinquishMagickMemory(cache_block);
514     RelinquishMagickMemory(decompress_block);
515     (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image");
516     return NULL;
517   }
518
519   zip_info.zalloc=AcquireZIPMemory;
520   zip_info.zfree=RelinquishZIPMemory;
521   zip_info.opaque = (voidpf) NULL;
522   zip_status = inflateInit(&zip_info);
523   if (zip_status != Z_OK)
524     {
525       RelinquishMagickMemory(cache_block);
526       RelinquishMagickMemory(decompress_block);
527       (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
528         "UnableToUncompressImage","`%s'",clone_info->filename);
529       (void) fclose(mat_file);
530       RelinquishUniqueFileResource(clone_info->filename);
531       return NULL;
532     }
533   /* zip_info.next_out = 8*4;*/
534
535   zip_info.avail_in = 0;
536   zip_info.total_out = 0;
537   while(*Size>0 && !EOFBlob(orig))
538   {
539     magick_size = ReadBlob(orig, (*Size < 16384) ? *Size : 16384, (unsigned char *) cache_block);
540     zip_info.next_in = (Bytef *) cache_block;
541     zip_info.avail_in = (uInt) magick_size;
542
543     while(zip_info.avail_in>0)
544     {
545       zip_info.avail_out = 4096;
546       zip_info.next_out = (Bytef *) decompress_block;
547       zip_status = inflate(&zip_info,Z_NO_FLUSH);
548       if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
549         break;
550       extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file);
551       (void) extent;
552       TotalSize += 4096-zip_info.avail_out;
553
554       if(zip_status == Z_STREAM_END) goto DblBreak;
555     }
556     if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
557       break;
558
559     *Size -= (unsigned int) magick_size;
560   }
561 DblBreak:
562
563   inflateEnd(&zip_info);
564   (void)fclose(mat_file);
565   RelinquishMagickMemory(cache_block);
566   RelinquishMagickMemory(decompress_block);
567   *Size = TotalSize;
568
569   if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
570   if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;
571   status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
572   if (status == MagickFalse)
573   {
574     DeleteImageFromList(&image2);
575 EraseFile:
576     fclose(clone_info->file);
577     clone_info->file = NULL;
578 UnlinkFile:
579     RelinquishUniqueFileResource(clone_info->filename);
580     return NULL;
581   }
582
583   return image2;
584 }
585 #endif
586
587 static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,
588   ExceptionInfo *exception)
589 {
590   typedef struct {
591     unsigned char Type[4];
592     unsigned int nRows;
593     unsigned int nCols;
594     unsigned int imagf;
595     unsigned int nameLen;
596   } MAT4_HDR;
597
598   long
599     ldblk;
600
601   EndianType
602     endian;
603
604   Image
605     *rotated_image;
606
607   MagickBooleanType
608     status;
609
610   MAT4_HDR
611     HDR;
612
613   QuantumInfo
614     *quantum_info;
615
616   QuantumFormatType
617     format_type;
618
619   register ssize_t
620     i;
621
622   ssize_t
623     count,
624     y;
625
626   unsigned char
627     *pixels;
628
629   unsigned int
630     depth;
631
632
633   quantum_info=(QuantumInfo *) NULL;
634   (void) SeekBlob(image,0,SEEK_SET);
635   while (EOFBlob(image) == MagickFalse)
636   {
637     /*
638      Object parser loop.
639     */
640     ldblk=ReadBlobLSBLong(image);
641     if ((ldblk > 9999) || (ldblk < 0))
642       break;
643     HDR.Type[3]=ldblk % 10; ldblk /= 10;  /* T digit */
644     HDR.Type[2]=ldblk % 10; ldblk /= 10;  /* P digit */
645     HDR.Type[1]=ldblk % 10; ldblk /= 10;  /* O digit */
646     HDR.Type[0]=ldblk;        /* M digit */
647     if (HDR.Type[3] != 0)
648       break;  /* Data format */
649     if (HDR.Type[2] != 0)
650       break;  /* Always 0 */
651     if (HDR.Type[0] == 0)
652       {
653         HDR.nRows=ReadBlobLSBLong(image);
654         HDR.nCols=ReadBlobLSBLong(image);
655         HDR.imagf=ReadBlobLSBLong(image);
656         HDR.nameLen=ReadBlobLSBLong(image);
657         endian=LSBEndian;
658       }
659     else
660       {
661         HDR.nRows=ReadBlobMSBLong(image);
662         HDR.nCols=ReadBlobMSBLong(image);
663         HDR.imagf=ReadBlobMSBLong(image);
664         HDR.nameLen=ReadBlobMSBLong(image);
665         endian=MSBEndian;
666       }
667     if ((HDR.imagf != 0) && (HDR.imagf != 1))
668       break;
669     if (HDR.nameLen > 0xFFFF)
670       return((Image *) NULL);
671     for (i=0; i < (ssize_t) HDR.nameLen; i++)
672     {
673       int
674         byte;
675
676       /*
677         Skip matrix name.
678       */
679       byte=ReadBlobByte(image);
680       if (byte == EOF)
681         {
682           ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
683             image->filename);
684           break;
685         }
686     }
687     image->columns=(size_t) HDR.nRows;
688     image->rows=(size_t) HDR.nCols;
689     if ((image->columns == 0) || (image->rows == 0))
690       return(image);
691     if (image_info->ping != MagickFalse)
692       {
693         Swap(image->columns,image->rows);
694         if(HDR.imagf==1) ldblk *= 2;
695         SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);
696         if ((image->columns == 0) || (image->rows == 0)) 
697           return(image->previous == (Image *) NULL ? (Image *) NULL : image);
698         goto skip_reading_current;
699       }
700     status=SetImageExtent(image,image->columns,image->rows,exception);
701     if (status == MagickFalse)
702       return((Image *) NULL);
703     (void) SetImageBackgroundColor(image,exception);
704     (void) SetImageColorspace(image,GRAYColorspace,exception);
705     quantum_info=AcquireQuantumInfo(image_info,image);
706     if (quantum_info == (QuantumInfo *) NULL)
707       return((Image *) NULL);
708     switch(HDR.Type[1])
709     {
710       case 0:
711         format_type=FloatingPointQuantumFormat;
712         depth=64;
713         break;
714       case 1:
715         format_type=FloatingPointQuantumFormat;
716         depth=32;
717         break;
718       case 2:
719         format_type=UnsignedQuantumFormat;
720         depth=16;
721         break;
722       case 3:
723         format_type=SignedQuantumFormat;
724         depth=16;
725         break;
726       case 4:
727         format_type=UnsignedQuantumFormat;
728         depth=8;
729         break;
730       default:
731         format_type=UnsignedQuantumFormat;
732         depth=8;
733         break;
734     }
735     image->depth=depth;
736     if (HDR.Type[0] != 0)
737       SetQuantumEndian(image,quantum_info,MSBEndian);
738     status=SetQuantumFormat(image,quantum_info,format_type);
739     status=SetQuantumDepth(image,quantum_info,depth);
740     status=SetQuantumEndian(image,quantum_info,endian);
741     SetQuantumScale(quantum_info,1.0);
742     pixels=(unsigned char *) GetQuantumPixels(quantum_info);
743     for (y=0; y < (ssize_t) image->rows; y++)
744     {
745       register Quantum
746         *magick_restrict q;
747
748       count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
749       if (count == -1)
750         break;
751       q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,
752         exception);
753       if (q == (Quantum *) NULL)
754         break;
755       (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
756         GrayQuantum,pixels,exception);
757       if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
758         FixSignedValues(image,q,(int) image->columns);
759       if (SyncAuthenticPixels(image,exception) == MagickFalse)
760         break;
761       if (image->previous == (Image *) NULL)
762         {
763           status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
764             image->rows);
765           if (status == MagickFalse)
766             break;
767         }
768     }
769     if (HDR.imagf == 1)
770       for (y=0; y < (ssize_t) image->rows; y++)
771       {
772         /*
773           Read complex pixels.
774         */
775         count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
776         if (count == -1)
777           break;
778         if (HDR.Type[1] == 0)
779           InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);
780         else
781           InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);
782       }
783     if (quantum_info != (QuantumInfo *) NULL)
784       quantum_info=DestroyQuantumInfo(quantum_info);
785     if (EOFBlob(image) != MagickFalse)
786       {
787         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
788           image->filename);
789         break;
790       }
791     rotated_image=RotateImage(image,90.0,exception);
792     if (rotated_image != (Image *) NULL)
793       {
794         rotated_image->page.x=0;
795         rotated_image->page.y=0;
796         rotated_image->colors = image->colors;
797         DestroyBlob(rotated_image);
798         rotated_image->blob=ReferenceBlob(image->blob);
799         AppendImageToList(&image,rotated_image);
800         DeleteImageFromList(&image);
801       }
802     /*
803       Proceed to next image.
804     */
805     if (image_info->number_scenes != 0)
806       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
807         break;
808     /*
809       Allocate next image structure.
810     */
811 skip_reading_current:
812     AcquireNextImage(image_info,image,exception);
813     if (GetNextImageInList(image) == (Image *) NULL)
814       {
815         image=DestroyImageList(image);
816         return((Image *) NULL);
817       }
818     image=SyncNextImageInList(image);
819     status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
820       GetBlobSize(image));
821     if (status == MagickFalse)
822       break;
823   }
824   (void) CloseBlob(image);
825   return(GetFirstImageInList(image));
826 }
827 \f
828 /*
829 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
830 %                                                                             %
831 %                                                                             %
832 %                                                                             %
833 %   R e a d M A T L A B i m a g e                                             %
834 %                                                                             %
835 %                                                                             %
836 %                                                                             %
837 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
838 %
839 %  ReadMATImage() reads an MAT X image file and returns it.  It
840 %  allocates the memory necessary for the new Image structure and returns a
841 %  pointer to the new image.
842 %
843 %  The format of the ReadMATImage method is:
844 %
845 %      Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
846 %
847 %  A description of each parameter follows:
848 %
849 %    o image:  Method ReadMATImage returns a pointer to the image after
850 %      reading. A null image is returned if there is a memory shortage or if
851 %      the image cannot be read.
852 %
853 %    o image_info: Specifies a pointer to a ImageInfo structure.
854 %
855 %    o exception: return any errors or warnings in this structure.
856 %
857 */
858 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
859 {
860   Image *image, *image2=NULL,
861    *rotated_image;
862   register Quantum *q;
863
864   unsigned int status;
865   MATHeader MATLAB_HDR;
866   size_t size;
867   size_t CellType;
868   QuantumInfo *quantum_info;
869   ImageInfo *clone_info;
870   int i;
871   ssize_t ldblk;
872   unsigned char *BImgBuff = NULL;
873   double MinVal, MaxVal;
874   unsigned z, z2;
875   unsigned Frames;
876   int logging;
877   int sample_size;
878   MagickOffsetType filepos=0x80;
879
880   unsigned int (*ReadBlobXXXLong)(Image *image);
881   unsigned short (*ReadBlobXXXShort)(Image *image);
882   void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
883   void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
884
885
886   assert(image_info != (const ImageInfo *) NULL);
887   assert(image_info->signature == MagickCoreSignature);
888   assert(exception != (ExceptionInfo *) NULL);
889   assert(exception->signature == MagickCoreSignature);
890   logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
891
892   /*
893      Open image file.
894    */
895   image = AcquireImage(image_info,exception);
896   image2 = (Image *) NULL;
897
898   status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
899   if (status == MagickFalse)
900     {
901       image=DestroyImageList(image);
902       return((Image *) NULL);
903     }
904   /*
905      Read MATLAB image.
906    */
907   quantum_info=(QuantumInfo *) NULL;
908   clone_info=(ImageInfo *) NULL;
909   if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
910     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
911   if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
912     {
913       image2=ReadMATImageV4(image_info,image,exception);
914       if (image2  == NULL)
915         goto MATLAB_KO;
916       image=image2;
917       goto END_OF_READING;
918     }
919   MATLAB_HDR.Version = ReadBlobLSBShort(image);
920   if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
921     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
922
923   if (logging)
924     (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  Endian %c%c",
925       MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
926   if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
927   {
928     ReadBlobXXXLong = ReadBlobLSBLong;
929     ReadBlobXXXShort = ReadBlobLSBShort;
930     ReadBlobDoublesXXX = ReadBlobDoublesLSB;
931     ReadBlobFloatsXXX = ReadBlobFloatsLSB;
932     image->endian = LSBEndian;
933   }
934   else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
935   {
936     ReadBlobXXXLong = ReadBlobMSBLong;
937     ReadBlobXXXShort = ReadBlobMSBShort;
938     ReadBlobDoublesXXX = ReadBlobDoublesMSB;
939     ReadBlobFloatsXXX = ReadBlobFloatsMSB;
940     image->endian = MSBEndian;
941   }
942   else
943     {
944 MATLAB_KO:
945       if ((image != image2) && (image2 != (Image *) NULL))
946         image2=DestroyImage(image2);
947       if (clone_info != (ImageInfo *) NULL)
948         clone_info=DestroyImageInfo(clone_info);
949       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
950     }
951
952   filepos = TellBlob(image);
953   while(!EOFBlob(image)) /* object parser loop */
954   {
955     Frames = 1;
956     if(SeekBlob(image,filepos,SEEK_SET) != filepos) break;
957     /* printf("pos=%X\n",TellBlob(image)); */
958
959     MATLAB_HDR.DataType = ReadBlobXXXLong(image);
960     if(EOFBlob(image)) break;
961     MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
962     if(EOFBlob(image)) break;
963     if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))
964       goto MATLAB_KO;
965     filepos += MATLAB_HDR.ObjectSize + 4 + 4;
966
967     if (clone_info != (ImageInfo *) NULL)
968       clone_info=DestroyImageInfo(clone_info);
969     clone_info=CloneImageInfo(image_info);
970     if ((image != image2) && (image2 != (Image *) NULL))
971       image2=DestroyImage(image2);
972     image2 = image;
973 #if defined(MAGICKCORE_ZLIB_DELEGATE)
974     if(MATLAB_HDR.DataType == miCOMPRESSED)
975     {
976       image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
977       if(image2==NULL) continue;
978       MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
979     }
980 #endif
981
982     if (MATLAB_HDR.DataType!=miMATRIX)
983       {
984         clone_info=DestroyImageInfo(clone_info);
985         continue;  /* skip another objects. */
986       }
987
988     MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
989     MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
990
991     MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
992     MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
993     MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
994
995     MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
996     if(image!=image2)
997       MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */
998     MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
999     MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
1000     MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
1001     MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
1002
1003
1004     switch(MATLAB_HDR.DimFlag)
1005     {
1006       case  8: z2=z=1; break;      /* 2D matrix*/
1007       case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/
1008            (void) ReadBlobXXXLong(image2);
1009          if(z!=3)
1010            {
1011              if (clone_info != (ImageInfo *) NULL)
1012                clone_info=DestroyImageInfo(clone_info);
1013              if ((image != image2) && (image2 != (Image *) NULL))
1014                image2=DestroyImage(image2);
1015              ThrowReaderException(CoderError,
1016                "MultidimensionalMatricesAreNotSupported");
1017            }
1018          break;
1019       case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */
1020          if(z!=3 && z!=1)
1021            {
1022              if (clone_info != (ImageInfo *) NULL)
1023                clone_info=DestroyImageInfo(clone_info);
1024              if ((image != image2) && (image2 != (Image *) NULL))
1025                image2=DestroyImage(image2);
1026              ThrowReaderException(CoderError,
1027                "MultidimensionalMatricesAreNotSupported");
1028            }
1029          Frames = ReadBlobXXXLong(image2);
1030          if (Frames == 0)
1031            {
1032              if (clone_info != (ImageInfo *) NULL)
1033                clone_info=DestroyImageInfo(clone_info);
1034              if ((image != image2) && (image2 != (Image *) NULL))
1035                image2=DestroyImage(image2);
1036              ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1037            }
1038          break;
1039       default:
1040         if (clone_info != (ImageInfo *) NULL)
1041           clone_info=DestroyImageInfo(clone_info);
1042         if ((image != image2) && (image2 != (Image *) NULL))
1043           image2=DestroyImage(image2);
1044         ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
1045     }
1046
1047     MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
1048     MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
1049
1050     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1051           "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
1052     if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
1053         MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */
1054         MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */
1055         MATLAB_HDR.StructureClass != mxINT8_CLASS &&
1056         MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */
1057         MATLAB_HDR.StructureClass != mxINT16_CLASS &&
1058         MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */
1059         MATLAB_HDR.StructureClass != mxINT32_CLASS &&
1060         MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */
1061         MATLAB_HDR.StructureClass != mxINT64_CLASS &&
1062         MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */
1063       {
1064         if ((image2 != (Image*) NULL) && (image2 != (Image *) image))
1065           {
1066             CloseBlob(image2);
1067             DeleteImageFromList(&image2);
1068           }
1069         if (clone_info != (ImageInfo *) NULL)
1070           clone_info=DestroyImageInfo(clone_info);
1071         ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
1072       }
1073
1074     switch (MATLAB_HDR.NameFlag)
1075     {
1076       case 0:
1077         size = ReadBlobXXXLong(image2);  /* Object name string size */
1078         size = 4 * (ssize_t) ((size + 3 + 1) / 4);
1079         (void) SeekBlob(image2, size, SEEK_CUR);
1080         break;
1081       case 1:
1082       case 2:
1083       case 3:
1084       case 4:
1085         (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
1086         break;
1087       default:
1088         goto MATLAB_KO;
1089     }
1090
1091     CellType = ReadBlobXXXLong(image2);    /* Additional object type */
1092     if (logging)
1093       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1094         "MATLAB_HDR.CellType: %.20g",(double) CellType);
1095
1096     (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */
1097
1098     NEXT_FRAME:
1099     switch (CellType)
1100     {
1101       case miINT8:
1102       case miUINT8:
1103         sample_size = 8;
1104         if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
1105           image->depth = 1;
1106         else
1107           image->depth = 8;         /* Byte type cell */
1108         ldblk = (ssize_t) MATLAB_HDR.SizeX;
1109         break;
1110       case miINT16:
1111       case miUINT16:
1112         sample_size = 16;
1113         image->depth = 16;        /* Word type cell */
1114         ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
1115         break;
1116       case miINT32:
1117       case miUINT32:
1118         sample_size = 32;
1119         image->depth = 32;        /* Dword type cell */
1120         ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
1121         break;
1122       case miINT64:
1123       case miUINT64:
1124         sample_size = 64;
1125         image->depth = 64;        /* Qword type cell */
1126         ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
1127         break;
1128       case miSINGLE:
1129         sample_size = 32;
1130         image->depth = 32;        /* double type cell */
1131         (void) SetImageOption(clone_info,"quantum:format","floating-point");
1132         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
1133   {              /* complex float type cell */
1134   }
1135         ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
1136         break;
1137       case miDOUBLE:
1138         sample_size = 64;
1139         image->depth = 64;        /* double type cell */
1140         (void) SetImageOption(clone_info,"quantum:format","floating-point");
1141 DisableMSCWarning(4127)
1142         if (sizeof(double) != 8)
1143 RestoreMSCWarning
1144           {
1145             if (clone_info != (ImageInfo *) NULL)
1146               clone_info=DestroyImageInfo(clone_info);
1147             if ((image != image2) && (image2 != (Image *) NULL))
1148               image2=DestroyImage(image2);
1149             ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
1150           }
1151         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
1152   {                         /* complex double type cell */
1153   }
1154         ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
1155         break;
1156       default:
1157         if ((image != image2) && (image2 != (Image *) NULL))
1158           image2=DestroyImage(image2);
1159         if (clone_info)
1160           clone_info=DestroyImageInfo(clone_info);
1161         ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
1162     }
1163     (void) sample_size;
1164     image->columns = MATLAB_HDR.SizeX;
1165     image->rows = MATLAB_HDR.SizeY;
1166     image->colors = GetQuantumRange(image->depth);
1167     if (image->columns == 0 || image->rows == 0)
1168       goto MATLAB_KO;
1169     if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
1170       goto MATLAB_KO;
1171     /* Image is gray when no complex flag is set and 2D Matrix */
1172     if ((MATLAB_HDR.DimFlag == 8) &&
1173         ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
1174       {
1175         image->type=GrayscaleType;
1176         SetImageColorspace(image,GRAYColorspace,exception);
1177       }
1178
1179
1180     /*
1181       If ping is true, then only set image size and colors without
1182       reading any image data.
1183     */
1184     if (image_info->ping)
1185     {
1186       size_t temp = image->columns;
1187       image->columns = image->rows;
1188       image->rows = temp;
1189       goto done_reading; /* !!!!!! BAD  !!!! */
1190     }
1191     status=SetImageExtent(image,image->columns,image->rows,exception);
1192     if (status == MagickFalse)
1193       {
1194         if (clone_info != (ImageInfo *) NULL)
1195           clone_info=DestroyImageInfo(clone_info);
1196         if ((image != image2) && (image2 != (Image *) NULL))
1197           image2=DestroyImage(image2);
1198         return(DestroyImageList(image));
1199       }
1200     (void) SetImageBackgroundColor(image,exception);
1201     quantum_info=AcquireQuantumInfo(clone_info,image);
1202     if (quantum_info == (QuantumInfo *) NULL)
1203       {
1204         if (clone_info != (ImageInfo *) NULL)
1205           clone_info=DestroyImageInfo(clone_info);
1206         if ((image != image2) && (image2 != (Image *) NULL))
1207           image2=DestroyImage(image2);
1208         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1209       }
1210
1211   /* ----- Load raster data ----- */
1212     BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */
1213     if (BImgBuff == NULL)
1214       {
1215         if (clone_info != (ImageInfo *) NULL)
1216           clone_info=DestroyImageInfo(clone_info);
1217         if ((image != image2) && (image2 != (Image *) NULL))
1218           image2=DestroyImage(image2);
1219         if (quantum_info != (QuantumInfo *) NULL)
1220           quantum_info=DestroyQuantumInfo(quantum_info);
1221         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1222       }
1223     (void) memset(BImgBuff,0,ldblk*sizeof(double));
1224
1225     MinVal = 0;
1226     MaxVal = 0;
1227     if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */
1228     {
1229       CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
1230     }
1231
1232     /* Main loop for reading all scanlines */
1233     if(z==1) z=0; /* read grey scanlines */
1234     /* else read color scanlines */
1235     do
1236     {
1237       for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
1238       {
1239         q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
1240         if (q == (Quantum *) NULL)
1241   {
1242     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1243               "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
1244     goto done_reading;    /* Skip image rotation, when cannot set image pixels    */
1245   }
1246         if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
1247   {
1248     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1249              "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
1250     goto ExitLoop;
1251   }
1252         if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
1253         {
1254           FixLogical((unsigned char *)BImgBuff,ldblk);
1255           if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
1256     {
1257 ImportQuantumPixelsFailed:
1258       if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1259               "  MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
1260       break;
1261     }
1262         }
1263         else
1264         {
1265           if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
1266       goto ImportQuantumPixelsFailed;
1267
1268
1269           if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */
1270           (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
1271       FixSignedValues(image,q,MATLAB_HDR.SizeX);
1272         }
1273
1274         if (!SyncAuthenticPixels(image,exception))
1275   {
1276     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1277             "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
1278     goto ExitLoop;
1279   }
1280       }
1281     } while(z-- >= 2);
1282 ExitLoop:
1283
1284
1285     /* Read complex part of numbers here */
1286     if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
1287     {        /* Find Min and Max Values for complex parts of floats */
1288       CellType = ReadBlobXXXLong(image2);    /* Additional object type */
1289       i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/
1290
1291       if (CellType==miDOUBLE || CellType==miSINGLE)
1292       {
1293         CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
1294       }
1295
1296       if (CellType==miDOUBLE)
1297         for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
1298   {
1299           ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
1300           InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
1301             exception);
1302   }
1303
1304       if (CellType==miSINGLE)
1305         for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
1306   {
1307           ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
1308           InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
1309             exception);
1310   }
1311     }
1312
1313       /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
1314     if ((MATLAB_HDR.DimFlag == 8) &&
1315         ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
1316       image->type=GrayscaleType;
1317     if (image->depth == 1)
1318       image->type=BilevelType;
1319
1320     if(image2==image)
1321         image2 = NULL;    /* Remove shadow copy to an image before rotation. */
1322
1323       /*  Rotate image. */
1324     rotated_image = RotateImage(image, 90.0, exception);
1325     if (rotated_image != (Image *) NULL)
1326     {
1327         /* Remove page offsets added by RotateImage */
1328       rotated_image->page.x=0;
1329       rotated_image->page.y=0;
1330       rotated_image->colors = image->colors;
1331       DestroyBlob(rotated_image);
1332       rotated_image->blob=ReferenceBlob(image->blob);
1333       AppendImageToList(&image,rotated_image);
1334       DeleteImageFromList(&image);
1335     }
1336
1337 done_reading:
1338
1339     if(image2!=NULL)
1340       if(image2!=image)
1341       {
1342         DeleteImageFromList(&image2);
1343   if(clone_info)
1344   {
1345           if(clone_info->file)
1346     {
1347             fclose(clone_info->file);
1348             clone_info->file = NULL;
1349             (void) remove_utf8(clone_info->filename);
1350     }
1351         }
1352       }
1353     if (EOFBlob(image) != MagickFalse)
1354       break;
1355
1356       /* Allocate next image structure. */
1357     AcquireNextImage(image_info,image,exception);
1358     if (image->next == (Image *) NULL) break;
1359     image=SyncNextImageInList(image);
1360     image->columns=image->rows=0;
1361     image->colors=0;
1362
1363       /* row scan buffer is no longer needed */
1364     RelinquishMagickMemory(BImgBuff);
1365     BImgBuff = NULL;
1366     if (quantum_info != (QuantumInfo *) NULL)
1367       quantum_info=DestroyQuantumInfo(quantum_info);
1368
1369     if(--Frames>0)
1370     {
1371       z = z2;
1372       if(image2==NULL) image2 = image;
1373       if(!EOFBlob(image) && TellBlob(image)<filepos)
1374         goto NEXT_FRAME;
1375     }
1376     if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */
1377       {
1378 /*  CloseBlob(image2); */
1379         DeleteImageFromList(&image2);
1380         if(clone_info)
1381         {
1382           if(clone_info->file)
1383           {
1384             fclose(clone_info->file);
1385             clone_info->file = NULL;
1386             (void) remove_utf8(clone_info->filename);
1387           }
1388         }
1389         }
1390
1391     if (clone_info)
1392       clone_info=DestroyImageInfo(clone_info);
1393   }
1394
1395   RelinquishMagickMemory(BImgBuff);
1396   if (quantum_info != (QuantumInfo *) NULL)
1397     quantum_info=DestroyQuantumInfo(quantum_info);
1398 END_OF_READING:
1399   CloseBlob(image);
1400
1401
1402   {
1403     Image *p;
1404     ssize_t scene=0;
1405
1406     /*
1407       Rewind list, removing any empty images while rewinding.
1408     */
1409     p=image;
1410     image=NULL;
1411     while (p != (Image *) NULL)
1412       {
1413         Image *tmp=p;
1414         if ((p->rows == 0) || (p->columns == 0)) {
1415           p=p->previous;
1416           if (tmp == image2)
1417             image2=(Image *) NULL;
1418           DeleteImageFromList(&tmp);
1419         } else {
1420           image=p;
1421           p=p->previous;
1422         }
1423       }
1424
1425     /*
1426       Fix scene numbers
1427     */
1428     for (p=image; p != (Image *) NULL; p=p->next)
1429       p->scene=scene++;
1430   }
1431
1432   if(clone_info != NULL)  /* cleanup garbage file from compression */
1433   {
1434     if(clone_info->file)
1435     {
1436       fclose(clone_info->file);
1437       clone_info->file = NULL;
1438       (void) remove_utf8(clone_info->filename);
1439     }
1440     DestroyImageInfo(clone_info);
1441     clone_info = NULL;
1442   }
1443   if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1444   if ((image != image2) && (image2 != (Image *) NULL))
1445     image2=DestroyImage(image2);
1446   if (image == (Image *) NULL)
1447     ThrowReaderException(CorruptImageError,"ImproperImageHeader")
1448   return(image);
1449 }
1450 \f
1451 /*
1452 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1453 %                                                                             %
1454 %                                                                             %
1455 %                                                                             %
1456 %   R e g i s t e r M A T I m a g e                                           %
1457 %                                                                             %
1458 %                                                                             %
1459 %                                                                             %
1460 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1461 %
1462 %  Method RegisterMATImage adds attributes for the MAT image format to
1463 %  the list of supported formats.  The attributes include the image format
1464 %  tag, a method to read and/or write the format, whether the format
1465 %  supports the saving of more than one frame to the same file or blob,
1466 %  whether the format supports native in-memory I/O, and a brief
1467 %  description of the format.
1468 %
1469 %  The format of the RegisterMATImage method is:
1470 %
1471 %      size_t RegisterMATImage(void)
1472 %
1473 */
1474 ModuleExport size_t RegisterMATImage(void)
1475 {
1476   MagickInfo
1477     *entry;
1478
1479   entry=AcquireMagickInfo("MAT","MAT","MATLAB level 5 image format");
1480   entry->decoder=(DecodeImageHandler *) ReadMATImage;
1481   entry->encoder=(EncodeImageHandler *) WriteMATImage;
1482   entry->flags^=CoderBlobSupportFlag;
1483   entry->flags|=CoderDecoderSeekableStreamFlag;
1484   (void) RegisterMagickInfo(entry);
1485   return(MagickImageCoderSignature);
1486 }
1487 \f
1488 /*
1489 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1490 %                                                                             %
1491 %                                                                             %
1492 %                                                                             %
1493 %   U n r e g i s t e r M A T I m a g e                                       %
1494 %                                                                             %
1495 %                                                                             %
1496 %                                                                             %
1497 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1498 %
1499 %  Method UnregisterMATImage removes format registrations made by the
1500 %  MAT module from the list of supported formats.
1501 %
1502 %  The format of the UnregisterMATImage method is:
1503 %
1504 %      UnregisterMATImage(void)
1505 %
1506 */
1507 ModuleExport void UnregisterMATImage(void)
1508 {
1509   (void) UnregisterMagickInfo("MAT");
1510 }
1511 \f
1512 /*
1513 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1514 %                                                                             %
1515 %                                                                             %
1516 %                                                                             %
1517 %   W r i t e M A T L A B I m a g e                                           %
1518 %                                                                             %
1519 %                                                                             %
1520 %                                                                             %
1521 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1522 %
1523 %  Function WriteMATImage writes an Matlab matrix to a file.
1524 %
1525 %  The format of the WriteMATImage method is:
1526 %
1527 %      MagickBooleanType WriteMATImage(const ImageInfo *image_info,
1528 %        Image *image,ExceptionInfo *exception)
1529 %
1530 %  A description of each parameter follows.
1531 %
1532 %    o image_info: Specifies a pointer to a ImageInfo structure.
1533 %
1534 %    o image:  A pointer to an Image structure.
1535 %
1536 %    o exception: return any errors or warnings in this structure.
1537 %
1538 */
1539 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,
1540   ExceptionInfo *exception)
1541 {
1542   char
1543     MATLAB_HDR[0x80];
1544
1545   MagickBooleanType
1546     status;
1547
1548   MagickOffsetType
1549     scene;
1550
1551   struct tm
1552     local_time;
1553
1554   time_t
1555     current_time;
1556
1557   /*
1558     Open output image file.
1559   */
1560   assert(image_info != (const ImageInfo *) NULL);
1561   assert(image_info->signature == MagickCoreSignature);
1562   assert(image != (Image *) NULL);
1563   assert(image->signature == MagickCoreSignature);
1564   (void) LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1565   assert(exception != (ExceptionInfo *) NULL);
1566   assert(exception->signature == MagickCoreSignature);
1567   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1568   if (status == MagickFalse)
1569     return(MagickFalse);
1570   image->depth=8;
1571
1572   current_time=time((time_t *) NULL);
1573 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1574   (void) localtime_r(&current_time,&local_time);
1575 #else
1576   (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time));
1577 #endif
1578   (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1579   FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
1580     "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1581     OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1582     local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1583     local_time.tm_sec,local_time.tm_year+1900);
1584   MATLAB_HDR[0x7C]=0;
1585   MATLAB_HDR[0x7D]=1;
1586   MATLAB_HDR[0x7E]='I';
1587   MATLAB_HDR[0x7F]='M';
1588   (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1589   scene=0;
1590   do
1591   {
1592     char
1593       padding;
1594
1595     MagickBooleanType
1596       is_gray;
1597
1598     QuantumInfo
1599       *quantum_info;
1600
1601     size_t
1602       data_size;
1603
1604     unsigned char
1605       *pixels;
1606
1607     unsigned int
1608       z;
1609
1610     (void) TransformImageColorspace(image,sRGBColorspace,exception);
1611     is_gray=SetImageGray(image,exception);
1612     z=(is_gray != MagickFalse) ? 0 : 3;
1613
1614     /*
1615       Store MAT header.
1616     */
1617     data_size = image->rows * image->columns;
1618     if (is_gray == MagickFalse)
1619       data_size*=3;
1620     padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7;
1621
1622     (void) WriteBlobLSBLong(image,miMATRIX);
1623     (void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+
1624       ((is_gray != MagickFalse) ? 48 : 56));
1625     (void) WriteBlobLSBLong(image,0x6); /* 0x88 */
1626     (void) WriteBlobLSBLong(image,0x8); /* 0x8C */
1627     (void) WriteBlobLSBLong(image,0x6); /* 0x90 */
1628     (void) WriteBlobLSBLong(image,0);
1629     (void) WriteBlobLSBLong(image,0x5); /* 0x98 */
1630     (void) WriteBlobLSBLong(image,(is_gray != MagickFalse) ? 0x8 : 0xC); /* 0x9C - DimFlag */
1631     (void) WriteBlobLSBLong(image,(unsigned int) image->rows);    /* x: 0xA0 */
1632     (void) WriteBlobLSBLong(image,(unsigned int) image->columns); /* y: 0xA4 */
1633     if (is_gray == MagickFalse)
1634       {
1635         (void) WriteBlobLSBLong(image,3); /* z: 0xA8 */
1636         (void) WriteBlobLSBLong(image,0);
1637       }
1638     (void) WriteBlobLSBShort(image,1);  /* 0xB0 */
1639     (void) WriteBlobLSBShort(image,1);  /* 0xB2 */
1640     (void) WriteBlobLSBLong(image,'M'); /* 0xB4 */
1641     (void) WriteBlobLSBLong(image,0x2); /* 0xB8 */
1642     (void) WriteBlobLSBLong(image,(unsigned int) data_size); /* 0xBC */
1643
1644     /*
1645       Store image data.
1646     */
1647     quantum_info=AcquireQuantumInfo(image_info,image);
1648     if (quantum_info == (QuantumInfo *) NULL)
1649       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1650     pixels=(unsigned char *) GetQuantumPixels(quantum_info);
1651     do
1652     {
1653       const Quantum
1654         *p;
1655
1656       ssize_t
1657         y;
1658
1659       for (y=0; y < (ssize_t)image->columns; y++)
1660       {
1661         p=GetVirtualPixels(image,y,0,1,image->rows,exception);
1662         if (p == (const Quantum *) NULL)
1663           break;
1664         (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1665           z2qtype[z],pixels,exception);
1666         (void) WriteBlob(image,image->rows,pixels);
1667       }
1668       if (SyncAuthenticPixels(image,exception) == MagickFalse)
1669         break;
1670     } while (z-- >= 2);
1671     while (padding-- > 0)
1672       (void) WriteBlobByte(image,0);
1673     quantum_info=DestroyQuantumInfo(quantum_info);
1674     if (GetNextImageInList(image) == (Image *) NULL)
1675       break;
1676     image=SyncNextImageInList(image);
1677     status=SetImageProgress(image,SaveImagesTag,scene++,
1678       GetImageListLength(image));
1679     if (status == MagickFalse)
1680       break;
1681   } while (image_info->adjoin != MagickFalse);
1682   (void) CloseBlob(image);
1683   return(status);
1684 }