File Coverage

blib/lib/Data/MATFile.pm
Criterion Covered Total %
statement 208 379 54.8
branch 62 182 34.0
condition 5 24 20.8
subroutine 31 40 77.5
pod 3 30 10.0
total 309 655 47.1


line stmt bran cond sub pod time code
1             package Data::MATFile;
2             require Exporter;
3             @ISA = qw(Exporter);
4             @EXPORT_OK = qw/read_matfile mi2word mx2word/;
5 1     1   31712 use warnings;
  1         3  
  1         33  
6 1     1   5 use strict;
  1         2  
  1         33  
7 1     1   19 use 5.008;
  1         7  
  1         41  
8 1     1   5 use Carp;
  1         1  
  1         218  
9             our $VERSION = 0.02;
10 1     1   8061 use IO::Uncompress::Gunzip qw/gunzip $GunzipError/;
  1         97211  
  1         1295  
11              
12             # Nasty flag for debuggers
13              
14             our $VERBOSE;
15              
16             # Matlab constants
17              
18             # Top-level types
19              
20             use constant {
21 1         353 miINT8 => 1,
22             miUINT8 => 2,
23             miINT16 => 3,
24             miUINT16 => 4,
25             miINT32 => 5,
26             miUINT32 => 6,
27             miSINGLE => 7,
28             miRESERVE1 => 8,
29             miDOUBLE => 9,
30             miRESERVE2 => 10,
31             miRESERVE3 => 11,
32             miINT64 => 12,
33             miUINT64 => 13,
34             miMATRIX => 14,
35             miCOMPRESSED => 15,
36             miUTF8 => 16,
37             miUTF16 => 17,
38             miUTF32 => 18,
39 1     1   12 };
  1         3  
40              
41             my %names = reverse (
42             miINT8 => 1,
43             miUINT8 => 2,
44             miINT16 => 3,
45             miUINT16 => 4,
46             miINT32 => 5,
47             miUINT32 => 6,
48             miSINGLE => 7,
49             miRESERVE1 => 8,
50             miDOUBLE => 9,
51             miRESERVE2 => 10,
52             miRESERVE3 => 11,
53             miINT64 => 12,
54             miUINT64 => 13,
55             miMATRIX => 14,
56             miCOMPRESSED => 15,
57             miUTF8 => 16,
58             miUTF16 => 17,
59             miUTF32 => 18,
60             );
61              
62             # Matrix types
63              
64             use constant {
65 1         3746 mxCELL_CLASS => 1,
66             mxSTRUCT_CLASS => 2,
67             mxOBJECT_CLASS => 3,
68             mxCHAR_CLASS => 4,
69             mxSPARSE_CLASS => 5,
70             mxDOUBLE_CLASS => 6,
71             mxSINGLE_CLASS => 7,
72             mxINT8_CLASS => 8,
73             mxUINT8_CLASS => 9,
74             mxINT16_CLASS => 10,
75             mxUINT16_CLASS => 11,
76             mxINT32_CLASS => 12,
77             mxUINT32_CLASS => 13,
78             mxINT64_CLASS => 14,
79             mxUINT64_CLASS => 15,
80 1     1   5 };
  1         3  
81              
82             my %mx = reverse (
83             mxCELL_CLASS => 1,
84             mxSTRUCT_CLASS => 2,
85             mxOBJECT_CLASS => 3,
86             mxCHAR_CLASS => 4,
87             mxSPARSE_CLASS => 5,
88             mxDOUBLE_CLASS => 6,
89             mxSINGLE_CLASS => 7,
90             mxINT8_CLASS => 8,
91             mxUINT8_CLASS => 9,
92             mxINT16_CLASS => 10,
93             mxUINT16_CLASS => 11,
94             mxINT32_CLASS => 12,
95             mxUINT32_CLASS => 13,
96             mxINT64_CLASS => 14,
97             mxUINT64_CLASS => 15,
98             );
99              
100             # See MATFile.pod for documentation
101              
102             sub mi2word
103             {
104 0     0 1 0 my ($type) = @_;
105 0         0 return $names{$type};
106             }
107              
108             # See MATFile.pod for documentation
109              
110             sub mx2word
111             {
112 0     0 1 0 my ($class) = @_;
113 0         0 return $mx{$class};
114             }
115              
116             # See MATFile.pod for documentation
117              
118             sub read_matfile
119             {
120 1     1 1 12 my ($file_name) = @_;
121 1         5 validate_file_name ($file_name);
122 1         37 my $obj = Data::MATFile->new ($file_name);
123 1         6 $obj->read_file_header ();
124              
125 5         15 again:
126             my $ok = $obj->read_object ();
127 5 100       12 if ($ok) {
128 4         11 goto again;
129             }
130              
131 1         4 return $obj;
132             }
133              
134             # Private functions below this.
135              
136             =head2 read_file_header
137              
138             $obj->read_file_header ();
139              
140             Read the header of the MAT-File. This stores the "descriptive text" of
141             the file in a field
142              
143             $obj->{descriptive_text}
144              
145             It also sets the endian-ness of the file.
146              
147             =cut
148              
149             sub read_file_header
150             {
151 1     1 0 2 my ($obj) = @_;
152 1         5 $obj->{descriptive_text} = $obj->read_bytes (116, 1);
153 1 50       4 if ($obj->{verbose}) {
154 0         0 print "The descriptive text is \"$obj->{descriptive_text}\".\n";
155             }
156 1         4 $obj->{subsys_data_offset} = $obj->read_bytes (8);
157             # Header Flag Fields
158 1         1 my $hff;
159 1         3 $hff = $obj->read_bytes (4, 1);
160 1         6 my ($v, $e) = unpack ("SS", $hff);
161 1 50       4 if ($v != 0x0100) {
162 0         0 carp "$obj->{file_name}: Unknown version $v";
163             }
164 1         5 $obj->set_endianness ($e);
165 1 50       3 if ($obj->{verbose}) {
166 0         0 print "Successfully read file header.\n";
167             }
168 1         2 return;
169             }
170              
171             =head2 validate_file_name
172              
173             validate_file_name ('file-name.mat');
174              
175             Given a file name, make sure that it is not an empty string and that
176             the file exists. This does not return a value since it dies on error.
177              
178             =cut
179              
180             sub validate_file_name
181             {
182 1     1 0 3 my ($file_name) = @_;
183 1 50       3 if (! $file_name) {
184 0         0 croak "supply a file name";
185             }
186 1 50       41 if (! -f $file_name) {
187 0         0 croak "no such file '$file_name'";
188             }
189 1         2 return;
190             }
191              
192             =head2 new
193              
194             my $obj = Data::MATFile->new ('file-name.mat');
195              
196             Start a new object for reading the specified file name. The file name
197             must be supplied, but is not checked (the checking is part of
198             L).
199              
200             =cut
201              
202             sub new
203             {
204 1     1 0 3 my ($package, $file_name) = @_;
205 1         4 my $obj = {
206             file_name => $file_name,
207             };
208 1         3 bless $obj;
209 1         9 $obj->{verbose} = $VERBOSE;
210 1 50       5 if ($obj->{verbose}) {
211 0         0 print <<'EOF';
212             __ __ _ _ _ _
213             \ \ / /__ _ __| |__ ___ ___ ___ ___ | |__ (_) ___ ___| |_
214             \ \ / / _ \ '__| '_ \ / _ \/ __|/ _ \ / _ \| '_ \| |/ _ \/ __| __|
215             \ V / __/ | | |_) | (_) \__ \ __/ | (_) | |_) | | __/ (__| |_
216             \_/ \___|_| |_.__/ \___/|___/\___| \___/|_.__// |\___|\___|\__|
217             |__/
218              
219             EOF
220 0         0 print "File name is $obj->{file_name}.\n";
221             }
222 1         6 $obj->open_matfile ();
223 1         3 return $obj;
224             }
225              
226             =head2 open_matfile
227              
228             $obj->open_matfile ();
229              
230             Open the MAT-File for reading and set up the file handle in the object.
231              
232             =cut
233              
234             sub open_matfile
235             {
236 1     1 0 3 my ($obj) = @_;
237 1         52 open ($obj->{fh}, "<:raw", $obj->{file_name});
238 1 50       5 if (! $obj->{fh}) {
239             # Don't use $obj->error since file not open yet.
240 0         0 croak "could not open $obj->{file_name}: $!";
241             }
242 1         2 return;
243             }
244              
245             =head2 set_endianness
246              
247             $obj->set_endianness ($flag);
248              
249             Set the endian-ness of C<$obj> from C<$flag>, which is part of the
250             header, as read in L.
251              
252             =cut
253              
254             sub set_endianness
255             {
256 1     1 0 2 my ($obj, $flag) = @_;
257 1         4 my $e = chr ($flag / 0x100) . chr ($flag % 0x100);
258 1 50       5 if ($e eq 'MI') {
    0          
259 1         2 $obj->{endian} = 0;
260             }
261             elsif ($e eq 'IM') {
262 0         0 $obj->{endian} = 1;
263 0         0 $obj->error ("Opposite endian-ness files are not supported");
264             }
265             else {
266 0         0 $obj->error ("Endian-ness flag $flag of $obj->{file_name} was not parsed");
267             }
268 1 50       4 if ($obj->{verbose}) {
269 0         0 print "Endian-ness of input file is $obj->{endian}.\n";
270             }
271 1         1 return;
272             }
273              
274             sub set_data
275             {
276 0     0 0 0 my ($obj, $data) = @_;
277 0         0 $obj->{input_data} = $data;
278             }
279              
280             # Data-reading functions
281              
282             =head2 read_object
283              
284             my $array = $obj->read_object ();
285              
286             Read an object from the file.
287              
288             =cut
289              
290             sub read_object
291             {
292 5     5 0 6 my ($obj) = @_;
293 5 50       12 die "bad call" if wantarray != 0;
294 5         12 my ($type, $n_bytes, $data) = $obj->read_data_header ();
295 5 100       14 if ($obj->{eof}) {
296 1         3 return undef;
297             }
298 4 50       13 if ($type == miCOMPRESSED) {
    50          
299 0         0 print "Oh, you have $n_bytes of data.\n";
300 0         0 my $cdata = $obj->read_bytes ($n_bytes);
301 0 0       0 gunzip \$cdata, \my $uncdata
302             or $obj->error ("gunzip failed: $GunzipError");
303 0         0 $obj->set_data ($uncdata);
304 0         0 print "Read again as uncompressed.\n";
305 0         0 my $value = $obj->read_object ();
306 0         0 $obj->set_data (undef);
307 0         0 return $value;
308             }
309             elsif ($type == miMATRIX) {
310 4         11 return $obj->read_matrix ($n_bytes, $data);
311             }
312             else {
313 0         0 my $name = $names{$type};
314 0 0       0 if (! defined $name) {
315 0         0 $name = 'unknown';
316             }
317 0         0 $obj->error ("cannot handle non-matrix data of type $name here");
318             }
319 0         0 return undef;
320             }
321              
322             sub read_matrix
323             {
324 4     4 0 6 my ($obj, $n_bytes, $data) = @_;
325 4 50       10 if ($obj->{verbose}) {
326 0         0 print <<'EOF';
327            
328             __ _ _ __ _ __ __ _ _ _
329             / _` | '__| '__/ _` | | | |
330             | (_| | | | | | (_| | |_| |
331             \__,_|_| |_| \__,_|\__, |
332             |___/
333              
334             EOF
335             }
336 4         21 my ($class) = $obj->read_array_flags ();
337             # Flag for numeric classes.
338 4         11 my $numeric = $obj->is_numeric ($class);
339 4         10 my @dim = $obj->get_array_dimensions ();
340 4         12 my $name = $obj->get_array_name ();
341              
342             # This is the return value. It has to be stored in this
343             # convoluted way because we need to store things like the
344             # "complex" flag and the name of the matrix.
345              
346 4         27 my $matrix = {
347             dimensions => \@dim,
348             name => $name,
349             class => $class,
350             };
351              
352             # Handle the different possible types of matrix data.
353              
354 4 50       9 if ($numeric) {
    0          
    0          
    0          
355 4         12 my $numbers = $obj->get_numeric_array ($class, \@dim);
356 4         11 $matrix->{array} = $numbers,
357             }
358             elsif ($class == mxSTRUCT_CLASS) {
359 0         0 my $field_names = $obj->read_field_names ();
360 0         0 for (0..$#$field_names) {
361 0         0 my $name = $field_names->[$_];
362 0 0       0 if (! $name) {
363 0         0 $obj->error ("no name for element $_");
364             }
365 0         0 my $subarray = $obj->read_matrix ();
366 0         0 $matrix->{array}->{$name} = $subarray;
367             }
368             }
369             elsif ($class == mxCELL_CLASS) {
370 0         0 my $cells = $obj->read_cells (\@dim);
371 0         0 $matrix->{array} = $cells;
372             }
373             elsif ($class == mxCHAR_CLASS) {
374 0         0 my $chars = $obj->read_chars ();
375 0 0       0 if ($obj->{verbose}) {
376 0         0 print "$_: $chars\n";
377             }
378 0         0 $matrix->{array} = $chars;
379             }
380             else {
381              
382             # Unsupported matrix class.
383              
384 0         0 $obj->error ("cannot handle $mx{$class} matrices");
385             }
386              
387 4 50       10 if (! defined $matrix->{array}) {
388 0         0 die "error: empty data section of matrix";
389             }
390 4         13 $obj->{data}->{$matrix->{name}} = $matrix;
391 4         11 return $matrix;
392             }
393              
394             =head2 read_chars
395              
396             my $chars = $obj->read_chars ();
397              
398             Read the characters from a cell matrix consisting of characters.
399              
400             =cut
401              
402             sub read_chars
403             {
404 0     0 0 0 my ($obj) = @_;
405 0         0 my ($type, $n_bytes, $data) = $obj->read_data_header ();
406 0 0       0 if (! $data) {
407 0         0 $data = $obj->read_bytes ($n_bytes);
408             }
409 0         0 my @chars = unpack ("ax" x ($n_bytes/2), $data);
410 0         0 my $chars = join '', @chars;
411 0         0 return $chars;
412             }
413              
414             =head2 read_cells
415              
416             $obj->read_cells ($dim);
417              
418             Read the cells of a mxCELL_CLASS submatrix.
419              
420             =cut
421              
422             sub read_cells
423             {
424 0     0 0 0 my ($obj, $dim) = @_;
425 0 0       0 die "bad call" if wantarray () != 0;
426 0         0 my $n_cells = n_from_dim ($dim);
427 0         0 my @cells;
428 0         0 for (1..$n_cells) {
429 0         0 my $cell = $obj->read_matrix ();
430 0         0 push @cells, $cell;
431             }
432 0         0 return \@cells;
433             }
434              
435             =head2 read_array_flags
436              
437             my ($class) = $obj->read_array_flags ();
438              
439             Read the Array Flags. Currently this only returns the class of the
440             array. For the sake of future expansion, always call in list context.
441              
442             =cut
443              
444             sub read_array_flags
445             {
446 4     4 0 5 my ($obj) = @_;
447 4         6 my ($type, $n_bytes, $data) = $obj->read_data_header ();
448 4 50       10 if ($type != miUINT32) {
449 0         0 $obj->error ("bad type $type for array flags");
450             }
451 4 50       10 if ($n_bytes != 8) {
452 0         0 $obj->error ("array flags $n_bytes not 8 bytes");
453             }
454 4         6 my $f = $obj->read_bytes (8);
455 4         10 my ($x, $y) = unpack ("LL", $f);
456 4         8 my $flags = int ($x / 0x100) % 0x100;
457 4         6 my $complex = $flags & 0x10;
458 4 50       9 if ($obj->{verbose}) {
459 0 0       0 if ($complex) {
460 0         0 print "Is complex.\n";
461             }
462             else {
463 0         0 print "Is not complex.\n";
464             }
465             }
466 4 50       8 if ($complex) {
467 0         0 $obj->error ("Cannot handle complex matrices");
468             }
469 4         5 my $class = $x % 0x100;
470 4 50       84 if ($class > 15) {
471 0         0 carp "Unknown matrix class $class";
472             }
473 4 50       8 if ($obj->{verbose}) {
474 0         0 print "Class is $mx{$class}.\n";
475             }
476 4         8 return ($class);
477             }
478              
479             =head2 read_field_names
480              
481             my $names = $obj->read_field_names ();
482              
483             Read the field names of a "Structure MAT-File Data Element".
484              
485             =cut
486              
487             sub read_field_names
488             {
489 0     0 0 0 my ($obj) = @_;
490 0 0       0 if ($obj->{verbose}) {
491 0         0 print "Reading field names of a structure.\n";
492             }
493 0         0 my ($type, $n_bytes, $data) = $obj->read_data_header ();
494 0 0       0 if ($type != miINT32) {
495 0         0 $obj->error ("wrong type $type for field name length");
496             }
497 0 0       0 if ($n_bytes != 4) {
498 0         0 $obj->error ("wrong number $n_bytes for field name length");
499             }
500 0 0       0 if (! defined $data) {
501 0         0 $obj->error ("Field name length is not provided");
502             }
503 0         0 my $field_name_length = unpack ("l", $data);
504 0 0       0 if ($obj->{verbose}) {
505 0         0 print "Field name length is $field_name_length.\n";
506             }
507 0         0 ($type, $n_bytes, $data) = $obj->read_data_header ();
508 0 0       0 if ($type != miINT8) {
509 0         0 $obj->error ("wrong type $type for field names");
510             }
511 0         0 my $n_names = $n_bytes / $field_name_length;
512 0 0       0 if ($n_names != int ($n_names)) {
513 0         0 $obj->error ("name field bytes $n_bytes not multiple of $field_name_length");
514             }
515             # The list of extracted names.
516 0         0 my @names;
517 0         0 for (1..$n_names) {
518 0         0 my $name = $obj->read_bytes ($field_name_length);
519 0         0 $name = unpack ("A*", $name);
520 0 0       0 if ($obj->{verbose}) {
521 0         0 print "Name: \"$name\"\n";
522             }
523 0         0 push @names, $name;
524             }
525 0         0 return \@names;
526             }
527              
528             =head2
529              
530             if (is_numeric ($class)) {
531              
532             A true or false routine which returns true if C<$class> is a numeric
533             matrix type and false if not.
534              
535             =cut
536              
537             sub is_numeric
538             {
539 4     4 0 5 my ($obj, $class) = @_;
540 4         4 my $numeric;
541 4 0 33     11 if ($class == mxDOUBLE_CLASS ||
      33        
      0        
      0        
      0        
      0        
      0        
542             $class == mxSINGLE_CLASS ||
543             $class == mxINT8_CLASS ||
544             $class == mxUINT8_CLASS ||
545             $class == mxINT16_CLASS ||
546             $class == mxUINT16_CLASS ||
547             $class == mxINT32_CLASS ||
548             $class == mxUINT32_CLASS) {
549 4         6 $numeric = 1;
550             }
551 4 50       9 if ($obj->{verbose}) {
552 0 0       0 if ($numeric) {
553 0         0 print "Numeric.\n";
554             }
555             else {
556 0         0 print "Non-numeric.\n";
557             }
558             }
559 4         6 return $numeric;
560             }
561              
562             =head2 get_numeric_array
563              
564             $array = $obj->get_numeric_array ($class, \@dim);
565              
566             Given an array class for numeric data, C<$class>, and the dimensions
567             of the array, C<@dim>, this returns an array reference of numerical
568             data read from the file handle and arranged into a multidimensional
569             array using C<@dim>.
570              
571             =cut
572              
573             sub get_numeric_array
574             {
575 4     4 0 6 my ($obj, $class, $dim) = @_;
576 4         7 my ($type, $n_bytes, $data) = $obj->read_data_header ();
577 4         7 my $numbers;
578 4 50       8 if ($type == miDOUBLE) {
579 4 50       8 if ($class != mxDOUBLE_CLASS) {
580 0         0 $obj->error ("Mismatch of class and data type");
581             }
582 4         11 $numbers = $obj->get_doubles ($n_bytes);
583             }
584             else {
585 0 0       0 if (! $data) {
586 0         0 $data = $obj->read_bytes ($n_bytes);
587             }
588 0 0       0 if ($type == miINT8) {
    0          
    0          
    0          
    0          
    0          
589 0         0 $numbers = [unpack ("c*", $data)];
590             }
591             elsif ($type == miUINT8) {
592 0         0 $numbers = [unpack ("C*", $data)];
593             }
594             elsif ($type == miINT16) {
595 0         0 $numbers = [unpack ("s*", $data)];
596             }
597             elsif ($type == miUINT16) {
598 0         0 $numbers = [unpack ("S*", $data)];
599             }
600             elsif ($type == miINT32) {
601 0         0 $numbers = [unpack ("l*", $data)];
602             }
603             elsif ($type == miUINT32) {
604 0         0 $numbers = [unpack ("L*", $data)];
605 0         0 print "NUMBERS @$numbers\n";
606             }
607             else {
608 0         0 die "$names{$type} not supported";
609             }
610             }
611 4         78 return $obj->make_n_d_array ($dim, $numbers);
612             }
613              
614             =head2 make_n_d_array
615              
616             my $array = make_n_d_array (\@dim, \@numbers);
617              
618             Make an n-dimensional array with dimensions from C<@dim> with the
619             values in C<@numbers>. For example, if C<@dim = (2, 3)> and
620              
621             @numbers = (1, 2, 3, 4, 5, 6),
622              
623             the return value of this is an array reference formatted as follows:
624              
625             $array = [[1, 2, 3], [4, 5, 6]];
626              
627             using the values in C<@dim>.
628              
629             =cut
630              
631             sub make_n_d_array
632             {
633 4     4 0 7 my ($obj, $dim, $numbers) = @_;
634 4         10 my $n = n_from_dim ($dim);
635 4 50       19 if (scalar @$numbers != $n) {
636 0         0 $obj->error ("Got $n numbers, expected ". (scalar @$numbers));
637             }
638 4         45 my $m = [];
639              
640             # For the two-D case, we can zip through the matrix:
641              
642 4 50       11 if (@$dim == 2) {
643 4         5 my $d = $dim->[0];
644 4         9 for my $i (0..$n - 1) {
645 22         30 my $j = int ($i / $d);
646 22         22 my $k = $i % $d;
647 22         238 $m->[$k][$j] = $numbers->[$i];
648             }
649             }
650             else {
651              
652             # _ _
653             # | |__ ___ __ _ _ _ ___ ___ ___ __| | ___
654             # | '_ \ / _ \ / _` | | | / __| / __/ _ \ / _` |/ _ \
655             # | |_) | (_) | (_| | |_| \__ \ | (_| (_) | (_| | __/
656             # |_.__/ \___/ \__, |\__,_|___/ \___\___/ \__,_|\___|
657             # |___/
658              
659             # This is mega-slow and totally insane
660              
661 0         0 for my $i (0..$n - 1) {
662 0         0 my @i;
663 0         0 my $ij = $i;
664 0         0 for my $j (0..$#$dim) {
665 0         0 my $d = $dim->[$j];
666 0         0 $i[$j] = $ij % $d;
667 0         0 $ij /= $d;
668             }
669 0         0 my $stuff = '$m->[' . join ('][', @i) . ']';
670 0         0 $stuff = "$stuff=$numbers->[$i]";
671             # print "@i $stuff\n";
672            
673             # Horrors!
674              
675 0         0 eval $stuff;
676             }
677             }
678             # for (@$m) {
679             # print "@$_\n";
680             # }
681 4         14 return $m;
682             }
683              
684             =head2 n_from_dim
685              
686             my $n = n_from_dim (\@dim);
687              
688             Given the dimensions of a matrix, return the total number of
689             elements in the matrix.
690              
691             =cut
692              
693             sub n_from_dim
694             {
695 4     4 0 5 my ($dim) = @_;
696 4         4 my $n = 1;
697 4         7 for (@$dim) {
698 8         15 $n *= $_;
699             }
700 4         6 return $n;
701             }
702              
703             =head2 get_doubles
704              
705             my $doubles = $obj->get_doubles ($n_bytes);
706              
707             Get C<$n_bytes / 8> doubles and put them in an array.
708              
709             =cut
710              
711             sub get_doubles
712             {
713 4     4 0 10 my ($obj, $n_bytes) = @_;
714 4 50       9 if ($n_bytes % 8 != 0) {
715 0         0 $obj->error ("Bad byte count $n_bytes for doubles");
716             }
717 4         6 my $n_doubles = $n_bytes / 8;
718 4         7 my $bytes = $obj->read_bytes ($n_bytes);
719 4         5 my @doubles;
720 4         9 for (0..$n_doubles - 1) {
721 22         49 my $double = parse_double (substr ($bytes, $_ * 8, 8));
722 22 50       64 if ($obj->{verbose}) {
723 0         0 printf "Got a $double.\n";
724             }
725 22         67 push @doubles, $double;
726             }
727 4         10 return \@doubles;
728             }
729              
730             =head2 parse_double
731              
732             my $double = parse_double ($bytes);
733              
734             This converts the MAT-File double (eight bytes, the IEEE 754 "double
735             64" format) into a Perl floating point number.
736              
737             =cut
738              
739             # http://www.perlmonks.org/bare/?node_id=703222
740              
741 3     3 0 1559 sub double_from_hex { unpack 'd', scalar reverse pack 'H*', $_[0] }
742              
743 1     1   6 use constant POS_INF => double_from_hex '7FF0000000000000';
  1         2  
  1         3  
744 1     1   4 use constant NEG_INF => double_from_hex 'FFF0000000000000';
  1         2  
  1         3  
745 1     1   5 use constant NaN => double_from_hex '7FF8000000000000';
  1         2  
  1         4  
746              
747             sub parse_double
748             {
749 22     22 0 37 my ($bytes) = @_;
750 22         36 my ($bottom, $top) = unpack ("LL", $bytes);
751             # Reference:
752             # http://en.wikipedia.org/wiki/Double_precision_floating-point_format
753              
754             # Eight zero bytes represents 0.0.
755 22 50       111 if ($bottom == 0) {
    50          
756 0 0       0 if ($top == 0) {
    0          
    0          
    0          
757 0         0 return 0;
758             }
759             elsif ($top == 0x80000000) {
760 0         0 return -0;
761             }
762             elsif ($top == 0x7ff00000) {
763 0         0 return POS_INF;
764             }
765             elsif ($top == 0xfff00000) {
766 0         0 return NEG_INF;
767             }
768             }
769             elsif ($top == 0x7ff00000) {
770 0         0 return NaN;
771             }
772 22         24 my $sign = $top >> 31;
773             # print "$sign\n";
774 22         27 my $exponent = (($top >> 20) & 0x7FF) - 1023;
775             # print "$exponent\n";
776 22         23 my $e = ($top >> 20) & 0x7FF;
777 22         47 my $t = $top & 0xFFFFF;
778             # printf ("--> !%011b%020b \n--> %032b\n", $e, $t, $top);
779 22         35 my $mantissa = ($bottom + ($t*(2**32))) / 2**52 + 1;
780             # print "$mantissa\n";
781 22         53 my $double = (-1)**$sign * 2**$exponent * $mantissa;
782 22         36 return $double;
783             }
784              
785             =head2 get_array_name
786              
787             my $name = $obj->get_array_name ();
788              
789             Get the name of an array from the next point in the file. If the array
790             does not have a name, the return value is the undefined value.
791              
792             =cut
793              
794             sub get_array_name
795             {
796 4     4 0 5 my ($obj) = @_;
797 4 50       10 if ($obj->{verbose}) {
798 0         0 print "Trying to read the array's name.\n";
799             }
800 4         12 my ($type, $n_bytes, $data) = $obj->read_data_header ();
801 4 50       9 if ($type != miINT8) {
802 0         0 $obj->error ("bad type $type for array name");
803             }
804             # Arrays within a struct have name fields with zero bytes.
805 4 50       9 if ($n_bytes == 0) {
806 0         0 return undef;
807             }
808 4 50       22 if (! $data) {
809 4         9 $data = $obj->read_bytes ($n_bytes);
810             }
811             # Remove trailing bytes from the string.
812 4         7 $data = substr $data, 0, $n_bytes;
813 4 50       10 if ($obj->{verbose}) {
814 0         0 print "The array's name is \"$data\".\n";
815             }
816 4         8 return $data;
817             }
818              
819             =head2 get_array_dimensions
820              
821             my @dim = $obj->get_array_dimensions ();
822              
823             Get the dimensions of an array from the file, as an array. Matlab
824             arrays always have at least two dimensions, so @dim is at least size
825             2.
826              
827             =cut
828              
829             sub get_array_dimensions
830             {
831 4 50   4 0 7 die "Bad call" if (! wantarray);
832 4         6 my ($obj) = @_;
833 4         6 my ($type, $n_bytes, $data) = $obj->read_data_header ();
834 4 50       9 if ($type != miINT32) {
835 0         0 $obj->error ("bad type $type for array dimensions");
836             }
837 4         9 my $dim = $obj->read_bytes ($n_bytes);
838 4         15 my @dim = unpack ("L" x ($n_bytes / 4), $dim);
839 4 50       16 if ($obj->{verbose}) {
840 0         0 print "The array's dimensions are @dim.\n";
841             }
842 4         13 return @dim;
843             }
844              
845             =head2 read_data_header
846              
847             my ($type, $n_bytes, $data) = $obj->read_data_header ();
848              
849             Read an eight-byte data header from the file and parse it.
850              
851             =cut
852              
853             sub read_data_header
854             {
855 21     21 0 24 my ($obj) = @_;
856 21 50       47 if ($obj->{verbose}) {
857 0         0 print "Reading data header.\n";
858             }
859 21         110 my $h = $obj->read_bytes (8);
860 21 100       45 if ($obj->{eof}) {
861 1         2 return;
862             }
863 20         104 my ($type, $n_bytes, $data) = $obj->parse_data_header ($h);
864 20         42 return ($type, $n_bytes, $data);
865             }
866              
867              
868             =head2 parse_data_header
869              
870             my ($type, $n_bytes, $data) = $obj->parse_data_header ($h);
871              
872             Parse the data header in C<$h> without reading from the file
873             itself. C<$h> must be eight bytes long.
874              
875             This takes an eight-byte data header and parses out the type and the
876             number of bytes from it. Should this be a Small Data Element Format
877             piece of data, it will also return the value in C<$data>. If C<$data>
878             is undefined, that indicates that it was not a Small Data Element
879             Format piece of data, so the data will need to be read separately.
880              
881             =cut
882              
883             sub parse_data_header
884             {
885 20     20 0 25 my ($obj, $h) = @_;
886 20 50       41 if ($obj->{verbose}) {
887 0         0 print "Parsing data header.\n";
888             }
889 20 50       35 if (length $h != 8) {
890 0         0 $obj->error ("Bad length " . (length $h) . " for data header");
891             }
892 20         21 my $type;
893             my $n_bytes;
894 20         65 ($type, $n_bytes) = unpack ("LL", $h);
895 20         21 my $data;
896 20         28 my $sdef = int ($type / 0x10000);
897 20 50       40 if ($sdef) {
898             # Small Data Element Format
899 0 0       0 if ($obj->{verbose}) {
900 0         0 print "Small Data Element Format with $sdef bytes.\n";
901             }
902 0         0 $n_bytes = $sdef;
903 0         0 $type = $type % 0x10000;
904 0         0 (undef, $data) = unpack ("a4a4", $h);
905             # Remove padding bytes
906 0         0 $data = substr ($data, 0, $n_bytes);
907             }
908 20 50       37 if ($type > 18) {
909 0         0 $obj->warning ("Unknown data type $type");
910             }
911 20 50       48 if ($obj->{verbose}) {
912 0         0 printf "%X: Type and number of bytes are $names{$type} and %u.\n",
913             tell ($obj->{fh}) - 8, $n_bytes;
914             }
915 20         48 return ($type, $n_bytes, $data);
916             }
917              
918             # Basic byte reader
919              
920             =head2 read_bytes
921              
922             my $bytes = $obj->read_bytes ($n_bytes);
923              
924             Read C<$n_bytes> bytes from the MAT-File. It rounds the number up to
925             an eight-byte multiple unless a second, true, argument is given:
926              
927             my $bytes = $obj->read_bytes ($n_bytes, 1);
928              
929             =cut
930              
931             sub read_bytes
932             {
933 40     40 0 56 my ($obj, $n, $no_pad) = @_;
934 40         39 my $r;
935 40         40 my $nbytes = $n;
936 40 50       74 if ($obj->{eof}) {
937 0         0 croak "attempt to read beyond end of $obj->{file_name}";
938             }
939 40 50       76 if ($obj->{verbose}) {
940 0 0       0 if ($no_pad) {
941 0         0 print "Not padding to eight-byte boundary.\n";
942             }
943             }
944 40         37 my $padded;
945             # Round up to eight-byte boundary.
946 40 100 100     157 if (! $no_pad && $n % 8 != 0) {
947 4         5 $nbytes += (8 - $n % 8);
948 4         5 $padded = 1;
949             }
950              
951             # Read from uncompressed data if available.
952              
953 40 50       102 if ($obj->{input_data}) {
954 0         0 print "Reading $nbytes ($n) from uncompressed data.\n";
955 0         0 my $has = length ($obj->{input_data});
956 0 0       0 if ($nbytes > $has) {
957 0         0 $obj->error ("Cannot read $nbytes, only have $has left");
958             }
959 0         0 $r = substr ($obj->{input_data}, 0, $nbytes);
960             # Remove $nbytes bytes from input_data.
961 0         0 $obj->{input_data} = substr ($obj->{input_data}, $nbytes);
962             }
963             else {
964 40         369 my $nread = read ($obj->{fh}, $r, $nbytes);
965 40 50       135 if (! defined $nread) {
966 0         0 $obj->error ("could not read $n bytes: $!");
967             }
968 40 100       146 if ($nread == 0) {
    50          
969 1         4 $obj->{eof} = 1;
970             }
971             elsif ($nread != $nbytes) {
972 0         0 $obj->error ("Tried to read $n bytes and got $nread");
973             }
974             }
975             # If the read data is padded, chop off the padding.
976 40 100       70 if ($padded) {
977 4 50       9 if ($obj->{verbose}) {
978 0         0 print "Chopping padding to length $n.\n";
979             }
980 4         9 $r = substr ($r, 0, $n);
981             }
982 40         123 return $r;
983             }
984              
985             # Error-handlers
986              
987             =head2 error
988              
989             $obj->error ($message);
990              
991             This is for errors during reading of the file. A call to "croak" with
992             C<$message> and the current file location and name taken from C<$obj>.
993              
994             =cut
995              
996             sub error
997             {
998 0     0 0   my ($obj, $message) = @_;
999 0           $message = $obj->error_message ($message);
1000 0           croak $message;
1001             }
1002              
1003             =head2 warning
1004              
1005             $obj->warning ($message);
1006              
1007             This is for warnings during reading of the file. A call to "carp" with
1008             C<$message> and the current file location and name taken from C<$obj>.
1009              
1010             =cut
1011              
1012             sub warning
1013             {
1014 0     0 0   my ($obj, $message) = @_;
1015 0           $message = $obj->error_message ($message);
1016 0           carp $message;
1017             }
1018              
1019             =head2 error_message
1020              
1021             my $message = $obj->error_message ($message);
1022              
1023             Make an error message with the current byte and file name.
1024              
1025             =cut
1026              
1027             sub error_message
1028             {
1029 0     0 0   my ($obj, $message) = @_;
1030 0           my $byte = tell ($obj->{fh});
1031 0           my $hexbyte = sprintf ("%X", $byte);
1032 0           $message = "$message near byte $byte (0x$hexbyte) of $obj->{file_name}";
1033 0           return $message;
1034             }
1035              
1036             1;
1037