blib/lib/EBook/Tools/IMP.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/EBook/Tools/MSReader.pm ↑ Summary blib/lib/EBook/Tools/LZSS.pm »
1 package EBook::Tools::IMP;
2 2 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use version 0.74; our $VERSION = qv("0.4.8");
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # Perl Critic overrides:
7 ## no critic (Package variable)
8 # RequireBriefOpen seems to be way too brief to be useful
9 ## no critic (RequireBriefOpen)
10 # Double-sigils are needed for lexical filehandles in clear print statements
11 ## no critic (Double-sigil dereference)
12  
13 =head1 NAME
14  
15 EBook::Tools::IMP - Object class for manipulating the SoftBook/GEB/REB/eBookWise C<.IMP> and C<.RES> e-book formats
16  
17 =head1 SYNOPSIS
18  
19 use EBook::Tools::IMP qw(:all)
20 my $imp = EBook::Tools::IMP->new();
21 $imp->load('myfile.imp');
22  
23 =cut
24  
25 require Exporter;
26 2 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 our @EXPORT_OK;
29 @EXPORT_OK = qw (
30 &detect_resource_type
31 &parse_imp_resource_v1
32 &parse_imp_resource_v2
33 );
34 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
35  
36 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 2 ▶use Cwd qw(getcwd realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
38 2 ▶use EBook::Tools qw(:all);
Subroutine BEGIN: called CC=1 SCAR=2.6
39 use EBook::Tools::LZSS qw(:all);
40 use Encode;
41 use File::Basename qw(basename dirname fileparse);
42 use File::Path; # Exports 'mkpath' and 'rmtree'
43 use Image::Size;
44 use List::MoreUtils qw(any none);
45 binmode(STDERR,":utf8");
46  
47 my $drmsupport = 0;
48 eval
49 {
50 require EBook::Tools::DRM;
51 EBook::Tools::DRM->import();
52 }; # Trailing semicolon is required here
53 unless($@){ $drmsupport = 1; }
54  
55  
56 # Constants for $self->{device},
57 use constant DEVICE_SB200 => 0; # SoftBook 200/250
58 use constant DEVICE_REB1200 => 1; # REB 1200/GEB 2150
59 use constant DEVICE_EBW1150 => 2; # EBW 1150/GEB 1150
60  
61 use constant IMAGETYPES => ('png','jpg','gif','pic');
62 use constant IMAGERESOURCES => ('GIF ','JPEG','PICT','PIC2','PNG ');
63 my %IMAGE_RESOURCE_MAP = (
64 'GIF ' => 'gif',
65 'JPEG' => 'jpg',
66 'PICT' => 'pic',
67 'PIC2' => 'png',
68 'PNG ' => 'png',
69 );
70  
71  
72 ####################################################
73 ########## CONSTRUCTOR AND INITIALIZATION ##########
74 ####################################################
75  
76 my %rwfields = (
77 'version' => 'integer',
78 'filename' => 'string',
79 'filecount' => 'integer',
80 'resdirlength' => 'integer',
81 'resdiroffset' => 'integer',
82 'compression' => 'integer',
83 'encryption' => 'integer',
84 'device' => 'integer',
85 'zoomstates' => 'integer',
86 'identifier' => 'string',
87 'category' => 'string',
88 'subcategory' => 'string',
89 'title' => 'string',
90 'lastname' => 'string',
91 'middlename' => 'string',
92 'firstname' => 'string',
93 'etiserverdata' => 'hash', # Extra data after book properties
94 'resdirname' => 'string',
95 'RSRC.INF' => 'string',
96 'resfiles' => 'array', # Array of hashrefs
97 'toc' => 'array', # Table of Contents, array of hashes
98 'resources' => 'hash', # Hash of hashrefs keyed on 'type'
99 'lzsslengthbits' => 'integer',
100 'lzssoffsetbits' => 'integer',
101 'text' => 'string', # Uncompressed text
102 'imrn' => 'hash', # Hash of hashes of ImRn resource data
103 'gif' => 'hash', # Hash of hashes of GIF image data
104 'jpg' => 'hash', # Hash of hashes of JPEG image data
105 'pic' => 'hash', # Hash of hashes of PICT image data
106 'png' => 'hash', # Hash of hashes of PNG image data
107 'offsetelements' => 'hash', # Hash of text offsets to HTML elements
108 );
109  
110 my %rofields = (
111 'unknown0x0a' => 'string',
112 'unknown0x18' => 'integer',
113 'unknown0x1c' => 'integer',
114 'unknown0x28' => 'integer',
115 'unknown0x2a' => 'integer',
116 'unknown0x2c' => 'integer',
117 );
118 my %privatefields = (
119 );
120  
121 # A simple 'use fields' will not work here: use takes place inside
122 # BEGIN {}, so the @...fields variables won't exist.
123 require fields;
124 fields->import(
125 keys(%rwfields),keys(%rofields),keys(%privatefields)
126 );
127  
128  
129 =head1 CONSTRUCTOR AND INITIALIZATION
130  
131 =head2 C<new($filename)>
132  
133 Instantiates a new EBook::Tools::IMP object. If C<$filename> is
134 specified, it will also immediately initialize itself via the C<load>
135 method.
136  
137 =cut
138  
139 sub new ## no critic (Always unpack @_ first)
140 {
141 my $self = shift;
142 my $class = ref($self) || $self;
143 my ($filename) = @_;
144 my $subname = (caller(0))[3];
145 debug(2,"DEBUG[",$subname,"]");
146  
147 $self = fields::new($class);
148 if($filename)
149 {
150 $self->{filename} = $filename;
151 $self->load();
152 }
153 return $self;
154 }
155  
156  
157 =head2 C<load($filename)>
158  
159 Loads a .imp file, parsing it into the various object attributes.
160 Returns 1 on success, or undef on failure.
161  
162 =cut
163  
164 sub load :method
165 {
166 my $self = shift;
167 my ($filename) = @_;
168 my $subname = (caller(0))[3];
169 croak($subname . "() called as a procedure!\n") unless(ref $self);
170 debug(2,"DEBUG[",$subname,"]");
171  
172 if(!$self->{filename} and !$filename)
173 {
174 carp($subname,"(): no filename specified!\n");
175 return;
176 }
177  
178 $self->{filename} = $filename if($filename);
179 $filename = $self->{filename} if(!$filename);
180  
181 my $fh_imp;
182 my $headerdata;
183 my $bookpropdata;
184 my $retval;
185 my $toc_size;
186 my $tocdata;
187 my $entrydata;
188 my $resource; # Hashref
189  
190  
191 if(! -f $filename)
192 {
193 carp($subname,"(): '",$filename,"' not found!\n");
194 return;
195 }
196  
197 open($fh_imp,'<:raw',$filename)
198 or croak($subname,"(): unable to open '",$filename,
199 "' for reading!\n");
200 sysread($fh_imp,$headerdata,48);
201 $retval = $self->parse_imp_header($headerdata);
202 if(!$retval)
203 {
204 carp($subname,"(): '",$filename,"' is not an IMP file!\n");
205 return;
206 }
207  
208 if(!$self->{resdiroffset})
209 {
210 carp($subname,"(): '",$filename,"' has no res dir offset!\n");
211 return;
212 }
213 my $bookproplength = $self->{resdiroffset} - 24;
214 sysread($fh_imp,$bookpropdata,$bookproplength);
215 $retval = $self->parse_imp_book_properties($bookpropdata);
216  
217 if(!$self->{resdirlength})
218 {
219 carp($subname,"(): '",$filename,"' has no directory name!\n");
220 return;
221 }
222  
223 sysread($fh_imp,$self->{resdirname},$self->{resdirlength});
224  
225 debug(1,"DEBUG: resource directory = '",$self->{resdirname},"'");
226  
227 if($self->{version} == 1)
228 {
229 $toc_size = 10 * $self->{filecount};
230 sysread($fh_imp,$tocdata,$toc_size)
231 or croak($subname,"(): unable to read TOC data!\n");
232 $self->parse_imp_toc_v1($tocdata);
233  
234 $self->{resources} = ();
235 foreach my $entry (@{$self->{toc}})
236 {
237 sysread($fh_imp,$entrydata,$entry->{size}+10);
238 $resource = parse_imp_resource_v1($entrydata);
239 if($resource->{type} ne $entry->{type})
240 {
241 carp($subname,"():\n",
242 " '",$entry->{type},"' TOC entry pointed to '",
243 $resource->{type},"' resource!\n");
244 }
245 $self->{resources}->{$resource->{type}} = $resource;
246 }
247 }
248 elsif($self->{version} == 2)
249 {
250 $toc_size = 20 * $self->{filecount};
251 sysread($fh_imp,$tocdata,$toc_size)
252 or croak($subname,"(): unable to read TOC data!\n");
253 $self->parse_imp_toc_v2($tocdata);
254  
255 $self->{resources} = ();
256 foreach my $entry (@{$self->{toc}})
257 {
258 sysread($fh_imp,$entrydata,$entry->{size}+20);
259 $resource = parse_imp_resource_v2($entrydata);
260 $self->{resources}->{$resource->{type}} = $resource;
261 }
262 }
263 else
264 {
265 carp($subname,"(): IMP version ",$self->{version}," not supported!\n");
266 return;
267 }
268  
269 $self->parse_resource_images();
270 $self->parse_resource_imrn();
271 $self->parse_text();
272  
273 close($fh_imp)
274 or croak($subname,"(): failed to close '",$filename,"'!\n");
275  
276 debug(3,$self->{text});
277 return 1;
278 }
279  
280  
281 =head2 C<load_resdir($dirname)>
282  
283 Loads a C<.RES> resource directory, parsing it into the object
284 attributes. Returns 1 on success, or undef on failure.
285  
286 =cut
287  
288 sub load_resdir
289 {
290 my $self = shift;
291 my ($dirname) = @_;
292 my $subname = (caller(0))[3];
293 croak($subname . "() called as a procedure!\n") unless(ref $self);
294 debug(2,"DEBUG[",$subname,"]");
295  
296 if(!$dirname)
297 {
298 carp($subname,"(): no resource directory specified!\n");
299 return;
300 }
301  
302 if(! -d $dirname)
303 {
304 carp($subname,"(): resource directory '",$dirname,"' not found!\n");
305 return;
306 }
307  
308 if(! -f $dirname . '/DATA.FRK')
309 {
310 carp($subname,"():\n",
311 " resource directory '",$dirname,"' has no text resource!\n");
312 return;
313 }
314 if(! -f $dirname . '/RSRC.INF')
315 {
316 carp($subname,"()\n",
317 " resource directory '",$dirname,"' has no RSRC.INF!\n");
318 return;
319 }
320  
321 my $fh_resource;
322 my $rsrcinf;
323 my @list;
324  
325 open($fh_resource,'<:raw',$dirname . '/RSRC.INF')
326 or croak($subname,"():\n",
327 " unable to open '$dirname/RSRC.INF' for reading!\n");
328 sysread($fh_resource,$rsrcinf,-s "$dirname/RSRC.INF");
329 close($fh_resource)
330 or croak($subname,"():\n",
331 " unable to close '$dirname/RSRC.INF'!\n");
332  
333 if(length($rsrcinf) < 48)
334 {
335 carp($subname,"():\n",
336 " RSRC.INF is too short (only ",length($rsrcinf)," bytes)!\n");
337 return;
338 }
339  
340 if(substr($rsrcinf,2,8) ne 'BOOKDOUG')
341 {
342 carp($subname,"():\n",
343 " RSRC.INF does not contain a valid header!\n");
344 return;
345 }
346  
347 $self->{resdirname} = basename($dirname);
348 $self->{resdirlength} = length($self->{resdirname});
349 debug(2,"DEBUG: IMP resdir name = ",$self->{resdirname});
350  
351 # We have no idea what to put here, so fill it with nulls
352 $self->{unknown0x0a} = "\x00\x00\x00\x00\x00\x00\x00\x00";
353  
354 # No matter what the RSRC.INF says, we're going to use a v2 format
355 $self->{version} = 2;
356 @list = unpack('nNNNNnCCN',substr($rsrcinf,10,26));
357 $self->{resdiroffset} = $list[0];
358 $self->{unknown0x18} = $list[1];
359 $self->{unknown0x1c} = $list[2];
360 $self->{compression} = $list[3];
361 $self->{encryption} = $list[4];
362 $self->{unknown0x28} = $list[5];
363 $self->{unknown0x2a} = $list[6];
364 $self->{device} = $list[7] >> 4;
365 $self->{zoomstates} = $list[7] & 0x0f;
366 $self->{unknown0x2c} = $list[8];
367  
368 debug(2,"DEBUG: IMP resdir offset = ",$self->{resdiroffset});
369 debug(2,"DEBUG: Unknown 0x18 = ",$self->{unknown0x18});
370 debug(2,"DEBUG: Unknown 0x1c = ",$self->{unknown0x1c});
371 debug(2,"DEBUG: IMP compression = ",$self->{compression});
372 debug(2,"DEBUG: IMP encryption = ",$self->{encryption});
373 debug(2,"DEBUG: Unknown 0x28 = ",$self->{unknown0x28});
374 debug(2,"DEBUG: Unknown 0x2A = ",$self->{unknown0x2a});
375 debug(2,"DEBUG: IMP device = ",$self->{device});
376 debug(2,"DEBUG: IMP zoom state = ",$self->{zoomstates});
377 debug(2,"DEBUG: Unknown 0x2c = ",$self->{unknown0x2c});
378  
379 @list = unpack('Z*Z*Z*Z*Z*Z*Z*',substr($rsrcinf,36));
380 $self->{identifier} = $list[0];
381 $self->{category} = $list[1];
382 $self->{subcategory} = $list[2];
383 $self->{title} = $list[3];
384 $self->{lastname} = $list[4];
385 $self->{middlename} = $list[5];
386 $self->{firstname} = $list[6];
387  
388 my $proplength = $self->bookproplength;
389 if(length($rsrcinf) > $proplength + 36)
390 {
391 debug(1,"Book properties data has extra ETI server data appended");
392 $self->parse_eti_server_data(substr($rsrcinf,$proplength + 36));
393 }
394  
395 my $cwd = getcwd();
396  
397 if(! chdir($dirname))
398 {
399 carp($subname,"(): unable to enter directory '",$dirname,"'!\n");
400 return;
401 }
402  
403 my @filelist = <*>;
404 $self->{resources} = {};
405 $self->{toc} = ();
406 foreach my $file (@filelist)
407 {
408 my $resdata;
409 my %resource;
410 my %tocentry;
411  
412 next if($file eq 'RSRC.INF');
413 unless($file =~ /^ ([A-Z]{4} | DATA\.FRK) $/x)
414 {
415 debug(1,"DEBUG: invalid resource filename '",$file,
416 "' -- skipping");
417 next;
418 }
419 if(-z $file)
420 {
421 debug(1,"DEBUG: resource file '",$file,
422 "' has zero size -- skipping");
423 next;
424 }
425 open($fh_resource,'<:raw',$file)
426 or croak($subname,"():\n",
427 " unable to open '",$file,"' for reading!\n");
428 sysread($fh_resource,$resdata,-s $file);
429 close($fh_resource)
430 or croak($subname,"(): unable to close '",$file,"'!\n");
431 if($file eq 'DATA.FRK')
432 {
433 $resource{name} = ' ';
434 $resource{type} = ' ';
435 }
436 else
437 {
438 $resource{name} = $file;
439 $resource{type} = detect_resource_type(\$resdata);
440 }
441 if(! $resource{type})
442 {
443 debug(1,"DEBUG: unable to determine resource type for file '",
444 $file,"' -- skipping");
445 next;
446 }
447 $resource{unknown1} = 0;
448 $resource{unknown2} = 0;
449 $resource{size} = length($resdata);
450 %tocentry = %resource;
451 push(@{$self->{toc}},\%tocentry);
452  
453 $resource{data} = $resdata;
454 $self->{resources}->{$resource{type}} = \%resource;
455 debug(2,"DEBUG: found resource '",$resource{name},
456 "', type '",$resource{type},"' [",$resource{size}," bytes]");
457 }
458 chdir($cwd);
459  
460 $self->parse_resource_images();
461 $self->parse_resource_imrn();
462 $self->parse_text();
463  
464 return 1;
465 }
466  
467  
468 ######################################
469 ########## ACCESSOR METHODS ##########
470 ######################################
471  
472  
473 =head2 C<author()>
474  
475 Returns the full name of the author of the book.
476  
477 Author information can either be found entirely in the
478 C<< $self->{firstname} >> attribute or split up into
479 C<< $self->{firstname} >>, C<< $self->{middlename} >>, and
480 C<< $self->{lastname} >>. If the last name is found separately,
481 the full name is returned in the format "Last, First Middle".
482 Otherwise, the full name is returned in the format "First Middle".
483  
484 =cut
485  
486 sub author :method
487 {
488 my $self = shift;
489 my $subname = (caller(0))[3];
490 croak($subname . "() called as a procedure!\n") unless(ref $self);
491 debug(2,"DEBUG[",$subname,"]");
492  
493 my $author;
494 if($self->{lastname})
495 {
496 $author = $self->{lastname};
497 if($self->{firstname})
498 {
499 $author .= ", " . $self->{firstname};
500 $author .= " " . $self->{middlename} if($self->{middlename});
501 }
502 }
503 else
504 {
505 $author = $self->{firstname};
506 $author .= " " . $self->{middlename} if($self->{middlename});
507 }
508  
509 return $author;
510 }
511  
512  
513 =head2 C<bookproplength()>
514  
515 Returns the total length in bytes of the book properties data,
516 including the trailing null used to pack the C-style strings, but
517 excluding any ETI server data appended to the end of the standard book
518 properties.
519  
520 =cut
521  
522 sub bookproplength :method
523 {
524 my $self = shift;
525 my $subname = (caller(0))[3];
526 croak($subname . "() called as a procedure!\n") unless(ref $self);
527 debug(2,"DEBUG[",$subname,"]");
528  
529 my $length = 0;
530 $length += length($self->{identifier}) + 1;
531 $length += length($self->{category}) + 1;
532 $length += length($self->{subcategory}) + 1;
533 $length += length($self->{title}) + 1;
534 $length += length($self->{lastname}) + 1;
535 $length += length($self->{middlename}) + 1;
536 $length += length($self->{firstname}) + 1;
537  
538 return $length;
539 }
540  
541  
542 =head2 C<filecount()>
543  
544 Returns the number of resource files as stored in
545 C<< $self->{filecount} >>. Note that this does NOT recompute that value
546 from the actual number of resources in C<< $self->{resources} >>. To do
547 that, use L</create_toc_from_resources()>.
548  
549 =cut
550  
551 sub filecount :method
552 {
553 my $self = shift;
554 my $subname = (caller(0))[3];
555 croak($subname . "() called as a procedure!\n") unless(ref $self);
556 debug(2,"DEBUG[",$subname,"]");
557 return $self->{filecount};
558 }
559  
560  
561 =head2 C<find_image_type($id,@excluded)>
562  
563 Goes through all stored images searching for one with the specified id
564 value, returning the first image type found or undef if there were no
565 matches or if no image id was specified. If the optional argument
566 C<@excluded> is specified, any types in the list will be skipped
567 during the search.
568  
569 Expected types are 'png', 'jpg', 'gif', and 'pic', searched for in
570 that order.
571  
572 This can be used to attempt to locate an alternate image for an
573 undisplayable PICT image.
574  
575 =cut
576  
577 sub find_image_type :method
578 {
579 my $self = shift;
580 my ($id,@excluded) = @_;
581 my $subname = (caller(0))[3];
582 croak($subname . "() called as a procedure!\n") unless(ref $self);
583 debug(2,"DEBUG[",$subname,"]");
584  
585 return unless($id);
586  
587 foreach my $type (IMAGETYPES)
588 {
589 next if(any {$type eq $_} @excluded);
590 return $type if($self->{$type}->{$id});
591 }
592 return;
593 }
594  
595  
596 =head2 C<find_resource_by_name($name)>
597  
598 Takes as a single argument a resource name and if a resource with that
599 name exists in C<< $self->{resources} >> returns the resource type
600 used as the hash key.
601  
602 Returns undef if no match was found or a name was not specified.
603  
604 =cut
605  
606 sub find_resource_by_name :method
607 {
608 my $self = shift;
609 my ($name) = @_;
610 my $subname = (caller(0))[3];
611 croak($subname . "() called as a procedure!\n") unless(ref $self);
612 debug(2,"DEBUG[",$subname,"]");
613  
614 return unless($name);
615 return unless($self->{resources});
616  
617 foreach my $type (keys %{$self->{resources}})
618 {
619 return $type if($self->{resources}->{$type}->{name} eq $name);
620 }
621 return;
622 }
623  
624  
625 =head2 C<image($type,$id)>
626  
627 Returns the image data stored in the resource of the specified type
628 (specifically, stored in C<< $self->{$type}->{$id}->{data} >> as
629 parsed from the JPEG resource) corresponding to the 16-bit identifier
630 provided as C<$id>.
631  
632 Valid values for C<$type> are 'gif','jpg', and 'png'.
633  
634 Carps a warning and returns undef if C<$type> is not provided or is
635 not valid, or if C<$id> is not provided.
636  
637 =cut
638  
639 sub image :method
640 {
641 my $self = shift;
642 my ($type,$id) = @_;
643 my $subname = (caller(0))[3];
644 croak($subname . "() called as a procedure!\n") unless(ref $self);
645 debug(2,"DEBUG[",$subname,"]");
646  
647 if(!$type)
648 {
649 carp($subname,"(): no image type specified!\n");
650 return;
651 }
652 if(none { $type eq $_ } IMAGETYPES)
653 {
654 carp($subname,"(): invalid image type '",$type,"'!\n");
655 return;
656 }
657 if(!$id)
658 {
659 carp($subname,"(): ID not specified!\n");
660 return;
661 }
662 return $self->{$type}->{$id}->{data};
663 }
664  
665  
666 =head2 C<image_hashref($type,$id)>
667  
668 Returns the raw object hashref used to store parsed image data for the
669 specified type, as stored in C<< $self->{$type} >>. Valid types are
670 'gif', 'jpg', and 'png'.
671  
672 Carps a warning and returns undef if C<$type> is not provided or is
673 not valid.
674  
675 If C<$id> is not specified, the keys of the returned hash are the
676 image IDs for the specified image type, and the values are hashrefs
677 pointing to hashes containing the following keys:
678  
679 =over
680  
681 =item * C<unknown>
682  
683 A 16-bit integer only available on EBW 1150 resources. Use with
684 caution. This key may be renamed if more information is found.
685  
686 =item * C<length>
687  
688 The length of the actual image data
689  
690 =item * C<offset>
691  
692 The byte offset inside of the raw resource data in which the JPEG
693 image data can be found.
694  
695 =item * C<const0>
696  
697 An unknown value, but it appears to always be zero. Use with caution.
698 This key may be renamed if more information is found.
699  
700 =back
701  
702 If the optional argument C<$id> is specified, only the hash for that
703 specific ID is returned, rather than the entire hash of hashrefs.
704  
705 =cut
706  
707 sub image_hashref :method
708 {
709 my $self = shift;
710 my ($type,$id) = @_;
711 my $subname = (caller(0))[3];
712 croak($subname . "() called as a procedure!\n") unless(ref $self);
713 debug(2,"DEBUG[",$subname,"]");
714  
715 if(!$type)
716 {
717 carp($subname,"(): no image type specified!\n");
718 return;
719 }
720 if(none { $type eq $_ } IMAGETYPES)
721 {
722 carp($subname,"(): invalid image type '",$type,"'!\n");
723 return;
724 }
725  
726 if($id)
727 {
728 return $self->{$type}->{$id};
729 }
730 return $self->{$type};
731 }
732  
733  
734 =head2 C<image_ids($type)>
735  
736 Returns a list of the 16-bit integer IDs of the the specified type of
737 image data stored in the associated resource (specifically, stored in
738 C<< $self->{$type} >> as parsed from the JPEG resource).
739  
740 Valid types are 'gif', 'jpg', and 'png'. The method will carp a
741 warning and return undef if another type is specified, or no type is
742 specified.
743  
744 =cut
745  
746 sub image_ids :method
747 {
748 my $self = shift;
749 my ($type) = @_;
750 my $subname = (caller(0))[3];
751 croak($subname . "() called as a procedure!\n") unless(ref $self);
752 debug(2,"DEBUG[",$subname,"]");
753  
754 if(!$type)
755 {
756 carp($subname,"(): no image type specified!\n");
757 return;
758 }
759  
760 if(none { $type eq $_ } IMAGETYPES)
761 {
762 carp($subname,"(): invalid image type '",$type,"'!\n");
763 return;
764 }
765  
766 return keys %{$self->{$type}};
767 }
768  
769  
770 =head2 C<is_1150()>
771  
772 Returns 1 if C<< $self->{device} == 2 >>, returns 0 if it is some
773 other value, and undef it is undefined. This has value because
774 resources packed for a EBW 1150 or GEB 1150 are in a different format
775 than resources packed for other IMP readers.
776  
777 =cut
778  
779 sub is_1150
780 {
781 my $self = shift;
782 my $subname = (caller(0))[3];
783 croak($subname . "() called as a procedure!\n") unless(ref $self);
784 debug(2,"DEBUG[",$subname,"]");
785  
786 return if(!defined $self->{device});
787 return 1 if($self->{device} == 2);
788 return 0;
789 }
790  
791  
792 =head2 C<offsetelement($offset)>
793  
794 Returns the text of the element corresponding to the given text offset
795 as stored in C<< $self->{offsetelements} >>, or undef if no such
796 element exists.
797  
798 =cut
799  
800 sub offsetelement :method
801 {
802 my $self = shift;
803 my ($offset) = @_;
804 my $subname = (caller(0))[3];
805 croak($subname . "() called as a procedure!\n") unless(ref $self);
806 debug(2,"DEBUG[",$subname,"]");
807  
808 return unless($offset);
809 return unless($self->{offsetelements});
810 return $self->{offsetelements}->{$offset};
811 }
812  
813  
814 =head2 C<pack_imp_book_properties()>
815  
816 Packs object attributes into the 7 null-terminated strings that
817 constitute the book properties section of the header. Returns that
818 string.
819  
820 Note that this does NOT pack the ETI server data appended to this
821 section in encrypted books downloaded directly from the ETI servers,
822 even if that data was found when the .imp file was loaded. This is
823 because the extra data can confuse the GEBLibrarian application, and
824 is not needed to read the book. The L</bookproplength()> and
825 L</pack_imp_header()> methods also assume that this data will not be
826 present.
827  
828 =cut
829  
830 sub pack_imp_book_properties :method
831 {
832 my $self = shift;
833 my $subname = (caller(0))[3];
834 croak($subname . "() called as a procedure!\n") unless(ref $self);
835 debug(2,"DEBUG[",$subname,"]");
836  
837 my $bookpropdata = pack("Z*Z*Z*Z*Z*Z*Z*",
838 $self->{identifier},
839 $self->{category},
840 $self->{subcategory},
841 $self->{title},
842 $self->{lastname},
843 $self->{middlename},
844 $self->{firstname});
845  
846 return $bookpropdata;
847 }
848  
849  
850 =head2 C<pack_imp_header()>
851  
852 Packs object attributes into the 48-byte string representing the IMP
853 header. Returns that string on success, carps a warning and returns
854 undef if a required attribute did not contain valid data.
855  
856 Note that in the case of an encrypted e-book with ETI server data in
857 it, this header will not be identical to the original -- the
858 resdiroffset value is recalculated for the position with the ETI
859 server data stripped. See L</bookproplength()> and
860 L</pack_imp_book_properties()>.
861  
862 =cut
863  
864 sub pack_imp_header :method
865 {
866 my $self = shift;
867 my $subname = (caller(0))[3];
868 croak($subname . "() called as a procedure!\n") unless(ref $self);
869 debug(2,"DEBUG[",$subname,"]");
870  
871 my $header;
872 my $filecount = scalar(keys %{$self->{resources}});
873 my $resdir = $self->{resdirname};
874  
875 if(!$filecount)
876 {
877 carp($subname,"():\n",
878 " No resources found (has a file been loaded?)\n");
879 return;
880 }
881  
882 if(!$resdir)
883 {
884 carp($subname,"():\n",
885 " No resource directory name specified!\n");
886 return;
887 }
888  
889 if(!$self->{version})
890 {
891 carp($subname,"():\n",
892 " No version specified (has a file been loaded?)\n");
893 return;
894 }
895 if($self->{version} > 2)
896 {
897 carp($subname,"():\n",
898 " invalid version ",$self->{version},"\n");
899 return;
900 }
901  
902 $header = pack('n',$self->{version});
903 $header .= 'BOOKDOUG';
904 if(! $self->{unknown0x0a}
905 or length($self->{unknown0x0a}) != 8)
906 {
907 carp($subname,"():\n",
908 " unknown data at 0x0a has incorrect length",
909 " -- substituting nulls\n");
910 $self->{unknown0x0a} = "\x00\x00\x00\x00\x00\x00\x00\x00";
911 }
912 $header .= $self->{unknown0x0a};
913 $header .= pack('nn',$filecount,length($resdir));
914 $header .= pack('n',$self->bookproplength + 24);
915 $header .= pack('NN',$self->{unknown0x18},$self->{unknown0x1c});
916 $header .= pack('NN',$self->{compression},$self->{encryption});
917 $header .= pack('nC',$self->{unknown0x28},$self->{unknown0x2a});
918 $header .= pack('C',$self->{device} * 16 + $self->{zoomstates});
919 $header .= pack('N',$self->{unknown0x2c});
920  
921 if(length($header) != 48)
922 {
923 croak($subname,"():\n",
924 " total header length not 48 bytes (found ",
925 length($header),")\n");
926 }
927 return $header;
928 }
929  
930  
931 =head2 C<pack_imp_resource(%args)>
932  
933 Packs the specified resource stored in C<< $self->{resources} >> into
934 a a data string suitable for writing into a .imp file, with a header
935 format determined by C<< $self->{version} >>.
936  
937 Returns a reference to that string if the resource was found, or undef
938 it was not.
939  
940 =head3 Arguments
941  
942 =over
943  
944 =item * C<name>
945  
946 Select the resource by resource name.
947  
948 If both this and C<type> are specified, the type is checked first and
949 the name is only used if the type lookup fails.
950  
951 =item * C<type>
952  
953 Select the resource by resource type. This is faster than selecting
954 by name (since resources are stored in a hash keyed by type) and is
955 recommended for most use.
956  
957 If both this and C<name> are specified, the type is checked first and
958 the name is only used if the type lookup fails.
959  
960 =back
961  
962 =cut
963  
964 sub pack_imp_resource :method
965 {
966 my $self = shift;
967 my %args = @_;
968 my $subname = (caller(0))[3];
969 croak($subname . "() called as a procedure!\n") unless(ref $self);
970 debug(2,"DEBUG[",$subname,"]");
971  
972 my %valid_args = (
973 'name' => 1,
974 'type' => 1,
975 );
976 foreach my $arg (keys %args)
977 {
978 croak($subname,"(): invalid argument '",$arg,"'")
979 if(!$valid_args{$arg});
980 }
981 if(!$args{name} and !$args{type})
982 {
983 carp($subname,"():\n",
984 " at least one of name or type must be specified!\n");
985 return;
986 }
987  
988 my $type = $args{type};
989 my $resource;
990 my $resdata;
991  
992 if(!($type and $self->{resources}->{$type}) and $args{name})
993 {
994 $type = $self->find_resource_by_name($args{name});
995 if(!$type or !$self->{resources}->{$type})
996 {
997 carp($subname,"():\n",
998 " no resource with name '",$args{name},"' found!\n");
999 return;
1000 }
1001 }
1002 if(!$self->{resources}->{$type})
1003 {
1004 carp($subname,"()\n",
1005 " no resource with type '",$args{type},"' found!\n");
1006 return;
1007 }
1008  
1009 $resource = $self->{resources}->{$type};
1010 if($self->{version} == 1)
1011 {
1012 $resdata = pack('a[4]nN',
1013 $resource->{name},
1014 $resource->{unknown1},
1015 $resource->{size});
1016 $resdata .= $resource->{data};
1017 }
1018 elsif($self->{version} == 2)
1019 {
1020 $resdata = pack('a[4]NNa[4]N',
1021 $resource->{name},
1022 $resource->{unknown1},
1023 $resource->{size},
1024 $resource->{type},
1025 $resource->{unknown2});
1026 $resdata .= $resource->{data};
1027 }
1028 else
1029 {
1030 carp($subname,"(): invalid version ",$self->{version},"!\n");
1031 return;
1032 }
1033  
1034 if(!$resdata)
1035 {
1036 carp($subname,"(): no resource data packed!\n");
1037 return;
1038 }
1039  
1040 return \$resdata;
1041 }
1042  
1043  
1044 =head2 C<pack_imp_rsrc_inf()>
1045  
1046 Packs object attributes into the data string that would be the content
1047 of the RSRC.INF file. Returns that string.
1048  
1049 =cut
1050  
1051 sub pack_imp_rsrc_inf :method
1052 {
1053 my $self = shift;
1054 my $subname = (caller(0))[3];
1055 croak($subname . "() called as a procedure!\n") unless(ref $self);
1056 debug(2,"DEBUG[",$subname,"]");
1057  
1058 my $rsrc;
1059  
1060 # Data from header
1061 $rsrc = pack('na[8]n',1,'BOOKDOUG',$self->{resdiroffset});
1062 $rsrc .= pack('NNNNnCCN',
1063 $self->{unknown0x18},$self->{unknown0x1c},
1064 $self->{compression},$self->{encryption},
1065 $self->{unknown0x28},$self->{unknown0x2a},
1066 ($self->{device} * 16) + $self->{zoomstates},
1067 $self->{unknown0x2c});
1068  
1069 # Data from book properties
1070 $rsrc .= pack('Z*',$self->{identifier});
1071 $rsrc .= pack('Z*Z*Z*',
1072 $self->{category},$self->{subcategory},$self->{title});
1073 $rsrc .= pack('Z*Z*Z*',
1074 $self->{lastname},$self->{middlename},$self->{firstname});
1075  
1076 if($self->{etiserverdata})
1077 {
1078 my $length = length($rsrc);
1079 my $padsize = length($self->{etiserverdata}->{pad});
1080  
1081 # Pad must result in the following record being 4-byte aligned
1082 if( ($length + $padsize) % 4 )
1083 {
1084 carp($subname,"():\n",
1085 " ETI server data has invalid pad, regenerating it...\n");
1086 undef($self->{etiserverdata}->{pad});
1087 $padsize = $length % 4;
1088 if($padsize)
1089 {
1090 $padsize = 4 - $padsize;
1091 $self->{etiserverdata}->{pad} = pack("a[$padsize]","\0");
1092 }
1093 }
1094  
1095 $rsrc .= $self->{etiserverdata}->{pad};
1096 $rsrc .= pack('NNZ*Z*',
1097 $self->{etiserverdata}->{unknown1},
1098 $self->{etiserverdata}->{issuenumber},
1099 $self->{etiserverdata}->{contentfeed},
1100 $self->{etiserverdata}->{source});
1101 if($self->{etiserverdata}->{unknown2})
1102 {
1103 $rsrc .= pack('N',$self->{etiserverdata}->{unknown2});
1104 }
1105 } # if($self->{etiserverdata}
1106  
1107 return $rsrc;
1108 }
1109  
1110  
1111 =head2 C<pack_imp_toc()>
1112  
1113 Packs the C<< $self->{toc} >> object attribute into a data string
1114 suitable for writing into a .imp file. The format is determined by
1115 C<< $self->{version} >>.
1116  
1117 Returns that string, or undef if valid version or TOC data is not
1118 found.
1119  
1120 =cut
1121  
1122 sub pack_imp_toc :method
1123 {
1124 my $self = shift;
1125 my $subname = (caller(0))[3];
1126 croak($subname . "() called as a procedure!\n") unless(ref $self);
1127 debug(2,"DEBUG[",$subname,"]");
1128  
1129 my $tocdata;
1130  
1131 if(!$self->{version})
1132 {
1133 carp($subname,"():\n",
1134 " no version information found (did you load a file first?)\n");
1135 return;
1136 }
1137 if($self->{version} > 2)
1138 {
1139 carp($subname,"():\n",
1140 " invalid version ",$self->{version},"!\n");
1141 return;
1142 }
1143  
1144 if(!$self->{toc})
1145 {
1146 carp($subname,"(): no TOC data found!\n");
1147 return;
1148 }
1149  
1150 foreach my $entry (@{$self->{toc}})
1151 {
1152 if($self->{version} == 1)
1153 {
1154 $tocdata .= pack('a[4]nN',
1155 $entry->{name},
1156 $entry->{unknown1},
1157 $entry->{size});
1158 }
1159 elsif($self->{version} == 2)
1160 {
1161 $tocdata .= pack('a[4]NNa[4]N',
1162 $entry->{name},
1163 $entry->{unknown1},
1164 $entry->{size},
1165 $entry->{type},
1166 $entry->{unknown2});
1167 }
1168 }
1169  
1170 if(!length($tocdata))
1171 {
1172 carp($subname,"(): no valid TOC data produced!\n");
1173 return;
1174 }
1175  
1176 return $tocdata;
1177 }
1178  
1179  
1180 =head2 C<resdirbase()>
1181  
1182 In scalar context, this returns the basename of C<< $self->{resdirname} >>.
1183 In list context, it actually returns the basename, directory, and
1184 extension as per C<fileparse> from L<File::Basename>.
1185  
1186 =cut
1187  
1188 sub resdirbase :method
1189 {
1190 my $self = shift;
1191 return fileparse($self->{resdirname},'\.\w+$');
1192 }
1193  
1194  
1195 =head2 C<resdirlength()>
1196  
1197 Returns the length of the .RES directory name as stored in
1198 C<< $self->{resdirlength} >>. Note that this does NOT recompute the
1199 length from the actual name stored in C<< $self->{resdirname} >> --
1200 for that, use L</set_resdirlength()>.
1201  
1202 =cut
1203  
1204 sub resdirlength :method
1205 {
1206 my $self = shift;
1207 my $subname = (caller(0))[3];
1208 croak($subname . "() called as a procedure!\n") unless(ref $self);
1209 debug(2,"DEBUG[",$subname,"]");
1210 return $self->{resdirlength};
1211 }
1212  
1213  
1214 =head2 C<resdirname()>
1215  
1216 Returns the .RES directory name stored in C<< $self->{resdirname} >>.
1217  
1218 =cut
1219  
1220 sub resdirname :method
1221 {
1222 my $self = shift;
1223 my $subname = (caller(0))[3];
1224 croak($subname . "() called as a procedure!\n") unless(ref $self);
1225 debug(2,"DEBUG[",$subname,"]");
1226 return $self->{resdirname};
1227 }
1228  
1229  
1230 =head2 C<resource($type)>
1231  
1232 Returns a hashref containing the resource data for the specified
1233 resource type, as stored in C<< $self->{resources}->{$type} >>.
1234  
1235 Returns undef if C<$type> is not specified, or if the specified type
1236 is not found.
1237  
1238 =cut
1239  
1240 sub resource :method
1241 {
1242 my $self = shift;
1243 my ($type) = @_;
1244 my $subname = (caller(0))[3];
1245 croak($subname . "() called as a procedure!\n") unless(ref $self);
1246 debug(2,"DEBUG[",$subname,"]");
1247 return unless($type);
1248 return $self->{resources}->{$type};
1249 }
1250  
1251  
1252 =head2 C<resources()>
1253  
1254 Returns a hashref of hashrefs containing all of the resource data
1255 keyed by type, as stored in C<< $self->{resources} >>.
1256  
1257 =cut
1258  
1259 sub resources :method
1260 {
1261 my $self = shift;
1262 my $subname = (caller(0))[3];
1263 croak($subname . "() called as a procedure!\n") unless(ref $self);
1264 debug(2,"DEBUG[",$subname,"]");
1265 return $self->{resources};
1266 }
1267  
1268  
1269 =head2 C<text()>
1270  
1271 Returns the uncompressed text originally stored in the DATA.FRK
1272 (C<' '>) resource. This will only work if the text was unencrypted.
1273  
1274 =cut
1275  
1276 sub text :method
1277 {
1278 my $self = shift;
1279 my $subname = (caller(0))[3];
1280 croak($subname . "() called as a procedure!\n") unless(ref $self);
1281 debug(2,"DEBUG[",$subname,"]");
1282 return $self->{text};
1283 }
1284  
1285  
1286 =head2 C<title()>
1287  
1288 Returns the book title as stored in C<< $self->{title} >>.
1289  
1290 =cut
1291  
1292 sub title :method
1293 {
1294 my $self = shift;
1295 my $subname = (caller(0))[3];
1296 croak($subname . "() called as a procedure!\n") unless(ref $self);
1297 debug(2,"DEBUG[",$subname,"]");
1298 return $self->{title};
1299 }
1300  
1301  
1302 =head2 C<tocentry($index)>
1303  
1304 Takes as a single argument an integer index to the table of contents
1305 data stored in C<< $self->{toc} >>. Returns the hashref corresponding
1306 to that TOC entry, if it exists, or undef otherwise.
1307  
1308 =cut
1309  
1310 sub tocentry :method
1311 {
1312 my $self = shift;
1313 my ($index) = @_;
1314 my $subname = (caller(0))[3];
1315 croak($subname . "() called as a procedure!\n") unless(ref $self);
1316 debug(2,"DEBUG[",$subname,"]");
1317 return $self->{toc}->[$index];
1318 }
1319  
1320  
1321 =head2 C<version()>
1322  
1323 Returns the version of the IMP format used to determine TOC and
1324 resource metadata size as stored in C<< $self->{version} >>. Expected
1325 values are 1 (10-byte metadata) and 2 (20-byte metadata).
1326  
1327 =cut
1328  
1329 sub version :method
1330 {
1331 my $self = shift;
1332 my $subname = (caller(0))[3];
1333 croak($subname . "() called as a procedure!\n") unless(ref $self);
1334 debug(2,"DEBUG[",$subname,"]");
1335 return $self->{version};
1336 }
1337  
1338  
1339 =head2 C<write_images(%args)>
1340  
1341 Writes the images, if any, to the specified output directory.
1342 Filenames are in the format C<JPEG_XXXX.jpg> or C<PNG_XXXX.png> where
1343 C<XXXX> is the image ID for that image type formatted as four
1344 hexadecimal characters.
1345  
1346 =head3 Arguments
1347  
1348 =over
1349  
1350 =item * C<dir>
1351  
1352 The output directory in which to write the file. This will be created
1353 if it does not exist. Defaults to the basename of the stored resource
1354 directory (see also L</resdirname()>).
1355  
1356 =back
1357  
1358 =cut
1359  
1360 sub write_images :method
1361 {
1362 my $self = shift;
1363 my %args = @_;
1364 my $subname = (caller(0))[3];
1365 croak($subname . "() called as a procedure!\n") unless(ref $self);
1366 debug(2,"DEBUG[",$subname,"]");
1367  
1368 my %valid_args = (
1369 'dir' => 1,
1370 );
1371 foreach my $arg (keys %args)
1372 {
1373 croak($subname,"(): invalid argument '",$arg,"'")
1374 if(!$valid_args{$arg});
1375 }
1376  
1377 my $dirname = $args{dir} || $self->resdirbase;
1378 my $cwd = usedir($dirname);
1379  
1380 foreach my $imagetype (IMAGETYPES)
1381 {
1382 foreach my $id (keys %{$self->{$imagetype}})
1383 {
1384 my $hexid = sprintf('%04X',$id);
1385 my $prefix = uc($imagetype) . '_';
1386 my $filename = "${prefix}${hexid}.${imagetype}";
1387 my $fh_image;
1388  
1389 if(! $self->{$imagetype}->{$id})
1390 {
1391 carp($subname,"(): data for image 0x",$hexid," not found!\n");
1392 next;
1393 }
1394  
1395 if(!open($fh_image,'>:raw',$filename))
1396 {
1397 carp($subname,"():\n",
1398 " unable to open '",$filename,"' for writing!\n");
1399 return;
1400 }
1401 print {*$fh_image} $self->{$imagetype}->{$id}->{data};
1402 if(!close($fh_image))
1403 {
1404 carp($subname,"():\n",
1405 " unable to close '",$filename,"'!\n");
1406 return;
1407 }
1408 } # foreach my $id (keys %{$self->{$imagetype}})
1409 }
1410 chdir($cwd);
1411 return 1;
1412 }
1413  
1414  
1415 =head2 C<write_imp($filename)>
1416  
1417 Takes as a sole argument the name of a file to write to, and writes a
1418 .imp file to that filename using the object attribute data.
1419  
1420 Returns 1 on success, or undef if required data (including the
1421 filename) was invalid or missing, or the file could not be written.
1422  
1423 =cut
1424  
1425 sub write_imp :method
1426 {
1427 my $self = shift;
1428 my ($filename) = @_;
1429 my $subname = (caller(0))[3];
1430 croak($subname . "() called as a procedure!\n") unless(ref $self);
1431 debug(2,"DEBUG[",$subname,"]");
1432  
1433 return unless($filename);
1434  
1435 my $fh_imp;
1436 if(!open($fh_imp,'>:raw',$filename))
1437 {
1438 carp($subname,"():\n",
1439 " unable to open '",$filename,"' for writing!\n");
1440 return;
1441 }
1442  
1443 my $headerdata = $self->pack_imp_header();
1444 my $bookpropdata = $self->pack_imp_book_properties();
1445 my $tocdata = $self->pack_imp_toc;
1446  
1447 if(!$headerdata or length($headerdata) != 48)
1448 {
1449 carp($subname,"(): invalid header data!\n");
1450 return;
1451 }
1452 if(!$bookpropdata)
1453 {
1454 carp($subname,"(): invalid book properties data!\n");
1455 return;
1456 }
1457 if(!$tocdata)
1458 {
1459 carp($subname,"(): invalid table of contents data!\n");
1460 return;
1461 }
1462 if(!$self->{resdirname})
1463 {
1464 carp($subname,"(): invalid .RES directory name!\n");
1465 return;
1466 }
1467 if(!scalar(keys %{$self->{resources}}))
1468 {
1469 carp($subname,"(): no resources found!\n");
1470 return;
1471 }
1472  
1473 print {*$fh_imp} $headerdata;
1474 print {*$fh_imp} $bookpropdata;
1475 print {*$fh_imp} $self->{resdirname};
1476 print {*$fh_imp} $tocdata;
1477  
1478 foreach my $tocentry (@{$self->{toc}})
1479 {
1480 print {*$fh_imp} ${$self->pack_imp_resource(type => $tocentry->{type})};
1481 }
1482  
1483 return 1;
1484 }
1485  
1486  
1487 =head2 C<write_resdir()>
1488  
1489 Writes a C<.RES> resource directory from the object attribute data,
1490 using C<< $self->{resdirname} >> as the directory name.
1491  
1492 =cut
1493  
1494 sub write_resdir :method
1495 {
1496 my $self = shift;
1497 my $subname = (caller(0))[3];
1498 croak($subname . "() called as a procedure!\n") unless(ref $self);
1499 debug(2,"DEBUG[",$subname,"]");
1500  
1501 if(!$self->{resdirname})
1502 {
1503 carp($subname,"(): .RES directory name not known!\n");
1504 return;
1505 }
1506  
1507 my $cwd = getcwd();
1508 my $fh_resource;
1509  
1510 mkpath($self->{resdirname});
1511 if(! -d $self->{resdirname})
1512 {
1513 croak($subname,"():\n",
1514 " unable to create .RES directory '",$self->{resdirname},
1515 "'!\n");
1516 }
1517 chdir($self->{resdirname});
1518  
1519 $self->{'RSRC.INF'} = $self->pack_imp_rsrc_inf;
1520  
1521 if($self->{'RSRC.INF'})
1522 {
1523 open($fh_resource,'>:raw','RSRC.INF')
1524 or croak($subname,"():\n",
1525 " unable to open 'RSRC.INF' for writing!\n");
1526  
1527 print {*$fh_resource} $self->{'RSRC.INF'};
1528 close($fh_resource)
1529 or croak($subname,"():\n",
1530 " unable to close 'RSRC.INF'!\n");
1531 }
1532 else
1533 {
1534 carp($subname,"():\n",
1535 " WARNING: no RSRC.INF data found!\n");
1536 }
1537  
1538 foreach my $restype (keys %{$self->{resources}})
1539 {
1540 my $filename = $self->{resources}->{$restype}->{name};
1541 $filename = 'DATA.FRK' if($filename eq ' ');
1542  
1543 open($fh_resource,'>:raw',$filename)
1544 or croak($subname,"():\n",
1545 " unable to open '",$filename,"' for writing!\n");
1546  
1547 print {*$fh_resource} $self->{resources}->{$restype}->{data};
1548 close($fh_resource)
1549 or croak($subname,"():\n",
1550 " unable to close '",$filename,"'!\n");
1551 }
1552  
1553 chdir($cwd);
1554 return 1;
1555 }
1556  
1557  
1558 =head2 C<write_text(%args)>
1559  
1560 Writes the uncompressed text, if any, to the specified output
1561 directory and file.
1562  
1563 =head3 Arguments
1564  
1565 =over
1566  
1567 =item * C<dir>
1568  
1569 The output directory in which to write the file. This will be created
1570 if it does not exist. Defaults to the basename of the stored resource
1571 directory (see also L</resdirname()>).
1572  
1573 =item * C<filename>
1574  
1575 The filename of the output file to write. If not specified, a warning
1576 will be carped and the method will return undef.
1577  
1578 =back
1579  
1580 =cut
1581  
1582 sub write_text :method
1583 {
1584 my $self = shift;
1585 my %args = @_;
1586 my $subname = (caller(0))[3];
1587 croak($subname . "() called as a procedure!\n") unless(ref $self);
1588 debug(2,"DEBUG[",$subname,"]");
1589  
1590 my %valid_args = (
1591 'dir' => 1,
1592 'filename' => 1,
1593 );
1594 foreach my $arg (keys %args)
1595 {
1596 croak($subname,"(): invalid argument '",$arg,"'")
1597 if(!$valid_args{$arg});
1598 }
1599  
1600 if(!$self->{text})
1601 {
1602 carp($subname,"(): no text to write!\n");
1603 return;
1604 }
1605  
1606 my $dirname = $args{dir} || $self->resdirbase;
1607 my $filename = $args{filename} || $self->resdirbase . '.html';
1608 $filename = $dirname . '/' . $filename;
1609 my $fh_text;
1610  
1611 mkpath($dirname) if(! -d $dirname);
1612  
1613 if(! -d $dirname)
1614 {
1615 carp($subname,"(): unable to create directory '",$dirname,"'!\n");
1616 return;
1617 }
1618  
1619 if(!open($fh_text,'>:raw',$filename))
1620 {
1621 carp($subname,"(): unable to open '",$filename,"' for writing!\n");
1622 return;
1623 }
1624 print {*$fh_text} $self->text;
1625 if(!close($fh_text))
1626 {
1627 carp($subname,"(): unable to close '",$filename,"'!\n");
1628 return;
1629 }
1630  
1631 return 1;
1632 }
1633  
1634  
1635 ######################################
1636 ########## MODIFIER METHODS ##########
1637 ######################################
1638  
1639 =head2 C<create_toc_from_resources()>
1640  
1641 Creates appropriate table of contents data from the metadata in
1642 C<< $self->{resources} >>, in the format specified by
1643 C<< $self->{version} >>. This will also set C<< $self->{filecount} >>
1644 to match the actual number of resources.
1645  
1646 Returns the number of resources found.
1647  
1648 =cut
1649  
1650 sub create_toc_from_resources :method
1651 {
1652 my $self = shift;
1653 my $subname = (caller(0))[3];
1654 croak($subname . "() called as a procedure!\n") unless(ref $self);
1655 debug(2,"DEBUG[",$subname,"]");
1656  
1657 $self->{toc} = ();
1658 return 0 unless($self->{resources});
1659  
1660 foreach my $type (sort keys %{$self->{resources}})
1661 {
1662 my %tocentry;
1663 $tocentry{name} = $self->{resources}->{$type}->{name};
1664 $tocentry{type} = $type;
1665 $tocentry{size} = length($self->{resources}->{$type}->{data});
1666 $tocentry{unknown1} = $self->{resources}->{$type}->{unknown1};
1667 $tocentry{unknown2} = $self->{resources}->{$type}->{unknown2};
1668 push(@{$self->{toc}},\%tocentry);
1669 }
1670  
1671 $self->{filecount} = scalar($self->{toc});
1672 debug(2,"DEBUG: created TOC data from ",$self->{filecount}," records");
1673 return $self->{filecount};
1674 }
1675  
1676  
1677 =head2 C<parse_eti_server_data($data)>
1678  
1679 Parses ETI server data, as potentially found appended to the end of
1680 .imp book properties or a RSRC.INF resource file on encrypted books
1681 downloaded directly from ETI servers.
1682  
1683 Takes as a single argument a string containing just the extra appended
1684 data, and stores the parsed values in C<< $self->{etiserverdata} >> as
1685 a hash. Note that parsing requires knowledge of the length of the
1686 book properties at the time this data was inserted; if the book
1687 properties have not been properly parsed or have been modified, the
1688 resulting behaviour of this method is not defined.
1689  
1690 Returns the number of bytes handled, zero if no data was provided.
1691  
1692 The data has the following format and keys:
1693  
1694 =over
1695  
1696 =item * [0-3 bytes]: padding data to make sure the following data is
1697 4-byte aligned, stored in key C<pad>.
1698  
1699 =item * [4 bytes, big-endian unsigned long int]: unknown value,
1700 usually = 2, stored in key C<unknown1>
1701  
1702 =item * [4 bytes, big-endian unsigned long int]: issue number for
1703 periodicals (always 0xffffffff for books), stored in key
1704 C<issuenumber>.
1705  
1706 =item * [variable-length null-terminated string]: content feed for
1707 periodicals, null string for books, stored in key C<contentfeed>.
1708  
1709 =item * [variable-length null-terminated string]: source string in the
1710 format C<'SOURCE_ID:SOURCE_TYPE:None'>, where C<SOURCE_ID> is usually
1711 '3' and C<SOURCE_TYPE> is usually 'B'.
1712  
1713 =item * [4 bytes, big-endian unsigned long int]: unknown value, stored
1714 in key C<unknown2>. This value may not be present at all.
1715  
1716 =back
1717  
1718 =cut
1719  
1720 sub parse_eti_server_data :method
1721 {
1722 my $self = shift;
1723 my ($data) = @_;
1724 my $subname = (caller(0))[3];
1725 croak($subname . "() called as a procedure!\n") unless(ref $self);
1726 debug(2,"DEBUG[",$subname,"]");
1727  
1728 return 0 unless($data);
1729  
1730 my $proplength = $self->bookproplength;
1731 my $length = length($data);
1732 if($length < 10)
1733 {
1734 carp($subname,"():\n",
1735 " data is too short to contain ETI server data! [",
1736 $length," bytes]\n");
1737 return 0;
1738 }
1739  
1740 $self->{etiserverdata} = {};
1741  
1742 # Up to 3 bytes of padding to make sure that the following data is
1743 # 4-byte aligned.
1744 my $padlength = $proplength % 4;
1745 my @list;
1746 if($padlength)
1747 {
1748 $padlength = 4 - $padlength;
1749 $self->{etiserverdata}->{pad} = substr($data,0,$padlength);
1750 $proplength += $padlength;
1751 }
1752  
1753 @list = unpack('NNZ*Z*N',substr($data,$padlength));
1754 $self->{etiserverdata}->{unknown1} = $list[0];
1755 $self->{etiserverdata}->{issuenumber} = $list[1];
1756 $self->{etiserverdata}->{contentfeed} = $list[2];
1757 $self->{etiserverdata}->{source} = $list[3];
1758 $self->{etiserverdata}->{unknown2} = $list[4];
1759 debug(2," pad=",hexstring($self->{etiserverdata}->{pad}))
1760 if($self->{etiserverdata}->{pad});
1761 debug(2,
1762 " unknown1=",$list[0]," \t\tissuenumber=",$list[1],"\n",
1763 " contentfeed='",$list[2],"' \tsource='",$list[3],"'");
1764 debug(2," unknown2=",$list[4]) if(defined $list[4]);
1765  
1766 return($length);
1767 }
1768  
1769  
1770 =head2 C<parse_imp_book_properties($propdata)>
1771  
1772 Takes as a single argument a string containing the book properties
1773 data. Sets the object variables from its contents, which should be
1774 seven null-terminated strings in the following order:
1775  
1776 =over
1777  
1778 =item * Identifier
1779  
1780 =item * Category
1781  
1782 =item * Subcategory
1783  
1784 =item * Title
1785  
1786 =item * Last Name
1787  
1788 =item * Middle Name
1789  
1790 =item * First Name
1791  
1792 =back
1793  
1794 Note that the entire name is frequently placed into the "First Name"
1795 component, and the "Last Name" and "Middle Name" components are left
1796 blank.
1797  
1798 In addition, ETI server data may be appended to this data on encrypted
1799 books downloaded from ETI servers. If present, that data will be
1800 stored in the hash C<< $self->{etiserverdata} >>. See
1801 L</parse_eti_server_data($data)> for details.
1802  
1803 A warning will be carped if the length of the parsed properties
1804 (including the C null string terminators) is not equal to the length
1805 of the data passed.
1806  
1807 =cut
1808  
1809 sub parse_imp_book_properties :method
1810 {
1811 my $self = shift;
1812 my ($propdata) = @_;
1813 my $subname = (caller(0))[3];
1814 croak($subname . "() called as a procedure!\n") unless(ref $self);
1815 debug(2,"DEBUG[",$subname,"]");
1816  
1817 my @properties = unpack("Z*Z*Z*Z*Z*Z*Z*",$propdata);
1818 if(scalar(@properties) != 7)
1819 {
1820 carp($subname,"(): WARNING: expected 7 book properties, but found ",
1821 scalar(@properties),"!\n");
1822 }
1823  
1824 $self->{identifier} = $properties[0];
1825 $self->{category} = $properties[1];
1826 $self->{subcategory} = $properties[2];
1827 $self->{title} = $properties[3];
1828 $self->{lastname} = $properties[4];
1829 $self->{middlename} = $properties[5];
1830 $self->{firstname} = $properties[6];
1831  
1832 debug(2,"DEBUG: found ",scalar(@properties)," properties: ");
1833 debug(2," Identifier: ",$self->{identifier});
1834 debug(2," Category: ",$self->{category});
1835 debug(2," Subcategory: ",$self->{subcategory});
1836 debug(2," Title: ",$self->{title});
1837 debug(2," Last Name: ",$self->{lastname});
1838 debug(2," Middle Name: ",$self->{middlename});
1839 debug(2," First Name: ",$self->{firstname});
1840  
1841  
1842 # On encrypted files, there may be addtional ETI server data
1843 # appended
1844 my $proplength = $self->bookproplength;
1845 if($proplength < length($propdata))
1846 {
1847 debug(1,"Book properties data has extra ETI server data appended");
1848 $self->parse_eti_server_data(substr($propdata,$proplength));
1849 }
1850 return 1;
1851 }
1852  
1853  
1854 =head2 C<parse_imp_header()>
1855  
1856 Parses the first 48 bytes of a .IMP file, setting object variables.
1857 The method croaks if it receives any more or less than 48 bytes.
1858  
1859 =head3 Header Format
1860  
1861 =over
1862  
1863 =item * Offset 0x00 [2 bytes, big-endian unsigned short int]
1864  
1865 Version. Expected values are 1 or 2; the version affects the format
1866 of the table of contents header. If this isn't 1 or 2, the method
1867 carps a warning and returns undef.
1868  
1869 =item * Offset 0x02 [8 bytes]
1870  
1871 Identifier. This is always 'BOOKDOUG', and the method carps a warning
1872 and returns undef if it isn't.
1873  
1874 =item * Offset 0x0A [8 bytes]
1875  
1876 Unknown data, stored in C<< $self->{unknown0x0a} >>. Use with caution
1877 -- this value may be renamed if more information is obtained.
1878  
1879 =item * Offset 0x12 [2 bytes, big-endian unsigned short int]
1880  
1881 Number of included files, stored in C<< $self->{filecount} >>.
1882  
1883 =item * Offset 0x14 [2 bytes, big-endian unsigned short int]
1884  
1885 Length in bytes of the .RES directory name, stored in
1886 C<< $self->{resdirlength} >>.
1887  
1888 =item * Offset 0x16 [2 bytes, big-endian unsigned short int]
1889  
1890 Offset from the point after this value to the .RES directory name,
1891 which also marks the end of the book properties, stored in
1892 C<< $self->{resdiroffset} >>. Note that this is NOT the length of the
1893 book properties. To get the length of the book properties, subtract
1894 24 from this value (the number of bytes remaining in the header after
1895 this point). It is also NOT the offset from the beginning of the file
1896 to the .RES directory name -- to find that, add 24 to this value (the
1897 number of bytes already parsed).
1898  
1899 =item * Offset 0x18 [4 bytes, big-endian unsigned long int?]
1900  
1901 Unknown value, stored in C<< $self->{unknown0x18} >>. Use with
1902 caution -- this value may be renamed if more information is obtained.
1903  
1904 =item * Offset 0x1C [4 bytes, big-endian unsigned long int?]
1905  
1906 Unknown value, stored in C<< $self->{unknown0x1c} >>. Use with
1907 caution -- this value may be renamed if more information is obtained.
1908  
1909 =item * Offset 0x20 [4 bytes, big-endian unsigned long int]
1910  
1911 Compression type, stored in C<< $self->{compression} >>. Expected
1912 values are 0 (no compression) and 1 (LZSS compression).
1913  
1914 =item * Offset 0x24 [4 bytes, big-endian unsigned long int]
1915  
1916 Encryption type, stored in C<< $self->{encryption} >>. Expected
1917 values are 0 (no encryption) and 2 (DES encryption).
1918  
1919 =item * Offset 0x28 [2 bytes, big-ending unsigned short int]
1920  
1921 Unknown value, stored in C<< $self->{unknown0x28} >>. Use with
1922 caution -- this value may be renamed if more information is obtained.
1923  
1924 =item * Offset 0x2A [1 byte]
1925  
1926 Unknown value, stored in C<< $self->{unknown0x2A} >>. Use with
1927 caution -- this value may be renamed if more information is obtained.
1928  
1929 =item * Offset 0x2B [2 nybbles (1 byte)]
1930  
1931 The upper nybble at this position is the IMP reader device for which the
1932 e-book was designed, stored in C<< $self->{device} >>. Expected values
1933 are 0 (Softbook 200/250e), 1 (REB 1200/GEB 2150), and 2 (EBW
1934 1150/GEB1150).
1935  
1936 The lower nybble marks the possible zoom states, stored in
1937 C<< $self->{zoomstates} >>. Expected values are 0 (both zooms), 1
1938 (small zoom), and 2 (large zoom)
1939  
1940 =item * Offset 0x2C [4 bytes, big-endian unsigned long int]
1941  
1942 Unknown value, stored in C<< $self->{unknown0x2c} >>. Use with
1943 caution -- this value may be renamed if more information is obtained.
1944  
1945 =back
1946  
1947 =cut
1948  
1949 sub parse_imp_header :method
1950 {
1951 my $self = shift;
1952 my ($headerdata) = @_;
1953 my $subname = (caller(0))[3];
1954 croak($subname . "() called as a procedure!\n") unless(ref $self);
1955 debug(2,"DEBUG[",$subname,"]");
1956  
1957 my $length = length($headerdata);
1958 if($length != 48)
1959 {
1960 croak($subname,"(): expected 48 bytes, was passed ",$length,"!\n");
1961 }
1962  
1963 my $identstring = substr($headerdata,2,8);
1964 if($identstring ne 'BOOKDOUG')
1965 {
1966 carp($subname,"(): invalid IMP header!\n");
1967 return;
1968 }
1969  
1970 $self->{version} = unpack('n',$headerdata);
1971 if($self->{version} < 1 or $self->{version} > 2)
1972 {
1973 carp($subname,"(): Version ",$self->{version}," is not supported!\n");
1974 return;
1975 }
1976  
1977 $self->{unknown0x0a} = substr($headerdata,10,8);
1978  
1979 # Unsigned short int values
1980 my @list = unpack('nnn',substr($headerdata,0x12,6));
1981 $self->{filecount} = $list[0];
1982 $self->{resdirlength} = $list[1];
1983 $self->{resdiroffset} = $list[2];
1984 debug(2,"DEBUG: IMP file count = ",$self->{filecount});
1985 debug(2,"DEBUG: IMP resdirlength = ",$self->{resdirlength});
1986 debug(2,"DEBUG: IMP resdir offset = ",$self->{resdiroffset});
1987  
1988 # Unknown long ints
1989 @list = unpack('NN',substr($headerdata,0x18,8));
1990 $self->{unknown0x18} = $list[0];
1991 $self->{unknown0x1c} = $list[1];
1992 debug(2,"DEBUG: Unknown long int at offset 0x18 = ",$self->{unknown0x18});
1993 debug(2,"DEBUG: Unknown long int at offset 0x1c = ",$self->{unknown0x1c});
1994  
1995 # Compression/Encryption/Unknown
1996 @list = unpack('NNnC',substr($headerdata,0x20,11));
1997 $self->{compression} = $list[0];
1998 $self->{encryption} = $list[1];
1999 $self->{unknown0x28} = $list[2];
2000 $self->{unknown0x2a} = $list[3];
2001 debug(2,"DEBUG: IMP compression = ",$self->{compression});
2002 debug(2,"DEBUG: IMP encryption = ",$self->{encryption});
2003 debug(2,"DEBUG: Unknown short int at offset 0x28 = ",$self->{unknown0x28});
2004 debug(2,"DEBUG: Unknown byte at offset 0x2A = ",$self->{unknown0x2a});
2005  
2006 # Zoom State, and Unknown
2007 @list = unpack('CN',substr($headerdata,0x2B,5));
2008 $self->{device} = $list[0] >> 4;
2009 $self->{zoomstates} = $list[0] & 0x0f;
2010 $self->{unknown0x2c} = $list[1];
2011  
2012 debug(2,"DEBUG: IMP device = ",$self->{device});
2013 debug(2,"DEBUG: IMP zoom state = ",$self->{zoomstates});
2014 debug(2,"DEBUG: Unknown long int at offset 0x2c = ",$self->{unknown0x2c});
2015  
2016 return 1;
2017 }
2018  
2019  
2020 =head2 C<parse_resource_cm()>
2021  
2022 Parses the C<!!cm> resource loaded into C<< $self->{resources} >>,
2023 if present, extracting the LZSS uncompression parameters into
2024 C<< $self->{lzssoffsetbits} >> and C<< $self->{lzsslengthbits} >>.
2025  
2026 Returns 1 on success, or undef if no C<!!cm> resource has been loaded
2027 yet or the resource data is invalid.
2028  
2029 =cut
2030  
2031 sub parse_resource_cm :method
2032 {
2033 my $self = shift;
2034 my $subname = (caller(0))[3];
2035 croak($subname . "() called as a procedure!\n") unless(ref $self);
2036 debug(2,"DEBUG[",$subname,"]");
2037  
2038 return unless($self->{resources}->{'!!cm'});
2039  
2040 my @list;
2041 my $version;
2042 my $ident; # Must be constant string '!!cm'
2043 my $unknown1;
2044 my $indexoffset;
2045 my $lzssdata;
2046  
2047 @list = unpack('na[4]NN',$self->{resources}->{'!!cm'}->{data});
2048 $version = $list[0];
2049 $ident = $list[1];
2050 $unknown1 = $list[2];
2051 $indexoffset = $list[3];
2052  
2053 if($ident ne '!!cm')
2054 {
2055 carp($subname,"():\n",
2056 " Invalid '!!cm' record!\n");
2057 return;
2058 }
2059 debug(2,"DEBUG: parsing !!cm v",$version,", index offset ",$indexoffset);
2060 $lzssdata = substr($self->{resources}->{'!!cm'}->{data},$indexoffset-4,4);
2061 @list = unpack('nn',$lzssdata);
2062  
2063 if($list[0] + $list[1] > 32
2064 or $list[0] < 2
2065 or $list[1] < 1)
2066 {
2067 carp($subname,"():\n",
2068 " invalid LZSS compression bit lengths!\n",
2069 "[",$list[0]," offset bits, ",
2070 $list[1]," length bits]\n");
2071 return;
2072 }
2073  
2074 $self->{lzssoffsetbits} = $list[0];
2075 $self->{lzsslengthbits} = $list[1];
2076 debug(2,"DEBUG: !!cm specifies ",$list[0]," offset bits, ",
2077 $list[1]," length bits");
2078 return 1;
2079 }
2080  
2081  
2082 =head2 C<parse_resource_images()>
2083  
2084 Parses the image data resources loaded into C<< $self->{resources} >>,
2085 if present, placing the image data and metadata of each image found
2086 into C<< $self->{jpg} >> and C<< $self->{png} >>, keyed by 16-bit
2087 image resource ID.
2088  
2089 Returns the total number of images found and parsed.
2090  
2091 This method is called automatically by L</load()> and L</load_resdir()>.
2092  
2093 See also accessor methods L</image(%args)> and L</image_hashrefs(%args)>.
2094  
2095 =cut
2096  
2097 sub parse_resource_images :method
2098 {
2099 my $self = shift;
2100 my $subname = (caller(0))[3];
2101 croak($subname . "() called as a procedure!\n") unless(ref $self);
2102 debug(2,"DEBUG[",$subname,"]");
2103  
2104 my $headersize;
2105 my $imgdata;
2106 my $imgcount;
2107 my $total = 0;
2108 my @list;
2109  
2110 if($self->{device} == DEVICE_EBW1150) { $headersize = 14; }
2111 else { $headersize = 12; }
2112  
2113 foreach my $resource (keys %IMAGE_RESOURCE_MAP)
2114 {
2115 next unless($self->{resources}->{$resource});
2116 my $rsize = $self->{resources}->{$resource}->{size};
2117 my $itype = $IMAGE_RESOURCE_MAP{$resource};
2118 next if ($rsize <= 32);
2119  
2120 @list = unpack('na[4]NNnNNNN',$self->{resources}->{$resource}->{data});
2121 my $version = $list[0];
2122 my $ident = $list[1];
2123 my $unknown1 = $list[2];
2124 my $tocoffset = $list[3];
2125 my $unknown2 = $list[4];
2126 my $unknown3 = $list[5];
2127 my $unknown4 = $list[6];
2128 my $unknown5 = $list[7];
2129 my $unknown6 = $list[8];
2130  
2131 if($ident ne $resource)
2132 {
2133 carp($subname,"():\n",
2134 " Invalid '",$resource,"' record!\n");
2135 next;
2136 }
2137  
2138 debug(2,"DEBUG: parsing ",$resource," resource v",$version,
2139 ", index offset ",$tocoffset);
2140  
2141 $imgcount = ($rsize - $tocoffset) / $headersize;
2142  
2143 debug(2,"DEBUG: ",$imgcount," ",$itype," images listed in header");
2144  
2145 $self->{$itype} = {};
2146 foreach my $pos (0 .. ($imgcount - 1))
2147 {
2148 my $id; # Image ID -- this is only unique for each imagetype
2149 my $hexid; # 4-digit hexadecimal string version of $id
2150  
2151 $imgdata = substr($self->{resources}->{$resource}->{data},
2152 $tocoffset + ($headersize * $pos),$headersize);
2153 if($self->{device} == DEVICE_EBW1150)
2154 {
2155 #Standard 1150 Header (14 bytes)
2156 @list = unpack("vvVVv",$imgdata);
2157 $id = $list[0];
2158 $self->{$itype}->{$id}->{unknown} = $list[1];
2159 $self->{$itype}->{$id}->{length} = $list[2];
2160 $self->{$itype}->{$id}->{offset} = $list[3];
2161 $self->{$itype}->{$id}->{const0} = $list[4];
2162 }
2163 else
2164 {
2165 #Standard 1200 Header (12 bytes)
2166 @list = unpack("nNNn",$imgdata);
2167 $id = $list[0];
2168 $self->{$itype}->{$id}->{length} = $list[1];
2169 $self->{$itype}->{$id}->{offset} = $list[2];
2170 $self->{$itype}->{$id}->{const0} = $list[3];
2171 }
2172  
2173 if($EBook::Tools::debug > 2)
2174 {
2175 printf(" id=%04X unk1=0x%04X length=%d offset=%d, const0=0x%04X\n",
2176 $id, $self->{$itype}->{$id}->{unknown},
2177 $self->{$itype}->{$id}->{length},
2178 $self->{$itype}->{$id}->{offset},
2179 $self->{$itype}->{$id}->{const0});
2180 }
2181  
2182 $hexid = sprintf("%04X",$id);
2183  
2184 $self->{$itype}->{$id}->{data} =
2185 substr($self->{resources}->{$resource}->{data},
2186 $self->{$itype}->{$id}->{offset},
2187 $self->{$itype}->{$id}->{length});
2188  
2189 my ($imagex,$imagey,$imagetype) =
2190 imgsize(\$self->{$itype}->{$id}->{data});
2191 if(defined($imagex) && $imagetype)
2192 {
2193 debug(2," ",$itype," image ",$pos," (ID '",$hexid,"') is valid ",
2194 $imagetype," image data (",$imagex," x ",$imagey,")");
2195 }
2196 else
2197 {
2198 carp($subname,"():\n",
2199 " ",$itype," image ",$pos," (ID '",$id,
2200 "') is not valid image data!\n");
2201 next;
2202 }
2203 } # foreach my $pos (0 .. ($imgcount - 1))
2204  
2205 my $found = scalar keys %{$self->{$itype}};
2206 if($found != $imgcount)
2207 {
2208 carp($subname,"()\n",
2209 " resource specified ",$imgcount," images, but found ",
2210 $found,"!\n");
2211 }
2212 $total += $found;
2213 } # foreach my $resource (keys %IMAGE_RESOURCE_MAP)
2214  
2215 return $total;
2216 }
2217  
2218  
2219 =head2 C<parse_resource_imrn()>
2220  
2221 Parses the index of text offsets to all images as stored in
2222 C<< $self->{resources}->{'ImRn'} >>, if present, storing them in
2223 C<< $self->{imrn} >> as a hash of hashrefs indexed by its
2224 32-bit integer offset to the 0x0F control code in the uncompressed
2225 text stored in the DATA.FRK resource.
2226  
2227 Returns the total number of offsets found and parsed.
2228  
2229 The hash keys of each offset hash are:
2230  
2231 =over
2232  
2233 =item * C<width>
2234  
2235 Image display width in pixels.
2236  
2237 =item * C<height>
2238  
2239 Image display height in pixels.
2240  
2241 =item * C<id>
2242  
2243 A 16-bit integer value used to uniquely identify the image inside a
2244 particular resource type.
2245  
2246 =item * C<restype>
2247  
2248 The four-letter resource type string.
2249  
2250 =item * C<constF1>
2251  
2252 A 32-bit value of unknown purpose which should always be 0xFFFFFFFF.
2253  
2254 =item * C<constF2>
2255  
2256 A second 32-bit value of unknown purpose which should always be 0xFFFFFFFF.
2257  
2258 =item * C<const0>
2259  
2260 A 32-bit integer value of unknown purpose which should always be 0x00000000.
2261  
2262 =item * C<constB>
2263  
2264 A 16-bit integer value of unknown purpose which could be 0xFFFA, 0xFFFB,
2265 0xFFFC, or 0xFFFE.
2266  
2267 =item * C<unknown16>
2268  
2269 A 16-bit integer value of unknown purpose found only in 1150 resources.
2270  
2271 =item * C<unknown32>
2272  
2273 A 32-bit integer value of unknown purpose.
2274  
2275 =back
2276  
2277 This method is called automatically by L</load()> and L</load_resdir()>.
2278  
2279 =cut
2280  
2281 sub parse_resource_imrn :method
2282 {
2283 my $self = shift;
2284 my $subname = (caller(0))[3];
2285 croak($subname . "() called as a procedure!\n") unless(ref $self);
2286 debug(2,"DEBUG[",$subname,"]");
2287  
2288 return unless($self->{resources}->{'ImRn'});
2289  
2290 my $headersize;
2291 my $imrndata;
2292 my $imrncount;
2293 my $total = 0;
2294 my @list;
2295 my $idxdata;
2296 my $idxsize;
2297 my $idx1id;
2298 my $idx1size;
2299 my $idx1offset;
2300 my $idx1const0;
2301  
2302 if($self->{device} == DEVICE_EBW1150)
2303 {
2304 $headersize = 36;
2305 $idxsize = 14;
2306 }
2307 else
2308 {
2309 $headersize = 32;
2310 $idxsize = 12;
2311 }
2312  
2313 my $rsize = $self->{resources}->{'ImRn'}->{size};
2314 next if ($rsize <= 32);
2315  
2316 @list = unpack('na[4]NNnNNNN',$self->{resources}->{'ImRn'}->{data});
2317 my $version = $list[0];
2318 my $ident = $list[1];
2319 my $unknown1 = $list[2];
2320 my $tocoffset = $list[3];
2321 my $unknown2 = $list[4];
2322 my $unknown3 = $list[5];
2323 my $unknown4 = $list[6];
2324 my $unknown5 = $list[7];
2325 my $unknown6 = $list[8];
2326  
2327 if($ident ne 'ImRn')
2328 {
2329 carp($subname,"():\n",
2330 " Invalid 'ImRn' record!\n");
2331 next;
2332 }
2333  
2334 debug(2,"DEBUG: parsing 'ImRn' resource v",$version,
2335 ", index offset ",$tocoffset);
2336  
2337 $imrncount = ($rsize - 32 - 12) / $headersize;
2338  
2339 debug(2,"DEBUG: ",$imrncount," images listed in header");
2340  
2341 $self->{imrn} = {};
2342 foreach my $pos (0 .. ($imrncount - 1))
2343 {
2344 my $offset; # offset within DATA.FRK text (0x0F) of image insertion
2345  
2346 # FIX: The last (number $imrncount) image record is 2 bytes shorter and
2347 # will not be of size 36, but 34. Currently this code will read into
2348 # the index record!
2349 $imrndata = substr($self->{resources}->{'ImRn'}->{data},
2350 32 + ($headersize * $pos),$headersize);
2351 if($self->{device} == DEVICE_EBW1150)
2352 {
2353 #imrn 1150 record
2354 @list = unpack("VVvvVvvVVa[4]v",$imrndata);
2355 $offset = $list[7];
2356  
2357 $self->{imrn}->{$offset}->{constF1} = $list[0];
2358 $self->{imrn}->{$offset}->{constF2} = $list[1];
2359 $self->{imrn}->{$offset}->{width} = $list[2];
2360 $self->{imrn}->{$offset}->{height} = $list[3];
2361 $self->{imrn}->{$offset}->{const0} = $list[4];
2362 $self->{imrn}->{$offset}->{unknown16} = $list[5];
2363 $self->{imrn}->{$offset}->{constB} = $list[6];
2364 $self->{imrn}->{$offset}->{unknown32} = $list[8];
2365 $self->{imrn}->{$offset}->{restype} = $list[9];
2366 $self->{imrn}->{$offset}->{id} = $list[10];
2367  
2368 # restypes only reversed in 1150 ebooks
2369 # (restypes in 1200 ebooks are not reversed)
2370 my %restypefix = (
2371 ' FIG' => 'GIF ',
2372 'GEPJ' => 'JPEG',
2373 ' GNP' => 'PNG ',
2374 '2CIP' => 'PIC2',
2375 'TCIP' => 'PICT',
2376 );
2377 my $type = $self->{imrn}->{$offset}->{restype};
2378 $self->{imrn}->{$offset}->{restype} = $restypefix{$type}
2379 if($restypefix{$type});
2380 }
2381 else
2382 {
2383 #imrn 1200 record
2384 @list = unpack("NNnnNnNNa[4]n",$imrndata);
2385 $offset = $list[6];
2386  
2387 $self->{imrn}->{$offset}->{constF1} = $list[0];
2388 $self->{imrn}->{$offset}->{constF2} = $list[1];
2389 $self->{imrn}->{$offset}->{width} = $list[2];
2390 $self->{imrn}->{$offset}->{height} = $list[3];
2391 $self->{imrn}->{$offset}->{const0} = $list[4];
2392 $self->{imrn}->{$offset}->{constB} = $list[5];
2393 $self->{imrn}->{$offset}->{unknown32} = $list[7];
2394 $self->{imrn}->{$offset}->{restype} = $list[8];
2395 $self->{imrn}->{$offset}->{id} = $list[9];
2396 }
2397  
2398 my $restype = $self->{imrn}->{$offset}->{restype};
2399 my $imgtype = $IMAGE_RESOURCE_MAP{$restype};
2400 my $hexid = sprintf('%04X',$self->{imrn}->{$offset}->{id});
2401 my $width = $self->{imrn}->{$offset}->{width};
2402 my $height = $self->{imrn}->{$offset}->{height};
2403  
2404 if(none { $restype eq $_ } (IMAGERESOURCES) )
2405 {
2406 carp($subname,"():\n",
2407 " invalid image type '",$restype,"' at offset ",$offset,"!\n");
2408 next;
2409 }
2410 debug(2,"DEBUG: ImRn offset ",$offset,": '",$restype,"' 0x",$hexid,
2411 " (",$width," x ",$height,")");
2412  
2413 # PICT images are unviewable, so see if there is an alternate to use instead
2414 if($imgtype and $imgtype eq 'pic')
2415 {
2416 my $id = $self->{imrn}->{$offset}->{id};
2417 my $alttype = $self->find_image_type($id,'pic');
2418 $imgtype = $alttype if($alttype);
2419 }
2420  
2421 #TODO: use height/width from Pcz0/PcZ0 records
2422 my $filename = uc($imgtype) . "_${hexid}.${imgtype}";
2423 $self->{offsetelements}->{$offset} =
2424 '<img src="' . $filename . '" width="' . $width . '" height="' . $height
2425 . '" alt="' . $filename . '" />';
2426  
2427 debug(2,"DEBUG: tag = '",$self->{offsetelements}->{$offset},"'");
2428 if($EBook::Tools::debug > 2)
2429 {
2430 printf(" offset=%d restype=%s imgid=%04X constF1=0x%04X constF2=0x%04X width=%d height=%d const0=0x%04X, constB=0x%04X",
2431 $offset, $self->{imrn}->{$offset}->{restype},
2432 $self->{imrn}->{$offset}->{id},
2433 $self->{imrn}->{$offset}->{constF1},
2434 $self->{imrn}->{$offset}->{constF2},
2435 $self->{imrn}->{$offset}->{width},
2436 $self->{imrn}->{$offset}->{height},
2437 $self->{imrn}->{$offset}->{const0},
2438 $self->{imrn}->{$offset}->{constB},
2439 $self->{imrn}->{$offset}->{unknown16},
2440 $self->{imrn}->{$offset}->{unknown32});
2441  
2442 if($self->{imrn}->{$offset}->{const2})
2443 {
2444 printf(" const2=0x%04X",
2445 $self->{imrn}->{$offset}->{const2});
2446 }
2447 printf("\n");
2448 }
2449 }
2450  
2451 $idxdata = substr($self->{resources}->{'ImRn'}->{data},$tocoffset,$idxsize);
2452 if($self->{device} == DEVICE_EBW1150)
2453 {
2454 #Standard 1150 (14-byte) Index Header
2455 @list = unpack("vVVV",$idxdata);
2456 }
2457 else
2458 {
2459 #Standard 1200 (12-byte) Index Header
2460 @list = unpack("nNNn",$idxdata);
2461 }
2462 $idx1id = $list[0];
2463 $idx1size = $list[1];
2464 $idx1offset = $list[2];
2465 $idx1const0 = $list[3];
2466  
2467 $total = scalar keys %{$self->{imrn}};
2468 if($total != $imrncount)
2469 {
2470 carp($subname,"()\n",
2471 " resource specified ",$imrncount," ImRn entries, but found ",
2472 $total,"!\n");
2473 }
2474  
2475 return $total;
2476 }
2477  
2478  
2479 =head2 C<parse_text()>
2480  
2481 Parses the C<' '> (DATA.FRK) resource loaded into
2482 C<< $self->{resources} >>, if present, extracting the text into
2483 C<< $self->{text} >>, uncompressing it if necessary. LZSS uncompression
2484 will use the C<< $self->{lzsslengthbits} >> and
2485 C<< $self->{lzssoffsetbits} >> attributes if present, and default to 3
2486 length bits and 14 offset bits otherwise.
2487  
2488 HTML headers and footers are then applied, and control codes replaced
2489 with appropriate tags.
2490  
2491 Returns the length of the raw uncompressed text before any HTML
2492 modification was done, or undef if no text resource was found or the
2493 text was encrypted.
2494  
2495 =cut
2496  
2497 sub parse_text :method
2498 {
2499 my $self = shift;
2500 my $subname = (caller(0))[3];
2501 croak($subname . "() called as a procedure!\n") unless(ref $self);
2502 debug(2,"DEBUG[",$subname,"]");
2503  
2504 return unless($self->{resources}->{' '});
2505  
2506 $self->parse_resource_cm();
2507 my $lengthbits = $self->{lzsslengthbits} || 3;
2508 my $offsetbits = $self->{lzssoffsetbits} || 14;
2509 my $lzss = EBook::Tools::LZSS->new(lengthbits => $lengthbits,
2510 offsetbits => $offsetbits,
2511 windowstart => 1);
2512 my $textref;
2513 my $textlength;
2514  
2515 if($self->{encryption})
2516 {
2517 warn($subname,"(): encrypted text not supported!\n");
2518 return;
2519 }
2520  
2521 if($self->{compression})
2522 {
2523 $textref = $lzss->uncompress(\$self->{resources}->{' '}->{data});
2524 }
2525 else
2526 {
2527 $textref = \$self->{resources}->{' '}->{data};
2528 }
2529 $textlength = length($$textref);
2530  
2531 if(!$textlength)
2532 {
2533 carp($subname,"(): no text extracted from DATA.FRK resource!\n");
2534 return;
2535 }
2536  
2537 $self->{text} = <<'END';
2538 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2539 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2540  
2541 <html xmlns="http://www.w3.org/1999/xhtml">
2542 <head>
2543 <meta http-equiv="CONTENT-TYPE" content="text/html; charset=windows-1252" />
2544 END
2545  
2546 $self->{text} .= " <title>$self->{title}</title>\n";
2547 $self->{text} .= "</head>\n<body>\n";
2548  
2549 my $pos = 0;
2550 my %ccharmap = (
2551 0x0A => "\n" . '<br style="page-break-before: always" />', # supported!
2552 0x0B => "\n<p>",
2553 0x0D => "<br />\n",
2554 0x0E => '', # Start of <table>, not yet supported
2555 0x13 => '', # End of table cell </td>, not yet supported
2556 0x14 => "\n<hr />\n",
2557 0x8E => "&eacute;",
2558 0xA0 => "&nbsp;",
2559 0xA5 => "&bull;",
2560 0xA8 => "&reg;",
2561 0xA9 => "&copy;",
2562 0xAA => "&trade;",
2563 0xAE => "&AElig;",
2564 0xC7 => "&laquo;",
2565 0xC8 => "&raquo;",
2566 0xC9 => "&hellip;",
2567 0xD0 => "&ndash;",
2568 0xD1 => "&mdash;",
2569 0xD2 => "&ldquo;",
2570 0xD3 => "&rdquo;",
2571 0xD4 => "&lsquo;",
2572 0xD5 => "&rsquo;",
2573 0xE1 => "&middot;",
2574 );
2575  
2576 while($pos < $textlength)
2577 {
2578 my $char = substr($$textref,$pos,1);
2579 my $ord = ord($char);
2580  
2581 if($ord == 0x0F) # Image
2582 {
2583 $self->{text} .= $self->{offsetelements}->{$pos};
2584 }
2585 elsif(defined $ccharmap{$ord})
2586 {
2587 $self->{text} .= $ccharmap{$ord};
2588 }
2589 else
2590 {
2591 $self->{text} .= $char;
2592 }
2593 $pos++;
2594 }
2595 $self->{text} .= "\n</body>\n</html>";
2596 $self->{text} =~ s/\x15 .*? \x15//gx; # Kill header - comment out?
2597 $self->{text} =~ s/\x16 .*? \x16//gx; # Kill footer
2598 return $textlength;
2599 }
2600  
2601  
2602 =head2 C<parse_imp_toc_v1($tocdata)>
2603  
2604 Takes as a single argument a string containing the table of contents
2605 data, and parses it into object attributes following the version 1
2606 format (10 bytes per entry).
2607  
2608 =head3 Format
2609  
2610 =over
2611  
2612 =item * Offset 0x00 [4 bytes, text]
2613  
2614 Resource name. Stored in hash key C<name>. In the case of the
2615 'DATA.FRK' text resource, this will be four spaces (C<' '>).
2616  
2617 =item * Offset 0x04 [2 bytes, big-endian unsigned short int]
2618  
2619 Unknown, but always zero or one. Stored in hash key C<unknown1>.
2620  
2621 =item * Offset 0x08 [4 bytes, big-endian unsigned long int]
2622  
2623 Size of the resource data in bytes. Stored in hash key C<size>.
2624  
2625 =back
2626  
2627 =cut
2628  
2629 sub parse_imp_toc_v1 :method
2630 {
2631 my $self = shift;
2632 my ($tocdata) = @_;
2633 my $subname = (caller(0))[3];
2634 croak($subname . "() called as a procedure!\n") unless(ref $self);
2635 debug(2,"DEBUG[",$subname,"]");
2636  
2637 my $length = length($tocdata);
2638 my $lengthexpected = 10 * $self->{filecount};
2639 my $tocentrydata;
2640 my $offset = 0;
2641  
2642 if($self->{version} != 1)
2643 {
2644 carp($subname,"(): attempting to parse a version 1 TOC,",
2645 " but the file appears to be version ",$self->{version},"!\n");
2646 }
2647  
2648 if($length != $lengthexpected)
2649 {
2650 carp($subname,"(): expected ",$lengthexpected," bytes, but received ",
2651 $length," -- aborting!\n");
2652 return;
2653 }
2654  
2655 $self->{toc} = ();
2656 foreach my $index (0 .. $self->{filecount} - 1)
2657 {
2658 my %tocentry;
2659 my @list;
2660 $tocentrydata = substr($tocdata,$offset,10);
2661 @list = unpack('a[4]nN',$tocentrydata);
2662  
2663 $tocentry{name} = $list[0];
2664 $tocentry{unknown1} = $list[1];
2665 $tocentry{size} = $list[2];
2666  
2667 debug(3,"DEBUG: found toc entry '",$tocentry{name},
2668 "', type '",$tocentry{type},"' [",$tocentry{size}," bytes]");
2669 push(@{$self->{toc}}, \%tocentry);
2670 $offset += 10;
2671 }
2672  
2673 return 1;
2674 }
2675  
2676  
2677 =head2 C<parse_imp_toc_v2($tocdata)>
2678  
2679 Takes as a single argument a string containing the table of contents
2680 data, and parses it into object attributes following the version 2
2681 format (20 bytes per entry).
2682  
2683 =head3 Format
2684  
2685 =over
2686  
2687 =item * Offset 0x00 [4 bytes, text]
2688  
2689 Resource name. Stored in C<name>. In the case of the 'DATA.FRK' text
2690 resource, this will be four spaces (C<' '>).
2691  
2692 =item * Offset 0x04 [4 bytes, big-endian unsigned long int]
2693  
2694 Unknown, but always zero. Stored in C<unknown1>.
2695  
2696 =item * Offset 0x08 [4 bytes, big-endian unsigned long int]
2697  
2698 Size of the resource data in bytes. Stored in C<size>.
2699  
2700 =item * Offset 0x0C [4 bytes, text]
2701  
2702 Resource type. Stored in C<type>, and used as the key for the stored
2703 resource hash.
2704  
2705 =item * Offset 0x10 [4 bytes, big-endian unsigned long int]
2706  
2707 Unknown, but always either zero or one. Stored in C<unknown2>.
2708  
2709 =back
2710  
2711 =cut
2712  
2713 sub parse_imp_toc_v2 :method
2714 {
2715 my $self = shift;
2716 my ($tocdata) = @_;
2717 my $subname = (caller(0))[3];
2718 croak($subname . "() called as a procedure!\n") unless(ref $self);
2719 debug(2,"DEBUG[",$subname,"]");
2720  
2721 my $length = length($tocdata);
2722 my $lengthexpected = 20 * $self->{filecount};
2723 my $template;
2724 my $tocentrydata;
2725 my $offset = 0;
2726  
2727 if($self->{version} != 2)
2728 {
2729 carp($subname,"(): attempting to parse a version 2 TOC,",
2730 " but the file appears to be version ",$self->{version},"!\n");
2731 }
2732  
2733 if($length != $lengthexpected)
2734 {
2735 carp($subname,"(): expected ",$lengthexpected," bytes, but received ",
2736 $length," -- aborting!\n");
2737 return;
2738 }
2739  
2740 $self->{toc} = ();
2741 foreach my $index (0 .. $self->{filecount} - 1)
2742 {
2743 my %tocentry;
2744 my @list;
2745 $tocentrydata = substr($tocdata,$offset,20);
2746 @list = unpack('a[4]NNa[4]N',$tocentrydata);
2747  
2748 $tocentry{name} = $list[0];
2749 $tocentry{unknown1} = $list[1];
2750 $tocentry{size} = $list[2];
2751 $tocentry{type} = $list[3];
2752 $tocentry{unknown2} = $list[4];
2753  
2754 debug(3,"DEBUG: found toc entry '",$tocentry{name},
2755 "', type '",$tocentry{type},"' [",$tocentry{size}," bytes,",
2756 " unk1=",$tocentry{unknown1}," unk2=",$tocentry{unknown2},"]");
2757 push(@{$self->{toc}}, \%tocentry);
2758 $offset += 20;
2759 }
2760  
2761 return 1;
2762 }
2763  
2764  
2765 =head2 C<set_book_properties(%args)>
2766  
2767 Sets the specified book properties. Returns 1 on success, or undef if
2768 no properties were specified.
2769  
2770 =head3 Arguments
2771  
2772 =over
2773  
2774 =item * C<identifier>
2775  
2776 The book identifier, as might be provided as an OPF C<< <dc:identifier> >>
2777 element.
2778  
2779 =item * C<category>
2780  
2781 The main book category, as might be provided as an OPF C<< <dc:subject> >>
2782 element.
2783  
2784 =item * C<subcategory>
2785  
2786 The subcategory, generally a set of search arguments for the ETI
2787 website.
2788  
2789 =item * C<title>
2790  
2791 The book title, as might be provided as an OPF C<< <dc:title> >>
2792 element.
2793  
2794 =item * C<lastname>
2795  
2796 The primary author's last name, but see the entry for C<firstname>
2797 before deciding how to handle name storage.
2798  
2799 =item * C<middlename>
2800  
2801 The primary author's middle name, but see the entry for C<firstname>
2802 before deciding how to handle name storage.
2803  
2804 =item * C<firstname>
2805  
2806 The primary author's first name, but this field is also used by a
2807 great many .imp books to store the entire name in "First Last" format.
2808 If this field is to be used this way, C<lastname> and C<middlename>
2809 must be blank.
2810  
2811 =back
2812  
2813 =head3 Example
2814  
2815 $imp->set_book_properties(title => 'My Best Book',
2816 category => 'Fiction',
2817 firstname => 'John Q. Public');
2818  
2819 =cut
2820  
2821 sub set_book_properties :method
2822 {
2823 my $self = shift;
2824 my %args = @_;
2825 my $subname = (caller(0))[3];
2826 croak($subname . "() called as a procedure!\n") unless(ref $self);
2827 debug(2,"DEBUG[",$subname,"]");
2828  
2829 my %valid_args = (
2830 'identifier' => 1,
2831 'category' => 1,
2832 'subcategory' => 1,
2833 'title' => 1,
2834 'lastname' => 1,
2835 'middlename' => 1,
2836 'firstname' => 1,
2837 );
2838 if(!%args)
2839 {
2840 carp($subname,"():\n",
2841 " at least one property must be specified!\n");
2842 return;
2843 }
2844 foreach my $arg (keys %args)
2845 {
2846 croak($subname,"(): invalid argument '",$arg,"'")
2847 if(!$valid_args{$arg});
2848 }
2849  
2850 $self->{identifier} = $args{identifier} if(defined $args{identifier});
2851 $self->{category} = $args{category} if(defined $args{category});
2852 $self->{subcategory} = $args{subcategory} if(defined $args{subcategory});
2853 $self->{title} = $args{title} if(defined $args{title});
2854 $self->{lastname} = $args{lastname} if(defined $args{lastname});
2855 $self->{middlename} = $args{middlename} if(defined $args{middlename});
2856 $self->{firstname} = $args{firstname} if(defined $args{firstname});
2857  
2858 return 1;
2859 }
2860  
2861  
2862 ################################
2863 ########## PROCEDURES ##########
2864 ################################
2865  
2866 =head1 PROCEDURES
2867  
2868 All procedures are exportable, but none are exported by default.
2869  
2870  
2871 =head2 C<detect_resource_type(\$data)>
2872  
2873 Takes as a sole argument a reference to the data component of a
2874 resource. Returns a 4-byte string containing the resource type if
2875 detected successfully, or undef otherwise.
2876  
2877 Detection will not work on the C<DATA.FRK> (C<' '>) resource. That
2878 one must be detected separately by name/type.
2879  
2880 =cut
2881  
2882 sub detect_resource_type
2883 {
2884 my ($dataref) = @_;
2885 my $subname = (caller(0))[3];
2886 debug(3,"DEBUG[",$subname,"]");
2887  
2888 if(!$dataref)
2889 {
2890 carp($subname,"(): no resource data provided!\n");
2891 return;
2892 }
2893 if(ref $dataref ne 'SCALAR')
2894 {
2895 carp($subname,"(): argument is not a scalar reference!\n");
2896 return;
2897 }
2898  
2899 my $id = substr($$dataref,2,4);
2900 if($id =~ m/^[\w! ]{4}$/)
2901 {
2902 return $id;
2903 }
2904 carp($subname,"(): resource not recognized!\n");
2905 return;
2906 }
2907  
2908  
2909 =head2 C<parse_imp_resource_v1()>
2910  
2911 Takes as a sole argument a string containing the data (including the
2912 10-byte header) of a version 1 IMP resource.
2913  
2914 Returns a hashref containing that data separated into the following
2915 keys:
2916  
2917 =over
2918  
2919 =item * C<name>
2920  
2921 The four-letter name of the resource.
2922  
2923 =item * C<type>
2924  
2925 The four-letter type of the resource. This is detected from the data,
2926 and is not part of the v1 header.
2927  
2928 =item * C<unknown1>
2929  
2930 A 16-bit unsigned int of unknown purpose. Expected values are 0 or 1.
2931  
2932 Use with caution. This key may be renamed later if more information
2933 is found.
2934  
2935 =item * C<size>
2936  
2937 The expected size in bytes of the actual resource data. A warning
2938 will be carped if this does not match the actual size of the data
2939 following the header.
2940  
2941 =item * C<data>
2942  
2943 The actual resource data.
2944  
2945 =back
2946  
2947 =cut
2948  
2949 sub parse_imp_resource_v1
2950 {
2951 my ($data) = @_;
2952 my $subname = (caller(0))[3];
2953 debug(3,"DEBUG[",$subname,"]");
2954  
2955 my @list; # Temporary list
2956 my %resource; # Hash containing resource data and metadata
2957 my $size; # Actual size of resource data
2958  
2959 @list = unpack('a[4]nN',$data);
2960 $resource{name} = $list[0];
2961 $resource{unknown1} = $list[1];
2962 $resource{size} = $list[2];
2963 $resource{data} = substr($data,10);
2964 if($resource{name} eq ' ')
2965 {
2966 $resource{type} = ' ';
2967 }
2968 else
2969 {
2970 $resource{type} = detect_resource_type(\$resource{data});
2971 }
2972  
2973 $size = length($resource{data});
2974 if($size != $resource{size})
2975 {
2976 carp($subname,"(): resource '",$resource{name},"' has ",
2977 $size," bytes (expected ",$resource{size},")!\n");
2978 }
2979  
2980 debug(2,"DEBUG: found resource '",$resource{name},
2981 "', type '",$resource{type},"' [",$resource{size}," bytes]");
2982  
2983 return \%resource;
2984 }
2985  
2986  
2987 =head2 C<parse_imp_resource_v2()>
2988  
2989 Takes as a sole argument a string containing the data (including the
2990 20-byte header) of a version 2 IMP resource.
2991  
2992 Returns a hashref containing that data separated into the following
2993 keys:
2994  
2995 =over
2996  
2997 =item * C<name>
2998  
2999 The four-letter name of the resource.
3000  
3001 =item * C<unknown1>
3002  
3003 A 32-bit unsigned int of unknown purpose. Expected values are 0 or 1.
3004  
3005 Use with caution. This key may be renamed later if more information
3006 is found.
3007  
3008 =item * C<size>
3009  
3010 The expected size in bytes of the actual resource data. A warning
3011 will be carped if this does not match the actual size of the data
3012 following the header.
3013  
3014 =item * C<type>
3015  
3016 The four-letter type of the resource.
3017  
3018 =item * C<unknown2>
3019  
3020 A 32-bit unsigned int of unknown purpose. Expected values are 0 or 1.
3021  
3022 Use with caution. This key may be renamed later if more information
3023 is found.
3024  
3025 =item * C<data>
3026  
3027 The actual resource data.
3028  
3029 =back
3030  
3031 =cut
3032  
3033 sub parse_imp_resource_v2
3034 {
3035 my ($data) = @_;
3036 my $subname = (caller(0))[3];
3037 debug(3,"DEBUG[",$subname,"]");
3038  
3039 my @list; # Temporary list
3040 my %resource; # Hash containing resource data and metadata
3041 my $size; # Actual size of resource data
3042  
3043 @list = unpack('a[4]NNa[4]N',$data);
3044 $resource{name} = $list[0];
3045 $resource{unknown1} = $list[1];
3046 $resource{size} = $list[2];
3047 $resource{type} = $list[3];
3048 $resource{unknown2} = $list[4];
3049 $resource{data} = substr($data,20);
3050  
3051 $size = length($resource{data});
3052 if($size != $resource{size})
3053 {
3054 carp($subname,"(): resource '",$resource{name},"' has ",
3055 $size," bytes (expected ",$resource{size},")!\n");
3056 }
3057  
3058 debug(2,"DEBUG: found resource '",$resource{name},
3059 "', type '",$resource{type},"' [",$resource{size}," bytes,",
3060 " unk1=",$resource{unknown1}," unk2=",$resource{unknown2},"]");
3061  
3062 return \%resource;
3063 }
3064  
3065  
3066 ########## END CODE ##########
3067  
3068 =head1 BUGS AND LIMITATIONS
3069  
3070 =over
3071  
3072 =item * Not finished. Do not try to use yet.
3073  
3074 =item * MacPaint PICT images are not well-supported. If present in
3075 the book, they will be saved, but a warning will be carped about
3076 invalid image data.
3077  
3078 =item * Support for v1 files is completely untested and implemented
3079 with some guesswork. Bug reports welcome.
3080  
3081 =back
3082  
3083 =head1 AUTHOR
3084  
3085 Zed Pobre <zed@debian.org>
3086  
3087 =head1 THANKS
3088  
3089 Thanks are due to Nick Rapallo <nrapallo@yahoo.ca> for invaluable
3090 assistance in understanding the .IMP format and testing this code.
3091  
3092 Thanks are also due to Jeffrey Kraus-yao <krausyaoj@ameritech.net> for
3093 his work reverse-engineering the .IMP format to begin with, and the
3094 documentation at L<http://krausyaoj.tripod.com/reb1200.htm>.
3095  
3096 =head1 LICENSE AND COPYRIGHT
3097  
3098 Copyright 2008 Zed Pobre
3099  
3100 Licensed to the public under the terms of the GNU GPL, version 2.
3101  
3102 =cut
3103  
3104 1;
3105 __END__
« blib/lib/EBook/Tools/MSReader.pm ↑ Summary blib/lib/EBook/Tools/LZSS.pm »