root / ImageMagick / trunk / coders / mat.c

Revision 12627, 38.7 kB (checked in by cristy, 3 days ago)
Line 
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
47/*
48  Include declarations.
49*/
50#include "magick/studio.h"
51#include "magick/blob.h"
52#include "magick/blob-private.h"
53#include "magick/color-private.h"
54#include "magick/exception.h"
55#include "magick/exception-private.h"
56#include "magick/image.h"
57#include "magick/image-private.h"
58#include "magick/list.h"
59#include "magick/magick.h"
60#include "magick/memory_.h"
61#include "magick/monitor.h"
62#include "magick/monitor-private.h"
63#include "magick/quantum-private.h"
64#include "magick/option.h"
65#include "magick/resource_.h"
66#include "magick/shear.h"
67#include "magick/static.h"
68#include "magick/string_.h"
69#include "magick/module.h"
70#include "magick/transform.h"
71#if defined(MAGICKCORE_ZLIB_DELEGATE)
72 #include "zlib.h"
73#endif
74
75/*
76  Forward declaration.
77*/
78static MagickBooleanType
79  WriteMATImage(const ImageInfo *,Image *);
80
81
82/* Auto coloring method, sorry this creates some artefact inside data
83MinReal+j*MaxComplex = red  MaxReal+j*MaxComplex = black
84MinReal+j*0 = white          MaxReal+j*0 = black
85MinReal+j*MinComplex = blue  MaxReal+j*MinComplex = black
86*/
87
88typedef struct
89{
90  char identific[124];
91  unsigned short Version;
92  char EndianIndicator[2];
93  unsigned long DataType;
94  unsigned long ObjectSize;
95  unsigned long unknown1;
96  unsigned long unknown2;
97
98  unsigned short unknown5;
99  unsigned char StructureFlag;
100  unsigned char StructureClass;
101  unsigned long unknown3;
102  unsigned long unknown4;
103  unsigned long DimFlag;
104
105  unsigned long SizeX;
106  unsigned long SizeY;
107  unsigned short Flag1;
108  unsigned short NameFlag;
109}
110MATHeader;
111
112static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
113static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
114static const char *OsDesc=
115#ifdef __WIN32__
116    "PCWIN";
117#else
118 #ifdef __APPLE__
119    "MAC";
120 #else
121    "LNX86";
122 #endif
123#endif
124
125typedef enum
126  {
127    miINT8 = 1,                 /* 8 bit signed */
128    miUINT8,                    /* 8 bit unsigned */
129    miINT16,                    /* 16 bit signed */
130    miUINT16,                   /* 16 bit unsigned */
131    miINT32,                    /* 32 bit signed */
132    miUINT32,                   /* 32 bit unsigned */
133    miSINGLE,                   /* IEEE 754 single precision float */
134    miRESERVE1,
135    miDOUBLE,                   /* IEEE 754 double precision float */
136    miRESERVE2,
137    miRESERVE3,
138    miINT64,                    /* 64 bit signed */
139    miUINT64,                   /* 64 bit unsigned */
140    miMATRIX,                   /* MATLAB array */
141    miCOMPRESSED,               /* Compressed Data */
142    miUTF8,                     /* Unicode UTF-8 Encoded Character Data */
143    miUTF16,                    /* Unicode UTF-16 Encoded Character Data */
144    miUTF32                     /* Unicode UTF-32 Encoded Character Data */
145  } mat5_data_type;
146
147typedef enum
148  {
149    mxCELL_CLASS=1,             /* cell array */
150    mxSTRUCT_CLASS,             /* structure */
151    mxOBJECT_CLASS,             /* object */
152    mxCHAR_CLASS,               /* character array */
153    mxSPARSE_CLASS,             /* sparse array */
154    mxDOUBLE_CLASS,             /* double precision array */
155    mxSINGLE_CLASS,             /* single precision floating point */
156    mxINT8_CLASS,               /* 8 bit signed integer */
157    mxUINT8_CLASS,              /* 8 bit unsigned integer */
158    mxINT16_CLASS,              /* 16 bit signed integer */
159    mxUINT16_CLASS,             /* 16 bit unsigned integer */
160    mxINT32_CLASS,              /* 32 bit signed integer */
161    mxUINT32_CLASS,             /* 32 bit unsigned integer */
162    mxINT64_CLASS,              /* 64 bit signed integer */
163    mxUINT64_CLASS,             /* 64 bit unsigned integer */
164    mxFUNCTION_CLASS            /* Function handle */
165  } arrayclasstype;
166
167#define FLAG_COMPLEX 0x8
168#define FLAG_GLOBAL  0x4
169#define FLAG_LOGICAL 0x2
170
171static const QuantumType z2qtype[4] = {IndexQuantum, BlueQuantum, GreenQuantum, RedQuantum};
172
173
174static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
175                                  double MaxVal)
176{
177  double f;
178  int x;
179  register PixelPacket *q;
180
181  if (MinVal == 0)
182    MinVal = -1;
183  if (MaxVal == 0)
184    MaxVal = 1;
185
186  q = SetImagePixels(image, 0, y, image->columns, 1);
187  if (q == (PixelPacket *) NULL)
188    return;
189  for (x = 0; x < (long) image->columns; x++)
190  {
191    if (*p > 0)
192    {
193      f = (*p / MaxVal) * (QuantumRange - q->red);
194      if (f + q->red > QuantumRange)
195        q->red = QuantumRange;
196      else
197        q->red += (int) f;
198      if ((int) f / 2.0 > q->green)
199        q->green = q->blue = 0;
200      else
201        q->green = q->blue -= (int) (f / 2.0);
202    }
203    if (*p < 0)
204    {
205      f = (*p / MaxVal) * (QuantumRange - q->blue);
206      if (f + q->blue > QuantumRange)
207        q->blue = QuantumRange;
208      else
209        q->blue += (int) f;
210      if ((int) f / 2.0 > q->green)
211        q->green = q->red = 0;
212      else
213        q->green = q->red -= (int) (f / 2.0);
214    }
215    p++;
216    q++;
217  }
218  if (!SyncImagePixels(image))
219    return;
220  /*          if (image->previous == (Image *) NULL)
221     if (QuantumTick(y,image->rows))
222     MagickMonitor(LoadImageText,image->rows-y-1,image->rows); */
223  return;
224}
225
226
227static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
228                                  double MaxVal)
229{
230  double f;
231  int x;
232  register PixelPacket *q;
233
234  if (MinVal == 0)
235    MinVal = -1;
236  if (MaxVal == 0)
237    MaxVal = 1;
238
239  q = SetImagePixels(image, 0, y, image->columns, 1);
240  if (q == (PixelPacket *) NULL)
241    return;
242  for (x = 0; x < (long) image->columns; x++)
243  {
244    if (*p > 0)
245    {
246      f = (*p / MaxVal) * (QuantumRange - q->red);
247      if (f + q->red > QuantumRange)
248        q->red = QuantumRange;
249      else
250        q->red += (int) f;
251      if ((int) f / 2.0 > q->green)
252        q->green = q->blue = 0;
253      else
254        q->green = q->blue -= (int) (f / 2.0);
255    }
256    if (*p < 0)
257    {
258      f = (*p / MaxVal) * (QuantumRange - q->blue);
259      if (f + q->blue > QuantumRange)
260        q->blue = QuantumRange;
261      else
262        q->blue += (int) f;
263      if ((int) f / 2.0 > q->green)
264        q->green = q->red = 0;
265      else
266        q->green = q->red -= (int) (f / 2.0);
267    }
268    p++;
269    q++;
270  }
271  if (!SyncImagePixels(image))
272    return;
273  /*          if (image->previous == (Image *) NULL)
274     if (QuantumTick(y,image->rows))
275     MagickMonitor(LoadImageText,image->rows-y-1,image->rows); */
276  return;
277}
278
279
280/************** READERS ******************/
281
282/* This function reads one block of floats*/
283static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
284{
285  while (len >= 4)
286  {
287    *data++ = ReadBlobFloat(image);
288    len -= sizeof(float);
289  }
290  if (len > 0)
291    (void) SeekBlob(image, len, SEEK_CUR);
292}
293
294static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
295{
296  while (len >= 4)
297  {
298    *data++ = ReadBlobFloat(image);
299    len -= sizeof(float);
300  }
301  if (len > 0)
302    (void) SeekBlob(image, len, SEEK_CUR);
303}
304
305/* This function reads one block of doubles*/
306static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
307{
308  while (len >= 8)
309  {
310    *data++ = ReadBlobDouble(image);
311    len -= sizeof(double);
312  }
313  if (len > 0)
314    (void) SeekBlob(image, len, SEEK_CUR);
315}
316
317static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
318{
319  while (len >= 8)
320  {
321    *data++ = ReadBlobDouble(image);
322    len -= sizeof(double);
323  }
324  if (len > 0)
325    (void) SeekBlob(image, len, SEEK_CUR);
326}
327
328/* Calculate minimum and maximum from a given block of data */
329static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, unsigned long CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
330{
331MagickOffsetType filepos;
332int i, x;
333void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
334void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
335double *dblrow;
336float *fltrow;
337
338  if (endian_indicator == LSBEndian)
339  {   
340    ReadBlobDoublesXXX = ReadBlobDoublesLSB;
341    ReadBlobFloatsXXX = ReadBlobFloatsLSB;   
342  }
343  else          /* MI */
344  {   
345    ReadBlobDoublesXXX = ReadBlobDoublesMSB;
346    ReadBlobFloatsXXX = ReadBlobFloatsMSB;   
347  }
348
349  filepos = TellBlob(image);       /* Please note that file seeking occurs only in the case of doubles */
350  for (i = 0; i < SizeY; i++)
351  {
352    if (CellType==miDOUBLE)
353    {
354      ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
355      dblrow = (double *)BImgBuff;
356      if (i == 0)
357      {
358        *Min = *Max = *dblrow;
359      }
360      for (x = 0; x < SizeX; x++)
361      {
362        if (*Min > *dblrow)
363          *Min = *dblrow;
364        if (*Max < *dblrow)
365          *Max = *dblrow;
366        dblrow++;
367      }
368    }
369    if (CellType==miSINGLE)
370    {
371      ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
372      fltrow = (float *)BImgBuff;
373      if (i == 0)
374      {
375        *Min = *Max = *fltrow;
376      }
377    for (x = 0; x < (long) SizeX; x++)
378      {
379        if (*Min > *fltrow)
380          *Min = *fltrow;
381        if (*Max < *fltrow)
382          *Max = *fltrow;
383        fltrow++;
384      }
385    }
386  }
387  (void) SeekBlob(image, filepos, SEEK_SET);
388}
389
390
391static void FixSignedValues(PixelPacket *q, int y)
392{
393  while(y-->0)
394  {
395     /* Please note that negative values will overflow
396        Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
397                       <-1;-128> + 127+1 = <0; 127> */
398    q->red += QuantumRange/2 + 1;
399    q->green += QuantumRange/ + 1;
400    q->blue += QuantumRange/ + 1;
401    q++;
402  }
403}
404
405
406/** Fix whole row of logical/binary data. It means pack it. */
407static void FixLogical(unsigned char *Buff,int ldblk)
408{
409unsigned char mask=128;
410unsigned char *BuffL = Buff;
411unsigned char val = 0;
412
413  while(ldblk-->0)
414  {
415    if(*Buff++ != 0)
416      val |= mask;   
417
418    mask >>= 1;
419    if(mask==0)
420    {
421      *BuffL++ = val;
422      val = 0;
423      mask = 128;
424    }   
425     
426  }
427  *BuffL = val;
428}
429
430
431/** This procedure decompreses an image block for a new MATLAB format. */
432static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
433{
434#if defined(MAGICKCORE_ZLIB_DELEGATE)
435
436Image *image2;
437void *CacheBlock, *DecompressBlock;
438z_stream zip_info;
439FILE *mat_file;
440size_t magick_size;
441
442int status;
443
444  if(clone_info==NULL) return NULL;
445  if(clone_info->file)          /* Close file opened from previous transaction. */
446  {
447    fclose(clone_info->file);
448    clone_info->file = NULL;
449    (void) unlink(clone_info->filename);
450  }
451
452  CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
453  if(CacheBlock==NULL) return NULL;
454  DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
455  if(DecompressBlock==NULL)
456  {
457    RelinquishMagickMemory(CacheBlock);   
458    return NULL;
459  }
460
461  mat_file = fdopen(AcquireUniqueFileResource(clone_info->filename),"w");
462  if(!mat_file)
463  {
464    RelinquishMagickMemory(CacheBlock);
465    RelinquishMagickMemory(DecompressBlock);
466    (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
467    return NULL;
468  }
469
470  zip_info.zalloc = (alloc_func) NULL;
471  zip_info.zfree = (free_func) NULL;
472  zip_info.opaque = (voidpf) NULL;
473  inflateInit(&zip_info);
474  /* zip_info.next_out = 8*4;*/
475
476  zip_info.avail_in = 0;
477  zip_info.total_out = 0;
478  while(Size>0 && !EOFBlob(orig))
479  {   
480    magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
481    zip_info.next_in = (Bytef *) CacheBlock;
482    zip_info.avail_in = (uInt) magick_size;   
483
484    while(zip_info.avail_in>0)
485    {
486      zip_info.avail_out = 4096;   
487      zip_info.next_out = (Bytef *) DecompressBlock;
488      status = inflate(&zip_info,Z_NO_FLUSH);     
489      fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
490
491      if(status == Z_STREAM_END) goto DblBreak;
492    }
493
494    Size -= magick_size;
495  }
496DblBreak:
497 
498  (void)fclose(mat_file);
499  RelinquishMagickMemory(CacheBlock);
500  RelinquishMagickMemory(DecompressBlock);
501
502  if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
503  if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile
504  status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
505  if (status == MagickFalse)
506  {
507    DeleteImageFromList(&image2);   
508EraseFile:
509    fclose(clone_info->file);
510    clone_info->file = NULL;
511UnlinkFile:
512    (void) unlink(clone_info->filename);
513    return NULL;
514  }
515
516  return image2;
517#else
518  return NULL;
519#endif
520}
521
522/*
523%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
524%                                                                             %
525%                                                                             %
526%                                                                             %
527%   R e a d M A T L A B i m a g e                                             %
528%                                                                             %
529%                                                                             %
530%                                                                             %
531%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
532%
533%  ReadMATImage() reads an MAT X image file and returns it.  It
534%  allocates the memory necessary for the new Image structure and returns a
535%  pointer to the new image.
536%
537%  The format of the ReadMATImage method is:
538%
539%      Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
540%
541%  A description of each parameter follows:
542%
543%    o image:  Method ReadMATImage returns a pointer to the image after
544%      reading. A null image is returned if there is a memory shortage or if
545%      the image cannot be read.
546%
547%    o image_info: Specifies a pointer to a ImageInfo structure.
548%
549%    o exception: return any errors or warnings in this structure.
550%
551*/
552
553static inline size_t MagickMin(const size_t x,const size_t y)
554{
555  if (x < y)
556    return(x);
557  return(y);
558}
559
560static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
561{
562  Image *image, *image2=NULL,
563   *rotated_image;
564  PixelPacket *q;
565
566  unsigned int status;
567  MATHeader MATLAB_HDR;
568  unsigned long size; 
569  unsigned long CellType;
570  QuantumInfo *quantum_info;
571  ImageInfo *clone_info;
572  int i;
573  long ldblk;
574  unsigned char *BImgBuff = NULL;
575  double MinVal, MaxVal;
576  unsigned long Unknown6;
577  unsigned z;
578  int logging;
579  int sample_size;
580  MagickOffsetType filepos=0x80;
581  BlobInfo *blob;
582 
583  unsigned long (*ReadBlobXXXLong)(Image *image);
584  unsigned short (*ReadBlobXXXShort)(Image *image);
585  void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
586  void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
587
588
589  assert(image_info != (const ImageInfo *) NULL);
590  assert(image_info->signature == MagickSignature);
591  assert(exception != (ExceptionInfo *) NULL);
592  assert(exception->signature == MagickSignature);
593  logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
594
595  /*
596     Open image file.
597   */
598  image = AcquireImage(image_info);
599
600  status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
601  if (status == MagickFalse)
602    {
603      image=DestroyImageList(image);
604      return((Image *) NULL);
605    }
606  /*
607     Read MATLAB image.
608   */
609  clone_info=CloneImageInfo(image_info);
610  if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
611    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
612  MATLAB_HDR.Version = ReadBlobLSBShort(image);
613  if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
614    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
615
616  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"  Endian %c%c",
617        MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
618  if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
619  {
620    ReadBlobXXXLong = ReadBlobLSBLong;
621    ReadBlobXXXShort = ReadBlobLSBShort;
622    ReadBlobDoublesXXX = ReadBlobDoublesLSB;
623    ReadBlobFloatsXXX = ReadBlobFloatsLSB;
624    image->endian = LSBEndian;
625  }
626  else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
627  {
628    ReadBlobXXXLong = ReadBlobMSBLong;
629    ReadBlobXXXShort = ReadBlobMSBShort;
630    ReadBlobDoublesXXX = ReadBlobDoublesMSB;
631    ReadBlobFloatsXXX = ReadBlobFloatsMSB;
632    image->endian = MSBEndian;
633  }
634  else 
635    goto MATLAB_KO;    /* unsupported endian */
636
637  if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
638MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
639
640  filepos = TellBlob(image);
641  while(!EOFBlob(image)) /* object parser loop */
642  {
643    (void) SeekBlob(image,filepos,SEEK_SET);
644    /* printf("pos=%X\n",TellBlob(image)); */
645
646    MATLAB_HDR.DataType = ReadBlobXXXLong(image);
647    if(EOFBlob(image)) break;
648    MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
649    if(EOFBlob(image)) break;
650    filepos += MATLAB_HDR.ObjectSize + 4 + 4;
651
652    image2 = image;
653#if defined(MAGICKCORE_ZLIB_DELEGATE)
654    if(MATLAB_HDR.DataType == miCOMPRESSED)
655    {
656      image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
657      if(image2==NULL) continue;
658      MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
659    }
660#endif   
661
662    if(MATLAB_HDR.DataType!=miMATRIX) continue/* skip another objects. */
663 
664    MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
665    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); 
666
667    MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
668    MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
669    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; 
670
671    MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
672    if(image!=image2)
673      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);    /* ??? don't understand why ?? */
674    MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
675    MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
676    MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
677    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); 
678   
679
680    switch(MATLAB_HDR.DimFlag)
681    {     
682      case  8: z=1; break;                      /* 2D matrix*/
683      case 12: z = ReadBlobXXXLong(image2);     /* 3D matrix RGB*/
684               Unknown6 = ReadBlobXXXLong(image2);
685               if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
686               break;
687      default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
688    } 
689
690    MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
691    MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
692
693    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
694          "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
695    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
696        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&          /* float + complex float */
697        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&          /* double + complex double */
698        MATLAB_HDR.StructureClass != mxINT8_CLASS &&
699        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&           /* uint8 + uint8 3D */
700        MATLAB_HDR.StructureClass != mxINT16_CLASS &&
701        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&          /* uint16 + uint16 3D */
702        MATLAB_HDR.StructureClass != mxINT32_CLASS &&
703        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&          /* uint32 + uint32 3D */
704        MATLAB_HDR.StructureClass != mxINT64_CLASS &&
705        MATLAB_HDR.StructureClass != mxUINT64_CLASS)            /* uint64 + uint64 3D */
706      ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
707
708    switch (MATLAB_HDR.NameFlag)
709    {
710      case 0:
711        size = ReadBlobXXXLong(image2); /* Object name string size */
712        size = 4 * (long) ((size + 3 + 1) / 4);
713        (void) SeekBlob(image2, size, SEEK_CUR);
714        break;
715      case 1:
716      case 2:
717      case 3:
718      case 4:
719        (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
720        break;
721      default:
722        goto MATLAB_KO;
723    }
724
725    CellType = ReadBlobXXXLong(image2);    /* Additional object type */
726    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
727          "MATLAB_HDR.CellType: %ld",CellType);
728 
729    (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */
730
731      /* Image is gray when no complex flag is set and 2D Matrix */
732    if ((MATLAB_HDR.DimFlag == 8) &&
733        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
734      image->type=GrayscaleType;
735
736    switch (CellType)
737    {
738      case miINT8:
739      case miUINT8:
740        sample_size = 8;
741        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
742          image->depth = 1;
743        else
744          image->depth = 8;         /* Byte type cell */
745        ldblk = (long) MATLAB_HDR.SizeX;     
746        break;
747      case miINT16:
748      case miUINT16:
749        sample_size = 16;
750        image->depth = 16;        /* Word type cell */
751        ldblk = (long) (2 * MATLAB_HDR.SizeX);
752        break;
753      case miINT32:
754      case miUINT32:
755        sample_size = 32;
756        image->depth = 32;        /* Dword type cell */
757        ldblk = (long) (4 * MATLAB_HDR.SizeX);     
758        break;
759      case miINT64:
760      case miUINT64:
761        sample_size = 64;
762        image->depth = 64;        /* Qword type cell */
763        ldblk = (long) (8 * MATLAB_HDR.SizeX);     
764        break;   
765      case miSINGLE:
766        sample_size = 32;
767        image->depth = 32;        /* double type cell */
768        (void) SetImageOption(clone_info,"quantum:format","floating-point");
769        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
770        {                                           /* complex float type cell */
771        }
772        ldblk = (long) (4 * MATLAB_HDR.SizeX);
773        break;
774      case miDOUBLE:
775        sample_size = 64;
776        image->depth = 64;        /* double type cell */
777        (void) SetImageOption(clone_info,"quantum:format","floating-point");
778        if (sizeof(double) != 8)
779          ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
780        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
781        {                         /* complex double type cell */       
782        }
783        ldblk = (long) (8 * MATLAB_HDR.SizeX);
784        break;
785      default:
786        ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
787    }
788    image->columns = MATLAB_HDR.SizeX;
789    image->rows = MATLAB_HDR.SizeY;   
790    quantum_info=AcquireQuantumInfo(clone_info,image);
791    image->colors = 1l << image->depth;
792    if (image->columns == 0 || image->rows == 0)
793      goto MATLAB_KO;
794
795    /* ----- Create gray palette ----- */
796
797    if (CellType==miUINT8 && z!=3)
798    {
799      if(image->colors>256) image->colors = 256;
800
801      if (!AcquireImageColormap(image, image->colors))
802      {
803 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
804    }
805
806    /*
807      If ping is true, then only set image size and colors without
808      reading any image data.
809    */
810    if (image_info->ping)
811    {
812      unsigned long temp = image->columns;
813      image->columns = image->rows;
814      image->rows = temp;
815      goto done_reading; /* !!!!!! BAD  !!!! */
816    } 
817
818  /* ----- Load raster data ----- */
819    BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *));    /* Ldblk was set in the check phase */
820    if (BImgBuff == NULL)
821      goto NoMemory;
822
823    MinVal = 0;
824    MaxVal = 0;
825    if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */
826    {
827      CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
828    }
829
830    /* Main loop for reading all scanlines */
831    if(z==1) z=0; /* read grey scanlines */
832                /* else read color scanlines */
833    do
834    {
835      for (i = 0; i < (long) MATLAB_HDR.SizeY; i++)
836      {
837        q=SetImagePixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1);
838        if (q == (PixelPacket *)NULL)
839        {
840          if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
841              "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
842          goto done_reading;            /* Skip image rotation, when cannot set image pixels      */
843        }
844        if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
845        {
846          if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
847             "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
848          goto ExitLoop;
849        }
850        if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
851        {
852          FixLogical((unsigned char *)BImgBuff,ldblk);
853          if(ImportQuantumPixels(image,quantum_info,z2qtype[z],BImgBuff) <= 0)
854          {
855ImportQuantumPixelsFailed:
856            if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
857              "  MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
858            break;
859          }
860        }
861        else
862        {
863          if(ImportQuantumPixels(image,quantum_info,z2qtype[z],BImgBuff) <= 0)
864            goto ImportQuantumPixelsFailed;
865
866
867          if (z<=1 &&                    /* fix only during a last pass z==0 || z==1 */
868                (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
869            FixSignedValues(q,MATLAB_HDR.SizeX);
870        }
871
872        if (!SyncImagePixels(image))
873        {
874          if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
875            "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
876          goto ExitLoop;
877        }
878      }
879    } while(z-- >= 2);
880ExitLoop:
881
882
883    /* Read complex part of numbers here */
884    if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
885    {        /* Find Min and Max Values for complex parts of floats */
886      CellType = ReadBlobXXXLong(image2);    /* Additional object type */
887      i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/
888
889      if (CellType==miDOUBLE || CellType==miSINGLE)
890      {
891        CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);     
892      }
893
894      if (CellType==miDOUBLE)
895        for (i = 0; i < (long) MATLAB_HDR.SizeY; i++)
896        {
897          ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
898          InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
899        }
900
901      if (CellType==miSINGLE)
902        for (i = 0; i < (long) MATLAB_HDR.SizeY; i++)
903        {
904          ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
905          InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
906        }   
907    }
908
909      /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
910    if ((MATLAB_HDR.DimFlag == 8) &&
911        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
912      image->type=GrayscaleType;
913    if (image->depth == 1)
914      image->type=BilevelType;
915
916    if(image2==image)
917        image2 = NULL;    /* Remove shadow copy to an image before rotation. */
918
919      /*  Rotate image. */
920    rotated_image = RotateImage(image, 90.0, exception);
921    if (rotated_image != (Image *) NULL)
922    {
923        /* Remove page offsets added by RotateImage */
924      rotated_image->page.x=0;
925      rotated_image->page.y=0;
926
927      blob = rotated_image->blob;
928      rotated_image->blob = image->blob;
929      rotated_image->colors = image->colors;
930      image->blob = blob;
931      AppendImageToList(&image,rotated_image);     
932      DeleteImageFromList(&image);     
933    }
934
935done_reading:
936
937    if(image2!=NULL)
938      if(image2!=image)
939      {
940        DeleteImageFromList(&image2);
941        if(clone_info)
942        {
943          if(clone_info->file)
944          {
945            fclose(clone_info->file);
946            clone_info->file = NULL;
947            (void) unlink(clone_info->filename);
948          }
949        }   
950      }
951
952      /* Allocate next image structure. */   
953    AcquireNextImage(image_info,image);
954    if (image->next == (Image *) NULL) break;               
955    image=SyncNextImageInList(image);
956    image->columns=image->rows=0;
957    image->colors=0;   
958
959      /* row scan buffer is no longer needed */
960    RelinquishMagickMemory(BImgBuff);
961    BImgBuff = NULL;
962  }
963    clone_info=DestroyImageInfo(clone_info);
964
965  RelinquishMagickMemory(BImgBuff);
966  CloseBlob(image);
967
968
969  {
970    Image *p;   
971    long scene=0;
972   
973    /*
974      Rewind list, removing any empty images while rewinding.
975    */
976    p=image;
977    image=NULL;
978    while (p != (Image *)NULL)
979      {
980        Image *tmp=p;
981        if ((p->rows == 0) || (p->columns == 0)) {
982