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