]> granicus.if.org Git - imagemagick/blob - coders/mat.c
Make MagickMax()/MagickMin() a macro rather than an inline.
[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-private.h"
70 #include "MagickCore/option.h"
71 #include "MagickCore/pixel.h"
72 #include "MagickCore/resource_.h"
73 #include "MagickCore/static.h"
74 #include "MagickCore/string_.h"
75 #include "MagickCore/module.h"
76 #include "MagickCore/transform.h"
77 #include "MagickCore/utility-private.h"
78 #if defined(MAGICKCORE_ZLIB_DELEGATE)
79  #include "zlib.h"
80 #endif
81 \f
82 /*
83   Forward declaration.
84 */
85 static MagickBooleanType
86   WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);
87
88
89 /* Auto coloring method, sorry this creates some artefact inside data
90 MinReal+j*MaxComplex = red  MaxReal+j*MaxComplex = black
91 MinReal+j*0 = white          MaxReal+j*0 = black
92 MinReal+j*MinComplex = blue  MaxReal+j*MinComplex = black
93 */
94
95 typedef struct
96 {
97   char identific[124];
98   unsigned short Version;
99   char EndianIndicator[2];
100   unsigned long DataType;
101   unsigned long ObjectSize;
102   unsigned long unknown1;
103   unsigned long unknown2;
104
105   unsigned short unknown5;
106   unsigned char StructureFlag;
107   unsigned char StructureClass;
108   unsigned long unknown3;
109   unsigned long unknown4;
110   unsigned long DimFlag;
111
112   unsigned long SizeX;
113   unsigned long SizeY;
114   unsigned short Flag1;
115   unsigned short NameFlag;
116 }
117 MATHeader;
118
119 static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
120 static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
121 static const char *OsDesc=
122 #ifdef __WIN32__
123     "PCWIN";
124 #else
125  #ifdef __APPLE__
126     "MAC";
127  #else
128     "LNX86";
129  #endif
130 #endif
131
132 typedef enum
133   {
134     miINT8 = 1,      /* 8 bit signed */
135     miUINT8,      /* 8 bit unsigned */
136     miINT16,      /* 16 bit signed */
137     miUINT16,      /* 16 bit unsigned */
138     miINT32,      /* 32 bit signed */
139     miUINT32,      /* 32 bit unsigned */
140     miSINGLE,      /* IEEE 754 single precision float */
141     miRESERVE1,
142     miDOUBLE,      /* IEEE 754 double precision float */
143     miRESERVE2,
144     miRESERVE3,
145     miINT64,      /* 64 bit signed */
146     miUINT64,      /* 64 bit unsigned */
147     miMATRIX,            /* MATLAB array */
148     miCOMPRESSED,          /* Compressed Data */
149     miUTF8,            /* Unicode UTF-8 Encoded Character Data */
150     miUTF16,            /* Unicode UTF-16 Encoded Character Data */
151     miUTF32      /* Unicode UTF-32 Encoded Character Data */
152   } mat5_data_type;
153
154 typedef enum
155   {
156     mxCELL_CLASS=1,    /* cell array */
157     mxSTRUCT_CLASS,    /* structure */
158     mxOBJECT_CLASS,    /* object */
159     mxCHAR_CLASS,    /* character array */
160     mxSPARSE_CLASS,    /* sparse array */
161     mxDOUBLE_CLASS,    /* double precision array */
162     mxSINGLE_CLASS,    /* single precision floating point */
163     mxINT8_CLASS,    /* 8 bit signed integer */
164     mxUINT8_CLASS,    /* 8 bit unsigned integer */
165     mxINT16_CLASS,    /* 16 bit signed integer */
166     mxUINT16_CLASS,    /* 16 bit unsigned integer */
167     mxINT32_CLASS,    /* 32 bit signed integer */
168     mxUINT32_CLASS,    /* 32 bit unsigned integer */
169     mxINT64_CLASS,    /* 64 bit signed integer */
170     mxUINT64_CLASS,    /* 64 bit unsigned integer */
171     mxFUNCTION_CLASS            /* Function handle */
172   } arrayclasstype;
173
174 #define FLAG_COMPLEX 0x8
175 #define FLAG_GLOBAL  0x4
176 #define FLAG_LOGICAL 0x2
177
178 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
179
180
181 static void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal,
182   double MaxVal,ExceptionInfo *exception)
183 {
184
185   double f;
186   int x;
187   register Quantum *q;
188
189   if (MinVal == 0)
190     MinVal = -1;
191   if (MaxVal == 0)
192     MaxVal = 1;
193
194   q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
195   if (q == (Quantum *) NULL)
196     return;
197   for (x = 0; x < (ssize_t) image->columns; x++)
198   {
199     if (*p > 0)
200     {
201       f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
202       if (f + GetPixelRed(image,q) > QuantumRange)
203         SetPixelRed(image,QuantumRange,q);
204       else
205         SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
206       if ((int) f / 2.0 > GetPixelGreen(image,q))
207         {
208           SetPixelGreen(image,0,q);
209           SetPixelBlue(image,0,q);
210         }
211       else
212         {
213           SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
214           SetPixelGreen(image,GetPixelBlue(image,q),q);
215         }
216     }
217     if (*p < 0)
218     {
219       f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q));
220       if (f+GetPixelBlue(image,q) > QuantumRange)
221         SetPixelBlue(image,QuantumRange,q);
222       else
223         SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);
224       if ((int) f / 2.0 > GetPixelGreen(image,q))
225         {
226           SetPixelRed(image,0,q);
227           SetPixelGreen(image,0,q);
228         }
229       else
230         {
231           SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
232           SetPixelGreen(image,GetPixelRed(image,q),q);
233         }
234     }
235     p++;
236     q+=GetPixelChannels(image);
237   }
238   if (!SyncAuthenticPixels(image,exception))
239     return;
240   return;
241 }
242
243
244 static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,
245   double MaxVal,ExceptionInfo *exception)
246 {
247   double f;
248   int x;
249   register Quantum *q;
250
251   if (MinVal == 0)
252     MinVal = -1;
253   if (MaxVal == 0)
254     MaxVal = 1;
255
256   q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
257   if (q == (Quantum *) NULL)
258     return;
259   for (x = 0; x < (ssize_t) image->columns; x++)
260   {
261     if (*p > 0)
262     {
263       f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
264       if (f+GetPixelRed(image,q) > QuantumRange)
265         SetPixelRed(image,QuantumRange,q);
266       else
267         SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
268       if ((int) f / 2.0 > GetPixelGreen(image,q))
269         {
270           SetPixelGreen(image,0,q);
271           SetPixelBlue(image,0,q);
272         }
273       else
274         {
275           SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
276           SetPixelGreen(image,GetPixelBlue(image,q),q);
277         }
278     }
279     if (*p < 0)
280     {
281       f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));
282       if (f + GetPixelBlue(image,q) > QuantumRange)
283         SetPixelBlue(image,QuantumRange,q);
284       else
285         SetPixelBlue(image,GetPixelBlue(image,q)+
286           (int) f,q);
287       if ((int) f / 2.0 > GetPixelGreen(image,q))
288         {
289           SetPixelGreen(image,0,q);
290           SetPixelRed(image,0,q);
291         }
292       else
293         {
294           SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
295           SetPixelGreen(image,GetPixelRed(image,q),q);
296         }
297     }
298     p++;
299     q++;
300   }
301   if (!SyncAuthenticPixels(image,exception))
302     return;
303   return;
304 }
305
306
307 /************** READERS ******************/
308
309 /* This function reads one block of floats*/
310 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
311 {
312   while (len >= 4)
313   {
314     *data++ = ReadBlobFloat(image);
315     len -= sizeof(float);
316   }
317   if (len > 0)
318     (void) SeekBlob(image, len, SEEK_CUR);
319 }
320
321 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
322 {
323   while (len >= 4)
324   {
325     *data++ = ReadBlobFloat(image);
326     len -= sizeof(float);
327   }
328   if (len > 0)
329     (void) SeekBlob(image, len, SEEK_CUR);
330 }
331
332 /* This function reads one block of doubles*/
333 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
334 {
335   while (len >= 8)
336   {
337     *data++ = ReadBlobDouble(image);
338     len -= sizeof(double);
339   }
340   if (len > 0)
341     (void) SeekBlob(image, len, SEEK_CUR);
342 }
343
344 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
345 {
346   while (len >= 8)
347   {
348     *data++ = ReadBlobDouble(image);
349     len -= sizeof(double);
350   }
351   if (len > 0)
352     (void) SeekBlob(image, len, SEEK_CUR);
353 }
354
355 /* Calculate minimum and maximum from a given block of data */
356 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
357 {
358 MagickOffsetType filepos;
359 int i, x;
360 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
361 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
362 double *dblrow;
363 float *fltrow;
364
365   if (endian_indicator == LSBEndian)
366   {    
367     ReadBlobDoublesXXX = ReadBlobDoublesLSB;
368     ReadBlobFloatsXXX = ReadBlobFloatsLSB;   
369   } 
370   else    /* MI */
371   {    
372     ReadBlobDoublesXXX = ReadBlobDoublesMSB;
373     ReadBlobFloatsXXX = ReadBlobFloatsMSB;   
374   }
375
376   filepos = TellBlob(image);     /* Please note that file seeking occurs only in the case of doubles */
377   for (i = 0; i < SizeY; i++)
378   {
379     if (CellType==miDOUBLE)
380     {
381       ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
382       dblrow = (double *)BImgBuff;
383       if (i == 0)
384       {
385         *Min = *Max = *dblrow;
386       }
387       for (x = 0; x < SizeX; x++)
388       {
389         if (*Min > *dblrow)
390           *Min = *dblrow;
391         if (*Max < *dblrow)
392           *Max = *dblrow;
393         dblrow++;
394       }
395     }
396     if (CellType==miSINGLE)
397     {
398       ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
399       fltrow = (float *)BImgBuff;
400       if (i == 0)
401       {
402         *Min = *Max = *fltrow;
403       }
404     for (x = 0; x < (ssize_t) SizeX; x++)
405       {
406         if (*Min > *fltrow)
407           *Min = *fltrow;
408         if (*Max < *fltrow)
409           *Max = *fltrow;
410         fltrow++;
411       }
412     }
413   }
414   (void) SeekBlob(image, filepos, SEEK_SET);
415 }
416
417
418 static void FixSignedValues(const Image *image,Quantum *q, int y)
419 {
420   while(y-->0)
421   {
422      /* Please note that negative values will overflow
423         Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> 
424            <-1;-128> + 127+1 = <0; 127> */
425     SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
426     SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
427     SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
428     q++;
429   }
430 }
431
432
433 /** Fix whole row of logical/binary data. It means pack it. */
434 static void FixLogical(unsigned char *Buff,int ldblk)
435 {
436 unsigned char mask=128;
437 unsigned char *BuffL = Buff;
438 unsigned char val = 0;
439
440   while(ldblk-->0)
441   {
442     if(*Buff++ != 0)
443       val |= mask;    
444
445     mask >>= 1;
446     if(mask==0)
447     {
448       *BuffL++ = val;
449       val = 0;
450       mask = 128;
451     }   
452       
453   }
454   *BuffL = val;
455 }
456
457 #if defined(MAGICKCORE_ZLIB_DELEGATE)
458 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
459   unsigned int size)
460 {
461   (void) context;
462   return((voidpf) AcquireQuantumMemory(items,size));
463 }
464
465 static void RelinquishZIPMemory(voidpf context,voidpf memory)
466 {
467   (void) context;
468   memory=RelinquishMagickMemory(memory);
469 }
470 #endif
471
472 #if defined(MAGICKCORE_ZLIB_DELEGATE)
473 /** This procedure decompreses an image block for a new MATLAB format. */
474 static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
475 {
476
477 Image *image2;
478 void *CacheBlock, *DecompressBlock;
479 z_stream zip_info;
480 FILE *mat_file;
481 size_t magick_size;
482 size_t extent;
483 int file;
484
485 int status;
486
487   if(clone_info==NULL) return NULL;
488   if(clone_info->file)    /* Close file opened from previous transaction. */
489   {
490     fclose(clone_info->file);
491     clone_info->file = NULL;
492     (void) remove_utf8(clone_info->filename);
493   }
494
495   CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
496   if(CacheBlock==NULL) return NULL;
497   DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
498   if(DecompressBlock==NULL) 
499   {
500     RelinquishMagickMemory(CacheBlock);    
501     return NULL;
502   }
503
504   mat_file=0;
505   file = AcquireUniqueFileResource(clone_info->filename);
506   if (file != -1)
507     mat_file = fdopen(file,"w");
508   if(!mat_file)
509   {
510     RelinquishMagickMemory(CacheBlock);
511     RelinquishMagickMemory(DecompressBlock);
512     (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
513     return NULL;
514   }
515
516   zip_info.zalloc=AcquireZIPMemory;
517   zip_info.zfree=RelinquishZIPMemory;
518   zip_info.opaque = (voidpf) NULL;
519   inflateInit(&zip_info);
520   /* zip_info.next_out = 8*4;*/
521
522   zip_info.avail_in = 0;
523   zip_info.total_out = 0;
524   while(Size>0 && !EOFBlob(orig))
525   {    
526     magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
527     zip_info.next_in = (Bytef *) CacheBlock;
528     zip_info.avail_in = (uInt) magick_size;    
529
530     while(zip_info.avail_in>0)
531     {
532       zip_info.avail_out = 4096;    
533       zip_info.next_out = (Bytef *) DecompressBlock;
534       status = inflate(&zip_info,Z_NO_FLUSH);      
535       extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
536       (void) extent;
537
538       if(status == Z_STREAM_END) goto DblBreak;
539     }
540
541     Size -= magick_size;
542   }
543 DblBreak:
544  
545   (void)fclose(mat_file);
546   RelinquishMagickMemory(CacheBlock);
547   RelinquishMagickMemory(DecompressBlock);
548
549   if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
550   if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;  
551   status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
552   if (status == MagickFalse)
553   {
554     DeleteImageFromList(&image2);    
555 EraseFile:
556     fclose(clone_info->file);
557     clone_info->file = NULL;
558 UnlinkFile:
559     (void) remove_utf8(clone_info->filename);
560     return NULL; 
561   }
562
563   return image2;
564 }
565 #endif
566 \f
567 /*
568 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
569 %                                                                             %
570 %                                                                             %
571 %                                                                             %
572 %   R e a d M A T L A B i m a g e                                             %
573 %                                                                             %
574 %                                                                             %
575 %                                                                             %
576 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
577 %
578 %  ReadMATImage() reads an MAT X image file and returns it.  It
579 %  allocates the memory necessary for the new Image structure and returns a
580 %  pointer to the new image.
581 %
582 %  The format of the ReadMATImage method is:
583 %
584 %      Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
585 %
586 %  A description of each parameter follows:
587 %
588 %    o image:  Method ReadMATImage returns a pointer to the image after
589 %      reading. A null image is returned if there is a memory shortage or if
590 %      the image cannot be read.
591 %
592 %    o image_info: Specifies a pointer to a ImageInfo structure.
593 %
594 %    o exception: return any errors or warnings in this structure.
595 %
596 */
597 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
598 {
599   Image *image, *image2=NULL,
600    *rotated_image;
601   register Quantum *q;
602
603   unsigned int status;
604   MATHeader MATLAB_HDR;
605   size_t size;  
606   size_t CellType;
607   QuantumInfo *quantum_info;
608   ImageInfo *clone_info;
609   int i;
610   ssize_t ldblk;
611   unsigned char *BImgBuff = NULL;
612   double MinVal, MaxVal;
613   unsigned z, z2;
614   unsigned Frames;
615   int logging;
616   int sample_size;
617   MagickOffsetType filepos=0x80;
618   BlobInfo *blob;
619   size_t one;
620   
621   unsigned int (*ReadBlobXXXLong)(Image *image);
622   unsigned short (*ReadBlobXXXShort)(Image *image);
623   void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
624   void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
625
626
627   assert(image_info != (const ImageInfo *) NULL);
628   assert(image_info->signature == MagickSignature);
629   assert(exception != (ExceptionInfo *) NULL);
630   assert(exception->signature == MagickSignature);
631   logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); 
632
633   /*
634      Open image file.
635    */
636   image = AcquireImage(image_info,exception);
637
638   status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
639   if (status == MagickFalse)
640     {
641       image=DestroyImageList(image);
642       return((Image *) NULL);
643     }
644   /*
645      Read MATLAB image.
646    */
647   clone_info=CloneImageInfo(image_info);
648   if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
649     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
650   MATLAB_HDR.Version = ReadBlobLSBShort(image);
651   if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
652     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
653
654   if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"  Endian %c%c",
655         MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
656   if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
657   {
658     ReadBlobXXXLong = ReadBlobLSBLong;
659     ReadBlobXXXShort = ReadBlobLSBShort;
660     ReadBlobDoublesXXX = ReadBlobDoublesLSB;
661     ReadBlobFloatsXXX = ReadBlobFloatsLSB;
662     image->endian = LSBEndian;
663   } 
664   else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
665   {
666     ReadBlobXXXLong = ReadBlobMSBLong;
667     ReadBlobXXXShort = ReadBlobMSBShort;
668     ReadBlobDoublesXXX = ReadBlobDoublesMSB;
669     ReadBlobFloatsXXX = ReadBlobFloatsMSB;
670     image->endian = MSBEndian;
671   }
672   else 
673     goto MATLAB_KO;    /* unsupported endian */
674
675   if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
676 MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
677
678   filepos = TellBlob(image);
679   while(!EOFBlob(image)) /* object parser loop */
680   {
681     Frames = 1;
682     (void) SeekBlob(image,filepos,SEEK_SET);
683     /* printf("pos=%X\n",TellBlob(image)); */
684
685     MATLAB_HDR.DataType = ReadBlobXXXLong(image);
686     if(EOFBlob(image)) break;
687     MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
688     if(EOFBlob(image)) break;
689     filepos += MATLAB_HDR.ObjectSize + 4 + 4;
690
691     image2 = image;
692 #if defined(MAGICKCORE_ZLIB_DELEGATE)
693     if(MATLAB_HDR.DataType == miCOMPRESSED)
694     {
695       image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
696       if(image2==NULL) continue;
697       MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
698     }
699 #endif    
700
701     if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */
702  
703     MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
704     MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);  
705
706     MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
707     MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
708     MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;  
709
710     MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
711     if(image!=image2)
712       MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */
713     MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
714     MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
715     MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
716     MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);  
717    
718
719     switch(MATLAB_HDR.DimFlag)
720     {     
721       case  8: z2=z=1; break;      /* 2D matrix*/
722       case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/
723            (void) ReadBlobXXXLong(image2);
724          if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
725          break;
726       case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */
727          if(z!=3 && z!=1)
728             ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
729            Frames = ReadBlobXXXLong(image2);
730          break;
731       default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
732     }  
733
734     MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
735     MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
736
737     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
738           "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
739     if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && 
740         MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */
741         MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */
742         MATLAB_HDR.StructureClass != mxINT8_CLASS &&
743         MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */
744         MATLAB_HDR.StructureClass != mxINT16_CLASS &&
745         MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */
746         MATLAB_HDR.StructureClass != mxINT32_CLASS &&
747         MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */
748         MATLAB_HDR.StructureClass != mxINT64_CLASS &&
749         MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */
750       ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
751
752     switch (MATLAB_HDR.NameFlag)
753     {
754       case 0:
755         size = ReadBlobXXXLong(image2);  /* Object name string size */
756         size = 4 * (ssize_t) ((size + 3 + 1) / 4);
757         (void) SeekBlob(image2, size, SEEK_CUR);
758         break;
759       case 1:
760       case 2:
761       case 3:
762       case 4:
763         (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
764         break;
765       default:
766         goto MATLAB_KO;
767     }
768
769     CellType = ReadBlobXXXLong(image2);    /* Additional object type */
770     if (logging)
771       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
772         "MATLAB_HDR.CellType: %.20g",(double) CellType);
773   
774     (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */
775
776     NEXT_FRAME:
777     switch (CellType)
778     {
779       case miINT8:
780       case miUINT8:
781         sample_size = 8;
782         if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) 
783           image->depth = 1;
784         else
785           image->depth = 8;         /* Byte type cell */
786         ldblk = (ssize_t) MATLAB_HDR.SizeX;      
787         break;
788       case miINT16:
789       case miUINT16:
790         sample_size = 16;
791         image->depth = 16;        /* Word type cell */
792         ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
793         break;
794       case miINT32:
795       case miUINT32:
796         sample_size = 32;
797         image->depth = 32;        /* Dword type cell */
798         ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);      
799         break;
800       case miINT64:
801       case miUINT64:
802         sample_size = 64;
803         image->depth = 64;        /* Qword type cell */
804         ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);      
805         break;   
806       case miSINGLE:
807         sample_size = 32;
808         image->depth = 32;        /* double type cell */
809         (void) SetImageOption(clone_info,"quantum:format","floating-point");
810         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
811   {              /* complex float type cell */
812   }
813         ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
814         break;
815       case miDOUBLE:
816         sample_size = 64; 
817         image->depth = 64;        /* double type cell */
818         (void) SetImageOption(clone_info,"quantum:format","floating-point");
819 DisableMSCWarning(4127)
820         if (sizeof(double) != 8)
821 RestoreMSCWarning
822           ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
823         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
824   {                         /* complex double type cell */        
825   }
826         ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
827         break;
828       default:
829         ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
830     }
831     (void) sample_size;
832     image->columns = MATLAB_HDR.SizeX;
833     image->rows = MATLAB_HDR.SizeY;    
834     quantum_info=AcquireQuantumInfo(clone_info,image);
835     if (quantum_info == (QuantumInfo *) NULL)
836       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
837     one=1;
838     image->colors = one << image->depth;
839     if (image->columns == 0 || image->rows == 0)
840       goto MATLAB_KO;
841     /* Image is gray when no complex flag is set and 2D Matrix */
842     if ((MATLAB_HDR.DimFlag == 8) &&
843         ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
844       {
845         image->type=GrayscaleType;
846         SetImageColorspace(image,GRAYColorspace,exception);
847       }
848
849
850     /*
851       If ping is true, then only set image size and colors without
852       reading any image data.
853     */
854     if (image_info->ping)
855     {
856       size_t temp = image->columns;
857       image->columns = image->rows;
858       image->rows = temp;
859       goto done_reading; /* !!!!!! BAD  !!!! */
860     }  
861     status=SetImageExtent(image,image->columns,image->rows,exception);
862     if (status == MagickFalse)
863       return(DestroyImageList(image));
864
865   /* ----- Load raster data ----- */
866     BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char));    /* Ldblk was set in the check phase */
867     if (BImgBuff == NULL)
868       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
869
870     MinVal = 0;
871     MaxVal = 0;
872     if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */
873     {
874       CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
875     }
876
877     /* Main loop for reading all scanlines */
878     if(z==1) z=0; /* read grey scanlines */
879     /* else read color scanlines */
880     do
881     {
882       for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
883       {
884         q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
885         if (q == (Quantum *) NULL)
886   {
887     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
888               "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
889     goto done_reading;    /* Skip image rotation, when cannot set image pixels    */
890   }
891         if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
892   {
893     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
894              "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
895     goto ExitLoop;
896   }
897         if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
898         {
899           FixLogical((unsigned char *)BImgBuff,ldblk);
900           if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
901     {
902 ImportQuantumPixelsFailed:
903       if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
904               "  MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
905       break;
906     }
907         }
908         else
909         {
910           if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
911       goto ImportQuantumPixelsFailed;
912
913
914           if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */
915           (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
916       FixSignedValues(image,q,MATLAB_HDR.SizeX);
917         }
918
919         if (!SyncAuthenticPixels(image,exception))
920   {
921     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
922             "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
923     goto ExitLoop;
924   }
925       }
926     } while(z-- >= 2);
927 ExitLoop:
928
929
930     /* Read complex part of numbers here */
931     if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
932     {        /* Find Min and Max Values for complex parts of floats */
933       CellType = ReadBlobXXXLong(image2);    /* Additional object type */
934       i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/
935
936       if (CellType==miDOUBLE || CellType==miSINGLE)
937       {
938         CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);      
939       }
940
941       if (CellType==miDOUBLE)
942         for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
943   {
944           ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
945           InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
946             exception);
947   }
948
949       if (CellType==miSINGLE)
950         for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
951   {
952           ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
953           InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
954             exception);
955   }    
956     }
957
958       /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
959     if ((MATLAB_HDR.DimFlag == 8) &&
960         ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
961       image->type=GrayscaleType;
962     if (image->depth == 1)
963       image->type=BilevelType;
964
965     if(image2==image)
966         image2 = NULL;    /* Remove shadow copy to an image before rotation. */
967
968       /*  Rotate image. */
969     rotated_image = RotateImage(image, 90.0, exception);
970     if (rotated_image != (Image *) NULL)
971     {
972         /* Remove page offsets added by RotateImage */
973       rotated_image->page.x=0;
974       rotated_image->page.y=0;
975
976       blob = rotated_image->blob;
977       rotated_image->blob = image->blob;
978       rotated_image->colors = image->colors;
979       image->blob = blob;
980       AppendImageToList(&image,rotated_image);      
981       DeleteImageFromList(&image);      
982     }
983
984 done_reading:
985
986     if(image2!=NULL)
987       if(image2!=image)
988       {
989         DeleteImageFromList(&image2); 
990   if(clone_info)
991   {
992           if(clone_info->file)
993     {
994             fclose(clone_info->file);
995             clone_info->file = NULL;
996             (void) remove_utf8(clone_info->filename);
997     }
998         }    
999       }
1000
1001       /* Allocate next image structure. */    
1002     AcquireNextImage(image_info,image,exception);
1003     if (image->next == (Image *) NULL) break;                
1004     image=SyncNextImageInList(image);
1005     image->columns=image->rows=0;
1006     image->colors=0;    
1007
1008       /* row scan buffer is no longer needed */
1009     RelinquishMagickMemory(BImgBuff);
1010     BImgBuff = NULL;
1011
1012     if(--Frames>0)
1013     {
1014       z = z2;
1015       if(image2==NULL) image2 = image;
1016       goto NEXT_FRAME;
1017     }
1018     if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */
1019       {
1020 /*  CloseBlob(image2); */
1021         DeleteImageFromList(&image2);
1022         if(clone_info)
1023         {
1024           if(clone_info->file)
1025           {
1026             fclose(clone_info->file);
1027             clone_info->file = NULL;
1028             (void) remove_utf8(clone_info->filename);
1029           }
1030         }
1031         }
1032   }
1033
1034   clone_info=DestroyImageInfo(clone_info);
1035   RelinquishMagickMemory(BImgBuff);
1036   CloseBlob(image);
1037
1038
1039   {
1040     Image *p;    
1041     ssize_t scene=0;
1042     
1043     /*
1044       Rewind list, removing any empty images while rewinding.
1045     */
1046     p=image;
1047     image=NULL;
1048     while (p != (Image *) NULL)
1049       {
1050         Image *tmp=p;
1051         if ((p->rows == 0) || (p->columns == 0)) {
1052           p=p->previous;
1053           DeleteImageFromList(&tmp);
1054         } else {
1055           image=p;
1056           p=p->previous;
1057         }
1058       }
1059     
1060     /*
1061       Fix scene numbers
1062     */
1063     for (p=image; p != (Image *) NULL; p=p->next)
1064       p->scene=scene++;
1065   }
1066
1067   if(clone_info != NULL)  /* cleanup garbage file from compression */
1068   {
1069     if(clone_info->file)
1070     {
1071       fclose(clone_info->file);
1072       clone_info->file = NULL;
1073       (void) remove_utf8(clone_info->filename);
1074     }
1075     DestroyImageInfo(clone_info);
1076     clone_info = NULL;
1077   }
1078   if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1079   if(image==NULL)
1080     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1081   return (image);
1082 }
1083 \f
1084 /*
1085 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1086 %                                                                             %
1087 %                                                                             %
1088 %                                                                             %
1089 %   R e g i s t e r M A T I m a g e                                           %
1090 %                                                                             %
1091 %                                                                             %
1092 %                                                                             %
1093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1094 %
1095 %  Method RegisterMATImage adds attributes for the MAT image format to
1096 %  the list of supported formats.  The attributes include the image format
1097 %  tag, a method to read and/or write the format, whether the format
1098 %  supports the saving of more than one frame to the same file or blob,
1099 %  whether the format supports native in-memory I/O, and a brief
1100 %  description of the format.
1101 %
1102 %  The format of the RegisterMATImage method is:
1103 %
1104 %      size_t RegisterMATImage(void)
1105 %
1106 */
1107 ModuleExport size_t RegisterMATImage(void)
1108 {
1109   MagickInfo
1110     *entry;
1111
1112   entry=SetMagickInfo("MAT");
1113   entry->decoder=(DecodeImageHandler *) ReadMATImage;
1114   entry->encoder=(EncodeImageHandler *) WriteMATImage;
1115   entry->blob_support=MagickFalse;
1116   entry->seekable_stream=MagickTrue;
1117   entry->description=AcquireString("MATLAB level 5 image format");
1118   entry->module=AcquireString("MAT");
1119   (void) RegisterMagickInfo(entry);
1120   return(MagickImageCoderSignature);
1121 }
1122 \f
1123 /*
1124 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1125 %                                                                             %
1126 %                                                                             %
1127 %                                                                             %
1128 %   U n r e g i s t e r M A T I m a g e                                       %
1129 %                                                                             %
1130 %                                                                             %
1131 %                                                                             %
1132 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1133 %
1134 %  Method UnregisterMATImage removes format registrations made by the
1135 %  MAT module from the list of supported formats.
1136 %
1137 %  The format of the UnregisterMATImage method is:
1138 %
1139 %      UnregisterMATImage(void)
1140 %
1141 */
1142 ModuleExport void UnregisterMATImage(void)
1143 {
1144   (void) UnregisterMagickInfo("MAT");
1145 }
1146 \f
1147 /*
1148 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1149 %                                                                             %
1150 %                                                                             %
1151 %                                                                             %
1152 %   W r i t e M A T L A B I m a g e                                           %
1153 %                                                                             %
1154 %                                                                             %
1155 %                                                                             %
1156 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1157 %
1158 %  Function WriteMATImage writes an Matlab matrix to a file.  
1159 %
1160 %  The format of the WriteMATImage method is:
1161 %
1162 %      MagickBooleanType WriteMATImage(const ImageInfo *image_info,
1163 %        Image *image,ExceptionInfo *exception)
1164 %
1165 %  A description of each parameter follows.
1166 %
1167 %    o image_info: Specifies a pointer to a ImageInfo structure.
1168 %
1169 %    o image:  A pointer to an Image structure.
1170 %
1171 %    o exception: return any errors or warnings in this structure.
1172 %
1173 */
1174 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,
1175   ExceptionInfo *exception)
1176 {
1177   ssize_t y;
1178   unsigned z;
1179   register const Quantum *p;
1180
1181   unsigned int status;
1182   int logging;
1183   size_t DataSize;
1184   char padding;
1185   char MATLAB_HDR[0x80];
1186   time_t current_time;
1187   struct tm local_time;
1188   unsigned char *pixels;
1189   int is_gray;
1190
1191   MagickOffsetType
1192     scene;
1193
1194   QuantumInfo
1195     *quantum_info;
1196
1197   /*
1198     Open output image file.
1199   */
1200   assert(image_info != (const ImageInfo *) NULL);
1201   assert(image_info->signature == MagickSignature);
1202   assert(image != (Image *) NULL);
1203   assert(image->signature == MagickSignature);
1204   logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1205   (void) logging;
1206   assert(exception != (ExceptionInfo *) NULL);
1207   assert(exception->signature == MagickSignature);
1208   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1209   if (status == MagickFalse)
1210     return(MagickFalse);
1211   image->depth=8;
1212
1213   current_time=time((time_t *) NULL);
1214 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1215   (void) localtime_r(&current_time,&local_time);
1216 #else
1217   (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time));
1218 #endif
1219   (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1220   FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
1221     "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1222     OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1223     local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1224     local_time.tm_sec,local_time.tm_year+1900);
1225   MATLAB_HDR[0x7C]=0;
1226   MATLAB_HDR[0x7D]=1;
1227   MATLAB_HDR[0x7E]='I';
1228   MATLAB_HDR[0x7F]='M';
1229   (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1230   scene=0;
1231   do
1232   {
1233     (void) TransformImageColorspace(image,sRGBColorspace,exception);
1234     is_gray = IsImageGray(image,exception);
1235     z = is_gray ? 0 : 3;
1236
1237     /*
1238       Store MAT header.
1239     */
1240     DataSize = image->rows /*Y*/ * image->columns /*X*/;
1241     if(!is_gray) DataSize *= 3 /*Z*/;
1242     padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
1243
1244     (void) WriteBlobLSBLong(image, miMATRIX);
1245     (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
1246     (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
1247     (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
1248     (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */  
1249     (void) WriteBlobLSBLong(image, 0);   
1250     (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
1251     (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
1252     (void) WriteBlobLSBLong(image, (unsigned int) image->rows);    /* x: 0xA0 */  
1253     (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */  
1254     if(!is_gray)
1255     {
1256       (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */  
1257       (void) WriteBlobLSBLong(image, 0);
1258     }
1259     (void) WriteBlobLSBShort(image, 1);  /* 0xB0 */  
1260     (void) WriteBlobLSBShort(image, 1);  /* 0xB2 */
1261     (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
1262     (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */  
1263     (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
1264
1265     /*
1266       Store image data.
1267     */
1268     quantum_info=AcquireQuantumInfo(image_info,image);
1269     if (quantum_info == (QuantumInfo *) NULL)
1270       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1271     pixels=GetQuantumPixels(quantum_info);
1272     do
1273     {
1274       for (y=0; y < (ssize_t)image->columns; y++)
1275       {
1276         p=GetVirtualPixels(image,y,0,1,image->rows,exception);
1277         if (p == (const Quantum *) NULL)
1278           break;
1279         (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1280           z2qtype[z],pixels,exception);
1281         (void) WriteBlob(image,image->rows,pixels);
1282       }    
1283       if (SyncAuthenticPixels(image,exception) == MagickFalse)
1284         break;
1285     } while(z-- >= 2);
1286     while(padding-->0) (void) WriteBlobByte(image,0);
1287     quantum_info=DestroyQuantumInfo(quantum_info);
1288     if (GetNextImageInList(image) == (Image *) NULL)
1289       break;
1290     image=SyncNextImageInList(image);
1291     status=SetImageProgress(image,SaveImagesTag,scene++,
1292       GetImageListLength(image));
1293     if (status == MagickFalse)
1294       break;
1295   } while (image_info->adjoin != MagickFalse);
1296   (void) CloseBlob(image);
1297   return(MagickTrue);
1298 }