Tools.pm

filter: Statementstmt 97.0% 66 / 68 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 23 / 23 Podpod n/a totaltotal 97.8% 89 / 91 CC 1 SCAR 0.1
CC
1
Cov
97%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Tools/Unpack.pm ↑ Summary
1 package EBook::Tools;
2 10 ▶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 10 ▶use v5.10.1; # Needed for smart-match operator and given/when
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use version 0.74; our $VERSION = qv("0.5.4");
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 #use warnings::unused;
8  
9 # Perl Critic overrides:
10 ## no critic (Package variable)
11 # RequireBriefOpen seems to be way too brief to be useful
12 ## no critic (RequireBriefOpen)
13 # Double-sigils are needed for lexical filehandles in clear print statements
14 ## no critic (Double-sigil dereference)
15 our $debug = 0;
16  
17  
18  
19 =head1 NAME
20  
21 EBook::Tools - Object class for manipulating and generating E-books
22  
23  
24 =head1 DESCRIPTION
25  
26 This module provides an object interface and a number of related
27 procedures intended to create or modify documents centered around the
28 International Digital Publishing Forum (IDPF) standards, currently
29 both OEBPS v1.2 and OPS/OPF v2.0.
30  
31 =cut
32  
33 =head1 SYNOPSIS
34  
35 use EBook::Tools qw(split_metadata system_tidy_xml);
36 $EBook::Tools::tidysafety = 2;
37  
38 my $opffile = split_metadata('ebook.html');
39 my $otheropffile = 'alternate.opf';
40 my $retval = system_tidy_xml($opffile,'tidy-backup.xml');
41 my $ebook = EBook::Tools->new($opffile);
42 $ebook->fix_opf20;
43 $ebook->fix_misc;
44 $ebook->print;
45 $ebook->save;
46  
47 $ebook->init($otheropffile);
48 $ebook->fix_oeb12;
49 $ebook->gen_epub;
50  
51  
52 =head1 DEPENDENCIES
53  
54 =head2 Perl Modules
55  
56 =over
57  
58 =item Archive::Zip
59  
60 =item Data::UUID (or OSSP::UUID)
61  
62 =item Date::Manip
63  
64 Note that Date::Manip will die on MS Windows system unless the
65 TZ environment variable is set in a specific manner. See:
66  
67 http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES
68  
69 =item File::MimeInfo
70  
71 =item HTML::Parser
72  
73 =item Lingua::EN::NameParse
74  
75 =item Tie::IxHash
76  
77 =item Time::Local
78  
79 =item URI::Escape
80  
81 =item XML::Twig
82  
83 =back
84  
85 =head2 Other Programs
86  
87 =over
88  
89 =item Tidy
90  
91 The command "tidy" needs to be available, and ideally on the path. If
92 it isn't on the path, package variable L</$tidycmd> can be set to its
93 absolute path. If tidy cannot be found, L</system_tidy_xml()> and
94 L</system_tidy_xhtml()> will be nonfunctional.
95  
96 =back
97  
98 =cut
99  
100  
101 require Exporter;
102 10 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
103  
104 our @EXPORT_OK;
105 @EXPORT_OK = qw (
106 &capitalize
107 &clean_filename
108 &create_epub_container
109 &create_epub_mimetype
110 &debug
111 &excerpt_line
112 &fix_datestring
113 &find_in_path
114 &find_links
115 &find_opffile
116 &hashvalue_key_self
117 &hexstring
118 &get_container_rootfile
119 &print_memory
120 &split_metadata
121 &split_pre
122 &strip_script
123 &system_result
124 &system_tidy_xml
125 &system_tidy_xhtml
126 &trim
127 &twigelt_create_uuid
128 &twigelt_fix_oeb12_atts
129 &twigelt_fix_opf20_atts
130 &twigelt_is_author
131 &usedir
132 &userconfigdir
133 &ymd_validate
134 );
135 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
136  
137 # OSSP::UUID will provide Data::UUID on systems such as Debian that do
138 # not distribute the original Data::UUID.
139 10 ▶use Data::UUID;
Subroutine BEGIN: called CC=1 SCAR=0.0
140  
141 10 ▶use Archive::Zip qw( :CONSTANTS :ERROR_CODES );
Subroutine BEGIN: called CC=1 SCAR=0.0
142 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
143 10 ▶use Cwd qw(getcwd realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
144 10 ▶use Date::Manip;
Subroutine BEGIN: called CC=1 SCAR=0.0
145 require EBook::Tools::BISG;
146 10 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
147 require Encode::Detect;
148 10 ▶use File::Basename qw(basename dirname fileparse);
Subroutine BEGIN: called CC=1 SCAR=0.0
149 # File::MimeInfo::Magic gets *.css right, but detects all html as
150 # text/html, even if it has an XML header.
151 10 ▶use File::MimeInfo::Magic;
Subroutine BEGIN: called CC=1 SCAR=0.0
152 # File::MMagic gets text/xml right (though it still doesn't properly
153 # detect XHTML), but detects CSS as x-system, and has a number of
154 # other weird bugs.
155 #use File::MMagic;
156 10 ▶use File::Path; # Exports 'mkpath' and 'rmtree'
Subroutine BEGIN: called CC=1 SCAR=0.0
157 10 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
158 10 ▶use HTML::Entities qw(decode_entities _decode_entities %entity2char);
Subroutine BEGIN: called CC=1 SCAR=0.0
159 #use HTML::Tidy;
160 10 ▶use Lingua::EN::NameParse qw(case_surname);
Subroutine BEGIN: called CC=1 SCAR=0.0
161 10 ▶use Tie::IxHash;
Subroutine BEGIN: called CC=1 SCAR=0.0
162 10 ▶use Time::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
163 10 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
164 0 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
165  
166  
167 =head1 CONFIGURABLE PACKAGE VARIABLES
168  
169 =over
170  
171 =item C<%bisacsubjects>
172  
173 A mapping of lowercase BISAC codes and text descriptions to standard
174 capitalized text descriptions. As BISG claims copyright on this and
175 does not allow the lists to be redistributed, this list must be
176 downloaded and cached locally via C<ebook dlbisac> before it is
177 available.
178  
179 Running the unit tests will cause this to happen automatically.
180  
181 =item C<%bisactolc>
182  
183 An extremely incomplete mapping of lowercase BISAC codes and text
184 descriptions to Library of Congress standard subjects.
185  
186 =item C<%booktypes>
187  
188 A hash mapping all-lowercase terms to a standard vocabulary to be used
189 in <dc:type> elements.
190  
191 =item C<%dcelements12>
192  
193 A tied IxHash mapping an all-lowercase list of Dublin Core metadata
194 element names to the capitalization dictated by the OEB 1.2
195 specification, used by the fix_oeb12() and fix_oeb12_dcmeta() methods.
196 Changing the tags in this list will change the tags recognized and
197 placed inside the <dc-metadata> element.
198  
199 Order is preserved and significant -- fix_oeb12 will output DC
200 metadata elements in the same order as in this hash, though order for
201 tags of the same name is preserved from the input file.
202  
203 =item C<%dcelements20>
204  
205 A tied IxHash mapping an all-lowercase list of Dublin Core metadata
206 element names to the all-lowercase form dictated by the OPF 2.0
207 specification (which means it maps the all-lowercase tags to
208 themselves). It is used by the fix_opf20() and fix_opf20_dcmeta()
209 methods. Changing the tags in this list will change the tags
210 recognized and placed directly under the <metadata> element.
211  
212 Order is preserved and significant -- fix_opf20 will output DC
213 metadata elements in the same order as in this hash, though order for
214 tags of the same name is preserved from the input file.
215  
216 =item C<%lcsubjects>
217  
218 An extremely incomplete mapping of lowercase terms to Library of
219 Congress subject classifications. This is used for automatic
220 normalization of subject elements. Every value in the hash has a
221 lowercase representation of itself as a key in addition to any
222 aliases.
223  
224 This MUST NOT contain mappings from BISAC codes or descriptors to
225 Library of Congress subjects. Use %bisactolc for that.
226  
227 =item C<%nonxmlentity2char>
228  
229 This is the %entity2char conversion map from HTML::Entities with the 5
230 pre-defined XML entities (amp, gt, lt, quot, apos) removed. This is
231 used during by L</init()> to sanitize the OPF file data before
232 parsing. This hash can be modified to allow and convert other
233 non-standard entities to unicode characters. See HTML::Entities for
234 details.
235  
236 =item C<%publishermap>
237  
238 A hash mapping known variants of publisher names to a canonical form,
239 used by L</fix_publisher()>, and thus also indirectly by
240 L</fix_misc()>.
241  
242 Keys should be entered in lowercase. The hash can also be set empty
243 to prevent fix_publisher() from taking any action at all.
244  
245 =item C<%referencetypes>
246  
247 A hash mapping valid OPF 2.0 reference types to themselves, along with
248 common variants to standard types.
249  
250 =item C<%relatorcodes>
251  
252 A hash mapping the MARC Relator Codes (see:
253 http://www.loc.gov/marc/relators/relacode.html) to their descriptive
254 names.
255  
256 =item C<%sexcodes>
257  
258 A hash normalizing subject tags for erotic fiction, as used by
259 StoriesOnline, ASSTR, and Literotica, among others.
260  
261 Unlike the other mappings, this one is *not* lowercased, and the keys
262 are case-sensitive. The hash maps only to the canonical base code,
263 but subject normalization will also add a prefix, defaulting to the
264 BISAC format of 'FICTION / Erotica / '.
265  
266 =item C<%strangenames>
267  
268 =item C<%strangefileas>
269  
270 Hashes mapping mapping known incorrect outputs of name normalization
271 to correct format. The first handles the main name display, the
272 second the file-as output.
273  
274 =item C<$tidycmd>
275  
276 The tidy executable name. This has to be a fully qualified pathname
277 if tidy isn't on the path. Defaults to 'tidy'.
278  
279 =item C<$tidyxhtmlerrors>
280  
281 The name of the error output file from system_tidy_xhtml(). Defaults
282 to 'tidyxhtml-errors.txt'
283  
284 =item C<$tidyxmlerrors>
285  
286 The name of the error output file from system_tidy_xml(). Defaults to
287 'tidyxml-errors.txt'
288  
289 =item C<$tidysafety>
290  
291 The safety level to use when running tidy (default is 1). Potential
292 values are:
293  
294 =over
295  
296 =item C<$tidysafety < 1>:
297  
298 No checks performed, no error files kept, works like a clean tidy -m
299  
300 This setting is DANGEROUS!
301  
302 =item C<$tidysafety == 1>:
303  
304 Overwrites original file if there were no errors, but even if there
305 were warnings. Keeps a log of errors, but not warnings.
306  
307 =item C<$tidysafety == 2>:
308  
309 Overwrites original file if there were no errors, but even if there
310 were warnings. Keeps a log of both errors and warnings.
311  
312 =item C<$tidysafety == 3>:
313  
314 Overwrites original file only if there were no errors or warnings.
315 Keeps a log of both errors and warnings.
316  
317 =item C<$tidysafety >= 4>:
318  
319 Never overwrites original file. Keeps a log of both errors and
320 warnings.
321  
322 =back
323  
324 =item C<%validspecs>
325  
326 A hash mapping valid specification strings to themselves, primarily
327 used to undefine unrecognized values. Default valid values are 'OEB12'
328 and 'OPF20'.
329  
330 =back
331  
332 =cut
333  
334 our $mobi2htmlcmd = 'mobi2html';
335 our $tidycmd = 'tidy'; # Specify full pathname if not on path
336 our $tidyxhtmlerrors = 'tidyxhtml-errors.txt';
337 our $tidyxmlerrors = 'tidyxml-errors.txt';
338 our $tidysafety = 1;
339  
340  
341 our $utf8xmldec = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
342 our $oeb12doctype =
343 '<!DOCTYPE package' . "\n" .
344 ' PUBLIC "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN"' . "\n" .
345 ' "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd">' . "\n";
346 our $opf20package =
347 '<package version="2.0" xmlns="http://www.idpf.org/2007/opf">' . "\n";
348  
349 my $bisg = EBook::Tools::BISG->new();
350 our %bisacsubjects = $bisg->bisac();
351  
352 our %bisactolc = (
353 # The entire ANTXXX line is ambiguous -- it could map to either
354 # subdivisions of Antiques or Collectibles. Work started here
355 # before this was realized is being left intact for now, but the
356 # list is incomplete for this reason.
357 'ant000000' => 'Antiques',
358 'ant001000' => 'Antiques--Americana',
359 'ant002000' => 'Antiques--Art',
360 'ant003000' => 'Autographs',
361 'ant004000' => 'Antiques--Baskets',
362 'ant005000' => 'Antiques--Books',
363 'ant006000' => 'Antiques--Bottles',
364 'ant010000' => 'Antiques--Clocks and watches',
365 'ant012000' => 'Antiques--Cartoons',
366 'ant015000' => 'Antiques--Dolls',
367 'ant016000' => 'Antiques--Firearms',
368 'ant017000' => 'Antiques--Furniture',
369 'ant018000' => 'Antiques--Glassware',
370 'ant021000' => 'Antiques--Jewelry',
371 'ant022000' => 'Antiques--Kitchen utensils',
372 'ant023000' => 'Antiques--Periodicals',
373 'ant026000' => 'Antiques--Musical instruments',
374 'ant031000' => 'Political collectibles',
375 'ant052000' => 'Collectibles--Popular culture',
376 'ant053000' => 'Antiques--Figurines',
377 'arc000000' => 'Architecture',
378 'arc005000' => 'Architecture--History',
379 'arc007000' => 'Interior decoration',
380 'art000000' => 'Art',
381 'art002000' => 'Airbrush art',
382 'art003000' => 'Calligraphy--Technique',
383 'art004000' => 'Cartooning',
384 'art006000' => 'Art collections',
385 'art008000' => 'Conceptual art',
386 'art009000' => 'Art criticism',
387 'art010000' => 'Drawing',
388 'art013000' => 'Folk art',
389 'art015010' => 'Art, African',
390 'art015020' => 'Art, American',
391 'art015030' => 'Art, European',
392 'art015040' => 'Art, Canadian',
393 'art016000' => 'Artists',
394 'art017000' => 'Mixed media (Art)',
395 'art019000' => 'Art, Asian',
396 'art020000' => 'Painting--Technique',
397 'art021000' => 'Pastel drawing--Technique',
398 'art023000' => 'Popular culture',
399 'art024000' => 'Prints--Technique',
400 'art026000' => 'Sculpture',
401 'art027000' => 'Arts--Study and teaching',
402 'art028000' => 'Art--Technique',
403 'art029000' => 'Watercolor painting--Technique',
404 'art033000' => 'Pen drawing--Technique',
405 'art034000' => 'Pencil drawing--Technique',
406 'art035000' => 'Religious art',
407 'art037000' => 'Politics in art',
408 'art038000' => 'African American art',
409 'art039000' => 'Asian American art',
410 'art040000' => 'Hispanic American art',
411 'art042000' => 'Art, Australian',
412 'art043000' => 'Art and business',
413 'art044000' => 'Art, Latin American',
414 'art045000' => 'Pottery',
415 'art046000' => 'Digital art',
416 'art047000' => 'Art--Middle East',
417 'art049000' => 'Art, Russian',
418 'art050000' => 'Art--Themes, motives',
419 'art050010' => 'Human beings in art',
420 'art050020' => 'Landscapes in art',
421 # 'ART050030' could translate to either 'Animals in art' or 'Plants in art'
422 'art050040' => 'Portraits',
423 'art050050' => 'Erotic art',
424 'art051000' => 'Color in art',
425 'art052000' => 'Human figure in art',
426 'art053000' => 'Sculpture--Technique',
427 'art055000' => 'Body art',
428 'art056000' => 'Art objects--Conservation and restoration',
429 'art057000' => 'Video art',
430 'art058000' => 'Street art',
431 'art060000' => 'Performance art',
432 'bib000000' => 'Bible',
433 'bio000000' => 'Biography',
434 'bio001000' => 'Artists--Biography',
435 'bio008000' => 'Military biography',
436 'bio009000' => 'Philosophers--Biography',
437 'bio011000' => 'Heads of state--Biography',
438 'bio022000' => 'Women--Biography',
439 'bio023000' => 'Explorers--Biography',
440 'bio024000' => 'Criminals--Biography',
441 'bio030000' => 'Environmentalists--Biography',
442 'bus000000' => 'Economics',
443 'bus001000' => 'Accounting',
444 'bus001030' => 'International business enterprises--Accounting',
445 'bus001050' => 'Accounting--Standards',
446 'bus002000' => 'Advertising',
447 'bus003000' => 'Auditing',
448 'bus004000' => 'Banks and banking',
449 'bus005000' => 'Bookkeeping',
450 'bus006000' => 'Budget',
451 'bus007000' => 'Business communication',
452 'bus007010' => 'Business meetings',
453 'bus008000' => 'Business ethics',
454 'bus009000' => 'Business etiquette',
455 'bus010000' => 'Commercial law',
456 'bus011000' => 'Business writing',
457 'bus012000' => 'Occupations',
458 'bus012010' => 'Internship programs',
459 'bus013000' => 'Commercial policy',
460 'bus014000' => 'Commodity exchanges',
461 'bus015000' => 'Consolidation and merger of corporations',
462 'bus016000' => 'Consumer behavior',
463 'bus017000' => 'Corporations--Finance',
464 'bus018000' => 'Customer relations',
465 'bus019000' => 'Decision making',
466 'bus020000' => 'Business--Development',
467 'bus021000' => 'Econometrics',
468 'bus022000' => 'Economic conditions',
469 'bus023000' => 'Economic history',
470 'bus024000' => 'Business education',
471 'bus025000' => 'Entrepreneurship',
472 'bus026000' => 'International trade',
473 'bus027000' => 'Finance',
474 'bus028000' => 'Foreign exchange',
475 'bus029000' => 'Free enterprise',
476 'bus030000' => 'Personnel management',
477 'bus031000' => 'Inflation (Finance)',
478 'bus032000' => 'Infrastructure (Economics)',
479 'bus033000' => 'Insurance',
480 'bus033010' => 'Automobile insurance',
481 'bus033020' => 'Casualty insurance',
482 'bus033040' => 'Health insurance',
483 'bus033050' => 'Liability insurance',
484 'bus033060' => 'Life insurance',
485 'bus033070' => 'Risk (Insurance)',
486 'bus033080' => 'Property insurance',
487 'bus034000' => 'Interest',
488 'bus035000' => 'International business enterprises',
489 'bus036000' => 'Investments',
490 'bus036010' => 'Bonds',
491 'bus036020' => 'Futures',
492 'bus036030' => 'Mutual funds',
493 'bus036040' => 'Options (Finance)',
494 'bus036050' => 'Real estate investment',
495 'bus036060' => 'Stocks',
496 'bus037000' => 'Job hunting',
497 'bus037020' => 'Job hunting',
498 'bus038000' => 'Labor',
499 'bus039000' => 'Macroeconomics',
500 'bus040000' => 'Mail-order business',
501 'bus041000' => 'Management',
502 'bus042000' => 'Management science',
503 'bus043000' => 'Marketing',
504 'bus043010' => 'Direct marketing',
505 'bus043020' => 'Industrial marketing',
506 'bus043030' => 'Export marketing',
507 'bus043040' => 'Multilevel marketing',
508 'bus043050' => 'Telemarketing',
509 'bus043060' => 'Marketing research',
510 'bus044000' => 'Microeconomics',
511 'bus045000' => 'Monetary policy',
512 'bus046000' => 'Achievement motivation',
513 'bus047000' => 'Negotiation',
514 'bus048000' => 'New business enterprises',
515 'bus049000' => 'Operations research',
516 'bus050000' => 'Finance, Personal',
517 'bus050010' => 'Budgets, Personal',
518 'bus050020' => 'Investments',
519 'bus050040' => 'Retirement--Planning',
520 'bus050050' => 'Income tax',
521 'bus051000' => 'Finance, Public',
522 'bus052000' => 'Public relations',
523 'bus053000' => 'Quality control',
524 'bus054000' => 'Real property',
525 # 'bus054010' could be either House Buying or House Selling
526 'bus054020' => 'Commercial real estate',
527 'bus054030' => 'Mortgages',
528 'bus055000' => 'Business--Reference books',
529 'bus056030' => 'Résumés (Employment)',
530 'bus057000' => 'Retail trade',
531 # 'bus058000' could be either Sales or Selling
532 'bus058010' => 'Sales management',
533 'bus059000' => 'Business--Training',
534 'bus060000' => 'Small business',
535 # 'bus061000' could be either 'Commercial statistics' or 'Economic statistics'
536 'bus062000' => 'Structural adjustment (Economic policy)',
537 'bus063000' => 'Strategic planning',
538 'bus064000' => 'Taxation',
539 'bus064010' => 'Corporations--Taxation',
540 'bus064020' => 'International business enterprises--Taxation',
541 'bus064030' => 'Small business--Taxation',
542 'bus065000' => 'Total quality management',
543 'bus066000' => 'Business--Training',
544 'bus067000' => 'Regional economics',
545 'bus068000' => 'Economic development',
546 'bus069000' => 'Economics',
547 'bus069010' => 'Comparative economics',
548 'bus069020' => 'Competition, International',
549 'bus069030' => 'Economics',
550 'bus070000' => 'Industries',
551 'bus070010' => 'Agricultural industries',
552 'bus070020' => 'Automobile industry and trade',
553 'bus070030' => 'Computer industry',
554 'bus070040' => 'Energy industries',
555 'bus070050' => 'Manufacturing industries',
556 'bus070060' => 'Communication and traffic',
557 'bus070070' => 'Parks--Management',
558 'bus070080' => 'Service industries',
559 'bus070090' => 'Textile industry',
560 'bus070100' => 'Transportation',
561 'bus070110' => 'Entertainment industry',
562 'bus070120' => 'Food industry and trade',
563 'bus070130' => 'Biotechnology industries',
564 'bus070140' => 'Financial services industry',
565 'bus070150' => 'Natural resources',
566 'bus071000' => 'Leadership',
567 'bus072000' => 'Sustainable development',
568 'bus073000' => 'Commerce',
569 'bus074000' => 'Nonprofit organizations',
570 # 'bus075000' is 'Consulting' which has no exact LC match
571 'bus076000' => 'Purchasing',
572 'bus077000' => 'Commerce--History',
573 'bus078000' => 'Distribution (Economic theory)',
574 'bus079000' => 'Industrial policy',
575 'bus080000' => 'Home-based businesses',
576 'bus081000' => 'Tourism',
577 'bus082000' => 'Industrial management',
578 'bus083000' => 'Information resources management',
579 'bus084000' => 'Office practice--Automation',
580 'bus085000' => 'Organizational behavior',
581 'bus086000' => 'Business forecasting',
582 'bus087000' => 'Production management',
583 'bus088000' => 'Time management',
584 'bus089000' => 'Secretaries--Training',
585 'bus090000' => 'Electronic commerce',
586 'bus090010' => 'Internet advertising',
587 'bus090020' => 'Internet banking',
588 'bus090030' => 'Electronic trading of securities',
589 'bus090040' => 'Internet auctions',
590 'bus091000' => 'Business mathematics',
591 'bus092000' => 'Economic development',
592 'bus093000' => 'Facility management',
593 'bus094000' => 'Business enterprises--Environmental aspects',
594 'bus095000' => 'Office equipment and supplies',
595 'bus096000' => 'Office management',
596 'bus097000' => 'Work environment',
597 'bus098000' => 'Intellectual capital',
598 'bus099000' => 'Environmental economics',
599 'bus100000' => 'Museum techniques',
600 'bus101000' => 'Project management',
601 'bus102000' => 'Contracting out',
602 'bus103000' => 'Organizational change',
603 'bus104000' => 'Corporate governance',
604 'bus105000' => 'Franchises (Retail trade)',
605 'bus106000' => 'Executive coaching',
606 'bus107000' => 'Success',
607 'bus108000' => 'Research and development projects',
608 'bus109000' => 'Businesswomen',
609 'bus110000' => 'Conflict management',
610 'cgn000000' => 'Comic books, strips, etc',
611 'cgn004080' => 'Superheroes',
612 'ckb000000' => 'Cooking',
613 'ckb001000' => 'Cooking, African',
614 'ckb002000' => 'Cooking, American',
615 'ckb002010' => 'Cooking, American--California style',
616 'ckb002020' => 'Cooking, American--Middle Atlantic States',
617 'ckb002030' => 'Cooking, American--Midwestern style',
618 'ckb002040' => 'Cooking, American--New England style',
619 'ckb002050' => 'Cooking, American--Northwestern States',
620 'ckb002060' => 'Cooking, American--Southern style',
621 'ckb002070' => 'Cooking, American--Southwestern style',
622 'ckb002080' => 'Cooking, American--Western style',
623 'ckb003000' => 'Appetizers',
624 'ckb004000' => 'Baking',
625 'ckb005000' => 'Barbecuing',
626 'ckb006000' => 'Bartending',
627 'ckb007000' => 'Cooking (Beer)',
628 'ckb008000' => 'Non-alcoholic beverages',
629 'ckb009000' => 'Cooking (Bread)',
630 'ckb010000' => 'Breakfasts',
631 # 'ckb011000' could be 'Cooking, English', 'Cooking, Scottish', or 'Cooking, Welsh'
632 'ckb012000' => 'Brunches',
633 # 'ckb013000' could be either 'Cooking, Cajun' or 'Cooking, Creole'
634 'ckb014000' => 'Cake',
635 'ckb015000' => 'Canning and preserving',
636 # 'ckb016000' could be either 'Cooking, Caribbean' or 'Cooking, West Indian'
637 'ckb017000' => 'Cooking, Chinese',
638 'ckb018000' => 'Cooking (Chocolate)',
639 # 'ckb019000' could be either 'Cooking (Coffee)' or 'Cooking (Tea)'
640 'ckb020000' => 'Cooking for one',
641 'ckb021000' => 'Cookies',
642 'ckb024000' => 'Desserts',
643 'ckb026000' => 'Weight loss',
644 'ckb029000' => 'Entertaining',
645 'ckb033000' => 'Garnishes (Cooking)',
646 'ckb034000' => 'Cooking, French',
647 'ckb036000' => 'Cooking, German',
648 'ckb038000' => 'Cooking, Greek',
649 # 'ckb040000' could be 'Cooking (Herbs)', 'Cooking (Spices)', or 'Condiments'
650 'ckb041000' => 'Cooking--History',
651 'ckb042000' => 'Holiday cooking',
652 'ckb050000' => 'Low-cholesterol diet',
653 'ckb051000' => 'Low-fat diet',
654 'ckb057000' => 'Microwave cooking',
655 'ckb060000' => 'Outdoor cooking',
656 'ckb062000' => 'Pastry',
657 'ckb063000' => 'Pies',
658 'ckb064000' => 'Pizza',
659 'ckb069000' => 'Quantity cooking',
660 'ckb070000' => 'Quick and easy cooking',
661 'ckb073000' => 'Salads',
662 # 'ckb079000' could map to either 'Soups' or 'Stews'
663 'ckb088000' => 'Cooking (Liquors)',
664 'ckb089000' => 'Wok cooking',
665 'ckb090000' => 'Cooking, Asian',
666 'ckb091000' => 'Cooking, Canadian',
667 'ckb092000' => 'Cooking, European',
668 'ckb095000' => 'Confectionery',
669 'ckb099000' => 'Cooking, Latin American',
670 'ckb100000' => 'Beverages',
671 'ckb101000' => 'Entrées (Cooking)',
672 'ckb102000' => 'Sauces',
673 'ckb103000' => 'Cancer--Nutritional aspects',
674 'ckb104000' => 'Heart--Diseases--Nutritional aspects',
675 'ckb106000' => 'Food allergy',
676 'ckb107000' => 'Baby foods',
677 'ckb108000' => 'Low-carbohydrate diet',
678 'ckb110000' => 'Raw foods',
679 'ckb111000' => 'Gluten-free foods',
680 'ckb112000' => 'Casserole cooking',
681 'com000000' => 'Computers',
682 'com001000' => 'Computer peripherals',
683 'com003000' => 'Application software',
684 'com004000' => 'Artificial intelligence',
685 "com006000" => "Computers--Buyers' guides",
686 'com007000' => 'CAD/CAM systems',
687 'com008000' => 'Calculators',
688 'com009000' => 'Optical disks',
689 'com010000' => 'Compilers (Computer programs)',
690 'com011000' => 'Computer architecture',
691 'com012000' => 'Computer graphics',
692 'com012040' => 'Computer games--Programming',
693 'com012050' => 'Image processing',
694 'com013000' => 'Computer literacy',
695 'com014000' => 'Computer science',
696 'com015000' => 'Malware (Computer software)',
697 # 'com016000' could be either 'Computer vision' or 'Pattern recognition systems'
698 'com018000' => 'Data processing',
699 'com020000' => 'Data transmission systems',
700 'com020010' => 'Electronic data interchange',
701 'com020050' => 'Broadband communication systems',
702 'com020060' => 'Modems',
703 'com020090' => 'Wireless communication systems',
704 'com021000' => 'Databases',
705 'com021030' => 'Data mining',
706 'com021040' => 'Data warehousing',
707 'com023000' => 'Computer software--Education',
708 'com024000' => 'Computer games',
709 'com025000' => 'Expert systems (Computer science)',
710 'com027000' => 'Finance, Personal--Software',
711 'com031000' => 'Information theory',
712 'com032000' => 'Information technology',
713 'com034000' => 'Interactive computer systems',
714 'com035000' => 'Keyboarding',
715 'com036000' => 'Logic design',
716 'com037000' => 'Machine theory',
717 'com039000' => 'Management information systems',
718 'com040000' => 'Memory management (Computer science)',
719 'com041000' => 'Microprocessors',
720 'com042000' => 'Computational linguistics',
721 'com043000' => 'Computer networks',
722 'com043020' => 'Local area networks (Computer networks)',
723 'com043040' => 'Computer network protocols',
724 'com043050' => 'Computer networks--Security measures',
725 'com044000' => 'Neural networks (Computer science)',
726 'com046000' => 'Operating systems (Computers)',
727 'com046090' => 'Virtual computer systems',
728 'com047000' => 'Optical data processing',
729 'com048000' => 'Electronic data processing--Distributed processing',
730 'com049000' => 'Computer peripherals',
731 'com050000' => 'Microcomputers',
732 'com050020' => 'Macintosh-compatible computers',
733 'com051000' => 'Computer programming',
734 'com051010' => 'Programming languages (Electronic computers)',
735 'com051020' => 'Ada (Computer program language)',
736 'com051030' => 'C (Computer program language)',
737 'com051040' => 'Assembly languages (Electronic computers)',
738 "com051050" => 'BASIC (Computer program language)',
739 'com051060' => 'C (Computer program language)',
740 'com051070' => 'C++ (Computer program language)',
741 'com051080' => 'COBOL (Computer program language)',
742 'com051090' => 'FORTRAN (Computer program language)',
743 'com051100' => 'LISP (Computer program language)',
744 'com051110' => 'C (Computer program language)',
745 'com051120' => 'Modula-2 (Computer program language)',
746 'com051130' => 'Pascal (Computer program language)',
747 'com051140' => 'Prolog (Computer program language)',
748 'com051150' => 'C (Computer program language)',
749 'com051160' => 'Smalltalk (Computer program language)',
750 'com051170' => 'SQL (Computer program language)',
751 'com051180' => 'C (Computer program language)',
752 'com051190' => 'Pascal (Computer program language)',
753 'com051210' => 'Object-oriented programming (Computer science)',
754 'com051220' => 'Parallel programming (Computer science)',
755 # 'com051230' could be either 'Computer software--Development' or 'Software engineering'
756 'com051240' => 'System analysis',
757 'com051260' => 'JavaScript (Computer program language)',
758 'com051270' => 'HTML (Document markup language)',
759 'com051280' => 'Java (Computer program language)',
760 'com051290' => 'RPG (Computer program language)',
761 'com051300' => 'Computer programming--Algorithms',
762 'com051310' => 'C# (Computer program language)',
763 'com051320' => 'XML (Document markup language)',
764 'com051330' => 'Computer software--Quality assurance',
765 'com051340' => 'Computer network protocols',
766 'com051350' => 'Perl (Computer program language)',
767 'com051360' => 'Python (Computer program language)',
768 'com051400' => 'PHP (Computer program language)',
769 'com051410' => 'Ruby (Computer program language)',
770 'com051420' => 'VBScript (Computer program language)',
771 'com051430' => 'Software engineering--Project management',
772 'com051450' => 'UML (Computer science)',
773 'com052000' => 'Computers--Reference',
774 'com053000' => 'Computer security',
775 'com054000' => 'Electronic spreadsheets--Software',
776 'com054010' => 'Electronic spreadsheets--Software',
777 'com054020' => 'Electronic spreadsheets--Software',
778 'com055000' => 'Computer technicians--Certification--Study guides',
779 'com057000' => 'Virtual reality',
780 'com058000' => 'Word processing--Software',
781 'com058010' => 'Word processing--Software',
782 'com058020' => 'Word processing--Software',
783 'com059000' => 'Computer engineering',
784 'com060000' => 'Internet',
785 # 'com060030' could be either 'Extranets (Computer networks)' or
786 # 'Intranets (Computer networks)'
787 'com060010' => 'Browsers (Computer programs)',
788 'com060040' => 'Internet--Safety measures',
789 'com060070' => 'Web sites--Directories',
790 'com060080' => 'World Wide Web',
791 'com060090' => 'Application software--Internet--Development',
792 'com060100' => 'Blogs',
793 'com060110' => 'Webcasting',
794 'com060120' => 'Web search engines',
795 'com060130' => 'Web sites--Design',
796 'com060140' => 'Online social networks',
797 'com060150' => 'User-generated content',
798 'com060160' => 'Web site development',
799 'com060180' => 'Web services',
800 'com063000' => 'Document imaging systems',
801 'com064000' => 'Electronic commerce',
802 'com065000' => 'Electronic publishing',
803 'com067000' => 'Computers',
804 'com069000' => 'Online information services',
805 'com069010' => 'Online information services',
806 'com070000' => 'User interfaces (Computer systems)',
807 'com071000' => 'Computer animation',
808 'com072000' => 'Computer simulation',
809 'com073000' => 'Speech processing systems',
810 'com074000' => 'Mobile computing',
811 'com076000' => 'Computers',
812 'com077000' => 'Computer software--Mathematics',
813 'com078000' => 'Presentation graphics software',
814 'com079000' => 'Computers--Social aspects',
815 'com079010' => 'Human-computer interaction',
816 'com080000' => 'Computers--History',
817 'com081000' => 'Project management--Software',
818 'com082000' => 'Bioinformatics',
819 'com083000' => 'Cryptography',
820 'com084000' => 'Application software',
821 'com084010' => 'Databases',
822 'com084020' => 'Electronic mail systems',
823 'com085000' => 'Technical writing',
824 'com087000' => 'Digital media',
825 'com088000' => 'Computers--Administration',
826 'com090000' => 'Tablet computers',
827 'computers/programming languages/javascript' => 'JavaScript (Computer program language)',
828 'computers/programming languages' => 'Programming languages (Electronic computers)',
829 'computers/reference' => 'Computers--Reference',
830 'juv000000' => 'Fiction, Juvenile',
831 'fic000000' => 'Fiction',
832 'fic009000' => 'Fantasy fiction',
833 'fic014000' => 'Historical fiction',
834 'fic027000' => 'Love stories',
835 'occ000000' => 'Superstition',
836 'occ003000' => 'Channeling (Spiritualism)',
837 'occ004000' => 'Crystals',
838 'occ005000' => 'Divination',
839 'occ006000' => 'Dreams',
840 'occ007000' => 'Extrasensory perception',
841 'occ008000' => 'Fortune-telling',
842 'occ009000' => 'Horoscopes',
843 'occ010000' => 'Meditation',
844 'occ011000' => 'Mental healing',
845 'occ011010' => 'Energy medicine',
846 'occ011020' => 'Spiritual healing',
847 'occ014000' => 'New Thought',
848 'occ015000' => 'Numerology',
849 'occ016000' => 'Occultism',
850 'occ017000' => 'Palmistry',
851 'occ018000' => 'Parapsychology',
852 'occ019000' => 'Inspiration--Religious aspects',
853 'occ020000' => 'Prophecy',
854 'occ022000' => 'Immortality',
855 'occ023000' => 'Supernatural',
856 'occ024000' => 'Tarot',
857 'occ025000' => 'Unidentified flying objects',
858 'occ026000' => 'Witchcraft',
859 'occ027000' => 'Spiritualism',
860 'occ028000' => 'Magic',
861 'occ031000' => 'Controversial literature',
862 'occ032000' => 'Guides (Spiritualism)',
863 'occ034000' => 'Near-death experiences',
864 'occ035000' => 'Astral projection',
865 'occ036000' => 'Spirituality',
866 'occ036030' => 'Shamanism',
867 'occ036050' => 'Goddess religion',
868 'occ037000' => 'Feng shui',
869 'occ039000' => 'Hallucinogenic drugs',
870 'occ040000' => 'Hermetism',
871 'occ041000' => 'Sex--Religious aspects',
872 );
873  
874 our %booktypes = (
875 # Fiction types, by length (definitions are not standardized)
876 'micro fiction' => 'Micro Fiction', # Below 100 words
877 'micro-fiction' => 'Micro Fiction',
878 'drabble' => 'Drabble', # 100 words, exactly
879 'flash fiction' => 'Flash Fiction', # Below 1000 words
880 'short short' => 'Flash Fiction',
881 'short short story' => 'Flash Fiction',
882 'short story' => 'Short Story', # Generally 1k-10k words
883 'short' => 'Short Story',
884 'novelette' => 'Novelette', # Generally 7.5k-15k words
885 'novella' => 'Novella', # Generally 12k-40k words
886 'novel' => 'Novel', # Over 50k words
887 'anthology' => 'Anthology', # Multiple novellas or shorter
888 'omnibus' => 'Omnibus', # Multiple novels
889 'complete works' => 'Complete Works', # Complete collection of all works by an author
890 'opera omnia' => 'Complete Works',
891 # Age categories
892 'picture book' => 'Picture Book', # For pre-readers or children ages 0-5
893 'early reader' => 'Early Reader', # For ages 5-7
894 'chapter book' => 'Chapter Book', # For ages 7-12
895 'young-adult novel' => 'Young-Adult Novel', # Subcategory of Novel aimed at ages 12-18
896 'ya novel' => 'Young-Adult Novel',
897 # Non-fiction types
898 'academic paper' => 'Academic Paper', # Creditable, peer-reviewed sources
899 'almanac' => 'Almanac',
900 'autobiography' => 'Autobiography',
901 'biography' => 'Biography',
902 'book report' => 'Book Report',
903 'creative nonfiction' => 'Creative Nonfiction', # Flexible imaginings of actual events
904 'design document' => 'Design Document',
905 'diary' => 'Diary',
906 'dictionary', => 'Dictionary',
907 'encyclopædia' => 'Encyclopedia',
908 'encyclopaedia' => 'Encyclopedia',
909 'encyclopedia' => 'Encyclopedia',
910 'essay' => 'Essay',
911 'essay collection' => 'Essay Collection',
912 'journal' => 'Journal', # Collection of papers, academic or technical, with or without review
913 'journalism' => 'Journalism',
914 'letter' => 'Letters', # Correspondence, singular or collective
915 'letters' => 'Letters',
916 'memoir' => 'Memoir',
917 'popular science' => 'Popular Science', # Interpretation of science for a general audience
918 'reference' => 'Reference', # Includes blueprints, guides, manuals, diagrams,
919 # but see also 'Technical Writing' below
920 'technical writing' => 'Technical Writing', # Includes 'how-to' books even on nontechnical topics
921 'technical' => 'Technical Writing',
922 'thesaurus' => 'Thesaurus',
923 'travelogue' => 'Travelogue',
924 # Other types
925 'art' => 'Art', # Collection of artistic images
926 'comic book' => 'Comic Book',
927 'graphic novel' => 'Graphic Novel',
928 'photography' => 'Photography',
929 'poetry' => 'Poetry', # One or more structured poems
930 'prose poetry' => 'Prose', # One or more unstructured prose works
931 'prose' => 'Prose',
932 );
933  
934 our %dcelements12;
935 tie %dcelements12, 'Tie::IxHash', (
936 "dc:identifier" => "dc:Identifier",
937 "dc:title" => "dc:Title",
938 "dc:creator" => "dc:Creator",
939 "dc:contributor" => "dc:Contributor",
940 "dc:subject" => "dc:Subject",
941 "dc:description" => "dc:Description",
942 "dc:publisher" => "dc:Publisher",
943 "dc:date" => "dc:Date",
944 "dc:type" => "dc:Type",
945 "dc:format" => "dc:Format",
946 "dc:source" => "dc:Source",
947 "dc:language" => "dc:Language",
948 "dc:relation" => "dc:Relation",
949 "dc:coverage" => "dc:Coverage",
950 "dc:rights" => "dc:Rights",
951 "dc:copyrights" => "dc:Rights"
952 );
953  
954 our %dcelements20;
955 tie %dcelements20, 'Tie::IxHash', (
956 "dc:identifier" => "dc:identifier",
957 "dc:title" => "dc:title",
958 "dc:creator" => "dc:creator",
959 "dc:contributor" => "dc:contributor",
960 "dc:subject" => "dc:subject",
961 "dc:description" => "dc:description",
962 "dc:publisher" => "dc:publisher",
963 "dc:date" => "dc:date",
964 "dc:type" => "dc:type",
965 "dc:format" => "dc:format",
966 "dc:source" => "dc:source",
967 "dc:language" => "dc:language",
968 "dc:relation" => "dc:relation",
969 "dc:coverage" => "dc:coverage",
970 "dc:rights" => "dc:rights",
971 "dc:copyrights" => "dc:rights"
972 );
973  
974 our %lcsubjects = (
975 'abolition of capital punishment' => 'Capital punishment',
976 'abolition of slavery' => 'Slavery',
977 'abolition' => 'Slavery',
978 'absent treatment' => 'Mental healing',
979 'abstract automata' => 'Machine theory',
980 'abstract machines' => 'Machine theory',
981 'absurd (philosophy)' => 'Absurd (Philosophy)',
982 'absurdist (philosophy)' => 'Absurd (Philosophy)',
983 'absurdist' => 'Absurd (Philosophy)',
984 'abuse of children' => 'Child abuse',
985 'accountancy' => 'Accounting',
986 'accounting' => 'Accounting',
987 'accounting standards' => 'Accounting--Standards',
988 'accounting--standards' => 'Accounting--Standards',
989 'achievement motivation' => 'Achievement motivation',
990 'aching, tiffany (fictitious character)' => 'Aching, Tiffany (Fictitious character)',
991 'aching, tiffany' => 'Aching, Tiffany (Fictitious character)',
992 'acquisition of corporations' => 'Consolidation and merger of corporations',
993 'acquisitions and mergers' => 'Consolidation and merger of corporations',
994 'action research' => 'Action research',
995 'acts of terrorism' => 'Terrorism',
996 'ada (computer program language)' => 'Ada (Computer program language)',
997 'ada' => 'Ada (Computer program language)',
998 'adding machines' => 'Calculators',
999 'adding-machines' => 'Calculators',
1000 'adiposity' => 'Obesity',
1001 'administration' => 'Management',
1002 'administrative communication' => 'Business communication',
1003 'ads' => 'Advertising',
1004 'adventure' => 'Adventure stories',
1005 'adventure stories' => 'Adventure stories',
1006 'advertisements' => 'Advertising',
1007 'advertising' => 'Advertising',
1008 'african art' => 'Art, African',
1009 'african american art' => 'African American art',
1010 'african cooking' => 'Cooking, African',
1011 'afro-american art' => 'African American art',
1012 'afterlife' => 'Immortality',
1013 'agents, search' => 'Search engines',
1014 'agoraphobia' => 'Agoraphobia',
1015 'agribusiness' => 'Agricultural industries',
1016 'agricultural industries' => 'Agricultural industries',
1017 'aias (greek mythology)' => 'Ajax (Greek mythology)',
1018 'ajax (greek mythology)' => 'Ajax (Greek mythology)',
1019 'ajax (legendary character)' => 'Ajax (Greek mythology)',
1020 'ajax (web site development technology)' => 'Ajax (Web site development technology)',
1021 'ajax the greater (greek mythology)' => 'Ajax (Greek mythology)',
1022 'ajax the greater' => 'Ajax (Greek mythology)',
1023 'algorism' => 'Algorithms',
1024 'algorithmic knowledge discovery' => 'Data mining',
1025 'algorithms' => 'Algorithms',
1026 'allocation of time' => 'Time management',
1027 'amalgamation of corporations' => 'Consolidation and merger of corporations',
1028 'american cooking' => 'Cooking, American',
1029 'americana' => 'Americana',
1030 'androids' => 'Androids',
1031 'animation, computer' => 'Computer animation',
1032 'angelology' => 'Angels',
1033 'angels' => 'Angels',
1034 'angleterre' => 'England',
1035 'anglii͡a' => 'England',
1036 'animals in art' => 'Animals in art',
1037 'antique and classic cars' => 'Antique and classic cars',
1038 'antique cars' => 'Antique and classic cars',
1039 'antiques' => 'Antiques',
1040 'antiques--americana' => 'Antiques--Americana',
1041 'antiques--art' => 'Antiques--Art',
1042 'antiques--baskets' => 'Antiques--Baskets',
1043 'antiques--books' => 'Antiques--Books',
1044 'antiques--bottles' => 'Antiques--Bottles',
1045 'antiques--buttons' => 'Antiques--Buttons',
1046 'antiques--cartoons' => 'Antiques--Cartoons',
1047 'antiques--clocks and watches' => 'Antiques--Clocks and watches',
1048 'antiques--coins' => 'Antiques--Coins',
1049 'antiques--dolls' => 'Antiques--Dolls',
1050 'antiques--figurines' => 'Antiques--Figurines',
1051 'antiques--firearms' => 'Antiques--Firearms',
1052 'antiques--furniture' => 'Antiques--Furniture',
1053 'antiques--glassware' => 'Antiques--Glassware',
1054 'antiques--jewelry' => 'Antiques--Jewelry',
1055 'antiques--kitchen utensils' => 'Antiques--Kitchen utensils',
1056 'antiques--musical instruments' => 'Antiques--Musical instruments',
1057 'antiques--periodicals' => 'Antiques--Periodicals',
1058 'antislavery' => 'Slavery',
1059 'appearance bias' => 'Physical-appearance-based bias',
1060 'appearance discrimination' => 'Physical-appearance-based bias',
1061 'appearance-based bias' => 'Physical-appearance-based bias',
1062 'appearance-based discrimination' => 'Physical-appearance-based bias',
1063 'ai' => 'Artificial intelligence',
1064 'airbrush art' => 'Airbrush art',
1065 'airbrush art--technique' => 'Airbrush art',
1066 'ais' => 'Artificial intelligence',
1067 'alimentation', => 'Nutrition',
1068 'alsatian cooking' => 'Cooking, French--Alsatian style',
1069 'alternate histories' => 'Alternative histories (Fiction)',
1070 'alternate histories (fiction)' => 'Alternative histories (Fiction)',
1071 'alternate history' => 'Alternative histories (Fiction)',
1072 'alternative histories' => 'Alternative histories (Fiction)',
1073 'alternative histories (fiction)' => 'Alternative histories (Fiction)',
1074 'alternative history' => 'Alternative histories (Fiction)',
1075 'american art' => 'Art, American',
1076 'american science fiction and fantasy' => 'Speculative fiction',
1077 'appetizers' => 'Appetizers',
1078 'application computer programs' => 'Application software',
1079 'application computer software' => 'Application software',
1080 'application software' => 'Application software',
1081 'application software--development' => 'Application software--Development',
1082 'application software--internet' => 'Application software--Internet',
1083 'application software--internet--development' => 'Application software--Internet--Development',
1084 'applications software' => 'Application software',
1085 'apps (computer software)' => 'Application software',
1086 'apps' => 'Application software',
1087 'ararat, mount (turkey)' => 'Ararat, Mount (Turkey)',
1088 'architecture' => 'Architecture',
1089 'architecture, computer' => 'Computer architecture',
1090 'architecture--history' => 'Architecture--History',
1091 'arithmetic' => 'Mathematics',
1092 'art' => 'Art',
1093 'art and business' => 'Art and business',
1094 'art collections' => 'Art collections',
1095 'art criticism' => 'Art criticism',
1096 'art objects' => 'Art objects',
1097 'art objects--conservation and restoration'
1098 => 'Art objects--Conservation and restoration',
1099 'art technique' => 'Art--Technique',
1100 'art, african' => 'Art, African',
1101 'art, african american' => 'African American art',
1102 'art, american' => 'Art, American',
1103 'art, asian' => 'Art, Asian',
1104 'art, asian american' => 'Asian American art',
1105 'art, asiatic' => 'Art, Asian',
1106 'art, australian' => 'Art, Australian',
1107 'art, canadian' => 'Art, Canadian',
1108 'art, caribbean' => 'Art, Caribbean',
1109 'art, conceptual' => 'Conceptual art',
1110 'art, digital' => 'Digital art',
1111 'art, erotic' => 'Erotic art',
1112 'art, european' => 'Art, European',
1113 'art, folk' => 'Folk art',
1114 'art, hispanic american' => 'Hispanic American art',
1115 'art, latin american' => 'Art, Latin American',
1116 'art, middle east' => 'Art--Middle East',
1117 'art, middle eastern' => 'Art--Middle East',
1118 'art, modern' => 'Art, Modern',
1119 'art, modern--europe' => 'Art, Modern--Europe',
1120 'art, oriental' => 'Art, Asian',
1121 'art, performance' => 'Performance art',
1122 'art, russian' => 'Art, Russian',
1123 'art, spanish american' => 'Art, Latin American',
1124 'art, street' => 'Street art',
1125 'art, video' => 'Video art',
1126 'art, wall' => 'Street art',
1127 'art--criticism' => 'Art criticism',
1128 'art--middle east' => 'Art--Middle East',
1129 'art--subjects' => 'Art--Themes, motives',
1130 'art--technique' => 'Art--Technique',
1131 'art--themes, motives' => 'Art--Themes, motives',
1132 'artificial intelligence' => 'Artificial intelligence',
1133 'artificial neural networks' => 'Neural networks (Computer science)',
1134 'artificial thinking' => 'Artificial intelligence',
1135 'artistic technique' => 'Art--Technique',
1136 'artists' => 'Artists',
1137 'artists--biography' => 'Artists--Biography',
1138 'arts--criticism' => 'Art criticism',
1139 'arts--study and teaching' => 'Arts--Study and teaching',
1140 'asian american art' => 'Asian American art',
1141 'asian cookery' => 'Cooking, Asian',
1142 'asian cooking' => 'Cooking, Asian',
1143 'asiatic art' => 'Art, Asian',
1144 'assembler language (computer program language)' => 'Assembly languages (Electronic computers)',
1145 'assembler language (electronic computers)' => 'Assembly languages (Electronic computers)',
1146 'assembler language' => 'Assembly languages (Electronic computers)',
1147 'assembler languages (electronic computers)' => 'Assembly languages (Electronic computers)',
1148 'assembler languages' => 'Assembly languages (Electronic computers)',
1149 'assembly language (electronic computers)' => 'Assembly languages (Electronic computers)',
1150 'assembly language' => 'Assembly languages (Electronic computers)',
1151 'assembly languages (electronic computers)' => 'Assembly languages (Electronic computers)',
1152 'assembly languages' => 'Assembly languages (Electronic computers)',
1153 'assurance (insurance)' => 'Insurance',
1154 'astral projection' => 'Astral projection',
1155 'astral travel' => 'Astral projection',
1156 'astrology' => 'Astrology',
1157 'astrology, chinese' => 'Astrology, Chinese',
1158 'asynchronous javascript and xml' => 'Ajax (Web site development technology)',
1159 'athletic competitions' => 'Sports',
1160 'athletics' => 'Sports',
1161 'attacks, terrorist' => 'Terrorism',
1162 'auditing' => 'Auditing',
1163 'audits' => 'Auditing',
1164 'augury' => 'Divination',
1165 'austen, jane, 1775-1817' => 'Austen, Jane, 1775-1817',
1166 'austen, jane' => 'Austen, Jane, 1775-1817',
1167 'australian art' => 'Art, Australian',
1168 'authoring (authorship)' => 'Authorship',
1169 'authoring' => 'Authorship',
1170 'authorship' => 'Authorship',
1171 'autobiography' => 'Biography',
1172 'autographs' => 'Autographs',
1173 'automatic computers' => 'Computers',
1174 'automatic data processing equipment' => 'Computers',
1175 'automatic data processors' => 'Computers',
1176 'automatic drafting' => 'Computer graphics',
1177 'automatic language processing' => 'Computational linguistics',
1178 'automobile industry' => 'Automobile industry and trade',
1179 'automobile industry and trade' => 'Automobile industry and trade',
1180 'automobile collision insurance' => 'Automobile insurance',
1181 'automobile insurance' => 'Automobile insurance',
1182 'automobile liability insurance' => 'Automobile insurance',
1183 'automobiles' => 'Automobiles',
1184 'automotive industry' => 'Automobile industry and trade',
1185 'auvergnat cooking' => 'Cooking, French--Auvergne style',
1186 'auvergne cooking' => 'Cooking, French--Auvergne style',
1187 'b-to-b marketing' => 'Industrial marketing',
1188 'b2b marketing' => 'Industrial marketing',
1189 'babies' => 'Infants',
1190 'baby foods' => 'Baby foods',
1191 'bagdad (iraq)' => 'Baghdad (Iraq)',
1192 'bagdad' => 'Baghdad (Iraq)',
1193 'bagddad (iraq)' => 'Baghdad (Iraq)',
1194 'bagddad' => 'Baghdad (Iraq)',
1195 'baghdad (iraq)' => 'Baghdad (Iraq)',
1196 'baghdad' => 'Baghdad (Iraq)',
1197 'baking bread' => 'Cooking (Bread)',
1198 'baking' => 'Baking',
1199 'bank robberies' => 'Bank robberies',
1200 'banking industry' => 'Banks and banking',
1201 'banking' => 'Banks and banking',
1202 'banks and banking' => 'Banks and banking',
1203 'barbecue cookery' => 'Barbecuing',
1204 'barbecue cooking' => 'Barbecuing',
1205 'barbecuing' => 'Barbecuing',
1206 'barbeque cookery' => 'Barbecuing',
1207 'barbeque cooking' => 'Barbecuing',
1208 'barbequing' => 'Barbecuing',
1209 'bargaining' => 'Negotiation',
1210 'bartending' => 'Bartending',
1211 'basic (computer program language)' => 'BASIC (Computer program language)',
1212 'basic rights' => 'Civil rights',
1213 'baskets' => 'Baskets',
1214 'bavarian cooking' => 'Cooking, German--Bavarian style',
1215 'bbq cooking' => 'Barbecuing',
1216 'beaurocracy' => 'Bureaucracy',
1217 'bedouin' => 'Bedouins',
1218 'bedouins' => 'Bedouins',
1219 'beduin' => 'Bedouins',
1220 'beduins' => 'Bedouins',
1221 'beer' => 'Beer',
1222 'beer--use in cooking' => 'Cooking (Beer)',
1223 "beginner's all-purpose symbolic instruction code" => 'BASIC (Computer program language)',
1224 'behavior in organizations' => 'Organizational behavior',
1225 'beverages' => 'Beverages',
1226 'beverages, non-alcoholic' => 'Non-alcoholic beverages',
1227 'bi-sexuality' => 'Bisexuality',
1228 'bible' => 'Bible',
1229 'big guns' => 'Ordnance',
1230 'bio-informatics' => 'Bioinformatics',
1231 'bio-terrorism' => 'Bioterrorism',
1232 'biography' => 'Biography',
1233 'bioinformatics' => 'Bioinformatics',
1234 'biological informatics' => 'Bioinformatics',
1235 'biological neural networks' => 'Neural networks (Neurobiology)',
1236 'bionics' => 'Bionics',
1237 'biotechnology industries' => 'Biotechnology industries',
1238 'biotechnology' => 'Biotechnology',
1239 'bioterrorism' => 'Bioterrorism',
1240 'bioterrorism--social aspects' => 'Bioterrorism--Social aspects',
1241 'biscuits, english' => 'Cookies',
1242 'bisexuality' => 'Bisexuality',
1243 'blogging' => 'Blogs',
1244 'blogs' => 'Blogs',
1245 'boats' => 'Boats',
1246 'body art' => 'Body art',
1247 'body building' => 'Bodybuilding',
1248 'body care' => 'Hygiene',
1249 'body sculpting' => 'Bodybuilding',
1250 'body sculpting (bodybuilding)' => 'Bodybuilding',
1251 'bodybuilding' => 'Bodybuilding',
1252 'bodysculpting' => 'Bodybuilding',
1253 'bodysculpting (bodybuilding)' => 'Bodybuilding',
1254 'bond issues' => 'Bonds',
1255 'bonds' => 'Bonds',
1256 'bookkeeping' => 'Bookkeeping',
1257 'books' => 'Books',
1258 'books--appraisal' => 'Criticism',
1259 'bottles' => 'Bottles',
1260 'bread' => 'Bread',
1261 'bread--use in cooking' => 'Cooking (Bread)',
1262 'breads' => 'Bread',
1263 'breakfasts' => 'Breakfasts',
1264 'breton cooking' => 'Cooking, French--Brittany style',
1265 'bric-a-brac' => 'Art objects',
1266 'brittany cooking' => 'Cooking, French--Brittany style',
1267 'broadband communication systems' => 'Broadband communication systems',
1268 'browsers (computer programs)' => 'Browsers (Computer programs)',
1269 'brunches' => 'Brunches',
1270 'budget' => 'Budget',
1271 'budgeting' => 'Budget',
1272 'budgets, family' => 'Budgets, Personal',
1273 'budgets, personal' => 'Budgets, Personal',
1274 'budgets, time' => 'Time management',
1275 'bureaucracy' => 'Bureaucracy',
1276 'burgundy cooking' => 'Cooking, French--Burgundy style',
1277 'business' => 'Commerce',
1278 'business administration' => 'Industrial management',
1279 'business and art' => 'Art and business',
1280 'business coaching' => 'Executive coaching',
1281 'business combinations' => 'Consolidation and merger of corporations',
1282 'business communication' => 'Business communication',
1283 'business data interchange, electronic' => 'Electronic data interchange',
1284 'business development' => 'Business--Development',
1285 'business education' => 'Business education',
1286 'business enterprises' => 'Business enterprises',
1287 'business enterprises, home' => 'Home-based businesses',
1288 'business enterprises, international' => 'International business enterprises',
1289 'business enterprises--environmental aspects' =>
1290 'Business enterprises--Environmental aspects',
1291 'business enterprises--management' => 'Industrial management',
1292 'business espionage' => 'Business intelligence',
1293 'business ethics' => 'Business ethics',
1294 'business etiquette' => 'Business etiquette',
1295 'business finance' => 'Corporations--Finance',
1296 'business forecasting' => 'Business forecasting',
1297 'business forecasts' => 'Business forecasting',
1298 'business graphics software' => 'Presentation graphics software',
1299 'business history' => 'Commerce--History',
1300 'business intelligence' => 'Business intelligence',
1301 'business law' => 'Commercial law',
1302 'business machines' => 'Office equipment and supplies',
1303 'business management' => 'Industrial management',
1304 'business math' => 'Business mathematics',
1305 'business mathematics' => 'Business mathematics',
1306 'business meetings' => 'Business meetings',
1307 'business mergers' => 'Consolidation and merger of corporations',
1308 'business organizations' => 'Business enterprises',
1309 'business presentation software' => 'Presentation graphics software',
1310 'business starts' => 'New business enterprises',
1311 'business statistics' => 'Commercial statistics',
1312 'business to business marketing' => 'Industrial marketing',
1313 'business training' => 'Business--Training',
1314 'business writing' => 'Business writing',
1315 'business--development' => 'Business--Development',
1316 'business--forecasting' => 'Business forecasting',
1317 'business--government policy' => 'Industrial policy',
1318 'business--public relations' => 'Public relations',
1319 'business--reference books' => 'Business--Reference books',
1320 'business--statistical methods' => 'Commercial statistics',
1321 'business--statistics' => 'Commercial statistics',
1322 'business--study and teaching' => 'Business education',
1323 'business--training' => 'Business--Training',
1324 'business-to-business marketing' => 'Industrial marketing',
1325 'businesses' => 'Business enterprises',
1326 'businesses, home' => 'Home-based businesses',
1327 'businesses, small' => 'Small business',
1328 'businesswomen' => 'Businesswomen',
1329 'buttons' => 'Buttons',
1330 'buyer behavior' => 'Consumer behavior',
1331 "buyers' guides" => "Buyers' guides",
1332 'buying' => 'Purchasing',
1333 'buyouts, corporate' => 'Consolidation and merger of corporations',
1334 'c (computer program language)' => 'C (Computer program language)',
1335 'c plus plus' => 'C++ (Computer program language)',
1336 'c# (computer program language)' => 'C# (Computer program language)',
1337 'c++ (computer program language)' => 'C++ (Computer program language)',
1338 'c++' => 'C++ (Computer program language)',
1339 'c-sharp (computer program language)' => 'C# (Computer program language)',
1340 'cad' => 'Computer-aided design',
1341 'cad/cam systems' => 'CAD/CAM systems',
1342 'cajan cooking' => 'Cooking, Cajun',
1343 'cajun cooking' => 'Cooking, Cajun',
1344 'cake' => 'Cake',
1345 'cakes' => 'Cake',
1346 'calculating machines' => 'Calculators',
1347 'calculating-machines' => 'Calculators',
1348 'calculators' => 'Calculators',
1349 'california cooking' => 'Cooking, American--California style',
1350 'call options' => 'Options (Finance)',
1351 'calligraphy' => 'Calligraphy',
1352 'calligraphy--technique' => 'Calligraphy--Technique',
1353 'calls (finance)' => 'Options (Finance)',
1354 'caloric content of food' => 'Food--Caloric content',
1355 'caloric content of foods' => 'Food--Caloric content',
1356 'calories (food)' => 'Food--Caloric content',
1357 'cambistry' => 'Foreign exchange',
1358 'camellia sinensis' => 'Tea',
1359 'camellia thea' => 'Tea',
1360 'camellia theifera' => 'Tea',
1361 'cameralistics' => 'Finance, Public',
1362 'camp cooking' => 'Outdoor cooking',
1363 'campfire cooking' => 'Outdoor cooking',
1364 'canadian art' => 'Art, Canadian',
1365 'canadian cooking' => 'Cooking, Canadian',
1366 'canapes' => 'Appetizers',
1367 'canapés' => 'Appetizers',
1368 'cancer' => 'Cancer',
1369 'cancer--nutritional aspects' => 'Cancer--Nutritional aspects',
1370 'cancers' => 'Cancer',
1371 'canning and preserving' => 'Canning and preserving',
1372 'cannon' => 'Ordnance',
1373 'cannons' => 'Ordnance',
1374 'capital equipment' => 'Industrial equipment',
1375 'capital goods' => 'Industrial equipment',
1376 'capital punishment' => 'Capital punishment',
1377 'capital punishment, abolition of' => 'Capital punishment',
1378 'capital, intellectual' => 'Intellectual capital',
1379 'capital, knowledge' => 'Intellectual capital',
1380 'carcinoma' => 'Cancer',
1381 'careers' => 'Occupations',
1382 'caribbean art' => 'Art, Caribbean',
1383 'caribbean cooking' => 'Cooking, Caribbean',
1384 'caricatures and cartoons' => 'Caricatures and cartoons',
1385 'cars (automobiles)' => 'Automobiles',
1386 'cars' => 'Automobiles',
1387 'cars, antique' => 'Antique and classic cars',
1388 'cars, classic' => 'Antique and classic cars',
1389 'cars, vintage' => 'Antique and classic cars',
1390 'cartooning' => 'Cartooning',
1391 'cartooning--technique' => 'Cartooning',
1392 'cartoons' => 'Caricatures and cartoons',
1393 'carvings' => 'Sculpture',
1394 'case studies' => 'Case studies',
1395 'casserole cookery' => 'Casserole cooking',
1396 'casserole cooking' => 'Casserole cooking',
1397 'casualty insurance' => 'Casualty insurance',
1398 'cats' => 'Cats',
1399 'cds' => 'Compact discs',
1400 'ceramic art' => 'Pottery',
1401 'ceramics (art)' => 'Pottery',
1402 'ceramics' => 'Pottery',
1403 'certification' => 'Certification',
1404 'change, organizational' => 'Organizational change',
1405 'channeling (spiritualism)' => 'Channeling (Spiritualism)',
1406 'channelling (spiritualism)' => 'Channeling (Spiritualism)',
1407 'cheirognomy' => 'Palmistry',
1408 'cheiromancy' => 'Palmistry',
1409 'cheirosophy' => 'Palmistry',
1410 'cherubim' => 'Angels',
1411 'cherubs (spirits)' => 'Angels',
1412 'cherubs' => 'Angels',
1413 'child abuse' => 'Child abuse',
1414 'child maltreatment' => 'Child abuse',
1415 'child molestation' => 'Child sexual abuse',
1416 'child molesting' => 'Child sexual abuse',
1417 'child neglect' => 'Child abuse',
1418 'child sexual abuse' => 'Child sexual abuse',
1419 'children' => 'Children',
1420 'children--abuse of' => 'Child abuse',
1421 'chinaware' => 'Pottery',
1422 'chinese astrology' => 'Astrology, Chinese',
1423 'chinese cooking' => 'Cooking, Chinese',
1424 'chinese historical fiction' => 'Historical fiction, Chinese',
1425 'chirognomy' => 'Palmistry',
1426 'chiromancy' => 'Palmistry',
1427 'chirosophy' => 'Palmistry',
1428 'chocolate' => 'Chocolate',
1429 'chocolate--use in cooking' => 'Cooking (Chocolate)',
1430 # 'chowders' could map to either 'Soups' or 'Stews'
1431 'christianity' => 'Christianity',
1432 'cipher stories' => 'Code and cipher stories',
1433 'ciphers' => 'Ciphers',
1434 'ciphers--fiction' => 'Code and cipher stories',
1435 'ciphers--juvenile fiction' => 'Code and cipher stories',
1436 'cities and towns' => 'Cities and towns',
1437 'cities and towns--economic aspects' => 'Urban economics',
1438 'cities' => 'Cities and towns',
1439 'cities, imaginary' => 'Imaginary places',
1440 'city economics' => 'Urban economics',
1441 'city of london (england)' => 'City of London (England)',
1442 'civil liberties' => 'Civil rights',
1443 'civil resistance' => 'Government, Resistance to',
1444 'civil rights' => 'Civil rights',
1445 'class distinction' => 'Social classes',
1446 'classes, social' => 'Social classes',
1447 'classic automobiles' => 'Antique and classic cars',
1448 'classic cars' => 'Antique and classic cars',
1449 'cleanliness' => 'Hygiene',
1450 'climate science' => 'Climatology',
1451 'climate' => 'Weather',
1452 'climate, workplace' => 'Work environment',
1453 'climatology' => 'Climatology',
1454 'clinical informatics' => 'Medical informatics',
1455 'clinical sciences' => 'Medicine',
1456 'clocks and watches' => 'Clocks and watches',
1457 'clocks' => 'Clocks and watches',
1458 'clones of macintosh computers' => 'Macintosh-compatible computers',
1459 'coaching, business' => 'Executive coaching',
1460 'coaching, executive' => 'Executive coaching',
1461 'cobol (computer program language)' => 'COBOL (Computer program language)',
1462 'cobol' => 'COBOL (Computer program language)',
1463 'code and cipher stories' => 'Code and cipher stories',
1464 'code stories' => 'Code and cipher stories',
1465 'codes' => 'Ciphers',
1466 'coffea arabica' => 'Coffee',
1467 'coffea' => 'Coffee',
1468 'coffee' => 'Coffee',
1469 'coffee--use in cooking' => 'Cooking (Coffee)',
1470 'cognitive psychology' => 'Cognitive psychology',
1471 'coins' => 'Coins',
1472 'cold war' => 'Cold War',
1473 'collectables' => 'Collectibles',
1474 'collectibles' => 'Collectibles',
1475 'collectibles, political' => 'Political collectibles',
1476 'collectibles--popular culture' => 'Collectibles--Popular culture',
1477 'collision insurance, automobile' => 'Automobile insurance',
1478 'color in art' => 'Color in art',
1479 'colors in art' => 'Color in art',
1480 'comic book heroes' => 'Superheroes',
1481 'comic books' => 'Comic books, strips, etc',
1482 'comic books, strips, etc' => 'Comic books, strips, etc',
1483 'comic strips' => 'Comic books, strips, etc',
1484 'comics' => 'Comic books, strips, etc',
1485 'coming of age' => 'Coming of age',
1486 'command of troops' => 'Command of troops',
1487 'command of troops--case studies' => 'Command of troops--Case studies',
1488 'commerce' => 'Commerce',
1489 'commerce--history' => 'Commerce--History',
1490 'commerce--statistical methods' => 'Commercial statistics',
1491 'commerce--statistics' => 'Commercial statistics',
1492 'commercial accounting' => 'Accounting',
1493 'commercial education' => 'Business education',
1494 'commercial ethics' => 'Business ethics',
1495 'commercial goods' => 'Commercial products',
1496 'commercial law' => 'Commercial law',
1497 'commercial policy' => 'Commercial policy',
1498 'commercial products' => 'Commercial products',
1499 'commercial property' => 'Commercial real estate',
1500 'commercial real estate' => 'Commercial real estate',
1501 'commercial real property' => 'Commercial real estate',
1502 'commercial space (real estate)' => 'Commercial real estate',
1503 'commercial space' => 'Commercial real estate',
1504 'commercial speech' => 'Advertising',
1505 'commercial statistics' => 'Commercial statistics',
1506 'commercial trade' => 'Commerce',
1507 'commodities exchange' => 'Commodity exchanges',
1508 'commodities exchanges' => 'Commodity exchanges',
1509 'commodities' => 'Commercial products',
1510 'commodity exchanges' => 'Commodity exchanges',
1511 'commodity markets' => 'Commodity exchanges',
1512 'common business-oriented language' => 'COBOL (Computer program language)',
1513 'common shares' => 'Stocks',
1514 'common stocks' => 'Stocks',
1515 'communication and traffic' => 'Communication and traffic',
1516 'communication systems, computer' => 'Computer networks',
1517 'communication systems, wireless' => 'Wireless communication systems',
1518 'communication theory' => 'Information theory',
1519 'communication, administrative' => 'Business communication',
1520 'communication, business' => 'Business communication',
1521 'communication, industrial' => 'Business communication',
1522 'communications industries' => 'Communication and traffic',
1523 'community health' => 'Public health',
1524 'compact discs' => 'Compact discs',
1525 'compact disks' => 'Compact discs',
1526 'companies' => 'Business enterprises',
1527 'comparative economic systems' => 'Comparative economics',
1528 'comparative economics' => 'Comparative economics',
1529 'compatible computers, macintosh' => 'Macintosh-compatible computers',
1530 'competitive intelligence' => 'Business intelligence',
1531 'compilers (computer programs)' => 'Compilers (Computer programs)',
1532 'compilers' => 'Compilers (Computer programs)',
1533 'compiling programs' => 'Compilers (Computer programs)',
1534 'computer graphics' => 'Computer graphics',
1535 "computers--buyers' guides" => "Computers--Buyers' guides",
1536 'competition, international' => 'Competition, International',
1537 'comprehensive health planning' => 'Health planning',
1538 'computational linguistics' => 'Computational linguistics',
1539 'computer aided design' => 'Computer-aided design',
1540 'computer aided manufacturing systems' => 'CAD/CAM systems',
1541 'computer animation' => 'Computer animation',
1542 'computer architecture' => 'Computer architecture',
1543 'computer assisted design' => 'Computer-aided design',
1544 'computer assisted animation' => 'Computer animation',
1545 'computer assisted filmmaking' => 'Computer animation',
1546 'computer code, malicious' => 'Malware (Computer software)',
1547 'computer communication systems' => 'Computer networks',
1548 'computer crimes' => 'Computer crimes',
1549 'computer engineering' => 'Computer engineering',
1550 'computer game programming' => 'Computer games--Programming',
1551 'computer games' => 'Computer games',
1552 'computer games--programming' => 'Computer games--Programming',
1553 'computer hardware' => 'Computers',
1554 'computer history' => 'Computers--History',
1555 'computer industry' => 'Computer industry',
1556 'computer languages' => 'Programming languages (Electronic computers)',
1557 'computer literacy' => 'Computer literacy',
1558 'computer modeling' => 'Computer simulation',
1559 'computer models' => 'Computer simulation',
1560 'computer network protocols' => 'Computer network protocols',
1561 'computer network security' => 'Computer networks--Security measures',
1562 'computer networks' => 'Computer networks',
1563 'computer networks--security measures' => 'Computer networks--Security measures',
1564 'computer operating systems' => 'Operating systems (Computers)',
1565 'computer peripherals' => 'Computer peripherals',
1566 'computer privacy' => 'Computer security',
1567 'computer program languages' => 'Programming languages (Electronic computers)',
1568 'computer programming languages' => 'Programming languages (Electronic computers)',
1569 'computer programming' => 'Computer programming',
1570 'computer programming--algorithms' => 'Computer programming--Algorithms',
1571 'computer science' => 'Computer science',
1572 'computer security' => 'Computer security',
1573 'computer simulation' => 'Computer simulation',
1574 'computer software' => 'Computer software',
1575 'computer software--development' => 'Computer software--Development',
1576 'computer software--education' => 'Computer software--Education',
1577 'computer software--mathematics' => 'Computer software--Mathematics',
1578 'computer software--quality assurance' => 'Computer software--Quality assurance',
1579 'computer system security' => 'Computer security',
1580 'computer systems--security measures' => 'Computer security',
1581 'computer systems--security' => 'Computer security',
1582 'computer technicians' => 'Computer technicians',
1583 'computer technicians--certification--study guides' =>
1584 'Computer technicians--Certification--Study guides',
1585 'computer technologists' => 'Computer technicians',
1586 'computer vision' => 'Computer vision',
1587 'computer-aided design' => 'Computer-aided design',
1588 'computer-aided manufacturing systems' => 'CAD/CAM systems',
1589 'computer-assisted design' => 'Computer-aided design',
1590 'computer-assisted animation' => 'Computer animation',
1591 'computer-assisted filmmaking' => 'Computer animation',
1592 'computer-generated animation' => 'Computer animation',
1593 'computer-human interaction' => 'Human-computer interaction',
1594 'computers' => 'Computers',
1595 'computers, mechanical' => 'Calculators',
1596 'computers--administration' => 'Computers--Administration',
1597 'computers--design and construction' => 'Computer engineering',
1598 'computers--history' => 'Computers--History',
1599 'computers--operating systems' => 'Operating systems (Computers)',
1600 'computers--programming' => 'Computer programming',
1601 'computers--reference' => 'Computers--Reference',
1602 'computers--security measures' => 'Computer security',
1603 'computers--security' => 'Computer security',
1604 'computers--social aspects' => 'Computers--Social aspects',
1605 'computing history' => 'Computers--History',
1606 'computing machines' => 'Computers',
1607 'concatenation, file (statistics)' => 'Statistical matching',
1608 'concept art' => 'Conceptual art',
1609 'conceptual art' => 'Conceptual art',
1610 'condiments' => 'Condiments',
1611 'confectionary' => 'Confectionery',
1612 'confectionery' => 'Confectionery',
1613 'confections' => 'Confectionery',
1614 'confederate cooking' => 'Cooking, American--Southern style',
1615 'conflict control' => 'Conflict management',
1616 'conflict management' => 'Conflict management',
1617 'conflict resolution' => 'Conflict management',
1618 'consciousness' => 'Consciousness',
1619 'consciousness-expanding drugs' => 'Hallucinogenic drugs',
1620 'conservation of art objects' => 'Art objects--Conservation and restoration',
1621 'consolidation and merger of corporations' => 'Consolidation and merger of corporations',
1622 'conspiracy' => 'Conspiracy',
1623 'constitutional rights' => 'Civil rights',
1624 'consumer advertising' => 'Advertising',
1625 'consumer behavior' => 'Consumer behavior',
1626 'consumer goods--marketing' => 'Marketing',
1627 'contract services' => 'Contracting out',
1628 'contracting for services' => 'Contracting out',
1629 'contracting out' => 'Contracting out',
1630 'contractions (topology)' => 'Contractions (Topology)',
1631 'controversial literature' => 'Controversial literature',
1632 'convenience cooking' => 'Quick and easy cooking',
1633 'cookery (appetizers)' => 'Appetizers',
1634 'cookery (baby foods)' => 'Baby foods',
1635 'cookery (beer)' => 'Cooking (Beer)',
1636 'cookery (bread)' => 'Cooking (Bread)',
1637 'cookery (chocolate)' => 'Cooking (Chocolate)',
1638 'cookery (coffee)' => 'Cooking (Coffee)',
1639 'cookery (entrées)' => 'Entrées (Cooking)',
1640 'cookery (garnishes)' => 'Garnishes (Cooking)',
1641 'cookery (herbs)' => 'Cooking (Herbs)',
1642 'cookery (liquors)' => 'Cooking (Liquors)',
1643 'cookery (spices)' => 'Cooking (Spices)',
1644 'cookery (tea)' => 'Cooking (Tea)',
1645 'cookery for one' => 'Cooking for one',
1646 'cookery' => 'Cooking',
1647 'cookery, african' => 'Cooking, African',
1648 'cookery, american' => 'Cooking, American',
1649 'cookery, asian' => 'Cooking, Asian',
1650 'cookery, cajan' => 'Cooking, Cajun',
1651 'cookery, cajun' => 'Cooking, Cajun',
1652 'cookery, canadian' => 'Cooking, Canadian',
1653 'cookery, caribbean' => 'Cooking, Caribbean',
1654 'cookery, chinese' => 'Cooking, Chinese',
1655 'cookery, english' => 'Cooking, English',
1656 'cookery, european' => 'Cooking, European',
1657 'cookery, french' => 'Cooking, French',
1658 'cookery, french-canadian' => 'Cooking, French-Canadian',
1659 'cookery, german' => 'Cooking, German',
1660 'cookery, greek' => 'Cooking, Greek',
1661 'cookery, latin american' => 'Cooking, Latin American',
1662 'cookery, oriental' => 'Cooking, Asian',
1663 'cookery, provencal' => 'Cooking, French--Provençal style',
1664 'cookery, provençal' => 'Cooking, French--Provençal style',
1665 'cookery, scottish' => 'Cooking, Scottish',
1666 'cookery, welsh' => 'Cooking, Welsh',
1667 'cookery, west indian' => 'Cooking, West Indian',
1668 'cookery--herbs' => 'Cooking (Herbs)',
1669 'cookery--history' => 'Cooking--History',
1670 'cookies (computer science)' => 'Cookies (Computer science)',
1671 'cookies' => 'Cookies',
1672 'cooking (appetizers)' => 'Appetizers',
1673 'cooking (beer)' => 'Cooking (Beer)',
1674 'cooking (bread)' => 'Cooking (Bread)',
1675 'cooking (chocolate)' => 'Cooking (Chocolate)',
1676 'cooking (coffee)' => 'Cooking (Coffee)',
1677 'cooking (entrées)' => 'Entrées (Cooking)',
1678 'cooking (garnishes)' => 'Garnishes (Cooking)',
1679 'cooking (herbs)' => 'Cooking (Herbs)',
1680 'cooking (liquors)' => 'Cooking (Liquors)',
1681 'cooking (spices)' => 'Cooking (Spices)',
1682 'cooking (spirits)' => 'Cooking (Liquors)',
1683 'cooking (spirits, alcoholic)' => 'Cooking (Liquors)',
1684 'cooking (tea)' => 'Cooking (Tea)',
1685 'cooking bread' => 'Cooking (Bread)',
1686 'cooking for one' => 'Cooking for one',
1687 'cooking for large numbers' => 'Quantity cooking',
1688 'cooking for many people' => 'Quantity cooking',
1689 'cooking history' => 'Cooking--History',
1690 'cooking utensils' => 'Kitchen utensils',
1691 'cooking with beer' => 'Cooking (Beer)',
1692 'cooking with bread' => 'Cooking (Bread)',
1693 'cooking with chocolate' => 'Cooking (Chocolate)',
1694 'cooking with coffee' => 'Cooking (Coffee)',
1695 'cooking with herbs' => 'Cooking (Herbs)',
1696 'cooking with liquors' => 'Cooking (Liquors)',
1697 'cooking with spices' => 'Cooking (Spices)',
1698 'cooking with tea' => 'Cooking (Tea)',
1699 'cooking' => 'Cooking',
1700 'cooking, african' => 'Cooking, African',
1701 'cooking, american' => 'Cooking, American',
1702 'cooking, american--california style' => 'Cooking, American--California style',
1703 'cooking, american--confederate style' => 'Cooking, American--Southern style',
1704 'cooking, american--middle atlantic states' => 'Cooking, American--Middle Atlantic States',
1705 'cooking, american--middle western style' => 'Cooking, American--Midwestern style',
1706 'cooking, american--midwestern style' => 'Cooking, American--Midwestern style',
1707 'cooking, american--new england style' => 'Cooking, American--New England style',
1708 'cooking, american--northwestern states' => 'Cooking, American--Northwestern States',
1709 'cooking, american--southern style' => 'Cooking, American--Southern style',
1710 'cooking, american--southwestern style' => 'Cooking, American--Southwestern style',
1711 'cooking, american--western style' => 'Cooking, American--Western style',
1712 'cooking, alsatian' => 'Cooking, French--Alsatian style',
1713 'cooking, asian' => 'Cooking, Asian',
1714 'cooking, auvergnat' => 'Cooking, French--Auvergne style',
1715 'cooking, auvergne' => 'Cooking, French--Auvergne style',
1716 'cooking, bavarian' => 'Cooking, German--Bavarian style',
1717 'cooking, breton' => 'Cooking, French--Brittany style',
1718 'cooking, brittany' => 'Cooking, French--Brittany style',
1719 'cooking, burgundy' => 'Cooking, French--Burgundy style',
1720 'cooking, cajan' => 'Cooking, Cajun',
1721 'cooking, cajun' => 'Cooking, Cajun',
1722 'cooking, california' => 'Cooking, American--California style',
1723 'cooking, canadian' => 'Cooking, Canadian',
1724 'cooking, caribbean' => 'Cooking, Caribbean',
1725 'cooking, central american and south american' => 'Cooking, Latin American',
1726 'cooking, central and south american' => 'Cooking, Latin American',
1727 'cooking, chinese' => 'Cooking, Chinese',
1728 'cooking, confederate style' => 'Cooking, American--Southern style',
1729 'cooking, confederate' => 'Cooking, American--Southern style',
1730 'cooking, cornish' => 'Cooking, English--Cornish style',
1731 'cooking, corsican' => 'Cooking, French--Corsican style',
1732 'cooking, creole' => 'Cooking, Creole',
1733 'cooking, cretan' => 'Cooking, Greek--Cretan style',
1734 'cooking, devon' => 'Cooking, English--Devon style',
1735 'cooking, devonshire' => 'Cooking, English--Devon style',
1736 'cooking, english' => 'Cooking, English',
1737 'cooking, english--cornish style' => 'Cooking, English--Cornish style',
1738 'cooking, english--devon style' => 'Cooking, English--Devon style',
1739 'cooking, european' => 'Cooking, European',
1740 'cooking, french' => 'Cooking, French',
1741 'cooking, french--alsatian style' => 'Cooking, French--Alsatian style',
1742 'cooking, french--auvergne style' => 'Cooking, French--Auvergne style',
1743 'cooking, french--brittany style' => 'Cooking, French--Brittany style',
1744 'cooking, french--burgundy style' => 'Cooking, French--Burgundy style',
1745 'cooking, french--corsican style' => 'Cooking, French--Corsican style',
1746 'cooking, french--gascony style' => 'Cooking, French--Gascony style',
1747 'cooking, french--lorraine style' => 'Cooking, French--Lorraine style',
1748 'cooking, french--normandy style' => 'Cooking, French--Normandy style',
1749 'cooking, french--provencal style' => 'Cooking, French--Provençal style',
1750 'cooking, french--provençal style' => 'Cooking, French--Provençal style',
1751 'cooking, french-canadian' => 'Cooking, French-Canadian',
1752 'cooking, gascon' => 'Cooking, French--Gascony style',
1753 'cooking, gascony' => 'Cooking, French--Gascony style',
1754 'cooking, german' => 'Cooking, German',
1755 'cooking, german--bavarian style' => 'Cooking, German--Bavarian style',
1756 'cooking, german--schleswig-holstein style' => 'Cooking, German--Schleswig-Holstein style',
1757 'cooking, german--southern style' => 'Cooking, German--Southern style',
1758 'cooking, german--westphalian style' => 'Cooking, German--Westphalian style',
1759 'cooking, greek' => 'Cooking, Greek',
1760 'cooking, greek--cretan style' => 'Cooking, Greek--Cretan style',
1761 'cooking, latin american' => 'Cooking, Latin American',
1762 'cooking, lorraine' => 'Cooking, French--Lorraine style',
1763 'cooking, microwave' => 'Microwave cooking',
1764 'cooking, midwestern style' => 'Cooking, American--Midwestern style',
1765 'cooking, midwestern' => 'Cooking, American--Midwestern style',
1766 'cooking, new england style' => 'Cooking, American--New England style',
1767 'cooking, new england' => 'Cooking, American--New England style',
1768 'cooking, norman' => 'Cooking, French--Normandy style',
1769 'cooking, normandy' => 'Cooking, French--Normandy style',
1770 'cooking, northwestern states' => 'Cooking, American--Northwestern States',
1771 'cooking, oriental' => 'Cooking, Asian',
1772 'cooking, provencal' => 'Cooking, French--Provençal style',
1773 'cooking, provençal' => 'Cooking, French--Provençal style',
1774 'cooking, schleswig-holstein' => 'Cooking, German--Schleswig-Holstein style',
1775 'cooking, scottish' => 'Cooking, Scottish',
1776 'cooking, southern (united states)' => 'Cooking, American--Southern style',
1777 'cooking, southern (germany)' => 'Cooking, German--Southern style',
1778 'cooking, southwestern (united states)' => 'Cooking, American--Southwestern style',
1779 'cooking, welsh' => 'Cooking, Welsh',
1780 'cooking, west indian' => 'Cooking, West Indian',
1781 'cooking, western (united states)' => 'Cooking, American--Western style',
1782 'cooking, westphalian' => 'Cooking, German--Westphalian style',
1783 'cooking--herbs' => 'Cooking (Herbs)',
1784 'cooking--history' => 'Cooking--History',
1785 'cornish cooking' => 'Cooking, English--Cornish style',
1786 'corporate acquisitions' => 'Consolidation and merger of corporations',
1787 'corporate buyouts' => 'Consolidation and merger of corporations',
1788 'corporate coaching' => 'Executive coaching',
1789 'corporate espionage' => 'Business intelligence',
1790 'corporate ethics' => 'Business ethics',
1791 'corporate finance' => 'Corporations--Finance',
1792 'corporate financial management' => 'Corporations--Finance',
1793 'corporate governance' => 'Corporate governance',
1794 'corporate income tax' => 'Corporations--Taxation',
1795 'corporate income taxes' => 'Corporations--Taxation',
1796 'corporate intelligence' => 'Business intelligence',
1797 'corporate management' => 'Industrial management',
1798 'corporate mergers' => 'Consolidation and merger of corporations',
1799 'corporate power' => 'Corporate power',
1800 'corporate takeovers' => 'Consolidation and merger of corporations',
1801 'corporate tax' => 'Corporations--Taxation',
1802 'corporate taxes' => 'Corporations--Taxation',
1803 'corporation ethics' => 'Business ethics',
1804 'corporation finance' => 'Corporations--Finance',
1805 'corporation income tax' => 'Corporations--Taxation',
1806 'corporation income taxes' => 'Corporations--Taxation',
1807 'corporation tax' => 'Corporations--Taxation',
1808 'corporation taxes' => 'Corporations--Taxation',
1809 'corporations' => 'Corporations',
1810 'corporations, federal' => 'Corporations, Government',
1811 'corporations, government' => 'Corporations, Government',
1812 'corporations, international' => 'International business enterprises',
1813 'corporations, nonprofit' => 'Nonprofit organizations',
1814 'corporations, religious' => 'Corporations, Religious',
1815 'corporations--consolidation' => 'Consolidation and merger of corporations',
1816 'corporations--finance' => 'Corporations--Finance',
1817 'corporations--management' => 'Industrial management',
1818 'corporations--mergers' => 'Consolidation and merger of corporations',
1819 'corporations--taxation' => 'Corporations--Taxation',
1820 'corpulence' => 'Obesity',
1821 'correspondence' => 'Letters',
1822 'corrupt practices' => 'Corruption',
1823 'corruption' => 'Corruption',
1824 'corsican cooking' => 'Cooking, French--Corsican style',
1825 'county parks' => 'Parks',
1826 'courting' => 'Courtship',
1827 'courtship' => 'Courtship',
1828 'courtship--fiction' => 'Courtship--Fiction',
1829 'coverage, insurance' => 'Insurance',
1830 'creole cooking' => 'Cooking, Creole',
1831 'cretan cooking' => 'Cooking, Greek--Cretan style',
1832 'criminals' => 'Criminals',
1833 'criminals--biography' => 'Criminals--Biography',
1834 'criticism' => 'Criticism',
1835 'crockery' => 'Pottery',
1836 'crockett, david, 1786-1836' => 'Crockett, Davy, 1786-1836',
1837 'crockett, davy, 1786-1836' => 'Crockett, Davy, 1786-1836',
1838 'cruelty to children' => 'Child abuse',
1839 'cryptanalysis' => 'Cryptography',
1840 'cryptogram stories' => 'Code and cipher stories',
1841 'cryptography' => 'Cryptography',
1842 'cryptography--fiction' => 'Code and cipher stories',
1843 'cryptography--juvenile fiction' => 'Code and cipher stories',
1844 'cryptology' => 'Cryptography',
1845 'crystals' => 'Crystals',
1846 'cuisine' => 'Cooking',
1847 'culture and politics' => 'Politics and culture',
1848 'culture conflict' => 'Culture conflict',
1849 'culture, popular' => 'Popular culture',
1850 'culture--political aspects' => 'Politics and culture',
1851 'currency exchange' => 'Foreign exchange',
1852 'currency' => 'Money',
1853 'curricula vitae' => 'Résumés (Employment)',
1854 'customer relations' => 'Customer relations',
1855 'cyber casting' => 'Webcasting',
1856 'cyber commerce' => 'Electronic commerce',
1857 'cyber crime' => 'Computer crimes',
1858 'cybercasting' => 'Webcasting',
1859 'cybercommerce' => 'Electronic commerce',
1860 'cybercrime' => 'Computer crimes',
1861 'cybernetics' => 'Cybernetics',
1862 'cyborg' => 'Cyborgs',
1863 'cyborgs' => 'Cyborgs',
1864 'c♯ (computer program language)' => 'C# (Computer program language)',
1865 'daniels, kate (fictitious character)' => 'Daniels, Kate (Fictitious character)',
1866 'daniels, kate--fiction' => 'Daniels, Kate (Fictitious character)',
1867 'data banks' => 'Databases',
1868 'data bases' => 'Databases',
1869 'data matching (statistics)' => 'Statistical matching',
1870 'data matching' => 'Statistical matching',
1871 'data merging (statistics)' => 'Statistical matching',
1872 'data merging' => 'Statistical matching',
1873 'data mining' => 'Data mining',
1874 'data networks' => 'Computer networks',
1875 'data networks, computer' => 'Computer networks',
1876 'data processing equipment' => 'Computers',
1877 'data processing' => 'Data processing',
1878 'data communication systems' => 'Data transmission systems',
1879 'data transmission systems' => 'Data transmission systems',
1880 'data transmission systems, broadband' => 'Broadband communication systems',
1881 'data transmission systems, wideband' => 'Broadband communication systems',
1882 'data transmission systems, wireless' => 'Wireless communication systems',
1883 'data warehousing' => 'Data warehousing',
1884 'databanks' => 'Databases',
1885 'database systems' => 'Databases',
1886 'databases' => 'Databases',
1887 'datamining' => 'Data mining',
1888 'death (personification)' => 'Death (Personification)',
1889 'death penalty' => 'Capital punishment',
1890 'death sentence' => 'Capital punishment',
1891 'death' => 'Death',
1892 'death--philosophy' => 'Death',
1893 'debentures' => 'Bonds',
1894 'debian (computer system)' => 'Debian (Computer system)',
1895 'debian' => 'Debian (Computer system)',
1896 'deciding' => 'Decision making',
1897 'decision (psychology)' => 'Decision making',
1898 'decision analysis' => 'Decision making',
1899 'decision making' => 'Decision making',
1900 'decision processes' => 'Decision making',
1901 'decoration of food' => 'Garnishes (Cooking)',
1902 'decoration, interior' => 'Interior decoration',
1903 'decoy ships' => 'Q-ships',
1904 'decriminalization of illegal drugs' => 'Drug legalization',
1905 'delivery of health care' => 'Medical care',
1906 'delivery of medical care' => 'Medical care',
1907 'depository institutions' => 'Banks and banking',
1908 'deprivation, sensory' => 'Sensory deprivation',
1909 'deprivation, sleep' => 'Sleep deprivation',
1910 'design of logic systems' => 'Logic design',
1911 'design, logic' => 'Logic design',
1912 'desk calculators' => 'Calculators',
1913 'desserts' => 'Desserts',
1914 'destitution' => 'Poverty',
1915 'devaluation of currency' => 'Monetary policy',
1916 'development of application software' => 'Application software--Development',
1917 'development of web sites' => 'Web site development',
1918 'development stage businesses' => 'New business enterprises',
1919 'development stage enterprises' => 'New business enterprises',
1920 'development, business' => 'Business--Development',
1921 'development, economic' => 'Economic development',
1922 'development, sustainable' => 'Sustainable development',
1923 'devon cooking' => 'Cooking, English--Devon style',
1924 'devonshire cooking' => 'Cooking, English--Devon style',
1925 'dickering' => 'Negotiation',
1926 'diet' => 'Diet',
1927 'diets' => 'Reducing diets',
1928 'digital art' => 'Digital art',
1929 'digital compact discs' => 'Compact discs',
1930 'digital compact disks' => 'Compact discs',
1931 'digital media' => 'Digital media',
1932 'digital publishing' => 'Electronic publishing',
1933 'dimensions' => 'Dimensions',
1934 'dip systems' => 'Document imaging systems',
1935 'direct mail campaigns' => 'Direct marketing',
1936 'direct marketing' => 'Direct marketing',
1937 'discoverers' => 'Explorers',
1938 'disc world (imaginary place)' => 'Discworld (Imaginary place)',
1939 'disc world' => 'Discworld (Imaginary place)',
1940 'discs, compact' => 'Compact discs',
1941 'discs, optical' => 'Optical disks',
1942 'discworld (imaginary place)' => 'Discworld (Imaginary place)',
1943 'discworld' => 'Discworld (Imaginary place)',
1944 'disk operating systems' => 'Operating systems (Computers)',
1945 'disks, compact' => 'Compact discs',
1946 'disks, optical' => 'Optical disks',
1947 'dispute settlement' => 'Conflict management',
1948 'distilled beverages' => 'Liquors',
1949 'distributed computer systems' => 'Electronic data processing--Distributed processing',
1950 'distributed computing systems' => 'Electronic data processing--Distributed processing',
1951 'distributed computing' => 'Electronic data processing--Distributed processing',
1952 'distributed processing' => 'Electronic data processing--Distributed processing',
1953 'distribution (economic theory)' => 'Distribution (Economic theory)',
1954 'distributorship, multilevel' => 'Multilevel marketing',
1955 'divination' => 'Divination',
1956 'divine healing' => 'Spiritual healing',
1957 'divine messengers' => 'Angels',
1958 'djin' => 'Jinn',
1959 'djinn' => 'Jinn',
1960 'djinni' => 'Jinn',
1961 'djinns' => 'Jinn',
1962 'djins' => 'Jinn',
1963 'depuy, william e. (william eugene), 1919-1992'
1964 => 'DePuy, William E. (William Eugene), 1919-1992',
1965 'doctrinal and controversial works' => 'Controversial literature',
1966 'document image processing' => 'Document imaging systems',
1967 'document imaging systems' => 'Document imaging systems',
1968 'document management systems' => 'Document imaging systems',
1969 'document management' => 'Document imaging systems',
1970 'doffing' => 'Textile industry',
1971 'dolls' => 'Dolls',
1972 'domestic fiction' => 'Domestic fiction',
1973 'domestic marketing' => 'Marketing',
1974 'domestic novels' => 'Domestic fiction',
1975 'domestic rabbit' => 'Rabbits',
1976 'domestic rabbits' => 'Rabbits',
1977 'double entry bookkeeping' => 'Bookkeeping',
1978 'drawing technique' => 'Drawing',
1979 'drawing' => 'Drawing',
1980 'drawing--technique' => 'Drawing',
1981 'dreaming' => 'Dreams',
1982 'dreams' => 'Dreams',
1983 'drinking water' => 'Drinking water',
1984 'drinks' => 'Beverages',
1985 'drug decriminalization' => 'Drug legalization',
1986 'drug legalization' => 'Drug legalization',
1987 'drugs' => 'Drugs',
1988 'dying' => 'Death',
1989 'e-business' => 'Electronic commerce',
1990 'e-commerce' => 'Electronic commerce',
1991 'e-mail correspondence' => 'Electronic mail messages',
1992 'e-mail messages' => 'Electronic mail messages',
1993 'e-mail software' => 'Electronic mail systems',
1994 'e-mail systems' => 'Electronic mail systems',
1995 'e-mail' => 'Electronic mail messages',
1996 'e-tailing' => 'Electronic commerce',
1997 'earthenware' => 'Pottery',
1998 'easy and quick cooking' => 'Quick and easy cooking',
1999 'ebusiness' => 'Electronic commerce',
2000 'ecclesiastical corporations' => 'Corporations, Religious',
2001 'ecological monitoring' => 'Environmental monitoring',
2002 'ecologically sustainable development' => 'Sustainable development',
2003 'ecommerce' => 'Electronic commerce',
2004 'econometrics' => 'Econometrics',
2005 'economic conditions' => 'Economic conditions',
2006 'economic development' => 'Economic development',
2007 'economic development, sustainable' => 'Sustainable development',
2008 'economic espionage' => 'Business intelligence',
2009 'economic goods' => 'Commercial products',
2010 'economic growth' => 'Economic development',
2011 # Works on the history of economics as a discipline are entered under Economics--History
2012 'economic history' => 'Economic history',
2013 'economic infrastructure' => 'Infrastructure (Economics)',
2014 'economic statistics' => 'Economic statistics',
2015 'economic sustainability' => 'Sustainable development',
2016 'economic theory' => 'Economics',
2017 'economics of cities' => 'Urban economics',
2018 'economics' => 'Economics',
2019 'economics, comparative' => 'Comparative economics',
2020 'economics--environmental aspects' => 'Environmental economics',
2021 'economics--history' => 'Economics--History',
2022 'edi (electronic data interchange)' => 'Electronic data interchange',
2023 'edi' => 'Electronic data interchange',
2024 'edinburgh (scotland)' => 'Edinburgh (Scotland)',
2025 'edinburgh, scotland' => 'Edinburgh (Scotland)',
2026 'education software' => 'Computer software--Education',
2027 'education' => 'Education',
2028 'education, business' => 'Business education',
2029 'educational software' => 'Computer software--Education',
2030 # Note that 'Educators' is different from 'Teachers'
2031 'educators' => 'Educators',
2032 'election monitoring' => 'Election monitoring',
2033 'election observation' => 'Election monitoring',
2034 'elections' => 'Elections',
2035 'electoral politics' => 'Elections',
2036 'electronic banking' => 'Internet banking',
2037 'electronic brains' => 'Artificial intelligence',
2038 'electronic business data interchange' => 'Electronic data interchange',
2039 'electronic business' => 'Electronic commerce',
2040 'electronic calculating machines' => 'Computers',
2041 'electronic calculating-machines' => 'Computers',
2042 'electronic commerce' => 'Electronic commerce',
2043 'electronic communication networks' => 'Computer networks',
2044 'electronic computer programming' => 'Computer programming',
2045 'electronic computers' => 'Computers',
2046 'electronic data interchange' => 'Electronic data interchange',
2047 'electronic data processing' => 'Data processing',
2048 'electronic data processing--distributed processing' => 'Electronic data processing--Distributed processing',
2049 'electronic data processing--programming' => 'Computer programming',
2050 'electronic document imaging systems' => 'Document imaging systems',
2051 'electronic document management systems' => 'Document imaging systems',
2052 'electronic information services' => 'Online information services',
2053 'electronic mail messages' => 'Electronic mail messages',
2054 'electronic mail systems' => 'Electronic mail systems',
2055 'electronic marketing' => 'Telemarketing',
2056 'electronic media' => 'Digital media',
2057 'electronic publishing' => 'Electronic publishing',
2058 'electronic social networks' => 'Online social networks',
2059 'electronic spread sheets' => 'Electronic spreadsheets',
2060 'electronic spreadsheet software' => 'Electronic spreadsheets--Software',
2061 'electronic spreadsheets' => 'Electronic spreadsheets',
2062 'electronic spreadsheets--software' => 'Electronic spreadsheets--Software',
2063 'electronic trading' => 'Electronic trading of securities',
2064 'electronic trading of securities' => 'Electronic trading of securities',
2065 'email correspondence' => 'Electronic mail messages',
2066 'email messages' => 'Electronic mail messages',
2067 'email software' => 'Electronic mail systems',
2068 'email systems' => 'Electronic mail systems',
2069 'email' => 'Electronic mail messages',
2070 'employment management' => 'Personnel management',
2071 'enchanters' => 'Wizards',
2072 'end of life' => 'Death',
2073 'energetic healing' => 'Energy medicine',
2074 'energy healing' => 'Energy medicine',
2075 'energy industries' => 'Energy industries',
2076 'energy medicine' => 'Energy medicine',
2077 'engeland' => 'England',
2078 'engineering design' => 'Engineering design',
2079 'engineering--authorship' => 'Technical writing',
2080 'engines, search' => 'Search engines',
2081 'england' => 'England',
2082 'england--fiction' => 'England--Fiction',
2083 'england--social life and customs' => 'England--Social life and customs',
2084 'england--social life and customs--19th century--fiction' => 'England--Social life and customs--19th century--Fiction',
2085 'english biscuits' => 'Cookies',
2086 'english cooking' => 'Cooking, English',
2087 'english customs' => 'England--Social life and customs',
2088 'english fiction' => 'English fiction',
2089 'english grammar' => 'English language--Grammar',
2090 'english language' => 'English language',
2091 'english language--grammar' => 'English language--Grammar',
2092 'english literature' => 'English literature',
2093 'enochian magic' => 'Enochian magic',
2094 'enochian magick' => 'Enochian magic',
2095 'enslavement' => 'Slavery',
2096 'enterprises' => 'Business enterprises',
2097 'enterprises, business' => 'Business enterprises',
2098 'entertaining' => 'Entertaining',
2099 # 'Entertainment industry' is not an official LC subject, but is submitted as one
2100 'entertainment industry' => 'Entertainment industry',
2101 'entheogens' => 'Hallucinogenic drugs',
2102 'entrées (cookery)' => 'Entrées (Cooking)',
2103 'entrées (cooking)' => 'Entrées (Cooking)',
2104 'entrepreneur' => 'Entrepreneurship',
2105 'entrepreneurs, women' => 'Businesswomen',
2106 'entrepreneurship' => 'Entrepreneurship',
2107 'environment, work' => 'Work environment',
2108 'environmental economics' => 'Environmental economics',
2109 'environmental monitoring' => 'Environmental monitoring',
2110 'environmental quality' => 'Environmental quality',
2111 'environmental quality--economic aspects' => 'Environmental economics',
2112 'environmental quality--measurement' => 'Environmental monitoring',
2113 'environmental quality--monitoring' => 'Environmental monitoring',
2114 'environmentalists' => 'Environmentalists',
2115 'environmentalists--biography' => 'Environmentalists--Biography',
2116 'environments, virtual' => 'Virtual reality',
2117 'equipment, capital' => 'Industrial equipment',
2118 'equipment, industrial' => 'Industrial equipment',
2119 'equities' => 'Stocks',
2120 'equity capital' => 'Stocks',
2121 'equity financing' => 'Stocks',
2122 'erotic art' => 'Erotic art',
2123 'erotic fiction' => 'Erotic stories',
2124 'erotic stories' => 'Erotic stories',
2125 'erotic' => 'Erotic stories',
2126 'erotica' => 'Erotic stories',
2127 'esd (ecologically sustainable development)' => 'Sustainable development',
2128 'esme weatherwax (fictitious character)' => 'Weatherwax, Granny (Fictitious character)',
2129 'esme weatherwax' => 'Weatherwax, Granny (Fictitious character)',
2130 'esmeralda weatherwax (fictitious character)' => 'Weatherwax, Granny (Fictitious character)',
2131 'esmeralda weatherwax' => 'Weatherwax, Granny (Fictitious character)',
2132 'esp' => 'Extrasensory perception',
2133 'espionage, business' => 'Business intelligence',
2134 'espionage, corporate' => 'Business intelligence',
2135 'espionage, economic' => 'Business intelligence',
2136 'espionage, industrial' => 'Business intelligence',
2137 'eternal life' => 'Immortality',
2138 'etheric world intelligences' => 'Guides (Spiritualism)',
2139 'ethics in government' => 'Political ethics',
2140 'ethics' => 'Ethics',
2141 'ethics, political' => 'Political ethics',
2142 'ethics, primitive' => 'Ethics',
2143 'ethology' => 'Ethics',
2144 'etiquette' => 'Etiquette',
2145 'european art' => 'Art, European',
2146 'european cooking' => 'Cooking, European',
2147 'evidence control' => 'Evidence preservation',
2148 'evidence preservation' => 'Evidence preservation',
2149 'evidence, criminal--preservation' => 'Evidence preservation',
2150 'ex-convicts' => 'Ex-convicts',
2151 'exchange, foreign' => 'Foreign exchange',
2152 'exchanges, commodity' => 'Commodity exchanges',
2153 'exchanges, produce' => 'Commodity exchanges',
2154 'excursions' => 'Tourism',
2155 'executive coaching' => 'Executive coaching',
2156 'executive information systems' => 'Management information systems',
2157 'executive power' => 'Executive power',
2158 'executive power--united states' => 'Executive power--United States',
2159 'exercise' => 'Physical fitness',
2160 'expert systems (computer science)' => 'Expert systems (Computer science)',
2161 'expert systems' => 'Expert systems (Computer science)',
2162 'explorers' => 'Explorers',
2163 'explorers--biography' => 'Explorers--Biography',
2164 'export marketing' => 'Export marketing',
2165 'exports & imports' => 'International trade',
2166 'exports and imports' => 'International trade',
2167 'extendible markup language' => 'XML (Document markup language)',
2168 'extensible markup language' => 'XML (Document markup language)',
2169 'external trade' => 'International trade',
2170 'extranets (computer networks)' => 'Extranets (Computer networks)',
2171 'extranets' => 'Extranets (Computer networks)',
2172 'extrasensory perception' => 'Extrasensory perception',
2173 'facilities management' => 'Facility management',
2174 'facility management' => 'Facility management',
2175 'factual data analysis' => 'Data mining',
2176 'faerie' => 'Fairies',
2177 'fairie' => 'Fairies',
2178 'fairies' => 'Fairies',
2179 'fairy tales' => 'Fairy tales',
2180 'fairy' => 'Fairies',
2181 'faith healing' => 'Spiritual healing',
2182 'faith-cure' => 'Spiritual healing',
2183 'family budgets' => 'Budgets, Personal',
2184 'family' => 'Family',
2185 'fantastic fiction' => 'Fantasy fiction',
2186 'fantasy fiction' => 'Fantasy fiction',
2187 'fantasy fiction--authorship' => 'Fantasy fiction--Authorship',
2188 'fantasy fiction--technique' => 'Fantasy fiction--Technique',
2189 'fantasy' => 'Fantasy fiction',
2190 'fat-free diet' => 'Low-fat diet',
2191 'fatness' => 'Obesity',
2192 'fear of being alone' => 'Agoraphobia',
2193 'fear of isolation' => 'Agoraphobia',
2194 'fear of open space' => 'Agoraphobia',
2195 'fear of open spaces' => 'Agoraphobia',
2196 'federal corporation tax' => 'Corporations--Taxation',
2197 'feng shui' => 'Feng shui',
2198 'festive cooking' => 'Holiday cooking',
2199 'fiction action adventure' => 'Adventure stories',
2200 'fiction' => 'Fiction',
2201 'fiction, juvenile' => 'Fiction, Juvenile',
2202 'fiction, paranormal' => 'Paranormal fiction',
2203 'fiction--fantasy' => 'Fantasy fiction',
2204 'fiction--paranormal' => 'Paranormal fiction',
2205 'fiction--science fiction' => 'Science fiction',
2206 'fictitious places' => 'Imaginary places',
2207 'figurines' => 'Figurines',
2208 'file concatenation (statistics)' => 'Statistical matching',
2209 'finance' => 'Finance',
2210 'finance, personal' => 'Finance, Personal',
2211 'finance, personal--planning' => 'Finance, Personal',
2212 'finance, personal--software' => 'Finance, Personal--Software',
2213 'finance, public' => 'Finance, Public',
2214 'financial analysis of corporations' => 'Corporations--Finance',
2215 'financial management of corporations' => 'Corporations--Finance',
2216 'financial management, corporate' => 'Corporations--Finance',
2217 'financial management, personal' => 'Finance, Personal',
2218 'financial planning of corporations' => 'Corporations--Finance',
2219 'financial planning, personal' => 'Finance, Personal',
2220 'financial risk management' => 'Financial risk management',
2221 'financial services industry' => 'Financial services industry',
2222 'financial services' => 'Financial services industry',
2223 'firearms' => 'Firearms',
2224 'firms' => 'Business enterprises',
2225 # 'First contact' is not directly a LC heading, but submitted as a recommendation
2226 'first contact' => 'First contact',
2227 'fitness, physical' => 'Physical fitness',
2228 'flasks' => 'Bottles',
2229 'flatboats' => 'Flatboats',
2230 'flight' => 'Flight',
2231 'flying saucers' => 'Unidentified flying objects',
2232 'flying-machines' => 'Flying-machines',
2233 'folk art' => 'Folk art',
2234 'food allergy' => 'Food allergy',
2235 'food calories' => 'Food--Caloric content',
2236 'food decoration' => 'Garnishes (Cooking)',
2237 'food industry and trade' => 'Food industry and trade',
2238 'food preparation industry' => 'Food industry and trade',
2239 'food preparation' => 'Cooking',
2240 'food processing industry' => 'Food industry and trade',
2241 'food processing' => 'Food industry and trade',
2242 'food trade' => 'Food industry and trade',
2243 'food, baby' => 'Baby foods',
2244 'food, raw' => 'Raw foods',
2245 'food--caloric content' => 'Food--Caloric content',
2246 'food--health aspects', => 'Nutrition',
2247 'foods, baby' => 'Baby foods',
2248 'foods, infant' => 'Baby foods',
2249 'foods, raw' => 'Raw foods',
2250 'forecasting, business' => 'Business forecasting',
2251 'foreign commerce' => 'International trade',
2252 'foreign exchange' => 'Foreign exchange',
2253 'foreign languages' => 'Language and languages',
2254 'foreign trade' => 'International trade',
2255 'foreign trade policy' => 'Commercial policy',
2256 'forex' => 'Foreign exchange',
2257 'fortran (computer program language)' => 'FORTRAN (Computer program language)',
2258 'fortune-telling' => 'Fortune-telling',
2259 'fortunetelling' => 'Fortune-telling',
2260 'franchises (retail trade)' => 'Franchises (Retail trade)',
2261 'franchises, retail' => 'Franchises (Retail trade)',
2262 'franchises, taxation of' => 'Corporations--Taxation',
2263 'franchises, taxation' => 'Corporations--Taxation',
2264 'franchises--taxation' => 'Corporations--Taxation',
2265 'free enterprise' => 'Free enterprise',
2266 'free markets' => 'Free enterprise',
2267 'french cooking' => 'Cooking, French',
2268 'french-canadian cooking' => 'Cooking, French-Canadian',
2269 'fundamental rights' => 'Civil rights',
2270 'funding' => 'Finance',
2271 'funnies' => 'Comic books, strips, etc',
2272 'furniture' => 'Furniture',
2273 'fusion of corporations' => 'Consolidation and merger of corporations',
2274 'fusion, data (statistics)' => 'Statistical matching',
2275 'fusion, data' => 'Statistical matching',
2276 # 'Future life' is a separate LC Subject meaning 'life after
2277 # death', not 'life in the future', but it is so confusing that it
2278 # just gets folded into 'Immortality' in this code.
2279 'future life' => 'Immortality',
2280 # 'Futures' is futures trading, not potential future events
2281 'futures contracts' => 'Futures',
2282 'futures trading' => 'Futures',
2283 'futures' => 'Futures',
2284 'fx (finance)' => 'Foreign exchange',
2285 'gaap (accounting)' => 'Accounting--Standards',
2286 'gaap' => 'Accounting--Standards',
2287 'gadgets' => 'Implements, utensils, etc',
2288 'game programming' => 'Computer games--Programming',
2289 'garnish, harry (fictitious character)' => 'Garnish, Harry (Fictitious character)',
2290 'garnishes (cookery)' => 'Garnishes (Cooking)',
2291 'garnishes (cooking)' => 'Garnishes (Cooking)',
2292 'garnishes' => 'Garnishes (Cooking)',
2293 'garnishing (cookery)' => 'Garnishes (Cooking)',
2294 'garnishing (cooking)' => 'Garnishes (Cooking)',
2295 'garnishing' => 'Garnishes (Cooking)',
2296 'gascon cooking' => 'Cooking, French--Gascony style',
2297 'gascony cooking' => 'Cooking, French--Gascony style',
2298 'gasoline automobiles' => 'Automobiles',
2299 'generally accepted accounting principles' => 'Accounting--Standards',
2300 'generals--united states' => 'Generals--United States',
2301 'genies' => 'Jinn',
2302 'genii' => 'Jinn',
2303 'german cooking' => 'Cooking, German',
2304 'ghost stories' => 'Ghost stories',
2305 'ghosts' => 'Ghost stories',
2306 'glass' => 'Glass',
2307 'glassman, josh (fictitious character)' => 'Glassman, Josh (Fictitious character)',
2308 'glassman, josh' => 'Glassman, Josh (Fictitious character)',
2309 'glassware' => 'Glassware',
2310 'global cities' => 'Cities and towns',
2311 'global commerce' => 'International trade',
2312 'global corporations' => 'International business enterprises',
2313 'global terrorism' => 'Terrorism',
2314 'global trade' => 'International trade',
2315 'gluten-free foods' => 'Gluten-free foods',
2316 'goal programming' => 'Programming (Mathematics)',
2317 'goblins' => 'Goblins',
2318 'goddess religion' => 'Goddess religion',
2319 'government' => 'Government',
2320 'government companies' => 'Corporations, Government',
2321 'government corporations' => 'Corporations, Government',
2322 'government ethics' => 'Political ethics',
2323 'government, resistance to' => 'Government, Resistance to',
2324 'government, resistance to--united states' => 'Government, Resistance to--United States',
2325 'graffiti' => 'Graffiti',
2326 'graffiti artists' => 'Graffiti artists',
2327 'graffiti culture' => 'Graffiti',
2328 'graphic data processing' => 'Computer graphics',
2329 'graphics, computer' => 'Computer graphics',
2330 'granny weatherwax (fictitious character)' => 'Weatherwax, Granny (Fictitious character)',
2331 'granny weatherwax' => 'Weatherwax, Granny (Fictitious character)',
2332 'greek cooking' => 'Cooking, Greek',
2333 'greek mythology' => 'Mythology, Greek',
2334 'green business' => 'Business enterprises--Environmental aspects',
2335 'grief' => 'Grief',
2336 'grilling (cooking)' => 'Barbecuing',
2337 'grim reaper' => 'Death (Personification)',
2338 'growing up' => 'Coming of age',
2339 'guests, entertaining' => 'Entertaining',
2340 'guides (spiritualism)' => 'Guides (Spiritualism)',
2341 'guides, spirit' => 'Guides (Spiritualism)',
2342 'gunning' => 'Shooting',
2343 'guns' => 'Firearms',
2344 'haggling' => 'Negotiation',
2345 'hares' => 'Rabbits',
2346 'harry garnish (fictitious character)' => 'Garnish, Harry (Fictitious character)',
2347 'higgling' => 'Negotiation',
2348 'hallucinations and illusions' => 'Hallucinations and illusions',
2349 'hallucinogenic drugs' => 'Hallucinogenic drugs',
2350 'hallucinogens' => 'Hallucinogenic drugs',
2351 'hardware, computer' => 'Computers',
2352 'heads of government' => 'Heads of state',
2353 'heads of state' => 'Heads of state',
2354 'heads of state--biography' => 'Heads of state--Biography',
2355 'healing' => 'Healing',
2356 'health & healing' => 'Healing',
2357 'health & fitness' => 'Physical fitness',
2358 'health and fitness' => 'Physical fitness',
2359 'health care delivery' => 'Medical care',
2360 'health care planning' => 'Health planning',
2361 'health care' => 'Medical care',
2362 'health informatics' => 'Medical informatics',
2363 'health insurance' => 'Health insurance',
2364 'health planning' => 'Health planning',
2365 'health plans' => 'Health planning',
2366 'health plans, prepaid' => 'Health insurance',
2367 'health services planning' => 'Health planning',
2368 'health services' => 'Medical care',
2369 'health thoughts' => 'Mental healing',
2370 'healthcare' => 'Medical care',
2371 'heart--diseases--nutritional aspects' => 'Heart--Diseases--Nutritional aspects',
2372 'heavy weapons' => 'Ordnance',
2373 'herbal cooking' => 'Cooking (Herbs)',
2374 'herbs' => 'Herbs',
2375 'herbs--use in cooking' => 'Cooking (Herbs)',
2376 'hermeticism' => 'Hermetism',
2377 'hermetism' => 'Hermetism',
2378 'high tech' => 'High technology',
2379 'high technology' => 'High technology',
2380 'hispanic american art' => 'Hispanic American art',
2381 'historical fiction' => 'Historical fiction',
2382 'historical fiction, chinese' => 'Historical fiction, Chinese',
2383 'history of cooking' => 'Cooking--History',
2384 'history' => 'History',
2385 'history--20th century' => 'History--20th century',
2386 'history--cooking' => 'Cooking--History',
2387 'history, economic' => 'Economic history',
2388 'history, military' => 'History, Military',
2389 'holiday cookery' => 'Holiday cooking',
2390 'holiday cooking' => 'Holiday cooking',
2391 'holiday industry' => 'Tourism',
2392 'home businesses' => 'Home-based businesses',
2393 'home buying' => 'House buying',
2394 'home computers' => 'Microcomputers',
2395 'home decoration' => 'Interior decoration',
2396 'home purchase' => 'House buying',
2397 'home purchasing' => 'House buying',
2398 'home selling' => 'House selling',
2399 'home-based businesses' => 'Home-based businesses',
2400 'homosexuality' => 'Homosexuality',
2401 'horoscopes' => 'Horoscopes',
2402 "hors d'oeuvres" => 'Appetizers',
2403 'hostile takeovers of corporations' => 'Consolidation and merger of corporations',
2404 'hostile takeovers' => 'Consolidation and merger of corporations',
2405 'hot dish cooking' => 'Casserole cooking',
2406 'hotdish cooking' => 'Casserole cooking',
2407 'house buying' => 'House buying',
2408 'house decoration' => 'Interior decoration',
2409 'house guests, entertaining' => 'Entertaining',
2410 'house hunting' => 'House buying',
2411 'house selling' => 'House selling',
2412 'houseguests, entertaining' => 'Entertaining',
2413 'household utensils' => 'Implements, utensils, etc',
2414 'how to start a business' => 'New business enterprises',
2415 'how to start businesses' => 'New business enterprises',
2416 'horror' => 'Horror',
2417 'html (document markup language)' => 'HTML (Document markup language)',
2418 'html' => 'HTML (Document markup language)',
2419 'http cookies (computer science)' => 'Cookies (Computer science)',
2420 'http cookies' => 'Cookies (Computer science)',
2421 # 'Human beings in art' is for representations of humans in art
2422 'human beings in art' => 'Human beings in art',
2423 'human body in art' => 'Human figure in art',
2424 'human body--care and hygiene' => 'Hygiene',
2425 'human factors in computing systems' => 'Human-computer interaction',
2426 'human females' => 'Women',
2427 # 'Human figure in art' is for art technique, not representations
2428 'human figure in art' => 'Human figure in art',
2429 'human resource management' => 'Personnel management',
2430 'human resources management' => 'Personnel management',
2431 'human rights' => 'Human rights',
2432 'human sexuality' => 'Sex',
2433 'human-computer interaction' => 'Human-computer interaction',
2434 'humans in art' => 'Human beings in art',
2435 'humanx' => 'Humanx Commonwealth (Imaginary organization)',
2436 'humanx commonwealth' => 'Humanx Commonwealth (Imaginary organization)',
2437 'humanx commonwealth (imaginary organization)'
2438 => 'Humanx Commonwealth (Imaginary organization)',
2439 'humanx commonwealth (imaginary organization)--fiction'
2440 => 'Humanx Commonwealth (Imaginary organization)',
2441 'humor' => 'Humor',
2442 'humor adult humor and comedy' => 'Humor',
2443 'humour' => 'Humor',
2444 'hygiene' => 'Hygiene',
2445 'hygiene, public' => 'Public health',
2446 'hygiene, social' => 'Public health',
2447 'hypertext markup language' => 'HTML (Document markup language)',
2448 'icebreakers (ships)' => 'Icebreakers (Ships)',
2449 'illiteracy' => 'Literacy',
2450 'illusions' => 'Hallucinations and illusions',
2451 'illusions, optical' => 'Optical illusions',
2452 'image processing' => 'Image processing',
2453 'imaginary cities' => 'Imaginary places',
2454 'imaginary islands' => 'Imaginary places',
2455 'imaginary places' => 'Imaginary places',
2456 # 'Immortalism' refers to living indefinitely in the flesh
2457 'immortalism' => 'Immortalism',
2458 # 'Immortality' refers to survival of the soul after death
2459 'immortality' => 'Immortality',
2460 'implements, utensils, etc' => 'Implements, utensils, etc',
2461 'imports & exports' => 'International trade',
2462 'imports and exports' => 'International trade',
2463 'imputation, mass (statistics)' => 'Statistical matching',
2464 'income tax' => 'Income tax',
2465 'indemnity insurance' => 'Insurance',
2466 'industrial administration' => 'Industrial management',
2467 'industrial communication' => 'Business communication',
2468 'industrial equipment' => 'Industrial equipment',
2469 'industrial equipment--marketing' => 'Industrial marketing',
2470 'industrial espionage' => 'Business intelligence',
2471 'industrial management' => 'Industrial management',
2472 'industrial marketing' => 'Industrial marketing',
2473 'industrial policy' => 'Industrial policy',
2474 'industrial production' => 'Industries',
2475 'industrial project management' => 'Project management',
2476 'industries' => 'Industries',
2477 'industries--equipment and supplies' => 'Industrial equipment',
2478 'industries--government policy' => 'Industrial policy',
2479 'industries--public relations' => 'Public relations',
2480 'industry and state' => 'Industrial policy',
2481 'industry' => 'Industries',
2482 'infancy' => 'Infants',
2483 'infant foods' => 'Baby foods',
2484 'infants' => 'Infants',
2485 'infants--food' => 'Baby foods',
2486 'inflation (finance)' => 'Inflation (Finance)',
2487 'inflation' => 'Inflation (Finance)',
2488 'informatics' => 'Computer science',
2489 'information resources management' => 'Information resources management',
2490 'information systems management' => 'Information resources management',
2491 'information technology' => 'Information technology',
2492 'information theory' => 'Information theory',
2493 'information warehousing' => 'Data warehousing',
2494 'infrastructure (economics)' => 'Infrastructure (Economics)',
2495 'inghilterra' => 'England',
2496 'inglaterra' => 'England',
2497 'ink drawing' => 'Pen drawing',
2498 'inspiration' => 'Inspiration',
2499 'inspiration--religious aspects' => 'Inspiration--Religious aspects',
2500 'instruction' => 'Education',
2501 'instructors' => 'Teachers',
2502 'instruments, musical' => 'Musical instruments',
2503 'insurance coverage' => 'Insurance',
2504 'insurance industry' => 'Insurance',
2505 'insurance protection' => 'Insurance',
2506 'insurance risk' => 'Risk (Insurance)',
2507 'insurance' => 'Insurance',
2508 'insurance, automobile' => 'Automobile insurance',
2509 'insurance, casualty' => 'Casualty insurance',
2510 'insurance, health' => 'Health insurance',
2511 'insurance, liability' => 'Liability insurance',
2512 'insurance, life' => 'Life insurance',
2513 'insurance, property' => 'Property insurance',
2514 'insurance--risk' => 'Risk (Insurance)',
2515 'intellectronics' => 'Artificial intelligence',
2516 'intellectual capital' => 'Intellectual capital',
2517 'intelligence, artificial' => 'Artificial intelligence',
2518 'intelligence, business' => 'Business intelligence',
2519 'intelligence, corporate' => 'Business intelligence',
2520 'intelligences, etheric world' => 'Guides (Spiritualism)',
2521 'intelligent machines' => 'Artificial intelligence',
2522 'interaction, human-computer' => 'Human-computer interaction',
2523 'interactive computer systems' => 'Interactive computer systems',
2524 'intercourse, sexual' => 'Sex',
2525 'interest and usury' => 'Interest',
2526 'interest' => 'Interest',
2527 'interfaces, user (computer systems)' => 'User interfaces (Computer systems)',
2528 'interfaces, user' => 'User interfaces (Computer systems)',
2529 'interior decoration' => 'Interior decoration',
2530 'interior design' => 'Interior decoration',
2531 'internal internets (computer networks)' => 'Intranets (Computer networks)',
2532 'internal internets' => 'Intranets (Computer networks)',
2533 'international accounting' => 'International business enterprises--Accounting',
2534 'international business enterprises' => 'International business enterprises',
2535 'international business enterprises--accounting' =>
2536 'International business enterprises--Accounting',
2537 'international business enterprises--taxation' =>
2538 'International business enterprises--Taxation',
2539 'international competition' => 'Competition, International',
2540 'international corporations' => 'International business enterprises',
2541 'international economics' => 'Competition, International',
2542 'international exchange' => 'Foreign exchange',
2543 'international marketing' => 'Export marketing',
2544 'international taxation' => 'International business enterprises--Taxation',
2545 'international taxes' => 'International business enterprises--Taxation',
2546 'international terrorism' => 'Terrorism',
2547 'international trade policy' => 'Commercial policy',
2548 'international trade' => 'International trade',
2549 'internet advertising' => 'Internet advertising',
2550 'internet application development' => 'Application software--Internet--Development',
2551 'internet application software' => 'Application software--Internet',
2552 'internet applications' => 'Application software--Internet',
2553 'internet apps' => 'Application software--Internet',
2554 'internet auctions' => 'Internet auctions',
2555 'internet banking' => 'Internet banking',
2556 'internet bookstores' => 'Internet bookstores',
2557 'internet broadcasting' => 'Webcasting',
2558 'internet browsers' => 'Browsers (Computer programs)',
2559 'internet commerce' => 'Electronic commerce',
2560 'internet drugstores' => 'Internet pharmacies',
2561 'internet marketing' => 'Internet advertising',
2562 'internet pharmacies' => 'Internet pharmacies',
2563 'internet retailing' => 'Electronic commerce',
2564 'internet' => 'Internet',
2565 'internet--safety measures' => 'Internet--Safety measures',
2566 'internship programs' => 'Internship programs',
2567 'internships' => 'Internship programs',
2568 'intranets (computer networks)' => 'Intranets (Computer networks)',
2569 'intranets' => 'Intranets (Computer networks)',
2570 'intrapreneur' => 'Entrepreneurship',
2571 'investing' => 'Investments',
2572 'investment companies' => 'Mutual funds',
2573 'investment in real estate' => 'Real estate investment',
2574 'investment management' => 'Investments',
2575 'investment options' => 'Options (Finance)',
2576 'investment trusts' => 'Mutual funds',
2577 'investments' => 'Investments',
2578 'irrationalism (philosophy)' => 'Irrationalism (Philosophy)',
2579 'irrationalism' => 'Irrationalism (Philosophy)',
2580 'irrationalist (philosophy)' => 'Irrationalism (Philosophy)',
2581 'irrationalist' => 'Irrationalism (Philosophy)',
2582 'islands, imaginary' => 'Imaginary places',
2583 'isolation' => 'Social isolation',
2584 'isolation, fear of' => 'Agoraphobia',
2585 'isolation, perceptual' => 'Sensory deprivation',
2586 'it (information technology)' => 'Information technology',
2587 'jackrabbits' => 'Rabbits',
2588 'jane austen' => 'Austen, Jane, 1775-1817',
2589 'jane austen, 1775-1817' => 'Austen, Jane, 1775-1817',
2590 'java (computer program language)' => 'Java (Computer program language)',
2591 'javascript (computer program language)' => 'JavaScript (Computer program language)',
2592 'javascript' => 'JavaScript (Computer program language)',
2593 'jewellery' => 'Jewelry',
2594 'jewelry' => 'Jewelry',
2595 'jewels' => 'Jewelry',
2596 'jinn' => 'Jinn',
2597 'jinni' => 'Jinn',
2598 'jinns' => 'Jinn',
2599 'job hunting' => 'Job hunting',
2600 'job résumés' => 'Résumés (Employment)',
2601 'job searching' => 'Job hunting',
2602 'joblessness' => 'Unemployment',
2603 'jobs' => 'Occupations',
2604 'josh glassman' => 'Glassman, Josh (Fictitious character)',
2605 'kate daniels (fictitious character)' => 'Daniels, Kate (Fictitious character)',
2606 'kate daniels' => 'Daniels, Kate (Fictitious character)',
2607 'kdd (information retrieval)' => 'Data mining',
2608 'kdd' => 'Data mining',
2609 'ketogenic diet' => 'Ketogenic diet',
2610 'keyboarding' => 'Keyboarding',
2611 'kids' => 'Children',
2612 'kitchen utensils' => 'Kitchen utensils',
2613 'kitchenware' => 'Kitchen utensils',
2614 'kittens' => 'Kittens',
2615 'knowledge capital' => 'Intellectual capital',
2616 'knowledge discovery in data' => 'Data mining',
2617 'knowledge discovery in databases' => 'Data mining',
2618 'knowledge-based systems' => 'Expert systems (Computer science)',
2619 'korean war' => 'Korean War, 1950-1953',
2620 'korean war, 1950-1953' => 'Korean War, 1950-1953',
2621 'labor and laboring classes' => 'Labor',
2622 'labor' => 'Labor',
2623 'laissez faire' => 'Free enterprise',
2624 'laissez-faire' => 'Free enterprise',
2625 'latin american art' => 'Art, Latin American',
2626 'landscapes' => 'Landscapes',
2627 'landscapes in art' => 'Landscapes in art',
2628 'language and languages' => 'Language and languages',
2629 'language and languages--data processing' => 'Computational linguistics',
2630 'language art' => 'Conceptual art',
2631 'language art (fine arts)' => 'Conceptual art',
2632 'language data processing' => 'Computational linguistics',
2633 'languages' => 'Language and languages',
2634 'lans (computer networks)' => 'Local area networks (Computer networks)',
2635 'lans' => 'Local area networks (Computer networks)',
2636 'laser discs' => 'Optical disks',
2637 'laser disks' => 'Optical disks',
2638 'laserdiscs' => 'Optical disks',
2639 'laserdisks' => 'Optical disks',
2640 'later life (human life cycle)' => 'Old age',
2641 'latin american cooking' => 'Cooking, Latin American',
2642 'law' => 'Law',
2643 'law, business' => 'Commercial law',
2644 'law, commercial' => 'Commercial law',
2645 'laws (statutes)' => 'Statutes',
2646 'leadership coaching' => 'Executive coaching',
2647 'leadership' => 'Leadership',
2648 'legalization of illegal drugs' => 'Drug legalization',
2649 'legislative acts' => 'Statutes',
2650 'legislative enactments' => 'Statutes',
2651 'letter writing' => 'Letter writing',
2652 'letters' => 'Letters',
2653 'liability insurance' => 'Liability insurance',
2654 'liability insurance, automobile' => 'Automobile insurance',
2655 'life' => 'Life',
2656 'life after death' => 'Immortality',
2657 'life drawing' => 'Human figure in art',
2658 'life insurance' => 'Life insurance',
2659 'life on other planets' => 'Life on other planets',
2660 'linguistic science' => 'Linguistics',
2661 'linguistics' => 'Linguistics',
2662 'linguistics--data processing' => 'Computational linguistics',
2663 'liquors' => 'Liquors',
2664 'liquors--use in cooking' => 'Cooking (Liquors)',
2665 'lisp (computer program language)' => 'LISP (Computer program language)',
2666 'list processing computer language' => 'LISP (Computer program language)',
2667 'listed options' => 'Options (Finance)',
2668 'literacy' => 'Literacy',
2669 'literacy, computer' => 'Computer literacy',
2670 'literary criticism' => 'Criticism',
2671 'literature/poetry' => 'Poetry',
2672 'local area computer networks' => 'Local area networks (Computer networks)',
2673 'local area networks (computer networks)' => 'Local area networks (Computer networks)',
2674 'local area networks' => 'Local area networks (Computer networks)',
2675 'logic design' => 'Logic design',
2676 'london' => 'City of London (England)',
2677 'london, england' => 'City of London (England)',
2678 'look-ism' => 'Physical-appearance-based bias',
2679 'lookism' => 'Physical-appearance-based bias',
2680 'looks-ism' => 'Physical-appearance-based bias',
2681 'looksism' => 'Physical-appearance-based bias',
2682 'lorraine cooking' => 'Cooking, French--Lorraine style',
2683 'losing weight' => 'Weight loss',
2684 'loss of weight' => 'Weight loss',
2685 'love stories' => 'Love stories',
2686 'lovemaking' => 'Sex',
2687 'low salt diet' => 'Salt-free diet',
2688 'low sodium diet' => 'Salt-free diet',
2689 'low-carb diet' => 'Low-carbohydrate diet',
2690 'low-carbohydrate diet' => 'Low-carbohydrate diet',
2691 'low-cholesterol diet' => 'Low-cholesterol diet',
2692 'low-fat diet' => 'Low-fat diet',
2693 'low-salt diet' => 'Salt-free diet',
2694 'low-sodium diet' => 'Salt-free diet',
2695 'machine intelligence' => 'Artificial intelligence',
2696 'machine systems, virtual' => 'Virtual computer systems',
2697 'machine theory' => 'Machine theory',
2698 'machine vision' => 'Computer vision',
2699 'mac clones' => 'Macintosh-compatible computers',
2700 'mac computers' => 'Macintosh-compatible computers',
2701 'machine language' => 'Programming languages (Electronic computers)',
2702 'machine languages' => 'Programming languages (Electronic computers)',
2703 'macintosh clones' => 'Macintosh-compatible computers',
2704 'macintosh compatibles (computers)' => 'Macintosh-compatible computers',
2705 'macintosh compatibles' => 'Macintosh-compatible computers',
2706 'macintosh-compatible computers' => 'Macintosh-compatible computers',
2707 'macintosh computers' => 'Macintosh-compatible computers',
2708 'macroeconomics' => 'Macroeconomics',
2709 'magazines' => 'Periodicals',
2710 'magic cookies (computer science)' => 'Cookies (Computer science)',
2711 'magic' => 'Magic',
2712 'magic--fiction' => 'Magic',
2713 'magicians' => 'Magicians',
2714 'magicians--fiction' => 'Magicians--Fiction',
2715 'mail-order business' => 'Mail-order business',
2716 'mail-order houses' => 'Mail-order business',
2717 'main courses (cooking)' => 'Entrées (Cooking)',
2718 'main dishes (cooking)' => 'Entrées (Cooking)',
2719 'making bread' => 'Cooking (Bread)',
2720 'making decisions' => 'Decision making',
2721 'malevolent software' => 'Malware (Computer software)',
2722 'malicious computer code' => 'Malware (Computer software)',
2723 'malicious software' => 'Malware (Computer software)',
2724 'malignancy (cancer)' => 'Cancer',
2725 'malignant tumors' => 'Cancer',
2726 'maltreatment of children' => 'Child abuse',
2727 'malware (computer software)' => 'Malware (Computer software)',
2728 'malware' => 'Malware (Computer software)',
2729 'management coaching' => 'Executive coaching',
2730 'management decisions' => 'Decision making',
2731 'management information systems' => 'Management information systems',
2732 'management of computer memory' => 'Memory management (Computer science)',
2733 'management of conflict' => 'Conflict management',
2734 'management science' => 'Management science',
2735 'management' => 'Management',
2736 'management, industrial' => 'Industrial management',
2737 'management, sales' => 'Sales management',
2738 'managing conflict' => 'Conflict management',
2739 'manga' => 'Comic books, strips, etc',
2740 'manhua' => 'Comic books, strips, etc',
2741 'manhwa' => 'Comic books, strips, etc',
2742 'manpower utilization' => 'Personnel management',
2743 'manufacturing industries' => 'Manufacturing industries',
2744 'manufacturing management' => 'Production management',
2745 'market research' => 'Marketing research',
2746 'marketing research' => 'Marketing research',
2747 'marketing' => 'Marketing',
2748 'marketing, multilevel' => 'Multilevel marketing',
2749 'marketing--research' => 'Marketing research',
2750 'markets' => 'Markets',
2751 'markets, free' => 'Free enterprise',
2752 'markets--research' => 'Marketing research',
2753 'marksmanship' => 'Shooting',
2754 'marshall, george c. (george catlett), 1880-1959'
2755 => 'Marshall, George C. (George Catlett), 1880-1959',
2756 'mass communication' => 'Communication and traffic',
2757 'mass culture' => 'Popular culture',
2758 'mass imputation' => 'Statistical matching',
2759 'massacres' => 'Massacres',
2760 'massacres--vietnam' => 'Massacres--Vietnam',
2761 'matching, data (statistics)' => 'Statistical matching',
2762 'matching, statistical' => 'Statistical matching',
2763 'math' => 'Mathematics',
2764 'mathematical machine theory' => 'Machine theory',
2765 'mathematical machines' => 'Calculators',
2766 'mathematical programming' => 'Programming (Mathematics)',
2767 'mathematics' => 'Mathematics',
2768 'mechanical computers' => 'Calculators',
2769 'medical and health care industry' => 'Medical care',
2770 'medical and healthcare industry' => 'Medical care',
2771 'medical care planning' => 'Health planning',
2772 'medical care' => 'Medical care',
2773 'medical care, prepaid' => 'Health insurance',
2774 'medical care--planning' => 'Health planning',
2775 'medical care--social aspects' => 'Social medicine',
2776 'medical informatics' => 'Medical informatics',
2777 'medical information science' => 'Medical informatics',
2778 'medical insurance' => 'Health insurance',
2779 'medical profession' => 'Medicine',
2780 'medical services' => 'Medical care',
2781 'medical sociology' => 'Social medicine',
2782 'medical' => 'Medical care',
2783 'medicaments' => 'Drugs',
2784 'medications' => 'Drugs',
2785 'medications' => 'Drugs',
2786 'medicine (drugs)' => 'Drugs',
2787 'medicine' => 'Medicine',
2788 'medicine, social' => 'Social medicine',
2789 'medicine--social aspects' => 'Social medicine',
2790 'medicines (drugs)' => 'Drugs',
2791 'medicines' => 'Drugs',
2792 'meditation' => 'Meditation',
2793 'medium-sized business' => 'Small business',
2794 'medium-sized businesses' => 'Small business',
2795 'memorabilia' => 'Collectibles',
2796 'memory management (computer science)' => 'Memory management (Computer science)',
2797 'memory management' => 'Memory management (Computer science)',
2798 'mental healing' => 'Mental healing',
2799 'mental prayer' => 'Meditation',
2800 'mental telepathy' => 'Telepathy',
2801 'mercantile law' => 'Commercial law',
2802 'merchandise' => 'Commercial products',
2803 'merger of corporations' => 'Consolidation and merger of corporations',
2804 'mergers & acquisitions' => 'Consolidation and merger of corporations',
2805 'mergers and acquisitions' => 'Consolidation and merger of corporations',
2806 'mergers and acquisitions of corporations' => 'Consolidation and merger of corporations',
2807 'mergers of corporations' => 'Consolidation and merger of corporations',
2808 'mergers, corporate' => 'Consolidation and merger of corporations',
2809 'merging, data (Statistics)' => 'Statistical matching',
2810 'merging, data' => 'Statistical matching',
2811 'metamorphosis--folklore' => 'Shapeshifting',
2812 'micro computers' => 'Microcomputers',
2813 'micro-businesses' => 'Small business',
2814 'micro-enterprises' => 'Small business',
2815 'microbusinesses' => 'Small business',
2816 'microcomputers' => 'Microcomputers',
2817 'microeconomics' => 'Microeconomics',
2818 'microenterprises' => 'Small business',
2819 'microprocessors' => 'Microprocessors',
2820 'micros (microcomputers)' => 'Microcomputers',
2821 'microsimulation modeling (statistics)' => 'Statistical matching',
2822 'microwave cookery' => 'Microwave cooking',
2823 'microwave cooking' => 'Microwave cooking',
2824 'mid-atlantic states' => 'Middle Atlantic States',
2825 'middle atlantic region' => 'Middle Atlantic States',
2826 'middle atlantic states' => 'Middle Atlantic States',
2827 'middle colonies' => 'Middle Atlantic States',
2828 'middle states' => 'Middle Atlantic States',
2829 'middle-atlantic states' => 'Middle Atlantic States',
2830 'midwestern cooking' => 'Cooking, American--Midwestern style',
2831 'military biography' => 'Military biography',
2832 'military history' => 'History, Military',
2833 'mind reading' => 'Telepathy',
2834 'mind-cure' => 'Mental healing',
2835 'mind-distorting drugs' => 'Hallucinogenic drugs',
2836 'mind-reading' => 'Telepathy',
2837 'mindreading' => 'Telepathy',
2838 'mining data' => 'Data mining',
2839 'mining, data' => 'Data mining',
2840 'mixed media (art)' => 'Mixed media (Art)',
2841 'mixed media crafts' => 'Mixed media (Art)',
2842 'mixology' => 'Bartending',
2843 'mobile computing' => 'Mobile computing',
2844 'modeling, computer' => 'Computer simulation',
2845 'modeling, microsimulation (statistics)' => 'Statistical matching',
2846 'models, computer' => 'Computer simulation',
2847 'modems' => 'Modems',
2848 'modern & contemporary fiction (post c 1945)' => 'Fiction--1945-',
2849 'modern art' => 'Art, Modern',
2850 'modula-2 (computer program language)' => 'Modula-2 (Computer program language)',
2851 'modula-2' => 'Modula-2 (Computer program language)',
2852 'molesting children' => 'Child sexual abuse',
2853 'molesting of children' => 'Child sexual abuse',
2854 'monetary management' => 'Monetary policy',
2855 'monetary policy' => 'Monetary policy',
2856 'money' => 'Money',
2857 'monitoring, election' => 'Election monitoring',
2858 'mongolians' => 'Mongols',
2859 'mongols' => 'Mongols',
2860 'mongols--fiction' => 'Mongols--Fiction',
2861 'mongols--history' => 'Mongols--History',
2862 'monitoring, environmental' => 'Environmental monitoring',
2863 'moral philosophy' => 'Ethics',
2864 'morality' => 'Ethics',
2865 'morals' => 'Ethics',
2866 'mortgages' => 'Mortgages',
2867 'motivational speakers' => 'Motivational speakers',
2868 'motorcars (automobiles)' => 'Automobiles',
2869 'motorcars' => 'Automobiles',
2870 'mount sneffels wilderness (colo.)' => 'Mount Sneffels Wilderness (Colo.)',
2871 'mourning' => 'Grief',
2872 'mui tsai' => 'Slavery',
2873 'multilevel distributorship' => 'Multilevel marketing',
2874 'multilevel marketing' => 'Multilevel marketing',
2875 'multilevel sales companies' => 'Multilevel marketing',
2876 'multinational corporations' => 'International business enterprises',
2877 'multinational enterprises' => 'International business enterprises',
2878 'municipalities' => 'Cities and towns',
2879 'murder' => 'Murder',
2880 'murder mystery' => 'Mystery and detective stories',
2881 'museology' => 'Museum techniques',
2882 'museum administration' => 'Museum techniques',
2883 'museum techniques' => 'Museum techniques',
2884 'museums' => 'Museums',
2885 'museums--technique' => 'Museum techniques',
2886 'musical instruments' => 'Musical instruments',
2887 'mutual funds' => 'Mutual funds',
2888 'mutual insurance' => 'Insurance',
2889 'mystery and detective stories' => 'Mystery and detective stories',
2890 'mystery' => 'Mystery and detective stories',
2891 'mystical theology' => 'Mysticism',
2892 'mysticism' => 'Mysticism',
2893 'mythology, greek' => 'Mythology, Greek',
2894 'national resources' => 'Natural resources',
2895 'natural language processing' => 'Computational linguistics',
2896 'natural resources' => 'Natural resources',
2897 'natural science' => 'Science',
2898 'naval tactics' => 'Naval tactics',
2899 'navigators' => 'Explorers',
2900 'near-death experiences' => 'Near-death experiences',
2901 'negotiating' => 'Negotiation',
2902 'negotiation' => 'Negotiation',
2903 'negotiations' => 'Negotiation',
2904 'neglect of children' => 'Child abuse',
2905 'negro art' => 'African American art',
2906 'netcasting' => 'Webcasting',
2907 'nets, neural (computer science)' => 'Neural networks (Computer science)',
2908 'nets, neural (neurobiology)' => 'Neural networks (Neurobiology)',
2909 'network marketing' => 'Multilevel marketing',
2910 'network security' => 'Computer networks--Security measures',
2911 'network security, computer' => 'Computer networks--Security measures',
2912 'networks, computer' => 'Computer networks',
2913 'networks, neural (computer science)' => 'Neural networks (Computer science)',
2914 'networks, neural (neurobiology)' => 'Neural networks (Neurobiology)',
2915 'neural nets (computer science)' => 'Neural networks (Computer science)',
2916 'neural nets (neurobiology)' => 'Neural networks (Neurobiology)',
2917 'neural networks (computer science)' => 'Neural networks (Computer science)',
2918 'neural networks (neurobiology)' => 'Neural networks (Neurobiology)',
2919 'new business enterprises' => 'New business enterprises',
2920 'new companies' => 'New business enterprises',
2921 'new england cooking' => 'Cooking, American--New England style',
2922 'new thought' => 'New Thought',
2923 'newspapers' => 'Newspapers',
2924 'non-alcoholic beverages' => 'Non-alcoholic beverages',
2925 'non-alcoholic drinks' => 'Non-alcoholic beverages',
2926 'non-profit organizations' => 'Nonprofit organizations',
2927 'non-profit sector' => 'Nonprofit organizations',
2928 'non-profits' => 'Nonprofit organizations',
2929 'non-resistance to government' => 'Government, Resistance to',
2930 'nonprofit organizations' => 'Nonprofit organizations',
2931 'nonprofit sector' => 'Nonprofit organizations',
2932 'nonprofits' => 'Nonprofit organizations',
2933 'norman cooking' => 'Cooking, French--Normandy style',
2934 'normandy cooking' => 'Cooking, French--Normandy style',
2935 'northwestern states' => 'Northwestern States',
2936 'northwestern united states' => 'Northwestern States',
2937 'not-for-profit organizations' => 'Nonprofit organizations',
2938 'npos' => 'Nonprofit organizations',
2939 'numerology' => 'Numerology',
2940 'nutrition', => 'Nutrition',
2941 'nutrition--health aspects', => 'Nutrition',
2942 'oacet (imaginary organization)' => 'OACET (Imaginary organization)',
2943 'oacet' => 'OACET (Imaginary organization)',
2944 'obe (parapsychology)' => 'Astral projection',
2945 'obesity' => 'Obesity',
2946 'obesity--control' => 'Weight loss',
2947 'obesity--etiology' => 'Obesity--Etiology',
2948 'object-oriented programming (computer science)' => 'Object-oriented programming (Computer science)',
2949 'object-oriented programming' => 'Object-oriented programming (Computer science)',
2950 'objective c' => 'Objective-C (Computer program language)',
2951 'objective-c (Computer program language)' => 'Objective-C (Computer program language)',
2952 'objective-c' => 'Objective-C (Computer program language)',
2953 'objects, art' => 'Art objects',
2954 "objets d'art" => 'Art objects',
2955 'occultism' => 'Occultism',
2956 'occupations' => 'Occupations',
2957 'office administration' => 'Office management',
2958 'office automation' => 'Office practice--Automation',
2959 'office equipment and supplies' => 'Office equipment and supplies',
2960 'office equipment' => 'Office equipment and supplies',
2961 'office etiquette' => 'Business etiquette',
2962 'office machines' => 'Office equipment and supplies',
2963 'office management' => 'Office management',
2964 'office practice--automation' => 'Office practice--Automation',
2965 'office products' => 'Office equipment and supplies',
2966 'office supplies' => 'Office equipment and supplies',
2967 'office systems' => 'Office equipment and supplies',
2968 'oil painting' => 'Painting',
2969 'old age' => 'Old age',
2970 'on-line information services' => 'Online information services',
2971 'online auctions' => 'Internet auctions',
2972 'online commerce' => 'Electronic commerce',
2973 'online information services' => 'Online information services',
2974 'online investing' => 'Electronic trading of securities',
2975 'online publishing' => 'Electronic publishing',
2976 'online services (information services)' => 'Online information services',
2977 'online social networks' => 'Online social networks',
2978 'online trading' => 'Electronic trading of securities',
2979 'online trading of securities' => 'Electronic trading of securities',
2980 'open spaces' => 'Open spaces',
2981 'open spaces, fear of' => 'Agoraphobia',
2982 'open-end mutual funds' => 'Mutual funds',
2983 'operational analysis' => 'Operations research',
2984 'operational research' => 'Operations research',
2985 'operations management' => 'Production management',
2986 'operations research' => 'Operations research',
2987 'operating systems (computers)' => 'Operating systems (Computers)',
2988 'operating systems' => 'Operating systems (Computers)',
2989 'operators, tour (industry)' => 'Tourism',
2990 'operators, tour' => 'Tourism',
2991 'optical computing' => 'Optical data processing',
2992 'optical data processing' => 'Optical data processing',
2993 'optical discs' => 'Optical disks',
2994 'optical disks' => 'Optical disks',
2995 'optical illusions' => 'Optical illusions',
2996 'options (finance)' => 'Options (Finance)',
2997 'options exchange' => 'Options (Finance)',
2998 'options market' => 'Options (Finance)',
2999 'options trading' => 'Options (Finance)',
3000 'ordnance' => 'Ordnance',
3001 'organization development' => 'Organizational change',
3002 'organizational behavior' => 'Organizational behavior',
3003 'organizational change' => 'Organizational change',
3004 'organizational development' => 'Organizational change',
3005 'organizational innovation' => 'Organizational change',
3006 'organizations, business' => 'Business enterprises',
3007 'organizations, nonprofit' => 'Nonprofit organizations',
3008 'oriental art' => 'Art, Asian',
3009 'oriental cooking' => 'Cooking, Asian',
3010 'out-of-body experiences' => 'Astral projection',
3011 'outdoor cookery' => 'Outdoor cooking',
3012 'outdoor cooking' => 'Outdoor cooking',
3013 'outsourcing' => 'Contracting out',
3014 'overseas marketing' => 'Export marketing',
3015 'ownership of slaves' => 'Slavery',
3016 'pad computers' => 'Tablet computers',
3017 'pages, web' => 'Web sites',
3018 'painting' => 'Painting',
3019 'painting, primitive' => 'Painting',
3020 'painting--technique' => 'Painting--Technique',
3021 'paintings' => 'Painting',
3022 'palm reading' => 'Palmistry',
3023 'palmistry' => 'Palmistry',
3024 'palmreading' => 'Palmistry',
3025 'papooses' => 'Infants',
3026 'parallel programming (computer science)' => 'Parallel programming (Computer science)',
3027 'parallel programming' => 'Parallel programming (Computer science)',
3028 'paranormal' => 'Paranormal fiction',
3029 'paranormal fiction' => 'Paranormal fiction',
3030 'paranormal phenomena' => 'Parapsychology',
3031 'paraphernalia, political' => 'Political collectibles',
3032 'parapsychology' => 'Parapsychology',
3033 'park administration' => 'Parks--Management',
3034 'park management' => 'Parks--Management',
3035 'parklands' => 'Parks',
3036 'parks' => 'Parks',
3037 'parks--management' => 'Parks--Management',
3038 'parody' => 'Parody',
3039 'pascal (computer program language)' => 'Pascal (Computer program language)',
3040 'pastel drawing' => 'Pastel drawing',
3041 'pastel drawing--technique' => 'Pastel drawing--Technique',
3042 'pastel painting' => 'Pastel drawing',
3043 'pastels' => 'Pastel drawing',
3044 'pastry' => 'Pastry',
3045 'pathfinder (game)' => 'Pathfinder (Game)',
3046 'pathfinder game' => 'Pathfinder (Game)',
3047 'pathfinder novel' => 'Pathfinder (Game)',
3048 'pathfinder roleplaying game' => 'Pathfinder (Game)',
3049 'pathfinder story' => 'Pathfinder (Game)',
3050 'pathologically eclectic rubbish lister' => 'Perl (Computer program language)',
3051 'pattern classification systems' => 'Pattern recognition systems',
3052 'pattern recognition computers' => 'Pattern recognition systems',
3053 'pattern recognition systems' => 'Pattern recognition systems',
3054 'pcs (microcomputers)' => 'Microcomputers',
3055 'pcs' => 'Microcomputers',
3056 'peasant art' => 'Folk art',
3057 'pedagogy' => 'Education',
3058 'pedology (child study)' => 'Children',
3059 'pen drawing' => 'Pen drawing',
3060 'pen drawing--technique' => 'Pen drawing--Technique',
3061 'pen and ink drawing' => 'Pen drawing',
3062 'pencil drawing' => 'Pencil drawing',
3063 'pencil drawing--technique' => 'Pencil drawing--Technique',
3064 'peng, rachel (fictitious character)' => 'Peng, Rachel (Fictitious character)',
3065 'peng, rachel' => 'Peng, Rachel (Fictitious character)',
3066 'perceptual isolation' => 'Sensory deprivation',
3067 'performance art' => 'Performance art',
3068 'performance motivation' => 'Achievement motivation',
3069 'performance pieces' => 'Performance art',
3070 'periodicals' => 'Periodicals',
3071 'peripheral computer devices' => 'Computer peripherals',
3072 'peripheral computer equipment' => 'Computer peripherals',
3073 'peripheral devices (computers)' => 'Computer peripherals',
3074 'peripheral equipment (computers)' => 'Computer peripherals',
3075 'peripherals, computer' => 'Computer peripherals',
3076 'perl (computer program language)' => 'Perl (Computer program language)',
3077 'perl' => 'Perl (Computer program language)',
3078 'perl/tk (computer program language)' => 'Perl/Tk (Computer program language)',
3079 'perl/tk' => 'Perl/Tk (Computer program language)',
3080 'persian gulf war, 1991' => 'Persian Gulf War, 1991',
3081 'persistent cookies (computer science)' => 'Cookies (Computer science)',
3082 'persistent cookies' => 'Cookies (Computer science)',
3083 'personal body care' => 'Hygiene',
3084 'personal budgets' => 'Budgets, Personal',
3085 'personal cleanliness' => 'Hygiene',
3086 'personal computers' => 'Microcomputers',
3087 'personal finance software' => 'Finance, Personal--Software',
3088 'personal finance' => 'Finance, Personal',
3089 'personal financial management' => 'Finance, Personal',
3090 'personal financial planning' => 'Finance, Personal',
3091 'personal health services' => 'Medical care',
3092 'personal hygiene' => 'Hygiene',
3093 'personal identity' => 'Personality',
3094 'personal income tax' => 'Income tax',
3095 'personal time management' => 'Time management',
3096 'personality' => 'Personality',
3097 'personality traits' => 'Personality',
3098 'personification of death' => 'Death (Personification)',
3099 'personnel administration' => 'Personnel management',
3100 'personnel management' => 'Personnel management',
3101 'personology' => 'Personality',
3102 'pharmaceuticals' => 'Drugs',
3103 'philosophers' => 'Philosophers',
3104 'philosophers--biography' => 'Philosophers--Biography',
3105 'philosophy, moral' => 'Ethics',
3106 'php (computer program language)' => 'PHP (Computer program language)',
3107 'php' => 'PHP (Computer program language)',
3108 'physical endurance' => 'Physical fitness',
3109 'physical fitness' => 'Physical fitness',
3110 'physical stamina' => 'Physical fitness',
3111 'physical-appearance-based bias' => 'Physical-appearance-based bias',
3112 'physique' => 'Bodybuilding',
3113 'pickling' => 'Canning and preserving',
3114 'pictorial data processing' => 'Image processing',
3115 'picture processing' => 'Image processing',
3116 'pies' => 'Pies',
3117 'pies, pizza' => 'Pizza',
3118 'pizza pies' => 'Pizza',
3119 'pizza' => 'Pizza',
3120 'pizzas' => 'Pizza',
3121 'pl/c (computer program language)' => 'PL/C (Computer program language)',
3122 'pl/c' => 'PL/C (Computer program language)',
3123 'pl/sql (computer program language)' => 'PL/SQL (Computer program language)',
3124 'pl/sql' => 'PL/SQL (Computer program language)',
3125 'places, imaginary' => 'Imaginary places',
3126 'planning' => 'Planning',
3127 'planning, strategic' => 'Strategic planning',
3128 'plants in art' => 'Plants in art',
3129 'plants, psychoactive' => 'Psychotropic plants',
3130 'plants, psychotropic' => 'Psychotropic plants',
3131 'pocket calculators' => 'Calculators',
3132 'poems' => 'Poetry',
3133 'poetry' => 'Poetry',
3134 'police' => 'Police',
3135 'police--england' => 'Police--England',
3136 'police--england--london' => 'Police--England--London',
3137 'police--england--london--fiction' => 'Police--England--London--Fiction',
3138 'political collectibles' => 'Political collectibles',
3139 'political ethics' => 'Political ethics',
3140 'political paraphernalia' => 'Political collectibles',
3141 'political science--moral and ethical aspects' => 'Political ethics',
3142 'political terrorism' => 'Terrorism',
3143 'politics and culture' => 'Politics and culture',
3144 'politics and culture--united states' => 'Politics and culture--United States',
3145 'politics in art' => 'Politics in art',
3146 'politics, practical' => 'Politics, Practical',
3147 'politics, practical--moral and ethical aspects' => 'Political ethics',
3148 'poll watching' => 'Election monitoring',
3149 'pop culture' => 'Popular culture',
3150 'popular arts' => 'Popular culture',
3151 'popular culture' => 'Popular culture',
3152 'portraits' => 'Portraits',
3153 'possible art' => 'Conceptual art',
3154 'post-object art' => 'Conceptual art',
3155 'potable liquids' => 'Beverages',
3156 'potable water' => 'Drinking water',
3157 'potables' => 'Beverages',
3158 'pottery' => 'Pottery',
3159 'pottery, primitive' => 'Pottery',
3160 'poverty' => 'Poverty',
3161 'pr' => 'Public relations',
3162 'practical extraction and report language' => 'Perl (Computer program language)',
3163 'practical politics' => 'Politics, Practical',
3164 'prayer, mental' => 'Meditation',
3165 'precog' => 'Precognition',
3166 'precognition' => 'Precognition',
3167 'prepaid health plans' => 'Health insurance',
3168 'prepaid medical care' => 'Health insurance',
3169 'prescription drugs' => 'Drugs',
3170 'presentation graphics software' => 'Presentation graphics software',
3171 'presentation software' => 'Presentation graphics software',
3172 'preservation of art objects' => 'Art objects--Conservation and restoration',
3173 'price theory' => 'Microeconomics',
3174 'princesses' => 'Princesses',
3175 'print making' => 'Prints--Technique',
3176 'printmaking' => 'Prints--Technique',
3177 'prints' => 'Prints',
3178 'prints--technique' => 'Prints--Technique',
3179 'privacy' => 'Privacy',
3180 'private enterprise' => 'Free enterprise',
3181 'procedural language/sql' => 'PL/SQL (Computer program language)',
3182 'processing, image' => 'Image processing',
3183 'processing, word' => 'Word processing',
3184 'processing, words' => 'Word processing',
3185 'produce exchanges' => 'Commodity exchanges',
3186 'product design' => 'Product design',
3187 'production management' => 'Production management',
3188 'products, commercial' => 'Commercial products',
3189 'professions' => 'Occupations',
3190 'profit-sharing trusts' => 'Mutual funds',
3191 'programming (electronic computers)' => 'Computer programming',
3192 'programming (mathematics)' => 'Programming (Mathematics)',
3193 'programming languages (computers)' => 'Programming languages (Electronic computers)',
3194 'programming languages (electronic computers)' => 'Programming languages (Electronic computers)',
3195 'programming languages' => 'Programming languages (Electronic computers)',
3196 'programming search engines' => 'Search engines--Programming',
3197 'programming' => 'Computer programming',
3198 'project management software' => 'Project management--Software',
3199 'project management' => 'Project management',
3200 'project management--software' => 'Project management--Software',
3201 'projection, astral' => 'Astral projection',
3202 'prolog (computer program language)' => 'Prolog (Computer program language)',
3203 'prolog' => 'Prolog (Computer program language)',
3204 'prolog++ (computer program language)' => 'Prolog++ (Computer program language)',
3205 'prolog++' => 'Prolog++ (Computer program language)',
3206 'property insurance' => 'Property insurance',
3207 'prophecy' => 'Prophecy',
3208 'prose poems' => 'Prose poems',
3209 'prose poetry' => 'Prose poems',
3210 'prostitution' => 'Prostitution',
3211 'protocols, computer network' => 'Computer network protocols',
3212 'provencal cooking' => 'Cooking, French--Provençal style',
3213 'provençal cooking' => 'Cooking, French--Provençal style',
3214 'provincial parks' => 'Parks',
3215 'psychedelic drugs' => 'Hallucinogenic drugs',
3216 'psychic healing' => 'Mental healing',
3217 'psychic phenomena' => 'Parapsychology',
3218 'psychic research' => 'Parapsychology',
3219 'psychical research' => 'Parapsychology',
3220 'psycho-kinesis' => 'Psychokinesis',
3221 'psychoactive plants' => 'Psychotropic plants',
3222 'psychokinesis' => 'Psychokinesis',
3223 'psychology' => 'Psychology',
3224 'psychology, cognitive' => 'Cognitive psychology',
3225 'psychotomimetic drugs' => 'Hallucinogenic drugs',
3226 'psychotropic plants' => 'Psychotropic plants',
3227 'public finance' => 'Finance, Public',
3228 'public health services' => 'Public health',
3229 'public health' => 'Public health',
3230 'public health--planning' => 'Health planning',
3231 'public hygiene' => 'Public health',
3232 'public markets' => 'Markets',
3233 'public relations' => 'Public relations',
3234 'public transportation' => 'Transportation',
3235 'punctuation' => 'Punctuation',
3236 'purchasing and buying' => 'Purchasing',
3237 'purchasing' => 'Purchasing',
3238 'purchasing--law and legislation' => 'Sales',
3239 'purchasing--law' => 'Sales',
3240 'put and call transactions' => 'Options (Finance)',
3241 'put options' => 'Options (Finance)',
3242 'puts (finance)' => 'Options (Finance)',
3243 'pyramid marketing' => 'Multilevel marketing',
3244 'pyramid sales clubs' => 'Multilevel marketing',
3245 'python (computer program language)' => 'Python (Computer program language)',
3246 'python' => 'Python (Computer program language)',
3247 'pythonidae' => 'Pythons',
3248 'pythoninae' => 'Pythons',
3249 'pythons' => 'Pythons',
3250 'q-boats' => 'Q-ships',
3251 'q-ships' => 'Q-ships',
3252 'quality assurance' => 'Quality assurance',
3253 'quality control' => 'Quality control',
3254 'quality management, total' => 'Total quality management',
3255 'quality of environment' => 'Environmental quality',
3256 'quantitative business analysis' => 'Management science',
3257 'quantity cookery' => 'Quantity cooking',
3258 'quantity cooking' => 'Quantity cooking',
3259 'quick and easy cookery' => 'Quick and easy cooking',
3260 'quick and easy cooking' => 'Quick and easy cooking',
3261 'quick-meal cookery' => 'Quick and easy cooking',
3262 'quick-meal cooking' => 'Quick and easy cooking',
3263 'r & d projects' => 'Research and development projects',
3264 'r & d' => 'Research and development projects',
3265 'r and d projects' => 'Research and development projects',
3266 'r&d projects' => 'Research and development projects',
3267 'r&d' => 'Research and development projects',
3268 'rabbits' => 'Rabbits',
3269 'rachel peng' => 'Peng, Rachel (Fictitious character)',
3270 'radio vision' => 'Television',
3271 'rationalization of industry' => 'Industrial management',
3272 'raw food' => 'Raw foods',
3273 'raw foods' => 'Raw foods',
3274 'real estate investment' => 'Real estate investment',
3275 'real estate' => 'Real property',
3276 'real property investment' => 'Real estate investment',
3277 'real property' => 'Real property',
3278 'reducing diets' => 'Reducing diets',
3279 'reduction of weight' => 'Weight loss',
3280 'realty' => 'Real property',
3281 'recreational shooting' => 'Shooting',
3282 'regional economics' => 'Regional economics',
3283 'regional parks' => 'Parks',
3284 'reicki (healing system)' => 'Reiki (Healing system)',
3285 'reicki' => 'Reiki (Healing system)',
3286 'reiki (healing system)' => 'Reiki (Healing system)',
3287 'reiki' => 'Reiki (Healing system)',
3288 'reincarnation' => 'Reincarnation',
3289 'religion and politics' => 'Religion and politics',
3290 'religion and politics--united states' => 'Religion and politics--United States',
3291 'religion and social problems' => 'Religion and social problems',
3292 'religious art' => 'Religious art',
3293 'religious corporations' => 'Corporations, Religious',
3294 'report program generator' => 'RPG (Computer program language)',
3295 'research & development projects' => 'Research and development projects',
3296 'research and development projects' => 'Research and development projects',
3297 'resistance to government' => 'Government, Resistance to',
3298 'resources, natural' => 'Natural resources',
3299 'restoration of art objects' => 'Art objects--Conservation and restoration',
3300 'resumes' => 'Résumés (Employment)',
3301 'resumes (employment)' => 'Résumés (Employment)',
3302 'résumés' => 'Résumés (Employment)',
3303 'résumés (employment)' => 'Résumés (Employment)',
3304 'retail industry' => 'Retail trade',
3305 'retail marketing' => 'Marketing',
3306 'retail trade' => 'Retail trade',
3307 'retail trade--marketing' => 'Marketing',
3308 'retail franchises' => 'Franchises (Retail trade)',
3309 'retailing' => 'Retail trade',
3310 'retirement planning' => 'Retirement--Planning',
3311 "rights of women" => "Women's rights",
3312 'retirement' => 'Retirement',
3313 'retirement--planning' => 'Retirement--Planning',
3314 'ridgway reservoir (colo.)' => 'Ridgway Reservoir (Colo.)',
3315 'ridgway' => 'Ridgway Reservoir (Colo.)',
3316 'right and left (political science)' => 'Right and left (Political science)',
3317 'rights, civil' => 'Civil rights',
3318 'risk (insurance)' => 'Risk (Insurance)',
3319 'risk' => 'Risk',
3320 'rivers' => 'Rivers',
3321 'rivers--england' => 'Rivers--England',
3322 'romance' => 'Love stories',
3323 'routines, utility' => 'Utilities (Computer programs)',
3324 'rpg (computer program language)' => 'RPG (Computer program language)',
3325 'rubies' => 'Rubies',
3326 'ruby (computer program language)' => 'Ruby (Computer program language)',
3327 'rulers' => 'Heads of state',
3328 'russian art' => 'Art, Russian',
3329 'safety measures' => 'Safety measures',
3330 'salads' => 'Salads',
3331 'sales management' => 'Sales management',
3332 'sales' => 'Sales',
3333 'sales--law and legislation' => 'Sales',
3334 'sales--law' => 'Sales',
3335 'salesmanship' => 'Selling',
3336 'salesmen and salesmanship' => 'Selling',
3337 'salt-free diet' => 'Salt-free diet',
3338 'sam vimes (fictitious character)' => 'Vimes, Samuel (Fictitious character)',
3339 'samuel vimes (fictitious character)' => 'Vimes, Samuel (Fictitious character)',
3340 'sanitary affairs' => 'Public health',
3341 'satire' => 'Satire',
3342 'sauces' => 'Sauces',
3343 'schleswig-holstein cooking' => 'Cooking, German--Schleswig-Holstein style',
3344 'schooling' => 'Education',
3345 'sci fi' => 'Science fiction',
3346 'sci-fi' => 'Science fiction',
3347 'sci/fi' => 'Science fiction',
3348 'science fiction & fantasy' => 'Speculative fiction',
3349 'science fiction and fantasy' => 'Speculative fiction',
3350 'science fiction' => 'Science fiction',
3351 'science fiction--authorship' => 'Science fiction--Authorship',
3352 'science fiction--general' => 'Science fiction',
3353 'science fiction--high tech' => 'High technology',
3354 'science fiction--technique' => 'Science fiction--Technique',
3355 'science fiction/fantasy' => 'Speculative fiction',
3356 'science of language' => 'Linguistics',
3357 'science of science' => 'Science',
3358 'science stories' => 'Science fiction',
3359 'science' => 'Science',
3360 'science, moral' => 'Ethics',
3361 'science--authorship' => 'Technical writing',
3362 'science--fiction' => 'Science fiction',
3363 'sciences' => 'Science',
3364 'scientific writing' => 'Technical writing',
3365 'scifi' => 'Science fiction',
3366 'scotland' => 'Scotland',
3367 'scottish cooking' => 'Cooking, Scottish',
3368 'screen trading (securities)' => 'Electronic trading of securities',
3369 'screen trading' => 'Electronic trading of securities',
3370 'sculpting' => 'Sculpture--Technique',
3371 'sculpture' => 'Sculpture',
3372 'sculpture--technique' => 'Sculpture--Technique',
3373 'search agents' => 'Search engines',
3374 'search engines' => 'Search engines',
3375 'search engines, web' => 'Web search engines',
3376 'search engines--programming' => 'Search engines--Programming',
3377 'second sight' => 'Precognition',
3378 'second world war' => 'World War, 1939-1945',
3379 'secret writing' => 'Cryptography',
3380 'secretarial aids & training' => 'Secretaries--Training',
3381 'secretarial aids and training' => 'Secretaries--Training',
3382 'secretaries' => 'Secretaries',
3383 'secretaries--training' => 'Secretaries--Training',
3384 'security of computer systems' => 'Computer security',
3385 'security of computer networks' => 'Computer networks--Security measures',
3386 'self-improvement' => 'Success',
3387 'selling homes' => 'House selling',
3388 'selling houses' => 'House selling',
3389 'selling' => 'Selling',
3390 'selling--law and legislation' => 'Sales',
3391 'selling--law' => 'Sales',
3392 'sensory deprivation therapy' => 'Sensory deprivation--Therapeutic use',
3393 'sensory deprivation' => 'Sensory deprivation',
3394 'sensory deprivation--therapeutic use' => 'Sensory deprivation--Therapeutic use',
3395 'sensory isolation' => 'Sensory deprivation',
3396 'seraphim' => 'Angels',
3397 'serial picture books' => 'Comic books, strips, etc',
3398 'service industries' => 'Service industries',
3399 'services, contracting for' => 'Contracting out',
3400 'services, financial' => 'Financial services industry',
3401 'sex' => 'Sex',
3402 'sex--religious aspects' => 'Sex--Religious aspects',
3403 'sexual abuse of children' => 'Child sexual abuse',
3404 'sexual behavior' => 'Sex',
3405 'sexual child abuse' => 'Child sexual abuse',
3406 'sexual practices' => 'Sex',
3407 'sexuality' => 'Sex',
3408 'shamanism' => 'Shamanism',
3409 'shape-shifters' => 'Shapeshifting',
3410 'shape-shifting' => 'Shapeshifting',
3411 'shapeshifters' => 'Shapeshifting',
3412 'shapeshifting' => 'Shapeshifting',
3413 'shapeshifting--fiction' => 'Shapeshifting',
3414 'shares of stock' => 'Stocks',
3415 'shooting sport' => 'Shooting',
3416 'shooting sports' => 'Shooting',
3417 'shooting' => 'Shooting',
3418 'short stories' => 'Short stories',
3419 'sickness insurance' => 'Health insurance',
3420 'simulation, computer' => 'Computer simulation',
3421 'sisters' => 'Sisters',
3422 'sisters--fiction' => 'Sisters--Fiction',
3423 'sites, web' => 'Web sites',
3424 'sixth sense' => 'Extrasensory perception',
3425 'sizeism' => 'Physical-appearance-based bias',
3426 'sizism' => 'Physical-appearance-based bias',
3427 'skills training' => 'Training',
3428 'slate computers' => 'Tablet computers',
3429 'slave holders' => 'Slaveholders',
3430 'slave keeping' => 'Slavery',
3431 'slave master' => 'Slaveholders',
3432 'slave masters' => 'Slaveholders',
3433 'slave owner' => 'Slaveholders',
3434 'slave owners' => 'Slaveholders',
3435 'slave ownership' => 'Slavery',
3436 'slave system' => 'Slavery',
3437 'slaveholders' => 'Slaveholders',
3438 'slaveholding' => 'Slavery',
3439 'slavemasters' => 'Slaveholders',
3440 'slaveowners' => 'Slaveholders',
3441 'slavery' => 'Slavery',
3442 'sleep deprivation' => 'Sleep deprivation',
3443 'sleep' => 'Sleep',
3444 'sleeping' => 'Sleep',
3445 'slimming' => 'Weight loss',
3446 'slumber' => 'Sleep',
3447 'small and medium-sized business' => 'Small business',
3448 'small and medium-sized businesses' => 'Small business',
3449 'small and medium-sized enterprise' => 'Small business',
3450 'small and medium-sized enterprises' => 'Small business',
3451 'small arms' => 'Firearms',
3452 'small business tax' => 'Small business--Taxation',
3453 'small business taxation' => 'Small business--Taxation',
3454 'small business taxes' => 'Small business--Taxation',
3455 'small business' => 'Small business',
3456 'small business--Taxation' => 'Small business--Taxation',
3457 'small businesses' => 'Small business',
3458 'smalltalk (computer program language)' => 'Smalltalk (Computer program language)',
3459 'smart growth' => 'Sustainable development',
3460 'sneffels' => 'Mount Sneffels Wilderness (Colo.)',
3461 'social action' => 'Social action',
3462 'social action--research' => 'Action research',
3463 'social action--religious aspects' => 'Religion and social problems',
3464 'social classes' => 'Social classes',
3465 'social classes--fiction' => 'Social classes--Fiction',
3466 'social exclusion' => 'Social isolation',
3467 'social hygiene' => 'Public health',
3468 'social infrastructure' => 'Infrastructure (Economics)',
3469 'social isolation' => 'Social isolation',
3470 'social medicine' => 'Social medicine',
3471 'social networking web sites' => 'Online social networks',
3472 'social networking' => 'Social networks',
3473 'social networks' => 'Social networks',
3474 'social overhead capital' => 'Infrastructure (Economics)',
3475 'social problems and religion' => 'Religion and social problems',
3476 'social support systems' => 'Social networks',
3477 'socioeconomic status' => 'Economic conditions',
3478 'sodium-restricted diet' => 'Salt-free diet',
3479 'software development' => 'Computer software--Development',
3480 'software engineering' => 'Software engineering',
3481 'software engineering--project management' => 'Software engineering--Project management',
3482 'software' => 'Computer software',
3483 'software, computer' => 'Computer software',
3484 'software, malevolent' => 'Malware (Computer software)',
3485 'software, malicious' => 'Malware (Computer software)',
3486 'soho (london, england)' => 'Soho (London, England)',
3487 'soothsaying' => 'Soothsaying',
3488 'sorcerers' => 'Wizards',
3489 'sorrow' => 'Grief',
3490 'soup' => 'Soups',
3491 'soups' => 'Soups',
3492 'south german cooking' => 'Cooking, German--Southern style',
3493 'southern cooking (united states)' => 'Cooking, American--Southern style',
3494 'southern cooking (germany)' => 'Cooking, German--Southern style',
3495 'southwestern cooking (united states)' => 'Cooking, American--Southwestern style',
3496 'space colonies' => 'Space colonies',
3497 'space opera' => 'Speculative fiction',
3498 'space rockets' => 'Space vehicles',
3499 'space ships' => 'Space vehicles',
3500 'space vehicles' => 'Space vehicles',
3501 'spacecraft' => 'Space vehicles',
3502 'spaceships' => 'Space vehicles',
3503 'spam (electronic mail)' => 'Spam (Electronic mail)',
3504 'spam' => 'Spam (Electronic mail)',
3505 'specfic' => 'Speculative fiction',
3506 'specie' => 'Coins',
3507 'speculative fantasy' => 'Speculative fiction',
3508 'speculative fiction' => 'Speculative fiction',
3509 'speech processing systems' => 'Speech processing systems',
3510 'speech processing' => 'Speech processing systems',
3511 'spices--use in cooking' => 'Cooking (Spices)',
3512 'spies' => 'Spy stories',
3513 'spirit channeling' => 'Channeling (Spiritualism)',
3514 'spirit guides' => 'Guides (Spiritualism)',
3515 'spiritism' => 'Spiritualism',
3516 'spirits, alcoholic' => 'Liquors',
3517 'spiritual healing' => 'Spiritual healing',
3518 'spiritual therapies' => 'Spiritual healing',
3519 'spiritual-mindedness' => 'Spirituality',
3520 'spiritualism' => 'Spiritualism',
3521 'spirituality' => 'Spirituality',
3522 'spirituous liquors' => 'Liquors',
3523 'sport shooting' => 'Shooting',
3524 'sports stories' => 'Sports stories',
3525 'sports' => 'Sports',
3526 'sports--fiction' => 'Sports stories',
3527 'sports--juvenile fiction' => 'Sports stories',
3528 'spread sheets' => 'Electronic spreadsheets',
3529 'spread sheets, electronic' => 'Electronic spreadsheets',
3530 'spreadsheet software' => 'Electronic spreadsheets--Software',
3531 'spreadsheeting, electronic' => 'Electronic spreadsheets',
3532 'spreadsheets' => 'Electronic spreadsheets',
3533 'spreadsheets, electronic' => 'Electronic spreadsheets',
3534 'spy stories' => 'Spy stories',
3535 'sql (computer program language)' => 'SQL (Computer program language)',
3536 'sql' => 'SQL (Computer program language)',
3537 'standard of value' => 'Money',
3538 'star trek fiction' => 'Star Trek fiction',
3539 'star trek' => 'Star Trek fiction',
3540 'star wars fiction' => 'Star Wars fiction',
3541 'star wars' => 'Star Wars fiction',
3542 'start-up business enterprises' => 'New business enterprises',
3543 'start-up businesses enterprises' => 'New business enterprises',
3544 'start-up companies' => 'New business enterprises',
3545 'start-up enterprises' => 'New business enterprises',
3546 'start-ups (business enterprises)' => 'New business enterprises',
3547 'start-ups' => 'New business enterprises',
3548 'starting a business' => 'New business enterprises',
3549 'startups (business enterprises)' => 'New business enterprises',
3550 'startups' => 'New business enterprises',
3551 'state parks' => 'Parks',
3552 'statistical matching' => 'Statistical matching',
3553 'statues' => 'Sculpture',
3554 'statuettes' => 'Figurines',
3555 'statutes' => 'Statutes',
3556 'steampunk fiction' => 'Steampunk fiction',
3557 'steampunk' => 'Steampunk fiction',
3558 'steganography' => 'Cryptography',
3559 'stereograms' => 'Stereograms',
3560 'stew' => 'Stews',
3561 'stews' => 'Stews',
3562 'stimulus deprivation' => 'Sensory deprivation',
3563 'stock issues' => 'Stocks',
3564 'stock offerings' => 'Stocks',
3565 'stock trading' => 'Stocks',
3566 'stocks' => 'Stocks',
3567 'stonework, decorative' => 'Sculpture',
3568 'strategic management' => 'Strategic planning',
3569 'strategic planning' => 'Strategic planning',
3570 'street art' => 'Street art',
3571 'structural adjustment (economic policy)' => 'Structural adjustment (Economic policy)',
3572 'structural adjustment' => 'Structural adjustment (Economic policy)',
3573 'structured query language' => 'SQL (Computer program language)',
3574 'study guides' => 'Study guides',
3575 'submarine boats' => 'Submarines (Ships)',
3576 'submarines (ships)' => 'Submarines (Ships)',
3577 'submarines' => 'Submarines (Ships)',
3578 'success' => 'Success',
3579 'super heroes' => 'Superheroes',
3580 'superannuation' => 'Retirement',
3581 'superheroes' => 'Superheroes',
3582 'supernatural' => 'Supernatural',
3583 'survival' => 'Survival',
3584 'survival skills' => 'Survival',
3585 'suspense fiction' => 'Suspense fiction',
3586 'suspense tales' => 'Suspense fiction',
3587 'suspense' => 'Suspense fiction',
3588 'sustainable development' => 'Sustainable development',
3589 'sustainable economic development' => 'Sustainable development',
3590 'sweets' => 'Confectionery',
3591 'system administration' => 'Computers--Administration',
3592 'system analysis' => 'System analysis',
3593 'systems administration' => 'Computers--Administration',
3594 'systems analysis' => 'System analysis',
3595 'systems architecture' => 'Computer architecture',
3596 'systems, expert (computer science)' => 'Expert systems (Computer science)',
3597 'systems, expert' => 'Expert systems (Computer science)',
3598 'tablet computers' => 'Tablet computers',
3599 'tablets (computers)' => 'Tablet computers',
3600 'takeovers, corporate' => 'Consolidation and merger of corporations',
3601 'tap water' => 'Drinking water',
3602 'tarot' => 'Tarot',
3603 'tattooing' => 'Tattooing',
3604 'tattoos (body markings)' => 'Tattooing',
3605 'tattoos' => 'Tattooing',
3606 'tax policy' => 'Taxation',
3607 'tax reform' => 'Taxation',
3608 'tax-exempt organizations' => 'Nonprofit organizations',
3609 'taxable income' => 'Income tax',
3610 'taxation of franchises' => 'Corporations--Taxation',
3611 'taxation of income' => 'Income tax',
3612 'taxation' => 'Taxation',
3613 'taxation, incidence of' => 'Taxation',
3614 'taxes' => 'Taxation',
3615 'tea' => 'Tea',
3616 'tea--use in cooking' => 'Cooking (Tea)',
3617 'teachers' => 'Teachers',
3618 'technical writing' => 'Technical writing',
3619 'technology' => 'Technology',
3620 'technology--authorship' => 'Technical writing',
3621 'technomancers' => 'Technomancers',
3622 'technomancy' => 'Technomancy',
3623 'telekinesis' => 'Psychokinesis',
3624 'telemarketing' => 'Telemarketing',
3625 'telepathy' => 'Telepathy',
3626 'telephone marketing' => 'Telemarketing',
3627 'telephone service' => 'Telephone',
3628 'telephone' => 'Telephone',
3629 'telephones' => 'Telephone',
3630 'teleportation' => 'Teleportation',
3631 'teleprocessing networks' => 'Computer networks',
3632 'television' => 'Television',
3633 'territorial parks' => 'Parks',
3634 'terror attacks' => 'Terrorism',
3635 'terrorism' => 'Terrorism',
3636 'terrorism, acts of' => 'Terrorism',
3637 'terrorist acts' => 'Terrorism',
3638 'terrorist attacks' => 'Terrorism',
3639 'textile industry and fabrics' => 'Textile industry',
3640 'textile industry' => 'Textile industry',
3641 'textiles industry' => 'Textile industry',
3642 'thames' => 'Thames River (England)',
3643 'thames river' => 'Thames River (England)',
3644 'thames river (england)' => 'Thames River (England)',
3645 'theology' => 'Theology',
3646 'theology, mystical' => 'Mysticism',
3647 'thieves' => 'Thieves',
3648 'thinking, artificial' => 'Artificial intelligence',
3649 'thought-transference' => 'Telepathy',
3650 'thralldom' => 'Slavery',
3651 'thriller' => 'Suspense fiction',
3652 'thrillers (fiction)' => 'Suspense fiction',
3653 'thrillers' => 'Suspense fiction',
3654 'tiffany aching (fictitious character)' => 'Aching, Tiffany (Fictitious character)',
3655 'tiffany aching' => 'Aching, Tiffany (Fictitious character)',
3656 'time allocation' => 'Time management',
3657 'time budgets' => 'Time management',
3658 'time management' => 'Time management',
3659 'time use' => 'Time management',
3660 'time' => 'Time',
3661 'time--management' => 'Time management',
3662 'time--organization' => 'Time management',
3663 'time--use of' => 'Time management',
3664 'time-saving cooking' => 'Quick and easy cooking',
3665 'timepieces' => 'Clocks and watches',
3666 'total quality management' => 'Total quality management',
3667 'tour operators' => 'Tourism',
3668 'tourism industry' => 'Tourism',
3669 'tourism operators' => 'Tourism',
3670 'tourism' => 'Tourism',
3671 'tourist industry' => 'Tourism',
3672 'tourist trade' => 'Tourism',
3673 'tourist traffic' => 'Tourism',
3674 'towns' => 'Cities and towns',
3675 'tqm (total quality management)' => 'Total quality management',
3676 'tqm' => 'Total quality management',
3677 'trade policy' => 'Commercial policy',
3678 'trade' => 'Commerce',
3679 'trade, international' => 'International trade',
3680 'trades' => 'Occupations',
3681 'trading of securities, electronic' => 'Electronic trading of securities',
3682 'trading, futures' => 'Futures',
3683 'trading, stock' => 'Stocks',
3684 'training' => 'Training',
3685 'transmission of data' => 'Data transmission systems',
3686 'transnational corporations' => 'International business enterprises',
3687 'transnational enterprises' => 'International business enterprises',
3688 'transport industry' => 'Transportation',
3689 'transport' => 'Transportation',
3690 'transportation companies' => 'Transportation',
3691 'transportation industry' => 'Transportation',
3692 'transportation' => 'Transportation',
3693 'travel industry' => 'Tourism',
3694 'travel, astral' => 'Astral projection',
3695 'tv' => 'Television',
3696 'u.s. government' => 'United States--Politics and government',
3697 'u.s. political culture' => 'Politics and culture--United States',
3698 'u.s. politics' => 'United States--Politics and government',
3699 'u.s.a.' => 'United States',
3700 'ufo phenomena' => 'Unidentified flying objects',
3701 'ufo' => 'Unidentified flying objects',
3702 'ufology' => 'Unidentified flying objects',
3703 'ufos' => 'Unidentified flying objects',
3704 'uits' => 'Mutual funds',
3705 'uml (computer science)' => 'UML (Computer science)',
3706 'uml' => 'UML (Computer science)',
3707 'uncooked food' => 'Raw foods',
3708 'underwater basket weaving' => 'Underwater construction--Baskets',
3709 'underwater basket-weaving' => 'Underwater construction--Baskets',
3710 'underwater construction' => 'Underwater construction',
3711 'underwater construction--baskets' => 'Underwater construction--Baskets',
3712 'underwriting' => 'Insurance',
3713 'unemployment' => 'Unemployment',
3714 'unfired food' => 'Raw foods',
3715 'unidentified flying objects' => 'Unidentified flying objects',
3716 'unified modeling language' => 'Unified Modeling Language',
3717 'unit investment trusts' => 'Mutual funds',
3718 'unit trusts' => 'Mutual funds',
3719 'united states political culture' => 'Politics and culture--United States',
3720 'united states' => 'United States',
3721 'united states, northwestern' => 'Northwestern States',
3722 'united states--collectibles' => 'Americana',
3723 'united states--politics and culture' => 'Politics and culture--United States',
3724 'united states--politics and government' => 'United States--Politics and government',
3725 'urban economics' => 'Urban economics',
3726 'us government' => 'United States--Politics and government',
3727 'us political culture' => 'Politics and culture--United States',
3728 'us politics' => 'United States--Politics and government',
3729 'us' => 'United States',
3730 'usa' => 'United States',
3731 'use of time' => 'Time management',
3732 'user created content' => 'User-generated content',
3733 'user generated content' => 'User-generated content',
3734 'user interfaces (computer systems)' => 'User interfaces (Computer systems)',
3735 'user interfaces' => 'User interfaces (Computer systems)',
3736 'user-created content' => 'User-generated content',
3737 'user-generated content' => 'User-generated content',
3738 'usury' => 'Interest',
3739 'utensils' => 'Implements, utensils, etc',
3740 'utilities (computer programs)' => 'Utilities (Computer programs)',
3741 'utility programs' => 'Utilities (Computer programs)',
3742 'utility routines' => 'Utilities (Computer programs)',
3743 'valdemar' => 'Valdemar (Imaginary place)',
3744 'valdemar (imaginary place)' => 'Valdemar (Imaginary place)',
3745 'vampires' => 'Vampires',
3746 'vbscript (computer program language)' => 'VBScript (Computer program language)',
3747 'vbscript' => 'VBScript (Computer program language)',
3748 'vessels (utensils)' => 'Implements, utensils, etc',
3749 'video art' => 'Video art',
3750 'video games' => 'Computer games',
3751 'vietnam' => 'Vietnam',
3752 'vietnam war' => 'Vietnam War, 1961-1975',
3753 'vietnam war, 1961-1975' => 'Vietnam War, 1961-1975',
3754 'vimes, samuel (fictitious character)' => 'Vimes, Samuel (Fictitious character)',
3755 'vintage automobiles' => 'Antique and classic cars',
3756 'vintage cars' => 'Antique and classic cars',
3757 'virtual computer systems' => 'Virtual computer systems',
3758 'virtual corporations' => 'Virtual corporations',
3759 'virtual environments' => 'Virtual reality',
3760 'virtual machine systems' => 'Virtual computer systems',
3761 'virtual machines' => 'Virtual computer systems',
3762 'virtual private networks' => 'Extranets (Computer networks)',
3763 'virtual reality' => 'Virtual reality',
3764 'virtual worlds' => 'Virtual reality',
3765 'vision, computer' => 'Computer vision',
3766 'vision, machine' => 'Computer vision',
3767 'visitor industry' => 'Tourism',
3768 'visual data processing' => 'Optical data processing',
3769 'voyagers' => 'Explorers',
3770 'vpns' => 'Extranets (Computer networks)',
3771 'vr' => 'Virtual reality',
3772 'w3 (world wide web)' => 'World Wide Web',
3773 'w3' => 'World Wide Web',
3774 'wall art' => 'Street art',
3775 'war stories' => 'War stories',
3776 'war' => 'War stories',
3777 'warehousing data' => 'Data warehousing',
3778 'warehousing information' => 'Data warehousing',
3779 'warehousing, data' => 'Data warehousing',
3780 'warehousing, information' => 'Data warehousing',
3781 'warlocks' => 'Warlocks',
3782 'warships' => 'Warships',
3783 'watches' => 'Clocks and watches',
3784 'water-color painting' => 'Watercolor painting',
3785 'water-color paintings' => 'Watercolor painting',
3786 'water-colors' => 'Watercolor painting',
3787 'watercolor painting' => 'Watercolor painting',
3788 'watercolor painting--technique' => 'Watercolor painting--Technique',
3789 'watercolor paintings' => 'Watercolor painting',
3790 'watercolors' => 'Watercolor painting',
3791 'weather' => 'Weather',
3792 'weatherwax, esme (fictitious character)' => 'Weatherwax, Granny (Fictitious character)',
3793 'weatherwax, esmerelda (fictitious character)' => 'Weatherwax, Granny (Fictitious character)',
3794 'weatherwax, granny (fictitious character)' => 'Weatherwax, Granny (Fictitious character)',
3795 'web (world wide web)' => 'World Wide Web',
3796 'web broadcasting' => 'Webcasting',
3797 'web browsers' => 'Browsers (Computer programs)',
3798 'web browsing software' => 'Browsers (Computer programs)',
3799 'web casting' => 'Webcasting',
3800 'web drugstores' => 'Internet pharmacies',
3801 'web logs' => 'Blogs',
3802 'web pages' => 'Web sites',
3803 'web pharmacies' => 'Internet pharmacies',
3804 'web programming' => 'Web site development',
3805 'web retailing' => 'Electronic commerce',
3806 'web search engines' => 'Web search engines',
3807 'web searching' => 'Web search engines',
3808 'web services' => 'Web services',
3809 'web site development' => 'Web site development',
3810 'web site directories' => 'Web sites--Directories',
3811 'web site programming' => 'Web site development',
3812 'web sites' => 'Web sites',
3813 'web sites--computer programming' => 'Web site development',
3814 'web sites--design' => 'Web sites--Design',
3815 'web sites--development' => 'Web site development',
3816 'web sites--directories' => 'Web sites--Directories',
3817 'web sites--programming' => 'Web site development',
3818 'webcasting' => 'Webcasting',
3819 'webliographies' => 'Web sites--Directories',
3820 'weblogs' => 'Blogs',
3821 'webpage design' => 'Web sites--Design',
3822 'webpages' => 'Web sites',
3823 'website design' => 'Web sites--Design',
3824 'website development' => 'Web site development',
3825 'website programming' => 'Web site development',
3826 'websites' => 'Web sites',
3827 'weight control of obesity' => 'Weight loss',
3828 'weight control' => 'Weight loss',
3829 'weight loss' => 'Weight loss',
3830 'weight reducing' => 'Weight loss',
3831 'weight reduction' => 'Weight loss',
3832 'welsh cooking' => 'Cooking, Welsh',
3833 'were-wolf' => 'Werewolves',
3834 'were-wolves' => 'Werewolves',
3835 'werewolf' => 'Werewolves',
3836 'werewolves' => 'Werewolves',
3837 'werewolves--fiction' => 'Werewolves',
3838 'werwolf' => 'Werewolves',
3839 'werwolves' => 'Werewolves',
3840 'west indian cooking' => 'Cooking, West Indian',
3841 'western cooking (united states)' => 'Cooking, American--Western style',
3842 'westphalian cooking' => 'Cooking, German--Westphalian style',
3843 'wideband communication systems' => 'Broadband communication systems',
3844 'wimmin' => 'Women',
3845 'wireless communication systems' => 'Wireless communication systems',
3846 'wireless data communication systems' => 'Wireless communication systems',
3847 'wireless data communication' => 'Wireless communication systems',
3848 'wireless data transmission systems' => 'Wireless communication systems',
3849 'wireless data transmission' => 'Wireless communication systems',
3850 'wireless information systems' => 'Wireless communication systems',
3851 'wireless telecommunication systems' => 'Wireless communication systems',
3852 'wireless telecommunication' => 'Wireless communication systems',
3853 'witchcraft' => 'Witchcraft',
3854 'wizard of london' => 'Wizards--England--London--Fiction',
3855 'wizards' => 'Wizards',
3856 'wizards--england--london--fiction' => 'Wizards--England--London--Fiction',
3857 'wok cookery' => 'Wok cooking',
3858 'wok cooking' => 'Wok cooking',
3859 'woman' => 'Women',
3860 'women' => 'Women',
3861 'women detectives' => 'Women detectives',
3862 'women entrepreneurs' => 'Businesswomen',
3863 'women heroes' => 'Women heroes',
3864 'women heroes--fiction' => 'Women heroes--Fiction',
3865 'women in business' => 'Businesswomen',
3866 'women--biography' => 'Women--Biography',
3867 "women--civil rights" => "Women's rights",
3868 "women--rights of women" => "Women's rights",
3869 'women--suffrage' => 'Women--Suffrage',
3870 "women's rights" => "Women's rights",
3871 'womon' => 'Women',
3872 'womyn' => 'Women',
3873 'wood furniture' => 'Furniture',
3874 'wooden furniture' => 'Furniture',
3875 'wooing' => 'Courtship',
3876 'word processing software' => 'Word processing--Software',
3877 'word processing' => 'Word processing',
3878 'word processing--software' => 'Word processing--Software',
3879 'work environment' => 'Work environment',
3880 'working conditions' => 'Work environment',
3881 'working conditions, physical' => 'Work environment',
3882 'working environment' => 'Work environment',
3883 'workplace climate' => 'Work environment',
3884 'workplace culture' => 'Work environment',
3885 'workplace environment' => 'Work environment',
3886 'workplace' => 'Work environment',
3887 'worksite environment' => 'Work environment',
3888 'world economics' => 'Competition, International',
3889 'world terrorism' => 'Terrorism',
3890 'world trade' => 'International trade',
3891 'world war, 1939-1945' => 'World War, 1939-1945',
3892 'world war 2' => 'World War, 1939-1945',
3893 'world war ii' => 'World War, 1939-1945',
3894 'world war two' => 'World War, 1939-1945',
3895 'world wide web' => 'World Wide Web',
3896 'world wide web pages' => 'Web sites',
3897 'world wide web searching' => 'Web search engines',
3898 'world wide web sites' => 'Web sites',
3899 'world wide web sites--directories' => 'Web sites--Directories',
3900 'world wide web--directories' => 'Web sites--Directories',
3901 'writing' => 'Writing',
3902 'writing letters' => 'Letter writing',
3903 'writing of letters' => 'Letter writing',
3904 'www (world wide web)' => 'World Wide Web',
3905 'www pages' => 'Web sites',
3906 'www sites' => 'Web sites',
3907 'www' => 'World Wide Web',
3908 'xml (document markup language)' => 'XML (Document markup language)',
3909 'xml' => 'XML (Document markup language)',
3910 'xml-based user interface language' => 'XUL (Document markup language)',
3911 'xul (document markup language)' => 'XUL (Document markup language)',
3912 'xul' => 'XUL (Document markup language)',
3913 'young women' => 'Young women',
3914 'young women--england--fiction' => 'Young women--England--Fiction',
3915 'young women--fiction' => 'Young women--Fiction',
3916 'youngsters' => 'Children',
3917 'zombies' => 'Zombies',
3918 'zombis' => 'Zombies',
3919 );
3920  
3921  
3922 our %mobibooktypes = (
3923 'Default' => undef,
3924 'eBook' => 'text/x-oeb1-document',
3925 'eNews' => 'application/x-mobipocket-subscription',
3926 'News feed' => 'application/x-mobipocket-subscription-feed',
3927 'News magazine' => 'application/x-mobipocket-subscription-magazine',
3928 'Images' => 'image/gif',
3929 'Microsoft Word document' => 'application/msword',
3930 'Microsoft Excel sheet' => 'application/vnd.ms-excel',
3931 'Microsoft Powerpoint presentation' => 'application/vnd.ms-powerpoint',
3932 'Plain text' => 'text/plain',
3933 'HTML' => 'text/html',
3934 'Mobipocket game' => 'application/vnd.mobipocket-game',
3935 'Franklin game' => 'application/vnd.mobipocket-franklin-ua-game'
3936 );
3937  
3938 our %publishermap = (
3939 'a.s.s.t.r' => 'ASSTR',
3940 'a.s.s.t.r.' => 'ASSTR',
3941 'ace books' => 'Ace Books',
3942 'ace' => 'Ace Books',
3943 'acebooks' => 'Ace Books',
3944 'alt sex stories text repository' => 'ASSTR',
3945 'alt.sex.stories text repository' => 'ASSTR',
3946 'alt.sex.stories' => 'ASSTR',
3947 'alt.sex.stories.moderated' => 'ASSTR',
3948 'anchor books' => 'Anchor Books',
3949 'anchor books a division of random house, inc.' => 'Anchor Books',
3950 'anchor booksa division of random house, inc.' => 'Anchor Books',
3951 'asstr' => 'ASSTR',
3952 'baen books' => 'Baen Publishing Enterprises',
3953 'baen publishing' => 'Baen Publishing Enterprises',
3954 'baen' => 'Baen Publishing Enterprises',
3955 'ballantine books' => 'Ballantine Books',
3956 'ballantine' => 'Ballantine Books',
3957 'barnes & noble' => 'Barnes and Noble Publishing',
3958 'barnes &amp; noble' => 'Barnes and Noble Publishing',
3959 'barnes and noble' => 'Barnes and Noble Publishing',
3960 'barnes&amp;noble' => 'Barnes and Noble Publishing',
3961 'barnes&noble' => 'Barnes and Noble Publishing',
3962 'barnesandnoble.com' => 'Barnes and Noble Publishing',
3963 'blackmask online' => 'Blackmask Online',
3964 'cpan' => 'CPAN',
3965 'del rey books' => 'Del Rey Books',
3966 'del rey' => 'Del Rey Books',
3967 'delrey' => 'Del Rey Books',
3968 'e-reads' => 'E-Reads',
3969 'electronic text center. university of virginia library.' => 'University of Virginia Library',
3970 'ereads' => 'E-Reads',
3971 'ereads.com' => 'E-Reads',
3972 'feedbooks (www.feedbooks.com)' => 'Feedbooks',
3973 'feedbooks' => 'Feedbooks',
3974 'fictionwise' => 'Fictionwise',
3975 'fictionwise, inc.' => 'Fictionwise',
3976 'fictionwise.com' => 'Fictionwise',
3977 'gutenberg' => 'Project Gutenberg',
3978 'gutenberg.org' => 'Project Gutenberg',
3979 'harmony books' => 'Harmony Books',
3980 'harmony' => 'Harmony Books',
3981 'harper collins' => 'HarperCollins',
3982 'harper-collins' => 'HarperCollins',
3983 'harpercollins' => 'HarperCollins',
3984 'http://www.blackmask.com' => 'Blackmask Online',
3985 'http://www.blackmask.com/' => 'Blackmask Online',
3986 'manybooks' => 'ManyBooks',
3987 'manybooks.net' => 'ManyBooks',
3988 'marion zimmer bradley literary works trust' => 'Marion Zimmer Bradley Literary Works Trust',
3989 'mzb literary works trust' => 'Marion Zimmer Bradley Literary Works Trust',
3990 'penguin group' => 'Penguin Group',
3991 'penguin group, usa' => 'Penguin Group',
3992 'penguin' => 'Penguin Group',
3993 'project gutenberg' => 'Project Gutenberg',
3994 'random-house.com' => 'Random House',
3995 'randomhouse' => 'Random House',
3996 'randomhouse.co.uk' => 'Random House',
3997 'rosetta books' => 'Rosetta Books',
3998 'rosetta' => 'Rosetta Books',
3999 'rosettabooks' => 'Rosetta Books',
4000 'siren publishing' => 'Siren Publishing',
4001 'siren' => 'Siren Publishing',
4002 'smashwords' => 'Smashwords',
4003 'smashwords, inc.' => 'Smashwords',
4004 'stonehouse press' => 'Stonehouse Press',
4005 'stories online' => 'World Literature Company',
4006 'storiesonline' => 'World Literature Company',
4007 'the random house publishing group' => 'Random House',
4008 'tom doherty associates' => 'Tom Doherty Associates',
4009 'university of virginia library' => 'University of Virginia Library',
4010 'university of virginia library.' => 'University of Virginia Library',
4011 'wildside press' => 'Wildside Press',
4012 'wildside' => 'Wildside Press',
4013 'world literature company' => 'World Literature Company',
4014 'www.blackmask.com' => 'Blackmask Online',
4015 'www.ereads.com' => 'E-Reads',
4016 'www.feedbooks.com' => 'Feedbooks',
4017 'www.fictionwise.com' => 'Fictionwise',
4018 'www.gutenberg.org' => 'Project Gutenberg',
4019 'www.random-house.com' => 'Random House',
4020 'www.randomhouse.co.uk' => 'Random House',
4021 );
4022  
4023  
4024 our %nonxmlentity2char = %entity2char;
4025 delete($nonxmlentity2char{'amp'});
4026 delete($nonxmlentity2char{'gt'});
4027 delete($nonxmlentity2char{'lt'});
4028 delete($nonxmlentity2char{'quot'});
4029 delete($nonxmlentity2char{'apos'});
4030  
4031 our %referencetypes = (
4032 # standard types
4033 'acknowledgements' => 'acknowledgements',
4034 'bibliography' => 'bibliography',
4035 'colophon' => 'colophon',
4036 'copyright-page' => 'copyright-page',
4037 'cover' => 'cover',
4038 'dedication' => 'dedication',
4039 'epigraph' => 'epigraph',
4040 'foreword' => 'foreword',
4041 'glossary' => 'glossary',
4042 'index' => 'index',
4043 'loi' => 'loi',
4044 'lot' => 'lot',
4045 'notes' => 'notes',
4046 'preface' => 'preface',
4047 'text' => 'text',
4048 'title-page' => 'title-page',
4049 'toc' => 'toc',
4050 # common nonstandard types
4051 'start' => 'text',
4052 'coverimage' => 'other.ms-coverimage',
4053 'coverimagestandard' => 'other.ms-coverimage-standard',
4054 'other.copyright' => 'copyright-page',
4055 'other.ms-firstpage' => 'text',
4056 'thumbimage' => 'other.ms-thumbimage',
4057 'thumbimagestandard' => 'other.ms-thumbimage-standard',
4058 );
4059  
4060 our %relatorcodes = (
4061 'act' => 'Actor',
4062 'adp' => 'Adapter',
4063 'ann' => 'Annotator',
4064 'ant' => 'Bibliographic antecedent',
4065 'app' => 'Applicant',
4066 'arc' => 'Architect',
4067 'arr' => 'Arranger',
4068 'art' => 'Artist',
4069 'asg' => 'Assignee',
4070 'asn' => 'Associated name',
4071 'att' => 'Attributed name',
4072 'aui' => 'Author of introduction',
4073 'aus' => 'Author of screenplay',
4074 'aut' => 'Author',
4075 'bdd' => 'Binding designer',
4076 'bjd' => 'Bookjacket designer',
4077 'bkd' => 'Book designer',
4078 'bkp' => 'Book producer',
4079 'bnd' => 'Binder',
4080 'bpd' => 'Bookplate designer',
4081 'bsl' => 'Bookseller',
4082 'chr' => 'Choreographer',
4083 'cli' => 'Client',
4084 'cll' => 'Calligrapher',
4085 'clt' => 'Collotyper',
4086 'cmm' => 'Commentator',
4087 'cmp' => 'Composer',
4088 'cmt' => 'Compositor',
4089 'cnd' => 'Conductor',
4090 'cns' => 'Censor',
4091 'coe' => 'Contestant-appellee',
4092 'col' => 'Collector',
4093 'com' => 'Compiler',
4094 'cos' => 'Contestant',
4095 'cot' => 'Contestant-appellant',
4096 'cpe' => 'Complainant-appellee',
4097 'cph' => 'Copyright holder',
4098 'cpl' => 'Complainant',
4099 'cpt' => 'Complainant-appellant',
4100 'crp' => 'Correspondent',
4101 'crr' => 'Corrector',
4102 'cst' => 'Costume designer',
4103 'cte' => 'Contestee-appellee',
4104 'ctg' => 'Cartographer',
4105 'cts' => 'Contestee',
4106 'ctt' => 'Contestee-appellant',
4107 'dfd' => 'Defendant',
4108 'dfe' => 'Defendant-appellee',
4109 'dft' => 'Defendant-appellant',
4110 'dln' => 'Delineator',
4111 'dnc' => 'Dancer',
4112 'dnr' => 'Donor',
4113 'dpt' => 'Depositor',
4114 'drt' => 'Director',
4115 'dsr' => 'Designer',
4116 'dst' => 'Distributor',
4117 'dte' => 'Dedicatee',
4118 'dto' => 'Dedicator',
4119 'dub' => 'Dubious author',
4120 'edt' => 'Editor',
4121 'egr' => 'Engraver',
4122 'elt' => 'Electrotyper',
4123 'eng' => 'Engineer',
4124 'etr' => 'Etcher',
4125 'flm' => 'Film editor',
4126 'fmo' => 'Former owner',
4127 'fnd' => 'Funder/Sponsor',
4128 'frg' => 'Forger',
4129 'grt' => 'Graphic technician (discontinued code)',
4130 'hnr' => 'Honoree',
4131 'ill' => 'Illustrator',
4132 'ilu' => 'Illuminator',
4133 'ins' => 'Inscriber',
4134 'inv' => 'Inventor',
4135 'itr' => 'Instrumentalist',
4136 'ive' => 'Interviewee',
4137 'ivr' => 'Interviewer',
4138 'lbt' => 'Librettist',
4139 'lee' => 'Libelee-appellee',
4140 'lel' => 'Libelee',
4141 'len' => 'Lender',
4142 'let' => 'Libelee-appellant',
4143 'lie' => 'Libelant-appellee',
4144 'lil' => 'Libelant',
4145 'lit' => 'Libelant-appellant',
4146 'lse' => 'Licensee',
4147 'lso' => 'Licensor',
4148 'ltg' => 'Lithographer',
4149 'lyr' => 'Lyricist',
4150 'mon' => 'Monitor/Contractor',
4151 'mte' => 'Metal-engraver',
4152 'nrt' => 'Narrator',
4153 'org' => 'Originator',
4154 'oth' => 'Other',
4155 'pbl' => 'Publisher',
4156 'pfr' => 'Proofreader',
4157 'pht' => 'Photographer',
4158 'plt' => 'Platemaker',
4159 'pop' => 'Printer of plates',
4160 'ppm' => 'Papermaker',
4161 'prd' => 'Production personnel',
4162 'prf' => 'Performer',
4163 'pro' => 'Producer',
4164 'prt' => 'Printer',
4165 'pte' => 'Plaintiff-appellee',
4166 'ptf' => 'Plaintiff',
4167 'pth' => 'Patent holder',
4168 'ptt' => 'Plaintiff-appellant',
4169 'rbr' => 'Rubricator',
4170 'rce' => 'Recording engineer',
4171 'rcp' => 'Recipient',
4172 'rse' => 'Respondent-appellee',
4173 'rsp' => 'Respondent',
4174 'rst' => 'Respondent-appellant',
4175 'sce' => 'Scenarist',
4176 'scr' => 'Scribe',
4177 'scl' => 'Sculptor',
4178 'sec' => 'Secretary',
4179 'sgn' => 'Signer',
4180 'srv' => 'Surveyor',
4181 'str' => 'Stereotyper',
4182 'trc' => 'Transcriber',
4183 'trl' => 'Translator',
4184 'tyd' => 'Type designer',
4185 'tyg' => 'Typographer',
4186 'voc' => 'Vocalist',
4187 'wam' => 'Writer of accompanying material',
4188 'wde' => 'Wood-engraver',
4189 'wit' => 'Witness',
4190 );
4191  
4192 our %sexcodes = (
4193 # Age/Gender
4194 'MF' => 'Ma/Fa', # Adult Male over 18, Adult Female over 18
4195 'mf' => 'mt/ft', # Teen Male under 18, Teen Female under 18
4196 'Mf' => 'Ma/ft', # Adult Male over 18, Teen Female under 18
4197 'mF' => 'mt/Fa', # Teen Male under 18, Adult Female
4198 'FF' => 'Fa/Fa', # 2 or more Females over 18
4199 'ff' => 'ft/ft', # 2 or more Teen Females under 18
4200 'Ff' => 'Fa/ft', # Adult Female, Teen female under 18
4201 'boy' => 'boy', # Boy 12 years old or younger
4202 'Boy' => 'boy',
4203 'girl' => 'gi', # Girl 12 years old or younger
4204 'Girl' => 'gi',
4205 'MM' => 'Ma/Ma', # 2 or more Adult Males over 18
4206 'Mm' => 'Ma/mt', # Adult Male, Teen Male under 18
4207 'mm' => 'mt/mt', # 2 or more Teen Males under 18
4208 'mult' => 'Mult', # Multiple Partner. ie MFF or mmmF
4209 'teen' => 'Teenagers', # Cast of story is mostly teenagers.
4210 'Teen' => 'Teenagers',
4211 'teenagers' => 'Teenagers',
4212  
4213 # Level of Consent
4214 'cons' => 'Consensual', # All parties are consenting to the act
4215 'consensual' => 'Consensual',
4216 'rom' => 'Romantic', # Mushy love story
4217 'romance' => 'Romantic',
4218 'romantic' => 'Romantic',
4219 'non-con' => 'NonConsensual', # At least one of the parties is not participating willfully
4220 'nonconsensual' => 'NonConsensual',
4221 'pedo' => 'Pedophilia', # An adult initiating sexual contact with a
4222 # pre-pubescent child (boy or girl, 12 or under)
4223 'pedophilia' => 'Pedophilia',
4224 'lolita' => 'Lolita', # A pre-pubescent child (boy or girl, 12 or
4225 # younger) initiates sexual contact with an adult
4226 'reluc' => 'Reluctant', # Start as non consentual and then the non
4227 # consenting party participates willingly
4228 'reluctant' => 'Reluctant',
4229 'rape' => 'Rape', # Stories with violent rape
4230 'coer' => 'Coercion', # Not exactly blackmail, but applying different
4231 # kinds of pressure to force into the act.
4232 'coercion' => 'Coercion',
4233 'Blkm' => 'Blackmail', # Blackmailing somebody to force them into the sex act depicted
4234 'blackmail' => 'Blackmail',
4235 'mc' => 'Mind Control', # Stories where one party somehow controls another's mind
4236 'mind control' => 'Mind Control',
4237 'MindControl' => 'Mind Control',
4238 'Mindcontrol' => 'Mind Control',
4239 'mindcontrol' => 'Mind Control',
4240 'hypno' => 'Hypnosis', # One party using hypnosis for sexual purposes
4241 'hypnosis' => 'Hypnosis',
4242 'dru' => 'Drunk/Drugged', # One party at least is drunk or drugged and
4243 # participates while under the influence without really knowing
4244 'drunk/drugged' => 'Drunk/Drugged',
4245 'Drunk' => 'Drunk/Drugged',
4246 'drunk' => 'Drunk/Drugged',
4247 'Drugged' => 'Drunk/Drugged',
4248 'drugged' => 'Drunk/Drugged',
4249 'mag' => 'Magic', # Contains magic and supernatural phenomenons
4250 'slave' => 'Slavery', # Slavery, sexual or otherwise
4251 'Slave' => 'Slavery',
4252 'slavery' => 'Slavery',
4253  
4254 # Sexual Orientations
4255 'gay' => 'Gay', # Self Explanatory
4256 'les' => 'Lesbian', # Self Explanatory
4257 'Les' => 'Lesbian',
4258 'lesbian' => 'Lesbian',
4259 'lesbian sex' => 'Lesbian',
4260 'bi' => 'BiSexual', # Self Explanatory
4261 'Bisexual' => 'BiSexual',
4262 'bisexual' => 'BiSexual',
4263 'het' => 'Heterosexual', # Self Explanatory
4264 'hetero' => 'Heterosexual',
4265 'heterosexual' => 'Heterosexual',
4266 'tg' => 'TransGender', # Gender crossing (note that code 'trans' refers to transformation)
4267 'Transgender' => 'TransGender',
4268 'transgender' => 'TransGender',
4269 'cd' => 'CrossDressing', # Men dressing as women and in women clothing, also vice-versa
4270 'Crossdressing' => 'CrossDressing',
4271 'crossdressing' => 'CrossDressing',
4272 'Crossdress' => 'CrossDressing',
4273 'crossdress' => 'CrossDressing',
4274 'herm' => 'Hermaphrodite', # Person having both male and female genitalia
4275 'hermaphrodite' => 'Hermaphrodite',
4276 'shem' => 'Shemale', # Trans women with male genitalia and female
4277 'shemale' => 'Shemale', # breasts from breast augmentation and/or use of hormones
4278  
4279 # Story Types
4280 'fict' => 'Fiction', # Fictitious story, not true
4281 'fiction' => 'Fiction',
4282 'true' => 'True Story', # A true story, according to the author.
4283 'hiFant' => 'High Fantasy', # High Fantasy, sword and sorcery and such
4284 'fanfic' => 'Fan Fiction', # A story using characters from movies, TV shows or Comics
4285 'celeb' => 'Celebrity', # A story about a real life celebrity, the
4286 # story is fictional of course.
4287 'ScFi' => 'Science Fiction', # Science Fiction
4288 'Scifi' => 'Science Fiction',
4289 'scifi' => 'Science Fiction',
4290 'TimeTr' => 'Time Travel', # Science Fiction involving travel through time
4291 'robot' => 'Robot', # Humans having relations, sexual or otherwise,
4292 # with non-biological entities (mechanical
4293 # robots or full blown androids)
4294 'PostApoc' => 'Post Apocalypse', # Post Apocalyptic world.
4295 'hist' => 'Historical', # Story that is set in past history, mostly
4296 # related to famous people and events.
4297 'horror' => 'Horror', # Horror Elements in the story, erotic or otherwise.
4298 'humor' => 'Humor', # Contains humor or the story is a spoof
4299 'tears' => 'Tear Jerker', # Sad story or containing sad moments
4300 'superhero' => 'Superhero', # Story contains Super Hero/Heroine
4301 'ESP' => 'Extra Sensory Perception', # Perceiving things by means other
4302 # than the known senses, e.g. by telepathy or clairvoyance.
4303 'Zoo' => 'Zoophilia ', # Different from bestiality, it's about
4304 # relationships between humans and animals, not just sex.
4305 'space' => 'Space', # Story set in outer space
4306 'myst' => 'Mystery', # A suspensful story about a mystery
4307 'sport' => 'Sports', # A story with a sports theme
4308 'west' => 'Western', # Set in the old US west
4309 'doover' => 'DoOver', # Getting to do one's life all over again
4310  
4311 # Paranormal
4312 'paranormal' => 'Paranormal', # Ghosts, angels, spirits, poltergeists, etc
4313 'vamp' => 'Vampires', # Vampires in the story
4314 'vampire' => 'Vampires',
4315 'vampires' => 'Vampires',
4316 'furry' => 'Furry', # Anthropomorphic animals or 'taurs' (animal
4317 # bodies with anthropomorphic torsos) it also
4318 # includes other forms such as dragons.
4319 'non-anthro' => 'non-anthro', # Animal in form with human level
4320 # intelligence, e.g. Werewolves
4321 'were' => 'Were animal', # A human that can turn into an animal temporarily.
4322 'zom' => 'Zombies', # Zombies in the story
4323  
4324 # Couples
4325 'cheat' => 'Cheating', # One party is cheating on their spouse
4326 'cheating' => 'Cheating',
4327 'wife' => 'Slut Wife', # Slutty wife
4328 'wimp' => 'Wimp Husband', # Husband does not stand up for himself when
4329 # faced with a cheating wife
4330 'cuckold' => 'Cuckold', # When man is being forced to accept
4331 # his wife's cheating against his will.
4332 'watch' => 'Wife Watching', # Man enjoys watching his wife getting fucked
4333 'reven' => 'Revenge', # One party gets revenge for spouse's cheating
4334  
4335 # Incest
4336 'inc' => 'Incest', # sex between the members of the same family
4337 'incest' => 'Incest',
4338 'mother' => 'Mother', # Self Explanatory
4339 'son' => 'Son', # Self Explanatory
4340 'bro' => 'Brother', # Self Explanatory
4341 'brother' => 'Brother',
4342 'sis' => 'Sister', # Self Explanatory
4343 'fath' => 'Father', # Self Explanatory
4344 'father' => 'Father',
4345 'dau' => 'Daughter', # Self Explanatory
4346 'daughter' => 'Daughter',
4347 'cous' => 'Cousins', # Self Explanatory
4348 'cousin' => 'Cousins',
4349 'cousins' => 'Cousins',
4350 'grand' => 'Grand Parent', # Self Explanatory
4351 'Grandfather' => 'Grand Parent',
4352 'grandfather' => 'Grand Parent',
4353 'Grandmother' => 'Grand Parent',
4354 'grandmother' => 'Grand Parent',
4355 'Grandparent' => 'Grand Parent',
4356 'grandparent' => 'Grand Parent',
4357 'grand parent' => 'Grand Parent',
4358 'unc' => 'Uncle', # Self Explanatory
4359 'uncle' => 'Uncle',
4360 'niece' => 'Niece', # Self Explanatory
4361 'aunt' => 'Aunt', # Self Explanatory
4362 'neph' => 'Nephew', # Self Explanatory
4363 'nephew' => 'Nephew',
4364 'in-law' => 'InLaws', # Self Explanatory
4365 'inlaw' => 'InLaws',
4366 'inlaws' => 'InLaws',
4367 'Inlaws' => 'InLaws',
4368  
4369 # BDSM Elements
4370 'BDSM' => 'BDSM', # Bondage and/or SadoMasochism
4371 'bdsm' => 'BDSM',
4372 'bd/sm' => 'BDSM',
4373 'Bondage' => 'BDSM',
4374 'bondage' => 'BDSM',
4375 'Sadomasochism' => 'BDSM',
4376 'sadomasochism' => 'BDSM',
4377 'D/S' => 'DomSub', # Story about domination, being sexual or otherwise
4378 'd/s' => 'DomSub',
4379 'Domsub' => 'DomSub',
4380 'domsub' => 'DomSub',
4381 'Domination' => 'DomSub',
4382 'domination' => 'DomSub',
4383 'Lesdom' => 'DomSub',
4384 'lesdom' => 'DomSub',
4385 'Mdom' => 'MaleDom', # Male Dominant
4386 'mdom' => 'MaleDom',
4387 'Fdom' => 'FemaleDom', # Female Dominant
4388 'fdom' => 'FemaleDom',
4389 'span' => 'Spanking', # Somebody gets spanked in the story, willingly or unwillingly
4390 'spank' => 'Spanking',
4391 'spanking' => 'Spanking',
4392 'rough' => 'Rough', # Rough sex
4393 'lght' => 'Light Bond', # Light Bondage, usually consensual and for
4394 # experimentation at the request of the one of the parties
4395 'humil' => 'Humiliation', # Degradation of somebody in the story and/or
4396 'Humil' => 'Humiliation', # humiliating them publicly
4397 'sad' => 'Sadistic', # Somebody inflicting pain, physical or mental, for the hell of it
4398 'sadism' => 'Sadistic',
4399 'Sadism' => 'Sadistic',
4400 'tort' => 'Torture', # Self Explanatory
4401 'torture' => 'Torture',
4402 'snuff' => 'Snuff', # Killing being done during the act of sex.
4403 # (Non-sexual murder is in violent)
4404  
4405 # Groups
4406 'swing' => 'Swinging', # Trading Sexual Partners
4407 'swingers' => 'Swinging',
4408 'swinging' => 'Swinging',
4409 'gang' => 'Gang Bang', # Multiple men fucking same woman
4410 'GangBang' => 'Gang Bang',
4411 'Gangbang' => 'Gang Bang',
4412 'gangbang' => 'Gang Bang',
4413 'group' => 'Group Sex', # Multiple couples in the same place or a threesome
4414 'orgy' => 'Orgy', # Everybody is Fucking everybody in a group
4415 'harem' => 'Harem', # There is a harem involved in the story.
4416 'poly' => 'Polygamy/Polyamory', # Multiple spouses or partners (multiple men or multiple women)
4417 'polygamy' => 'Polygamy/Polyamory',
4418 'Polygamy' => 'Polygamy/Polyamory',
4419 'polyamory' => 'Polygamy/Polyamory',
4420 'Polyamory' => 'Polygamy/Polyamory',
4421  
4422 # Interracial Elements
4423 'interr' => 'Interracial', # Sexual partners of different races
4424 'Interr' => 'Interracial',
4425 'interrracial' => 'Interracial',
4426 'WC' => 'White Couple', # Self Explanatory
4427 'BC' => 'Black Couple', # Self Explanatory
4428 'BF' => 'Black Female', # Self Explanatory
4429 'BM' => 'Black Male', # Self Explanatory
4430 'WM' => 'White Male', # Self Explanatory
4431 'WF' => 'White Female', # Self Explanatory
4432 'OM' => 'Oriental Male', # Self Explanatory
4433 'OF' => 'Oriental Female', # Self Explanatory
4434 'HM' => 'Hispanic Male', # Self Explanatory
4435 'HF' => 'Hispanic Female', # Self Explanatory
4436  
4437 # Sexual Activities
4438 '1st' => 'First', # One of the parties having sex is a virgin
4439 'first' => 'First', # One of the parties having sex is a virgin
4440 'safe' => 'Safe Sex', # Sex with proper protection
4441 'Safe' => 'Safe Sex',
4442 'oral' => 'Oral Sex', # Self Explanatory
4443 'oral sex' => 'Oral Sex',
4444 'fellatio' => 'Oral Sex',
4445 'cunnilingus' => 'Oral Sex',
4446 'anal' => 'Anal Sex', # Self Explanatory
4447 'mastrb' => 'Masturbation', # Self pleasuring, could be alone or while
4448 # with somebody else but no intercourse
4449 'masturbation' => 'Masturbation',
4450 'pett' => 'Petting', # Feeling up and such
4451 'petting' => 'Petting',
4452 'fingering' => 'Petting',
4453 'fist' => 'Fisting', # Hand and arm or foot insertion
4454 'Fist' => 'Fisting',
4455 'toys' => 'Sex Toys', # Sex with the help of sex toys, such as dildos and vibrators
4456 'Toys' => 'Sex Toys',
4457 'beast' => 'Bestiality', # Sex with animals
4458 'bestiality' => 'Bestiality',
4459 'squirt' => 'Squirting', # Female Ejaculation
4460 'squirting' => 'Squirting',
4461 'food' => 'Food', # Sex where food is involved, like doing it to
4462 # a pie or shoving a carrot
4463 'lac' => 'Lactation', # Drinking and playing with human milk
4464 'lact' => 'Lactation',
4465 'lactation' => 'Lactation',
4466 'ws' => 'Water Sports', # Peeing on each other
4467 'golden shower' => 'Water Sports',
4468 'enem' => 'Enema', # Getting an enema as a sexual thing
4469 'scat' => 'Scatology', # Playing with feces
4470 'preg' => 'Pregnancy', # Somebody gets pregnant in the story
4471 'Preg' => 'Pregnancy',
4472 'creampie' => 'Cream Pie', # Somebody licks a pussy full of cum
4473 'necro' => 'Necrophilia', # Sex with a corpse
4474 'Necro' => 'Necrophilia',
4475 'fart' => 'Flatulence', # Flatulence as a sexual fetish
4476 'spit' => 'Spitting', # Spitting as a sexual fetish
4477 'exhib' => 'Exhibitionism', # Enjoyment of self exposure
4478 'Exhib' => 'Exhibitionism',
4479 'voy' => 'Voyeurism', # Enjoyment of watching other people without their knowledge
4480 'Voy' => 'Voyeurism',
4481 'voyeur' => 'Voyeurism',
4482 'Voyeur' => 'Voyeurism',
4483 'DP' => 'Double Penetration', # Simultaneous Anal and Vaginal Penetration
4484 'dp' => 'Double Penetration',
4485  
4486 # Fetishes
4487 'size' => 'Size', # Where the size of the sex parts (penis,
4488 # breasts, toys) plays a major role in the story
4489 'doct' => 'Doctor/Nurse', # Medical Fetish, Doctor or Nurse Play a prominent role in the story
4490 'BBW' => 'BBW', # Big Beautiful Woman. Loving Big Women
4491 'feet' => 'Foot Fetish', # Foot fetish
4492 'legs' => 'Leg Fetish', # Leg fetish, often with stockings, garters and heels.
4493 'hairy' => 'Hairy Fetish', # with hairy men/women
4494 'mod' => 'Body Modification', # Erotic body modification, including
4495 # piercings and tattoos, plays a prominent role.
4496 'amput' => 'Amputee', # Sex with an amputee
4497 'needles' => 'Needles', # Includes injections and play or permanent piercings.
4498 'teach' => 'Teacher/Student', # Teacher/student relations
4499 'teacher/student' => 'Teacher/Student',
4500 'teacher student' => 'Teacher/Student',
4501 'bbsit' => 'Babysitter', # Sex with babysitters fetish
4502 'BBr' => 'Big Breasts', # Women with Big Breasts
4503 'clergy' => 'Clergy', # Involving members of the clergy (Priest, Bishops, nuns)
4504 'menses' => 'Menstrual Play', # Sex play with a woman who's on menstrual cycle
4505 'Menses' => 'Menstrual Play',
4506 'menstruation' => 'Menstrual Play',
4507 'Menstruation' => 'Menstrual Play',
4508 'public' => 'Public Sex', # Sexual events taking place in public
4509 'Public' => 'Public Sex',
4510  
4511 # Other
4512 'slow' => 'Slow', # There is a story and plot development before
4513 # any sex occurs. Not a stroke story.
4514 'clas' => 'Novel-Classic', # An old classic novel that is now in the public domain
4515 'bknk' => 'Novel-Pocketbook', # An old published pocketbook novel that
4516 # is not in circulation any more and the
4517 # publisher has gone under, so it's not going to be published again
4518 'caution' => 'Caution', # Story contains something that can't be
4519 # classified but requires caution on the reader's part
4520 '2nd' => '2nd POV', # Story written from the 2nd person POV
4521 'violent' => 'Violent', # Violence in the story, not necessarily of sexual nature
4522 'work' => 'Workplace', # Story centres around a workplace setting
4523 'workplace' => 'Workplace',
4524 'sch' => 'School', # Mostly in an educational setting (high-school, college, University)
4525 'school' => 'School',
4526 'schoolgirl' => 'School',
4527 'student' => 'School',
4528 'college' => 'School',
4529 'professor' => 'School',
4530 'university' => 'School',
4531 'secret' => 'Secret', # Secret or hidden or forbidden relationship
4532 'Secret' => 'Secret',
4533 'Secret Love' => 'Secret',
4534 'Secret love' => 'Secret',
4535 'secret love' => 'Secret',
4536 'Forbidden Love' => 'Secret',
4537 'Forbidden love' => 'Secret',
4538 'forbidden love' => 'Secret',
4539 'trans' => 'Transformation', # Un-natural physical transformation
4540 'prost' => 'Prostitution', # Prostitution elements
4541 'prostitute' => 'Prostitution',
4542 'prostitution' => 'Prostitution',
4543 'nud' => 'Nudism', # Features scenes set in a naturist/nudist environment
4544 'nudism' => 'Nudism',
4545 'nudist' => 'Nudism',
4546 'Mil' => 'Military', # Story in a Military setting
4547 'military' => 'Military',
4548 'pornThea' => 'Porn Theatre', # Story has events in a porn theatre or Adult bookstore
4549 'cf' => 'Cat-Fighting', # Women having a cat fight
4550 'catfight' => 'Cat-Fighting',
4551 'cannib' => 'Cannibalism', # Self explanatory
4552 'cannibalism' => 'Cannibalism',
4553 );
4554 hashvalue_key_self(\%sexcodes);
4555  
4556 our %strangenames = (
4557 'brian d foy' => 'brian d foy',
4558 'brian d. foy' => 'brian d foy',
4559 );
4560  
4561 our %strangefileas = (
4562 'foy, brian d' => 'd foy, brian',
4563 'foy, brian d.' => 'd foy, brian',
4564 );
4565  
4566 our %validspecs = (
4567 'OEB12' => 'OEB12',
4568 'OPF20' => 'OPF20',
4569 'MOBI12' => 'MOBI12',
4570 );
4571  
4572  
4573 #####################################################
4574 ########## CONSTRUCTORS AND INITIALIZATION ##########
4575 #####################################################
4576  
4577 my %rwfields = (
4578 'opffile' => 'string', # OPF filename (with no path)
4579 'opfsubdir' => 'string', # Subdirectory name where opffile is found
4580 'erotic' => 'scalar', # Enable special handling for erotic fiction
4581 'spec' => 'string',
4582 );
4583 my %rofields = (
4584 'topdir' => 'string', # Top-level directory of the unpacked book
4585 'twig' => 'scalar',
4586 'twig_unmodified' => 'scalar',
4587 'twigroot' => 'scalar',
4588 'errors' => 'arrayref',
4589 'warnings' => 'arrayref',
4590 );
4591 my %privatefields = (
4592 );
4593  
4594 # A simple 'use fields' will not work here: use takes place inside
4595 # BEGIN {}, so the @...fields variables won't exist.
4596 require fields;
4597 fields->import(
4598 keys(%rwfields),keys(%rofields),keys(%privatefields)
4599 );
4600  
4601  
4602 =head1 CONSTRUCTORS AND INITIALIZATION
4603  
4604 =head2 C<new($filename)>
4605  
4606 Instantiates a new EBook::Tools object. If C<$filename> is specified,
4607 it will also immediately initialize itself via the C<init> method.
4608  
4609 =cut
4610  
4611 sub new {
4612 my ($self,$filename) = @_;
4613 my $class = ref($self) || $self;
4614 my $subname = (caller(0))[3];
4615 debug(2,"DEBUG[",$subname,"]");
4616 my $bisg = EBook::Tools::BISG->new();
4617  
4618 $self = fields::new($class);
4619  
4620 if($filename) {
4621 debug(2,"DEBUG: new object from '",$filename,"'");
4622 $self->init($filename);
4623 }
4624 return $self;
4625 }
4626  
4627  
4628 =head2 C<init($filename)>
4629  
4630 Initializes the object from an existing OPF file. If C<$filename> is
4631 specified and exists, the OEB object will be set to read and write to
4632 that file before attempting to initialize. Otherwise, if the object
4633 currently points to an OPF file it will use that name. If there is no
4634 OPF filename data, and C<$filename> was not specified, it will make a
4635 last-ditch attempt to find an OPF file first by looking in
4636 META-INF/container.xml, and if nothing is found there, by looking in
4637 the current directory for a single OPF file.
4638  
4639 If no such files or found (or more than one is found), the
4640 initialization croaks.
4641  
4642 =cut
4643  
4644 sub init :method {
4645 my ($self,$filename) = @_;
4646 my $fh_opffile;
4647 my $opfstring;
4648 my $subname = (caller(0))[3];
4649 croak($subname . "() called as a procedure") unless(ref $self);
4650 debug(2,"DEBUG[",$subname,"]");
4651  
4652 $self->{topdir} = getcwd();
4653  
4654 if($filename) { $self->{opffile} = $filename; }
4655  
4656 if(!$self->{opffile})
4657 {
4658 $opfstring = find_opffile();
4659 $self->{opffile} = $opfstring if($opfstring);
4660 }
4661  
4662 if(!$self->{opffile})
4663 {
4664 croak($subname,"(): Unable to find an OPF file to work with!\n");
4665 }
4666  
4667 if(! -f $self->{opffile})
4668 {
4669 croak($subname,"(): '",$self->{opffile},
4670 "' does not exist or is not a regular file!")
4671 }
4672  
4673 if(-z $self->{opffile})
4674 {
4675 croak("OPF file '",$self->{opffile},"' has zero size!");
4676 }
4677  
4678 # At this point, we have definitely found an OPF file to work
4679 # with, but it might not be in the top level directory, and with
4680 # the exception of final book construction and EPUB metadata, we
4681 # want to be in the directory of the OPF.
4682 $self->{opfsubdir} = dirname($self->{opffile});
4683 $self->{opffile} = basename($self->{opffile});
4684 usedir($self->opfdir);
4685  
4686 debug(2,"DEBUG: init using '",$self->{opfsubdir},"/",$self->{opffile},"'");
4687  
4688 # Initialize the twig before use
4689 $self->{twig} = XML::Twig->new(
4690 keep_atts_order => 1,
4691 output_encoding => 'utf-8',
4692 pretty_print => 'record'
4693 );
4694  
4695 # Initialize a second copy to be used to check for changes
4696 $self->{twig_unmodified} = XML::Twig->new(
4697 keep_atts_order => 1,
4698 output_encoding => 'utf-8',
4699 pretty_print => 'record'
4700 );
4701  
4702 # Read and decode entities before parsing to avoid parsing errors
4703 open($fh_opffile,'<:encoding(:UTF-8)',$self->{opffile})
4704 or croak($subname,"(): failed to open '",$self->{opffile},
4705 "' for reading!");
4706 read($fh_opffile,$opfstring,-s $self->opffile)
4707 or croak($subname,"(): failed to read from '",$self->{opffile},"'!");
4708 close($fh_opffile)
4709 or croak($subname,"(): failed to close '",$self->{opffile},"'!");
4710  
4711 # We use _decode_entities and the custom hash to decode, but also
4712 # see below for the regexp
4713 _decode_entities($opfstring,\%nonxmlentity2char);
4714  
4715 # This runs decode_entities on the substring containing just the
4716 # entity for every entity *except* the 5 predefined internal
4717 # entities. It seems to be about the same speed as running
4718 # _decode_entities on a small file, but having the hash map as a
4719 # package variable has additional utility, so that technique gets
4720 # used instead.
4721 # $opfstring =~
4722 # s/(&
4723 # (?! (?:lt|gt|quot|apos|amp);
4724 # )\w+;
4725 # )
4726 # / decode_entities($1) /gex;
4727  
4728 $self->{twig}->parse($opfstring);
4729 $self->{twig_unmodified}->parse($opfstring);
4730 $self->{twigroot} = $self->{twig}->root;
4731 $self->opf_namespace;
4732 $self->twigcheck;
4733 debug(2,"DEBUG[/",$subname,"]");
4734 return $self;
4735 }
4736  
4737  
4738 =head2 C<init_blank(%args)>
4739  
4740 Initializes an object containing nothing more than the basic OPF
4741 framework, suitable for adding new documents when creating an e-book
4742 from scratch.
4743  
4744 =head3 Arguments
4745  
4746 C<init_blank> takes up to three optional named arguments:
4747  
4748 =over
4749  
4750 =item C<opffile>
4751  
4752 This specifies the OPF filename to use. If not specified, defaults to
4753 'content.opf'
4754  
4755 =item C<author>
4756  
4757 This specifies the content of the initial dc:creator element. If not
4758 specified, defaults to "Unknown Author".
4759  
4760 =item C<title>
4761  
4762 This specifies the content of the initial dc:title element. If not
4763 specified, defaults to "Unknown Title".
4764  
4765 =back
4766  
4767 =head3 Example
4768  
4769 init_blank('opffile' => 'newfile.opf',
4770 'title' => 'The Great Unknown');
4771  
4772 =cut
4773  
4774 sub init_blank :method {
4775 my ($self,%args) = @_;
4776 my $subname = ( caller(0) )[3];
4777 croak($subname . "() called as a procedure") unless(ref $self);
4778 debug(2,"DEBUG[",$subname,"]");
4779  
4780  
4781 my %valid_args = (
4782 'opffile' => 1,
4783 'author' => 1,
4784 'title' => 1,
4785 );
4786 foreach my $arg (keys %args) {
4787 croak($subname,"(): invalid argument '",$arg,"'")
4788 if(!$valid_args{$arg});
4789 }
4790  
4791 $args{opffile} ||= "content.opf";
4792  
4793 my $author = $args{author} || 'Unknown Author';
4794 my $title = $args{title} || 'Unknown Title';
4795 my $metadata;
4796 my $element;
4797  
4798 $self->{topdir} = getcwd();
4799 $self->{opfsubdir} = '.';
4800 $self->{opffile} = $args{opffile};
4801 $self->{twig} = XML::Twig->new(
4802 keep_atts_order => 1,
4803 output_encoding => 'utf-8',
4804 pretty_print => 'record'
4805 );
4806 $self->{twig_unmodified} = XML::Twig->new(
4807 keep_atts_order => 1,
4808 output_encoding => 'utf-8',
4809 pretty_print => 'record'
4810 );
4811  
4812 $element = XML::Twig::Elt->new('package');
4813 $self->{twig}->set_root($element);
4814 $self->{twig_unmodified}->set_root($element);
4815 $self->{twigroot} = $self->{twig}->root;
4816 $metadata = $self->{twigroot}->insert_new_elt('first_child','metadata');
4817  
4818 # dc:identifier
4819 $self->fix_packageid;
4820  
4821 # dc:title
4822 $element = $metadata->insert_new_elt('last_child','dc:title');
4823 $element->set_text($title);
4824  
4825 # dc:creator (author)
4826 $element = $metadata->insert_new_elt('last_child','dc:creator');
4827 $element->set_att('opf:role','aut');
4828 $element->set_text($author);
4829  
4830 $self->fix_opf20;
4831 return 1;
4832 }
4833  
4834  
4835 ######################################
4836 ########## ACCESSOR METHODS ##########
4837 ######################################
4838  
4839 =head1 ACCESSOR METHODS
4840  
4841 The following methods return data deeper in the structure than the
4842 auto-accessors, but still do not modify any object data or files.
4843  
4844  
4845 =head2 C<adult()>
4846  
4847 Returns the text of the Mobipocket-specific <Adult> element, if it
4848 exists. Expected values are 'yes' and undef.
4849  
4850 =cut
4851  
4852 sub adult :method {
4853 my $self = shift;
4854 my $subname = ( caller(0) )[3];
4855 croak($subname . "() called as a procedure") unless(ref $self);
4856 debug(2,"DEBUG[",$subname,"]");
4857 $self->twigcheck;
4858  
4859 my $twigroot = $self->{twigroot};
4860  
4861 my $element = $twigroot->first_descendant(qr/^adult$/ix);
4862 return unless($element);
4863  
4864 if($element->text) { return $element->text; }
4865 else { return; }
4866 }
4867  
4868  
4869 =head2 C<contributor_list()>
4870  
4871 Returns a list containing the text of all dc:contributor elements
4872 (case-insensitive) or undef if none are found.
4873  
4874 In scalar context, returns the first contributor, not the last.
4875  
4876 =cut
4877  
4878 sub contributor_list :method {
4879 my $self = shift;
4880 my $subname = ( caller(0) )[3];
4881 croak($subname . "() called as a procedure") unless(ref $self);
4882 debug(2,"DEBUG[",$subname,"]");
4883 $self->twigcheck;
4884  
4885 my @retval = ();
4886 my $twigroot = $self->{twigroot};
4887  
4888 my @elements = $twigroot->descendants(qr/dc:contributor/ix);
4889 return unless(@elements);
4890  
4891 foreach my $el (@elements)
4892 {
4893 push(@retval,$el->text) if($el->text);
4894 }
4895 return unless(@retval);
4896 if(wantarray) { return @retval; }
4897 else { return $retval[0]; }
4898 }
4899  
4900  
4901 =head2 C<coverimage()>
4902  
4903 Returns the href to the cover image, or undef if none is found.
4904  
4905 Checks the following in order:
4906  
4907 =over
4908  
4909 =item <reference type="other.ms-coverimage-standard">
4910  
4911 =item <EmbeddedCover>
4912  
4913 =item <meta name="cover"> (as href)
4914  
4915 =item <meta name="cover"> (as item id)
4916  
4917 =back
4918  
4919 =cut
4920  
4921 sub coverimage :method {
4922 my ($self) = @_;
4923 my $subname = ( caller(0) )[3];
4924 croak($subname . "() called as a procedure") unless(ref $self);
4925 debug(2,"DEBUG[",$subname,"]");
4926 $self->twigcheck();
4927  
4928 my $twigroot = $self->{twigroot};
4929 my $element;
4930 my $href;
4931 my $id;
4932  
4933 $element = $twigroot->first_descendant('reference[@type="other.ms-coverimage-standard"]');
4934 $href = $element->att('href') if $element;
4935 return $href if $href;
4936  
4937 $element = $twigroot->first_descendant('EmbeddedCover');
4938 $href = $element->text if $element;
4939 return $href if $href;
4940  
4941 $element = $twigroot->first_descendant('meta[@name="cover"]');
4942 if($element) {
4943 if(-f $element->att('content')) {
4944 return $element->att('content');
4945 }
4946 $id = $element->att('content');
4947 $element = $twigroot->first_descendant("item[\@id='${id}']");
4948 $href = $element->att('href') if $element;
4949 return $href if $href;
4950 }
4951 return;
4952 }
4953  
4954  
4955 =head2 C<date_list(%args)>
4956  
4957 Returns the text of all dc:date elements (case-insensitive) matching
4958 the specified attributes.
4959  
4960 In scalar context, returns the first match, not the last.
4961  
4962 Returns undef if no matches are found.
4963  
4964 =head3 Arguments
4965  
4966 =over
4967  
4968 =item * C<id> - 'id' attribute that must be matched exactly for the
4969 result to be added to the list
4970  
4971 =item * C<event> 'opf:event' or 'event' attribute that must be
4972 matched exactly for the result to be added to the list
4973  
4974 =back
4975  
4976 If both arguments are specified a value is added to the list if it
4977 matches either one (i.e. the logic is OR).
4978  
4979 =cut
4980  
4981 sub date_list :method {
4982 my ($self,%args) = @_;
4983 my %valid_args = (
4984 'id' => 1,
4985 'event' => 1,
4986 );
4987 my $subname = ( caller(0) )[3];
4988 croak($subname . "() called as a procedure") unless(ref $self);
4989 debug(2,"DEBUG[",$subname,"]");
4990 $self->twigcheck();
4991 foreach my $arg (keys %args) {
4992 croak($subname,"(): invalid argument '",$arg,"'")
4993 if(!$valid_args{$arg});
4994 }
4995  
4996 my @elements = $self->{twigroot}->descendants(qr/^ dc:date $/ix);
4997 my @list = ();
4998 my $id;
4999 my $scheme;
5000 foreach my $el (@elements) {
5001 if($args{id}) {
5002 $id = $el->att('id') || '';
5003 if($id eq $args{id}) {
5004 push(@list,$el->text);
5005 next;
5006 }
5007 }
5008 if($args{event}) {
5009 $scheme = $el->att('opf:event') || $el->att('event') || '';
5010 if($scheme eq $args{event}) {
5011 push(@list,$el->text);
5012 next;
5013 }
5014 }
5015 next if($args{id} || $args{event});
5016 push(@list,$el->text);
5017 }
5018 return unless(@list);
5019 if(wantarray) { return @list; }
5020 else { return $list[0]; }
5021 }
5022  
5023  
5024 =head2 C<description()>
5025  
5026 Returns the description of the e-book, if set, or undef otherwise.
5027  
5028 =cut
5029  
5030 sub description :method {
5031 my $self = shift;
5032 my $subname = ( caller(0) )[3];
5033 croak($subname . "() called as a procedure") unless(ref $self);
5034 debug(2,"DEBUG[",$subname,"]");
5035 $self->twigcheck;
5036  
5037 my $twigroot = $self->{twigroot};
5038  
5039 my $element = $twigroot->first_descendant(qr/^dc:description$/ix);
5040 return unless($element);
5041  
5042 if($element->text) { return $element->text; }
5043 else { return; }
5044 }
5045  
5046  
5047 =head2 C<element_list(%args)>
5048  
5049 Returns a list containing the text values of all elements matching the
5050 specified criteria.
5051  
5052 =head3 Arguments
5053  
5054 =over
5055  
5056 =item * C<cond>
5057  
5058 The L<XML::Twig> search condition used to find the elements.
5059 Typically this is just the GI (tag) of the element you wish to find,
5060 but it can also be a C<qr//> expression, coderef, or anything else
5061 that XML::Twig can work with. See the XML::Twig documentation for
5062 details.
5063  
5064 If this is not specified, an error is added and the method returns
5065 undef.
5066  
5067 =item * C<id> (optional)
5068  
5069 'id' attribute that must be matched exactly for the
5070 result to be added to the list
5071  
5072 =item * C<scheme> (optional)
5073  
5074 'opf:scheme' or 'scheme' attribute that must be
5075 matched exactly for the result to be added to the list
5076  
5077 =item * C<event> (optional)
5078  
5079 'opf:event' or 'event' attribute that must be matched exactly for the
5080 result to be added to the list
5081  
5082 =back
5083  
5084 If more than one of the arguments C<id>, C<scheme>, or C<event> are
5085 specified a value is added to the list if it matches any one (i.e. the
5086 logic is OR).
5087  
5088 =cut
5089  
5090 sub element_list :method {
5091 my ($self,%args) = @_;
5092 my %valid_args = (
5093 'cond' => 1,
5094 'id' => 1,
5095 'scheme' => 1,
5096 );
5097 my $subname = ( caller(0) )[3];
5098 croak($subname . "() called as a procedure") unless(ref $self);
5099 debug(2,"DEBUG[",$subname,"]");
5100 $self->twigcheck();
5101 foreach my $arg (keys %args) {
5102 croak($subname,"(): invalid argument '",$arg,"'")
5103 if(!$valid_args{$arg});
5104 }
5105 unless($args{cond}) {
5106 $self->add_error($subname,"(): no search condition specified");
5107 return;
5108 }
5109  
5110 my @elements = $self->{twigroot}->descendants($args{cond});
5111 my @list = ();
5112 my $id;
5113 my $scheme;
5114 foreach my $el (@elements) {
5115 if($args{id}) {
5116 $id = $el->att('id') || '';
5117 if($id eq $args{id}) {
5118 push(@list,$el->text);
5119 next;
5120 }
5121 }
5122 if($args{event}) {
5123 $scheme = $el->att('opf:event') || $el->att('event') || '';
5124 if($scheme eq $args{event}) {
5125 push(@list,$el->text);
5126 next;
5127 }
5128 }
5129 if($args{scheme}) {
5130 $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
5131 if($scheme eq $args{scheme}) {
5132 push(@list,$el->text);
5133 next;
5134 }
5135 }
5136 next if($args{id} || $args{event} || $args{scheme});
5137 push(@list,$el->text);
5138 }
5139 return unless(@list);
5140 if(wantarray) { return @list; }
5141 else { return $list[0]; }
5142 }
5143  
5144  
5145 =head2 C<errors()>
5146  
5147 Returns an arrayref containing any generated error messages.
5148  
5149 =cut
5150  
5151 sub errors :method {
5152 my $self = shift;
5153 my $subname = ( caller(0) )[3];
5154 croak($subname . "() called as a procedure") unless(ref $self);
5155 debug(2,"DEBUG[",$subname,"]");
5156 return $self->{errors};
5157 }
5158  
5159  
5160 =head2 C<identifier()>
5161  
5162 Returns the text of the dc:identifier element pointed to by the
5163 'unique-identifier' attribute of the root 'package' element, or undef
5164 if it could not be located.
5165  
5166 =cut
5167  
5168 sub identifier :method {
5169 my $self = shift;
5170 my $subname = ( caller(0) )[3];
5171 croak($subname . "() called as a procedure") unless(ref $self);
5172 debug(2,"DEBUG[",$subname,"]");
5173 $self->twigcheck;
5174  
5175 my $identid = $self->{twigroot}->att('unique-identifier');
5176 return unless($identid);
5177  
5178 my $identifier = $self->{twig}->first_elt("*[\@id='$identid']");
5179 return unless($identifier);
5180  
5181 my $idtext = $identifier->text;
5182 return unless($idtext);
5183  
5184 return($idtext);
5185 }
5186  
5187  
5188 =head2 C<isbn_list(%args)>
5189  
5190 Returns a list of all ISBNs matching the specified attributes. See
5191 L</twigelt_is_isbn()> for a detailed description of how the ISBN
5192 elements are found.
5193  
5194 Returns undef if no matches are found.
5195  
5196 In scalar context returns the first match, not the last.
5197  
5198 See also L</isbns(%args)>.
5199  
5200 =head3 Arguments
5201  
5202 =over
5203  
5204 =item * C<id> (optional)
5205  
5206 'id' attribute that must be matched exactly for the
5207 result to be added to the list
5208  
5209 =item * C<scheme> (optional)
5210  
5211 'opf:scheme' or 'scheme' attribute that must be
5212 matched exactly for the result to be added to the list
5213  
5214 =back
5215  
5216 If both arguments are specified a value is added to the list if it
5217 matches either one (i.e. the logic is OR).
5218  
5219 =cut
5220  
5221 sub isbn_list :method {
5222 my ($self,%args) = @_;
5223 my %valid_args = (
5224 'id' => 1,
5225 'scheme' => 1,
5226 );
5227 my $subname = ( caller(0) )[3];
5228 croak($subname . "() called as a procedure") unless(ref $self);
5229 debug(2,"DEBUG[",$subname,"]");
5230 $self->twigcheck();
5231 foreach my $arg (keys %args) {
5232 croak($subname,"(): invalid argument '",$arg,"'")
5233 if(!$valid_args{$arg});
5234 }
5235  
5236 my @list = $self->element_list(cond => \&twigelt_is_isbn,
5237 %args);
5238 return unless(@list);
5239 if(wantarray) { return @list; }
5240 else { return $list[0]; }
5241 }
5242  
5243  
5244 =head2 C<isbns(%args)>
5245  
5246 Returns all of the ISBN identifiers matching the specificied
5247 attributes as a list of hashrefs, with one hash per ISBN identifier
5248 presented in the order that the identifiers are found. The hash keys
5249 are 'id' (containing the value of the 'id' attribute), 'scheme'
5250 (containing the value of either the 'opf:scheme' or 'scheme'
5251 attribute, whichever is found first), and 'isbn' (containing the text
5252 of the element).
5253  
5254 If no entries are found, returns undef.
5255  
5256 In scalar context returns the first match, not the last.
5257  
5258 See also L</isbn_list(%args)>.
5259  
5260 =head3 Arguments
5261  
5262 C<isbns()> takes two optional named arguments:
5263  
5264 =over
5265  
5266 =item * C<id> - 'id' attribute that must be matched exactly for the
5267 result to be added to the list
5268  
5269 =item * C<scheme> - 'opf:scheme' or 'scheme' attribute that must be
5270 matched exactly for the result to be added to the list
5271  
5272 =back
5273  
5274 If both arguments are specified a value is added to the list if it
5275 matches either one (i.e. the logic is OR).
5276  
5277 =cut
5278  
5279 sub isbns :method {
5280 my ($self,%args) = @_;
5281 my %valid_args = (
5282 'id' => 1,
5283 'scheme' => 1,
5284 );
5285 my $subname = ( caller(0) )[3];
5286 croak($subname . "() called as a procedure") unless(ref $self);
5287 debug(2,"DEBUG[",$subname,"]");
5288 $self->twigcheck();
5289 foreach my $arg (keys %args) {
5290 croak($subname,"(): invalid argument '",$arg,"'")
5291 if(!$valid_args{$arg});
5292 }
5293  
5294 my @elements = $self->{twigroot}->descendants(\&twigelt_is_isbn);
5295 my @list = ();
5296 my $id;
5297 my $scheme;
5298 foreach my $el (@elements) {
5299 if($args{id}) {
5300 $id = $el->att('id') || '';
5301 if($id eq $args{id}) {
5302 push(@list,
5303 {
5304 'isbn' => $el->text,
5305 'id' => $el->att('id'),
5306 'scheme' => $el->att('scheme'),
5307 });
5308 next;
5309 }
5310 }
5311 if($args{scheme}) {
5312 $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
5313 if($scheme eq $args{scheme}) {
5314 push(@list,
5315 {
5316 'isbn' => $el->text,
5317 'id' => $el->att('id'),
5318 'scheme' => $el->att('scheme'),
5319 });
5320 next;
5321 }
5322 }
5323 next if($args{id} || $args{scheme});
5324 $scheme = $el->att('opf:scheme') || $el->att('scheme');
5325 push(@list,
5326 {
5327 'isbn' => $el->text,
5328 'id' => $el->att('id'),
5329 'scheme' => $scheme,
5330 });
5331 }
5332 return unless(@list);
5333 if(wantarray) { return @list; }
5334 else { return $list[0]; }
5335 }
5336  
5337  
5338 =head2 C<languages()>
5339  
5340 Returns a list containing the text of all dc:language
5341 (case-insensitive) entries, or undef if none are found.
5342  
5343 In scalar context returns the first match, not the last.
5344  
5345 =cut
5346  
5347 sub languages :method {
5348 my $self = shift;
5349 my $subname = ( caller(0) )[3];
5350 croak($subname . "() called as a procedure") unless(ref $self);
5351 debug(2,"DEBUG[",$subname,"]");
5352 $self->twigcheck;
5353  
5354 my @retval = ();
5355 my @elements = $self->{twigroot}->descendants(qr/^dc:language$/ix);
5356 foreach my $el (@elements) {
5357 push(@retval,$el->text) if($el->text);
5358 }
5359 return unless(@retval);
5360 if(wantarray) { return @retval; }
5361 else { return $retval[0]; }
5362 }
5363  
5364  
5365 =head2 C<manifest(%args)>
5366  
5367 Returns all of the items in the manifest as a list of hashrefs, with
5368 one hash per manifest item in the order that they appear, where the
5369 hash keys are 'id', 'href', and 'media-type', each returning the
5370 appropriate attribute, if any.
5371  
5372 In scalar context, returns the first match, not the last.
5373  
5374 =head3 Arguments
5375  
5376 C<manifest()> takes four optional named arguments:
5377  
5378 =over
5379  
5380 =item * C<id> - 'id' attribute to match
5381  
5382 =item * C<href> - 'href' attribute to match
5383  
5384 =item * C<mtype> - 'media-type' attribute to match
5385  
5386 =item * C<logic> - logic to use (valid values are 'and' or 'or', default: 'and')
5387  
5388 =back
5389  
5390 If any of the named arguments are specified, C<manifest()> will return
5391 only items matching the specified criteria. This is an exact
5392 case-sensitive match, but it can (especially in the case of mtype)
5393 still return multiple elements.
5394  
5395 =head3 Return values
5396  
5397 Returns undef if there is no <manifest> element directly underneath
5398 <package>, or if <manifest> contains no items.
5399  
5400 =head3 See also
5401  
5402 L</manifest_hrefs()>, L</spine()>
5403  
5404 =head3 Example
5405  
5406 @manifest = $ebook->manifest(id => 'ncx',
5407 mtype => 'text/xml',
5408 logic => 'or');
5409  
5410 =cut
5411  
5412 sub manifest :method {
5413 my ($self,%args) = @_;
5414 my %valid_args = (
5415 'id' => 1,
5416 'href' => 1,
5417 'mtype' => 1,
5418 'logic' => 1
5419 );
5420 my %valid_logic = (
5421 'and' => 1,
5422 'or' => 1
5423 );
5424 my $subname = ( caller(0) )[3];
5425 croak($subname . "() called as a procedure") unless(ref $self);
5426 debug(2,"DEBUG[",$subname,"]");
5427 $self->twigcheck();
5428  
5429 foreach my $arg (keys %args) {
5430 croak($subname,"(): invalid argument '",$arg,"'")
5431 if(!$valid_args{$arg});
5432 }
5433 if($args{logic}) {
5434 croak($subname,
5435 "(): logic must be 'and' or 'or' (got '",$args{logic},"')")
5436 if(!$valid_logic{$args{logic}});
5437 }
5438 else { $args{logic} = 'and'; }
5439  
5440 debug(1,"DEBUG: manifest() called with '",join(" ",keys(%args)),"'");
5441  
5442 my @elements;
5443 my @retarray;
5444 my $cond;
5445  
5446 if($args{id})
5447 {
5448 debug(1,"DEBUG: manifest searching on id");
5449 $cond = "item[\@id='$args{id}'";
5450 }
5451 if($args{href})
5452 {
5453 debug(1,"DEBUG: manifest searching on href");
5454 if($cond) { $cond .= " $args{logic} \@href='$args{href}'"; }
5455 else { $cond = "item[\@href='$args{href}'"; }
5456 }
5457 if($args{mtype})
5458 {
5459 debug(1,"DEBUG: manifest searching on mtype");
5460 if($cond) { $cond .= " $args{logic} \@media-type='$args{mtype}'"; }
5461 else { $cond = "item[\@media-type='$args{mtype}'"; }
5462 }
5463 if($cond) { $cond .= "]"; }
5464 else { $cond = "item"; }
5465  
5466 my $manifest = $self->{twigroot}->first_child('manifest');
5467 return unless($manifest);
5468  
5469 debug(1,"DEBUG: manifest search condition = '",$cond,"'");
5470 @elements = $manifest->children($cond);
5471 return unless(@elements);
5472  
5473 foreach my $el (@elements)
5474 {
5475 push(@retarray,
5476 {
5477 'id' => $el->id,
5478 'href' => $el->att('href'),
5479 'media-type' => $el->att('media-type')
5480 });
5481 }
5482 if(wantarray) { return @retarray; }
5483 else { return $retarray[0]; }
5484 }
5485  
5486  
5487 =head2 C<manifest_hrefs()>
5488  
5489 Returns a list of all of the hrefs in the current OPF manifest, or the
5490 empty list if none are found.
5491  
5492 In scalar context returns the first href, not the last.
5493  
5494 See also: C<manifest()>, C<spine_idrefs()>
5495  
5496 =cut
5497  
5498 sub manifest_hrefs :method {
5499 my $self = shift;
5500 my $subname = ( caller(0) )[3];
5501 croak($subname . "() called as a procedure") unless(ref $self);
5502 debug(2,"DEBUG[",$subname,"]");
5503 $self->twigcheck();
5504  
5505 my @items;
5506 my $href;
5507 my $manifest;
5508 my $mimetype;
5509 my @retval = ();
5510  
5511 $manifest = $self->{twigroot}->first_child('manifest');
5512 if(! $manifest) { return @retval; }
5513  
5514 @items = $manifest->descendants('item');
5515 foreach my $item (@items) {
5516 $href = $item->att('href');
5517 if($href) {
5518 $mimetype = mimetype($href) || "UNKNOWN";
5519 debug(3,"DEBUG: '",$href,"' has mime-type '",$mimetype,"'");
5520 push(@retval,$href);
5521 }
5522 }
5523 debug(2,"DEBUG[/",$subname,"]");
5524 if(wantarray) { return @retval; }
5525 else { return $retval[0]; }
5526 }
5527  
5528  
5529 =head2 C<opf_namespace()>
5530  
5531 Some OPF generators explicity assign 'opf:' in the gi as a prefix on
5532 OPF elements. This makes later parsing more complex and is
5533 unnecessary, so this is stripped before any parsing takes place.
5534  
5535 =cut
5536  
5537 sub opf_namespace :method {
5538 my $self = shift;
5539 my $subname = ( caller(0) )[3];
5540 croak($subname . "() called as a procedure") unless(ref $self);
5541 debug(3,"DEBUG[",$subname,"]");
5542  
5543 my @elements = $self->{twig}->descendants(qr/^opf:/ix);
5544 foreach my $el (@elements)
5545 {
5546 my $gi = $el->gi;
5547 $gi =~ s/^opf:(.*)/$1/ix;
5548 $el->set_gi($gi);
5549 }
5550 return;
5551 }
5552  
5553  
5554 =head2 C<opfdir()>
5555  
5556 Returns the full filesystem path to the directory where the OPF
5557 metadata file will be stored, or undef if either the top-level
5558 directory or the OPF subdirectory is not found.
5559  
5560 =cut
5561  
5562 sub opfdir :method {
5563 my $self = shift;
5564 my $subname = ( caller(0) )[3];
5565 croak($subname . "() called as a procedure") unless(ref $self);
5566 debug(3,"DEBUG[",$subname,"]");
5567 return unless($self->{topdir});
5568 return unless($self->{opfsubdir});
5569  
5570 if($self->{opfsubdir} eq '.') {
5571 return $self->{topdir};
5572 }
5573 return $self->{topdir} . '/' . $self->{opfsubdir};
5574 }
5575  
5576  
5577 =head2 C<opffile()>
5578  
5579 Returns the name of the file where the OPF metadata will be stored or
5580 undef if no value is found..
5581  
5582 =cut
5583  
5584 sub opffile :method {
5585 my $self = shift;
5586 my $subname = ( caller(0) )[3];
5587 croak($subname . "() called as a procedure") unless(ref $self);
5588 debug(3,"DEBUG[",$subname,"]");
5589 return unless($self->{opffile});
5590 return $self->{opffile};
5591 }
5592  
5593  
5594 =head2 C<opfpath()>
5595  
5596 Returns the full filesystem path to the file where the OPF metadata
5597 will be stored or undef if either the top level directory or the OPF
5598 filename is not found.
5599  
5600 =cut
5601  
5602 sub opfpath :method {
5603 my $self = shift;
5604 my $subname = ( caller(0) )[3];
5605 croak($subname . "() called as a procedure") unless(ref $self);
5606 debug(3,"DEBUG[",$subname,"]");
5607 return unless($self->{topdir});
5608 return unless($self->{opfsubdir});
5609 return unless($self->{opffile});
5610  
5611 return $self->{topdir} . '/' . $self->{opfsubdir} . '/' . $self->{opffile};
5612 }
5613  
5614  
5615 =head2 C<primary_author()>
5616  
5617 Finds the primary author of the book, defined as the first
5618 'dc:creator' entry (case-insensitive) where either the attribute
5619 opf:role="aut" or role="aut", or the first 'dc:creator' entry if no
5620 entries with either attribute can be found. Entries must actually
5621 have text to be considered.
5622  
5623 In list context, returns a two-item list, the first of which is the
5624 text of the entry (the author name), and the second element of which
5625 is the value of the 'opf:file-as' or 'file-as' attribute (where
5626 'opf:file-as' is given precedence if both are present).
5627  
5628 In scalar context, returns the text of the entry (the author name).
5629  
5630 If no entries are found, returns undef.
5631  
5632 Uses L</twigelt_is_author()> in the first half of the search.
5633  
5634 =head3 Example
5635  
5636 my ($fileas, $author) = $ebook->primary_author;
5637 my $author = $ebook->primary_author;
5638  
5639 =cut
5640  
5641 sub primary_author :method {
5642 my $self = shift;
5643 my $subname = ( caller(0) )[3];
5644 croak($subname . "() called as a procedure") unless(ref $self);
5645 debug(2,"DEBUG[",$subname,"]");
5646  
5647 my $twigroot = $self->{twigroot};
5648 my $element;
5649 my $fileas;
5650  
5651 $element = $twigroot->first_descendant(\&twigelt_is_author);
5652 $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
5653 if(! $element) {
5654 carp("## WARNING: no dc:creator elements found!");
5655 return;
5656 }
5657 if(! $element->text) {
5658 carp("## WARNING: dc:creator element is empty!");
5659 return;
5660 }
5661 $fileas = $element->att('opf:file-as');
5662 $fileas = $element->att('file-as') unless($fileas);
5663 if(wantarray) { return ($element->text, $fileas); }
5664 else { return $element->text; }
5665 }
5666  
5667  
5668 =head2 C<print_errors()>
5669  
5670 Prints the current list of errors to STDERR.
5671  
5672 =cut
5673  
5674 sub print_errors :method {
5675 my $self = shift;
5676 my $subname = ( caller(0) )[3];
5677 croak($subname . "() called as a procedure") unless(ref $self);
5678 debug(2,"DEBUG[",$subname,"]");
5679  
5680 my $errorref = $self->{errors};
5681  
5682 if(!$self->errors) {
5683 debug(1,"DEBUG: no errors found!");
5684 return 1;
5685 }
5686  
5687  
5688 foreach my $error (@$errorref) {
5689 print "ERROR: ",$error,"\n";
5690 }
5691 return 1;
5692 }
5693  
5694  
5695 =head2 C<print_warnings()>
5696  
5697 Prints the current list of warnings to STDERR.
5698  
5699 =cut
5700  
5701 sub print_warnings :method {
5702 my $self = shift;
5703 my $subname = ( caller(0) )[3];
5704 croak($subname . "() called as a procedure") unless(ref $self);
5705 debug(2,"DEBUG[",$subname,"]");
5706  
5707 my $warningref = $self->{warnings};
5708  
5709 if(!$self->warnings) {
5710 debug(2,"DEBUG: no warnings found!");
5711 return 1;
5712 }
5713  
5714 foreach my $warning (@$warningref) {
5715 print "WARNING: ",$warning,"\n";
5716 }
5717 return 1;
5718 }
5719  
5720  
5721 =head2 C<print_opf()>
5722  
5723 Prints the OPF file to the default filehandle
5724  
5725 =cut
5726  
5727 sub print_opf :method {
5728 my $self = shift;
5729 my $filehandle = shift;
5730 my $subname = ( caller(0) )[3];
5731 croak($subname . "() called as a procedure") unless(ref $self);
5732 debug(2,"DEBUG[",$subname,"]");
5733  
5734 if(defined $filehandle) { $self->{twig}->print($filehandle); }
5735 else { $self->{twig}->print; }
5736 return 1;
5737 }
5738  
5739  
5740 =head2 C<publishers()>
5741  
5742 Returns a list containing the text of all dc:publisher
5743 (case-insensitive) entries, or undef if none are found.
5744  
5745 In scalar context returns the first match, not the last.
5746  
5747 =cut
5748  
5749 sub publishers :method {
5750 my $self = shift;
5751 my $subname = ( caller(0) )[3];
5752 croak($subname . "() called as a procedure") unless(ref $self);
5753 debug(2,"DEBUG[",$subname,"]");
5754 $self->twigcheck;
5755  
5756 my @pubs = ();
5757 my @elements = $self->{twigroot}->descendants(qr/^dc:publisher$/ix);
5758 foreach my $el (@elements) {
5759 push(@pubs,$el->text) if($el->text);
5760 }
5761 return unless(@pubs);
5762 if(wantarray) { return @pubs; }
5763 else { return $pubs[0]; }
5764 }
5765  
5766  
5767 =head2 C<retailprice()>
5768  
5769 Returns a two-scalar list, the first scalar being the text of the
5770 Mobipocket-specific <SRP> element, if it exists, and the second being
5771 the 'Currency' attribute of that element, if it exists.
5772  
5773 In scalar context, returns just the text (price).
5774  
5775 Returns undef if the SRP element is not found.
5776  
5777 =cut
5778  
5779 sub retailprice :method {
5780 my $self = shift;
5781 my $subname = ( caller(0) )[3];
5782 croak($subname . "() called as a procedure") unless(ref $self);
5783 debug(2,"DEBUG[",$subname,"]");
5784 $self->twigcheck;
5785  
5786 my $twigroot = $self->{twigroot};
5787  
5788 my $element = $twigroot->first_descendant(qr/^ SRP $/ix);
5789 return unless($element);
5790 if(wantarray) { return ($element->text,$element->att('Currency')); }
5791 else { return $element->text };
5792 }
5793  
5794  
5795 =head2 C<review()>
5796  
5797 Returns the text of the Mobipocket-specific <Review> element, if it
5798 exists. Returns undef if one is not found.
5799  
5800 =cut
5801  
5802 sub review :method {
5803 my $self = shift;
5804 my $subname = ( caller(0) )[3];
5805 croak($subname . "() called as a procedure") unless(ref $self);
5806 debug(2,"DEBUG[",$subname,"]");
5807 $self->twigcheck;
5808  
5809 my $twigroot = $self->{twigroot};
5810  
5811 my $element = $twigroot->first_descendant(qr/^review$/ix);
5812 return unless($element);
5813 return $element->text;
5814 }
5815  
5816  
5817 =head2 C<< rights('id' => 'identifier') >>
5818  
5819 Returns a list containing the text of all of dc:rights or
5820 dc:copyrights (case-insensitive) entries in the e-book, or undef if
5821 none are found.
5822  
5823 In scalar context returns the first match, not the last.
5824  
5825 If the optional named argument 'id' is specified, it will only return
5826 entries where the id attribute matches the specified identifier.
5827 Although this still returns a list, if more than one entry is found, a
5828 warning is logged.
5829  
5830 Note that dc:copyrights is not a valid Dublin Core element -- it is
5831 included only because some broken Mobipocket books use it.
5832  
5833 =cut
5834  
5835 sub rights :method {
5836 my ($self,%args) = @_;
5837 my $subname = ( caller(0) )[3];
5838 croak($subname . "() called as a procedure") unless(ref $self);
5839 debug(2,"DEBUG[",$subname,"]");
5840 $self->twigcheck;
5841  
5842 my %valid_args = (
5843 'id' => 1,
5844 );
5845 foreach my $arg (keys %args)
5846 {
5847 croak($subname,"(): invalid argument '",$arg,"'")
5848 if(!$valid_args{$arg});
5849 }
5850  
5851  
5852 my @rights = ();
5853 my $id = $args{id};
5854 my @elements = $self->{twigroot}->descendants(qr/^dc:(copy)?rights$/ix);
5855  
5856 foreach my $element (@elements)
5857 {
5858 if($id)
5859 {
5860 next if($element->att('id') ne $id);
5861 push @rights,$element->text if($element->text);
5862 }
5863 else { push @rights,$element->text if($element->text); }
5864 }
5865  
5866 if($id)
5867 {
5868 add_warning($subname
5869 . "(): More than one rights entry found with id '"
5870 . $id ."'" )
5871 if(scalar(@rights) > 1);
5872 }
5873 return unless(@rights);
5874 if(wantarray) { return @rights; }
5875 else { return $rights[0]; }
5876 }
5877  
5878  
5879 =head2 C<search_knownuids()>
5880  
5881 Searches the OPF twig for the first dc:identifier (case-insensitive)
5882 element with an ID matching known UID IDs.
5883  
5884 Returns the ID if a match is found, undef otherwise
5885  
5886 =cut
5887  
5888 sub search_knownuids :method {
5889 my $self = shift;
5890 my $subname = ( caller(0) )[3];
5891 croak($subname . "() called as a procedure") unless(ref $self);
5892 debug(2,"DEBUG[",$subname,"]");
5893  
5894 my @elements;
5895  
5896 @elements = $self->{twigroot}->descendants(\&twigelt_is_knownuid);
5897 return unless(@elements);
5898 debug(1,"DEBUG: found known UID '",$elements[0]->id,"'");
5899 return $elements[0]->id;
5900 }
5901  
5902  
5903 =head2 C<search_knownuidschemes()>
5904  
5905 Searches descendants of the OPF twig element for the first
5906 <dc:identifier> or <dc:Identifier> subelement with the attribute
5907 'scheme' or 'opf:scheme' matching a known list of schemes for unique
5908 IDs
5909  
5910 NOTE: this is NOT a case-insensitive search! If you have to deal with
5911 really bizarre input, make sure that you run L</fix_oeb12()> or
5912 L</fix_opf20()> before calling L</fix_packageid()> or L</fix_misc()>.
5913  
5914 Returns the ID if a match is found, undef otherwise.
5915  
5916 =cut
5917  
5918 sub search_knownuidschemes :method {
5919 my ($self,$gi) = @_;
5920 if(!$gi) { $gi = 'dc:identifier'; }
5921 my $subname = ( caller(0) )[3];
5922 croak($subname . "() called as a procedure") unless(ref $self);
5923 debug(2,"DEBUG[",$subname,"]");
5924 $self->twigcheck;
5925  
5926 my $topelement = $self->{twigroot};
5927  
5928 my @knownuidschemes = (
5929 'GUID',
5930 'UUID',
5931 'FWID',
5932 );
5933  
5934 # Creating a regexp to search on works, but doesn't let you
5935 # specify priority. For that, you really do have to loop.
5936 # my $schemeregexp = "(" . join('|',@knownuidschemes) . ")";
5937  
5938 my @elems;
5939 my $id;
5940  
5941 my $retval = undef;
5942  
5943 foreach my $scheme (@knownuidschemes) {
5944 debug(2,"DEBUG: searching for scheme='",$scheme,"'");
5945 @elems = $topelement->descendants(
5946 "dc:identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
5947 );
5948 push @elems, $topelement->descendants(
5949 "dc:Identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
5950 );
5951 foreach my $elem (@elems) {
5952 debug(2,"DEBUG: working on scheme '",$scheme,"'");
5953 if(defined $elem) {
5954 if($scheme eq 'FWID') {
5955 # Fictionwise has a screwy output that sets the ID
5956 # equal to the text. Fix the ID to just be 'FWID'
5957 debug(1,"DEBUG: fixing FWID");
5958 $elem->set_id('FWID');
5959 }
5960  
5961 $id = $elem->id;
5962 unless(defined $id) {
5963 debug(1,"DEBUG: assigning ID from scheme '",$scheme,"'");
5964 $id = uc($scheme);
5965 $elem->set_id($id);
5966 }
5967 $retval = $id;
5968 debug(1,"DEBUG: found Package ID: ",$id);
5969 last;
5970 } # if(defined $elem)
5971 } # foreach my $elem (@elems)
5972 last if(defined $retval);
5973 }
5974 debug(2,"[/",$subname,"]");
5975 return $retval;
5976 }
5977  
5978  
5979 =head2 C<spec()>
5980  
5981 Returns the version of the OEB specification currently in use. Valid
5982 values are C<OEB12> and C<OPF20>. This value will default to undef
5983 until C<fix_oeb12> or C<fix_opf20> is called, as there is no way for
5984 the object to know what specification is being conformed to (if any)
5985 until it attempts to enforce it.
5986  
5987 =cut
5988  
5989 sub spec :method {
5990 my $self = shift;
5991 my $subname = ( caller(0) )[3];
5992 croak($subname . "() called as a procedure") unless(ref $self);
5993 debug(2,"DEBUG[",$subname,"]");
5994 return $self->{spec};
5995 }
5996  
5997  
5998 =head2 C<spine()>
5999  
6000 Returns all of the manifest items referenced in the spine as a list of
6001 hashrefs, with one hash per manifest item in the order that they
6002 appear, where the hash keys are 'id', 'href', and 'media-type', each
6003 returning the appropriate attribute, if any.
6004  
6005 In scalar context, returns the first item, not the last.
6006  
6007 Returns undef if there is no <spine> element directly underneath
6008 <package>, or if <spine> contains no itemrefs. If <spine> exists, but
6009 <manifest> does not, or a spine itemref exists but points an ID not
6010 found in the manifest, spine() logs an error and returns undef.
6011  
6012 See also: L</spine_idrefs()>, L</manifest()>
6013  
6014 =cut
6015  
6016 sub spine :method {
6017 my $self = shift;
6018 my $subname = ( caller(0) )[3];
6019 croak($subname . "() called as a procedure") unless(ref $self);
6020 debug(2,"DEBUG[",$subname,"]");
6021 $self->twigcheck();
6022  
6023 my $spine = $self->{twigroot}->first_child('spine');
6024 return unless($spine);
6025 my @spinerefs;
6026 my $idref;
6027 my $element;
6028 my @retarray;
6029  
6030 my $manifest = $self->{twigroot}->first_child('manifest');
6031 if(!$manifest)
6032 {
6033 $self->add_error(
6034 $subname . "(): <spine> found without <manifest>"
6035 );
6036 debug(1,"DEBUG: <spine> found without <manifest>!");
6037 return;
6038 }
6039  
6040 @spinerefs = $spine->children('itemref');
6041 return unless(@spinerefs);
6042  
6043 foreach my $spineref (@spinerefs)
6044 {
6045 $idref = $spineref->att('idref');
6046 if(!$idref)
6047 {
6048 $self->add_warning(
6049 $subname . "(): <itemref> found with no idref -- skipping"
6050 );
6051 debug(1,"DEBUG: <itemref> found with no idref -- skipping");
6052 next;
6053 }
6054 $element = $manifest->first_child("item[\@id='$idref']");
6055 if(!$element)
6056 {
6057 $self->add_error(
6058 $subname ."(): id '" . $idref . "' not found in manifest!"
6059 );
6060 debug(1,"DEBUG: id '",$idref," not found in manifest!");
6061 return;
6062 }
6063 push(@retarray,
6064 {
6065 'id' => $element->id,
6066 'href' => $element->att('href'),
6067 'media-type' => $element->att('media-type')
6068 });
6069 }
6070 if(wantarray) { return @retarray; }
6071 else { return $retarray[0]; }
6072 }
6073  
6074  
6075 =head2 C<spine_idrefs()>
6076  
6077 Returns a list of all of the idrefs in the current OPF spine, or the
6078 empty list if none are found.
6079  
6080 In scalar context, returns the first idref, not the last.
6081  
6082 See also: L</spine()>, L</manifest_hrefs()>
6083  
6084 =cut
6085  
6086 sub spine_idrefs :method {
6087 my $self = shift;
6088 my $subname = ( caller(0) )[3];
6089 croak($subname . "() called as a procedure") unless(ref $self);
6090 debug(2,"DEBUG[",$subname,"]");
6091 $self->twigcheck();
6092  
6093 my $spine = $self->{twigroot}->first_child('spine');;
6094 my @retval = ();
6095 my @itemrefs;
6096 my $idref;
6097  
6098 if(! $spine) { return @retval; }
6099  
6100 @itemrefs = $spine->children('itemref');
6101 foreach my $item (@itemrefs) {
6102 $idref = $item->att('idref');
6103 push(@retval,$idref) if($idref);
6104 }
6105 if(wantarray) { return @retval; }
6106 else { return $retval[0]; }
6107 }
6108  
6109  
6110 =head2 C<subject_list()>
6111  
6112 Returns a list containing the text of all dc:subject elements or undef
6113 if none are found.
6114  
6115 In scalar context, returns the first subject, not the last.
6116  
6117 =cut
6118  
6119 sub subject_list :method {
6120 my $self = shift;
6121 my $subname = ( caller(0) )[3];
6122 croak($subname . "() called as a procedure") unless(ref $self);
6123 debug(2,"DEBUG[",$subname,"]");
6124 $self->twigcheck;
6125  
6126 my @retval = ();
6127 my $twigroot = $self->{twigroot};
6128  
6129 my @subjects = $twigroot->descendants(qr/dc:subject/ix);
6130 return unless(@subjects);
6131  
6132 foreach my $subject (@subjects) {
6133 push(@retval,$subject->text) if($subject->text);
6134 }
6135 return unless(@retval);
6136 if(wantarray) { return @retval; }
6137 else { return $retval[0]; }
6138 }
6139  
6140  
6141 =head2 C<title()>
6142  
6143 Returns the title of the e-book, or undef if no dc:title element
6144 (case-insensitive) exists. If a dc:title element exists, but contains
6145 no text, returns an empty string.
6146  
6147 =cut
6148  
6149 sub title :method {
6150 my $self = shift;
6151 my $subname = ( caller(0) )[3];
6152 croak($subname . "() called as a procedure") unless(ref $self);
6153 debug(2,"DEBUG[",$subname,"]");
6154 $self->twigcheck;
6155  
6156 my $twigroot = $self->{twigroot};
6157 my $retval;
6158  
6159 my $element = $twigroot->first_descendant(qr/^dc:title$/ix);
6160 return unless($element);
6161 $retval = $element->text || '';
6162 $retval = trim($retval);
6163 return $retval;
6164 }
6165  
6166  
6167 =head2 C<twig()>
6168  
6169 Returns the raw L<XML::Twig> object used to store the OPF metadata.
6170  
6171 Although this twig can be manipulated via the standard XML::Twig
6172 methods, doing so requires caution and is not recommended. In
6173 particular, changing the root element from here will cause the
6174 EBook::Tools internal twig and twigroot attributes to become unlinked
6175 and the result of any subsequent action is not defined.
6176  
6177 =cut
6178  
6179 sub twig :method {
6180 my $self = shift;
6181 my $subname = ( caller(0) )[3];
6182 croak($subname . "() called as a procedure") unless(ref $self);
6183 debug(2,"DEBUG[",$subname,"]");
6184 return $self->{twig};
6185 }
6186  
6187  
6188 =head2 C<twigcheck()>
6189  
6190 Croaks showing the calling location unless C<$self> has both a twig and a
6191 twigroot, and the twigroot is <package>. Used as a sanity check for
6192 methods that use twig or twigroot.
6193  
6194 =cut
6195  
6196 sub twigcheck :method {
6197 my $self = shift;
6198 my $subname = ( caller(0) )[3];
6199 croak($subname . "() called as a procedure") unless(ref $self);
6200 debug(3,"DEBUG[",$subname,"]");
6201  
6202 my @calledfrom = caller(1);
6203 croak("twigcheck called from unknown location") if(!@calledfrom);
6204  
6205 croak($calledfrom[3],"(): undefined twig")
6206 if(!$self->{twig});
6207 croak($calledfrom[3],"(): twig isn't a XML::Twig")
6208 if( (ref $self->{twig}) ne 'XML::Twig' );
6209 croak($calledfrom[3],"(): twig root missing")
6210 if(!$self->{twigroot});
6211 croak($calledfrom[3],"(): twig root isn't a XML::Twig::Elt")
6212 if( (ref $self->{twigroot}) ne 'XML::Twig::Elt' );
6213 croak($calledfrom[3],"(): twig root is '" . $self->{twigroot}->gi
6214 . "' (needs to be 'package')")
6215 if($self->{twigroot}->gi ne 'package');
6216 debug(3,"DEBUG[/",$subname,"]");
6217 return 1;
6218 }
6219  
6220  
6221 =head2 C<twigroot()>
6222  
6223 Returns the raw L<XML::Twig> root element used to store the OPF
6224 metadata.
6225  
6226 This twig element can be manipulated via the standard XML::Twig::Elt
6227 methods, but care should be taken not to attempt to cut this element
6228 from its twig as doing so will cause the EBook::Tools internal twig
6229 and twigroot attributes to become unlinked and the result of any
6230 subsequent action is not defined.
6231  
6232 =cut
6233  
6234 sub twigroot :method {
6235 my $self = shift;
6236 my $subname = ( caller(0) )[3];
6237 croak($subname . "() called as a procedure") unless(ref $self);
6238 debug(2,"DEBUG[",$subname,"]");
6239 return $self->{twigroot};
6240 }
6241  
6242  
6243 =head2 C<warnings()>
6244  
6245 Returns an arrayref containing any generated warning messages.
6246  
6247 =cut
6248  
6249 sub warnings :method {
6250 my $self = shift;
6251 my $subname = ( caller(0) )[3];
6252 croak($subname . "() called as a procedure") unless(ref $self);
6253 debug(2,"DEBUG[",$subname,"]");
6254 return $self->{warnings};
6255 }
6256  
6257  
6258 ######################################
6259 ########## MODIFIER METHODS ##########
6260 ######################################
6261  
6262 =head1 MODIFIER METHODS
6263  
6264 Unless otherwise specified, all modifier methods return undef if an
6265 error was added to the error list, and true otherwise (even if a
6266 warning was added to the warning list).
6267  
6268  
6269 =head2 C<add_document($href,$id,$mediatype)>
6270  
6271 Adds a document to the OPF manifest and spine, creating <manifest> and
6272 <spine> if necessary. To add an item only to the OPF manifest, see
6273 add_item().
6274  
6275 =head3 Arguments
6276  
6277 =over
6278  
6279 =item C<$href>
6280  
6281 The href to the document in question. Usually, this is just a
6282 filename (or relative path and filename) of a file in the current
6283 working directory. If you are planning to eventually generate a .epub
6284 book, all hrefs MUST be in or below the current working directory.
6285  
6286 The method returns undef if $href is not defined or empty.
6287  
6288 =item C<$id>
6289  
6290 The XML ID to use. If not specified, defaults to the href with
6291 invalid characters removed.
6292  
6293 This must be unique not only to the manifest list, but to every
6294 element in the OPF file. If a duplicate ID exists, the method sets an
6295 error and returns undef.
6296  
6297 =item C<$mediatype> (optional)
6298  
6299 The mime type of the document. If not specified, will attempt to
6300 autodetect the mime type, and if that fails, will default to
6301 'application/xhtml+xml'.
6302  
6303 =back
6304  
6305 =cut
6306  
6307 sub add_document :method {
6308 my ($self,$href,$id,$mediatype) = @_;
6309 my $subname = (caller(0))[3];
6310 croak($subname . "() called as a procedure") unless(ref $self);
6311 debug(2,"DEBUG[",$subname,"]");
6312 $self->twigcheck();
6313  
6314 $href = trim($href);
6315 return unless($href);
6316  
6317 my $twig = $self->{twig};
6318 my $topelement = $self->{twigroot};
6319 my $element;
6320  
6321 $id = $href unless($id);
6322 $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
6323 $id =~ s/^[.\d -]+//gx; # Delete all nonvalid XML 1.0 namestartchars
6324  
6325 $element = $twig->first_elt("*[\@id='$id']");
6326 if($element)
6327 {
6328 $self->add_error(
6329 $subname . "(): ID '" . $id . "' already exists"
6330 . " (in a '" . $element->gi ."' tag)"
6331 );
6332 return;
6333 }
6334  
6335 if(!$mediatype)
6336 {
6337 my $mimetype = mimetype($href);
6338 if($mimetype) { $mediatype = $mimetype; }
6339 else { $mediatype = "application/xhtml+xml"; }
6340 debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,"'");
6341 }
6342  
6343 my $manifest = $topelement->first_child('manifest');
6344 $manifest = $topelement->insert_new_elt('last_child','manifest')
6345 if(!$manifest);
6346 my $spine = $topelement->first_child('spine');
6347 $spine = $topelement->insert_new_elt('last_child','spine')
6348 if(!$spine);
6349  
6350 my $item = $manifest->insert_new_elt('last_child','item');
6351 $item->set_id($id);
6352 $item->set_att(
6353 'href' => $href,
6354 'media-type' => $mediatype
6355 );
6356  
6357 my $itemref = $spine->insert_new_elt('last_child','itemref');
6358 $itemref->set_att('idref' => $id);
6359  
6360 return 1;
6361 }
6362  
6363  
6364 =head2 C<add_error(@errors)>
6365  
6366 Adds @errors to the list of object errors. Each member of
6367 @errors should be a string containing the entire text of the
6368 error, with no ending newline.
6369  
6370 SEE ALSO: L</add_warning()>, L</clear_errors()>, L</clear_warnerr()>
6371  
6372 =cut
6373  
6374 sub add_error :method {
6375 my ($self,@newerror) = @_;
6376 my $subname = (caller(0))[3];
6377 croak($subname . "() called as a procedure") unless(ref $self);
6378 debug(3,"DEBUG[",$subname,"]");
6379  
6380 my $currenterrors;
6381 $currenterrors = $self->{errors} if($self->{errors});
6382  
6383 if(@newerror) {
6384 my $error = join('',@newerror);
6385 debug(1,"ERROR: ",$error);
6386 push(@$currenterrors,$error);
6387 }
6388 $self->{errors} = $currenterrors;
6389 return 1;
6390 }
6391  
6392  
6393 =head2 C<add_identifier(%args)>
6394  
6395 Creates a new dc:identifier element containing the specified text, id,
6396 and scheme.
6397  
6398 If a <dc-metadata> element exists underneath <metadata>, the
6399 identifier element will be created underneath the <dc-metadata> in OEB
6400 1.2 format, otherwise the title element is created underneath
6401 <metadata> in OPF 2.0 format.
6402  
6403 Returns the twig element containing the new identifier.
6404  
6405 =head3 Arguments
6406  
6407 C<add_identifier()> takes three named arguments, one mandatory, two
6408 optional.
6409  
6410 =over
6411  
6412 =item * C<text> - the text of the identifier. This is mandatory, and
6413 the method croaks if it is not present.
6414  
6415 =item * C<scheme> - 'opf:scheme' or 'scheme' attribute to be added (optional)
6416  
6417 =item * C<id> - 'id' attribute to be added. If this is specified, and
6418 the id is already in use, a warning will be added but the method will
6419 continue, removing the id attribute from the element that previously
6420 contained it.
6421  
6422 =back
6423  
6424 =cut
6425  
6426 sub add_identifier :method {
6427 my ($self,%args) = @_;
6428 my %valid_args = (
6429 'text' => 1,
6430 'id' => 1,
6431 'scheme' => 1,
6432 );
6433 my $subname = ( caller(0) )[3];
6434 croak($subname . "() called as a procedure") unless(ref $self);
6435 debug(2,"DEBUG[",$subname,"]");
6436 $self->twigcheck();
6437 foreach my $arg (keys %args) {
6438 croak($subname,"(): invalid argument '",$arg,"'")
6439 if(!$valid_args{$arg});
6440 }
6441 croak($subname,"(): identifier text not specified")
6442 unless($args{text});
6443  
6444 $self->fix_metastructure_basic();
6445 my $meta = $self->{twigroot}->first_child('metadata');
6446 my $dcmeta = $meta->first_child('dc-metadata');
6447 my $element;
6448 my $idelem;
6449 my $newid = $args{id};
6450 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
6451  
6452 if($dcmeta) {
6453 $element = $dcmeta->insert_new_elt('last_child','dc:Identifier');
6454 $element->set_att('scheme' => $args{scheme}) if($args{scheme});
6455 }
6456 else {
6457 $element = $meta->insert_new_elt('last_child','dc:identifier');
6458 $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
6459 }
6460 $element->set_text($args{text});
6461  
6462 if($idelem && $idelem->cmp($element) ) {
6463 $self->add_warning(
6464 $subname,"(): reassigning id '",$newid,
6465 "' from a '",$idelem->gi,"' element!"
6466 );
6467 $idelem->del_att('id');
6468 }
6469 $element->set_att('id' => $newid) if($newid);
6470  
6471 return $element;
6472 }
6473  
6474  
6475 =head2 C<add_item($href,$id,$mediatype)>
6476  
6477 Adds a document to the OPF manifest (but not spine), creating
6478 <manifest> if necessary. To add an item only to both the OPF manifest
6479 and spine, see add_document().
6480  
6481 =head3 Arguments
6482  
6483 =over
6484  
6485 =item C<$href>
6486  
6487 The href to the document in question. Usually, this is just a
6488 filename (or relative path and filename) of a file in the current
6489 working directory. If you are planning to eventually generate a .epub
6490 book, all hrefs MUST be in or below the current working directory.
6491  
6492 =item C<$id>
6493  
6494 The XML ID to use. If not specified, defaults to the href with all
6495 nonword characters removed.
6496  
6497 This must be unique not only to the manifest list, but to every
6498 element in the OPF file. If a duplicate ID exists, the method sets an
6499 error and returns undef.
6500  
6501 =item C<$mediatype> (optional)
6502  
6503 The mime type of the document. If not specified, will attempt to
6504 autodetect the mime type, and if that fails, will set an error and
6505 return undef.
6506  
6507 =back
6508  
6509 =cut
6510  
6511 sub add_item :method {
6512 my ($self,$href,$id,$mediatype) = @_;
6513 my $subname = (caller(0))[3];
6514 croak($subname . "() called as a procedure") unless(ref $self);
6515 debug(2,"DEBUG[",$subname,"]");
6516 $self->twigcheck();
6517  
6518 $href = trim($href);
6519 return unless($href);
6520  
6521 my $twig = $self->{twig};
6522 my $topelement = $self->{twigroot};
6523 my $element;
6524  
6525 $id = $href unless($id);
6526 $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
6527 if($id =~ /^[.\d -]+/x) {
6528 # We're starting with a nonvalid XML 1.0 namestartchar, so
6529 # prefix with id_
6530 $id = 'id_' . $id;
6531 }
6532  
6533 $element = $twig->first_elt("*[\@id='$id']");
6534 if($element) {
6535 $self->add_error(
6536 $subname . "(): ID '" . $id . "' already exists"
6537 . " (in a '" . $element->gi ."' tag)"
6538 );
6539 debug(2,"DEBUG[/",$subname,"]");
6540 return;
6541 }
6542  
6543 if(!$mediatype) {
6544 my $mimetype = mimetype($href);
6545 if($mimetype) { $mediatype = $mimetype; }
6546 else { $mediatype = "application/xhtml+xml"; }
6547 debug(2,"DEBUG: '",$href,"' has mimetype '",$mediatype,"'");
6548 }
6549  
6550 my $manifest = $self->{twigroot}->first_child('manifest');
6551 $manifest = $topelement->insert_new_elt('last_child','manifest')
6552 if(!$manifest);
6553  
6554 debug(2,"DEBUG: adding item '",$id,"': '",$href,"'");
6555 my $item = $manifest->insert_new_elt('last_child','item');
6556 $item->set_id($id);
6557 $item->set_att(
6558 'href' => $href,
6559 'media-type' => $mediatype
6560 );
6561  
6562 debug(3,"DEBUG[/",$subname,"]");
6563 return 1;
6564 }
6565  
6566  
6567 =head2 add_metadata(%args)
6568  
6569 Creates a metadata element with the specified text, attributes, and parent.
6570  
6571 If a <dc-metadata> element exists underneath <metadata>, the language
6572 element will be created underneath the <dc-metadata> and any standard
6573 attributes will be created in OEB 1.2 format, otherwise the element is
6574 created underneath <metadata> in OPF 2.0 format.
6575  
6576 Returns 1 on success, returns undef if no gi or if no text was specified.
6577  
6578 =cut
6579  
6580 =head3 Arguments
6581  
6582 =over
6583  
6584 =item C<gi>
6585  
6586 The generic identifier (tag) of the metadata element to alter or
6587 create. If not specified, the method sets an error and returns undef.
6588  
6589 =item C<parent>
6590  
6591 The generic identifier (tag) of the parent to use for any newly
6592 created element. If not specified, defaults to 'dc-metadata' if
6593 'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.
6594  
6595 A newly created element will be created under the first element found
6596 with this gi. A modified element will be moved under the first
6597 element found with this gi.
6598  
6599 Newly created elements will use OPF 2.0 attribute names if the parent
6600 is 'metadata' and OEB 1.2 attribute names otherwise.
6601  
6602 =item C<text>
6603  
6604 This specifies the element text to set. If not specified, the method
6605 sets an error and returns undef.
6606  
6607 =item C<id> (optional)
6608  
6609 This specifies the ID to set on the element. If set and the ID is
6610 already in use, a warning is logged and the ID is removed from the
6611 other location and assigned to the element.
6612  
6613 =item C<fileas> (optional)
6614  
6615 This specifies the file-as attribute to set on the element.
6616  
6617 =item C<role> (optional)
6618  
6619 This specifies the role attribute to set on the element.
6620  
6621 =item C<scheme> (optional)
6622  
6623 This specifies the scheme attribute to set on the element.
6624  
6625 =back
6626  
6627 =head3 Example
6628  
6629 $retval = $ebook->add_metadata(gi => 'AuthorNonstandard',
6630 text => 'Element Text',
6631 id => 'customid',
6632 fileas => 'Text, Element',
6633 role => 'xxx',
6634 scheme => 'code');
6635  
6636 =cut
6637  
6638 sub add_metadata :method {
6639 my ($self,%args) = @_;
6640 my $subname = ( caller(0) )[3];
6641 croak($subname . "() called as a procedure") unless(ref $self);
6642 debug(3,"DEBUG[",$subname,"]");
6643 my %valid_args = (
6644 'gi' => 1,
6645 'parent' => 1,
6646 'text' => 1,
6647 'id' => 1,
6648 'fileas' => 1,
6649 'role' => 1,
6650 'scheme' => 1,
6651 );
6652 foreach my $arg (keys %args) {
6653 croak($subname,"(): invalid argument '",$arg,"'")
6654 if(!$valid_args{$arg});
6655 }
6656  
6657 my $gi = $args{gi};
6658 unless($gi) {
6659 $self->add_error($subname,"(): no gi specified");
6660 return;
6661 }
6662  
6663 my $text = $args{text};
6664 unless($text) {
6665 $self->add_error($subname,"(): no text specified");
6666 return;
6667 }
6668  
6669 my $newid = $args{id};
6670 my $idelem;
6671 my $element;
6672 my $meta;
6673 my $dcmeta;
6674 my $parent;
6675 my %dcatts;
6676  
6677 $self->fix_metastructure_basic();
6678 $parent = $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
6679 if($args{parent});
6680 $meta = $self->{twigroot}->first_child('metadata');
6681 $dcmeta = $meta->first_child('dc-metadata');
6682 $parent = $parent || $dcmeta || $meta;
6683 if($parent->gi eq 'metadata') {
6684 %dcatts = (
6685 'file-as' => 'opf:file-as',
6686 'role' => 'opf:role',
6687 'scheme' => 'opf:scheme',
6688 );
6689 }
6690 else {
6691 %dcatts = (
6692 'file-as' => 'file-as',
6693 'role' => 'role',
6694 'scheme' => 'scheme'
6695 );
6696 }
6697  
6698 debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
6699 $element = $parent->insert_new_elt('last_child',$gi);
6700 $element->set_att($dcatts{'file-as'},$args{fileas})
6701 if($args{fileas});
6702 $element->set_att($dcatts{'role'},$args{role})
6703 if($args{role});
6704 $element->set_att($dcatts{'scheme'},$args{scheme})
6705 if($args{scheme});
6706 $element->set_text($text);
6707  
6708 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
6709 if($idelem && $idelem->cmp($element) ) {
6710 $self->add_warning(
6711 $subname,"(): reassigning id '",$newid,
6712 "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
6713 );
6714 $idelem->del_att('id');
6715 }
6716 $element->set_att('id' => $newid) if($newid);
6717 return 1;
6718 }
6719  
6720  
6721 =head2 C<add_subject(%args)>
6722  
6723 Creates a new dc:subject element containing the specified text, code,
6724 and id.
6725  
6726 If a <dc-metadata> element exists underneath <metadata>, the
6727 subject element will be created underneath the <dc-metadata> in OEB
6728 1.2 format, otherwise the title element is created underneath
6729 <metadata> in OPF 2.0 format.
6730  
6731 Returns the twig element containing the new subject.
6732  
6733 =head3 Arguments
6734  
6735 C<add_subject()> takes four named arguments, one mandatory, three
6736 optional.
6737  
6738 =over
6739  
6740 =item * C<text> - the text of the subject. This is mandatory, and
6741 the method croaks if it is not present.
6742  
6743 =item * C<scheme> (optional) - 'opf:scheme' or 'scheme' attribute to
6744 be added. Be warned that neither the OEB 1.2 nor the OPF 2.0
6745 specifications allow a scheme to be added to this element, so if this
6746 is specified, the resulting OPF file will fail to validate against
6747 either standard.
6748  
6749 =item * C<basiccode> (optional) - 'BASICCode' attribute to be added.
6750 Be warned that this is a Mobipocket-specific attribute that does not
6751 exist in either the OEB 1.2 nor the OPF 2.0 specifications, so if this
6752 is specified, the resulting OPF file will fail to validate against
6753 either standard.
6754  
6755 =item * C<id> (optional) - 'id' attribute to be added. If this is
6756 specified, and the id is already in use, a warning will be added but
6757 the method will continue, removing the id attribute from the element
6758 that previously contained it.
6759  
6760 =back
6761  
6762 =cut
6763  
6764 sub add_subject :method {
6765 my ($self,%args) = @_;
6766 my %valid_args = (
6767 'text' => 1,
6768 'id' => 1,
6769 'scheme' => 1,
6770 'basiccode' => 1,
6771 );
6772 my $subname = ( caller(0) )[3];
6773 croak($subname . "() called as a procedure") unless(ref $self);
6774 debug(2,"DEBUG[",$subname,"]");
6775 $self->twigcheck();
6776 foreach my $arg (keys %args) {
6777 croak($subname,"(): invalid argument '",$arg,"'")
6778 if(!$valid_args{$arg});
6779 }
6780 croak($subname,"(): subject text not specified")
6781 unless($args{text});
6782  
6783 $self->fix_metastructure_basic();
6784 my $meta = $self->{twigroot}->first_child('metadata');
6785 my $dcmeta = $meta->first_child('dc-metadata');
6786 my $element;
6787 my $idelem;
6788 my $newid = $args{id};
6789 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
6790  
6791 if($dcmeta) {
6792 $element = $dcmeta->first_child('dc:Subject[string()="' . $args{text} . '"]');
6793 if(! $element) {
6794 $element = $dcmeta->insert_new_elt('last_child','dc:Subject');
6795 }
6796 $element->set_att('scheme' => $args{scheme}) if($args{scheme});
6797 }
6798 else {
6799 $element = $meta->first_child('dc:subject[string()="' . $args{text} . '"]');
6800 if(! $element) {
6801 $element = $meta->insert_new_elt('last_child','dc:subject');
6802 }
6803 $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
6804 }
6805 $element->set_text($args{text});
6806 $element->set_att('BASICCode' => $args{basiccode}) if($args{basiccode});
6807  
6808 if($idelem && $idelem->cmp($element) ) {
6809 $self->add_warning(
6810 $subname,"(): reassigning id '",$newid,
6811 "' from a '",$idelem->gi,"' element!"
6812 );
6813 $idelem->del_att('id');
6814 }
6815 $element->set_att('id' => $newid) if($newid);
6816  
6817 return $element;
6818 }
6819  
6820  
6821 =head2 C<add_warning(@newwarning)>
6822  
6823 Joins @newwarning to a single string and adds it to the list of object
6824 warnings. The warning should not end with a newline newline.
6825  
6826 SEE ALSO: L</add_error()>, L</clear_warnings()>, L</clear_warnerr()>
6827  
6828 =cut
6829  
6830 sub add_warning :method {
6831 my ($self,@newwarning) = @_;
6832 my $subname = (caller(0))[3];
6833 croak($subname . "() called as a procedure") unless(ref $self);
6834 debug(3,"DEBUG[",$subname,"]");
6835  
6836 my @currentwarnings;
6837 @currentwarnings = @{$self->{warnings}} if($self->{warnings});
6838  
6839 if (@newwarning) {
6840 my $warning = join('',@newwarning);
6841 debug(1,"WARNING: ",$warning);
6842 push(@currentwarnings,$warning);
6843 }
6844 $self->{warnings} = \@currentwarnings;
6845  
6846 debug(3,"DEBUG[/",$subname,"]");
6847 return 1;
6848 }
6849  
6850  
6851 =head2 C<clear_errors()>
6852  
6853 Clear the current list of errors
6854  
6855 =cut
6856  
6857 sub clear_errors :method {
6858 my $self = shift;
6859 my $subname = ( caller(0) )[3];
6860 croak($subname . "() called as a procedure") unless(ref $self);
6861 debug(2,"DEBUG[",$subname,"]");
6862  
6863 $self->{errors} = ();
6864 return 1;
6865 }
6866  
6867  
6868 =head2 C<clear_warnerr()>
6869  
6870 Clear both the error and warning lists
6871  
6872 =cut
6873  
6874 sub clear_warnerr :method {
6875 my $self = shift;
6876 my $subname = ( caller(0) )[3];
6877 croak($subname . "() called as a procedure") unless(ref $self);
6878 debug(2,"DEBUG[",$subname,"]");
6879  
6880 $self->{errors} = ();
6881 $self->{warnings} = ();
6882 return 1;
6883 }
6884  
6885  
6886 =head2 C<clear_warnings()>
6887  
6888 Clear the current list of warnings
6889  
6890 =cut
6891  
6892 sub clear_warnings :method {
6893 my $self = shift;
6894 my $subname = ( caller(0) )[3];
6895 croak($subname . "() called as a procedure") unless(ref $self);
6896 debug(2,"DEBUG[",$subname,"]");
6897  
6898 $self->{warnings} = ();
6899 return 1;
6900 }
6901  
6902  
6903 =head2 C<delete_meta_filepos()>
6904  
6905 Deletes metadata elements with the attribute 'filepos' underneath
6906 the given parent element
6907  
6908 These are secondary metadata elements included in the output from
6909 mobi2html may that are not used.
6910  
6911 =cut
6912  
6913 sub delete_meta_filepos :method {
6914 my $self = shift;
6915 my $subname = ( caller(0) )[3];
6916 croak($subname . "() called as a procedure") unless(ref $self);
6917 debug(2,"DEBUG[",$subname,"]");
6918 $self->twigcheck();
6919  
6920 my @elements = $self->{twigroot}->descendants('metadata[@filepos]');
6921 foreach my $el (@elements) {
6922 $el->delete;
6923 }
6924 return 1;
6925 }
6926  
6927  
6928 =head2 C<delete_subject(%args)>
6929  
6930 Deletes dc:subject and dc:Subject elements based on text content or
6931 the id, scheme, or basiccode attributes. Matches are case-sensitive.
6932  
6933 Specifying multiple arguments will delete subject matching any of them.
6934  
6935 This has the same potential arguments as add_subject.
6936  
6937 Returns the count of elements deleted.
6938  
6939 =cut
6940  
6941 sub delete_subject :method {
6942 my ($self,%args) = @_;
6943 my %valid_args = (
6944 'text' => 1,
6945 'id' => 1,
6946 'scheme' => 1,
6947 'basiccode' => 1,
6948 );
6949 my $subname = ( caller(0) )[3];
6950 croak($subname . "() called as a procedure") unless(ref $self);
6951 debug(2,"DEBUG[",$subname,"]");
6952 $self->twigcheck();
6953 foreach my $arg (keys %args) {
6954 croak($subname,"(): invalid argument '",$arg,"'")
6955 if(!$valid_args{$arg});
6956 }
6957  
6958 my @elements;
6959 my $count = 0;
6960  
6961 if(defined $args{text}) {
6962 @elements = $self->{twigroot}->descendants('dc:subject[text()="' . $args{text} . '"]');
6963 foreach my $el (@elements) {
6964 $el->delete;
6965 $count++;
6966 }
6967 @elements = $self->{twigroot}->descendants('dc:Subject[text()="' . $args{text} . '"]');
6968 foreach my $el (@elements) {
6969 $el->delete;
6970 $count++;
6971 }
6972 }
6973  
6974 if($args{id}) {
6975 @elements = $self->{twigroot}->descendants('dc:subject[@id="' . $args{id} . '"]');
6976 foreach my $el (@elements) {
6977 $el->delete;
6978 $count++;
6979 }
6980 @elements = $self->{twigroot}->descendants('dc:Subject[@id="' . $args{id} . '"]');
6981 foreach my $el (@elements) {
6982 $el->delete;
6983 $count++;
6984 }
6985 }
6986  
6987 if($args{scheme}) {
6988 @elements = $self->{twigroot}->descendants('dc:subject[@scheme="' . $args{scheme} . '"]');
6989 foreach my $el (@elements) {
6990 $el->delete;
6991 $count++;
6992 }
6993 @elements = $self->{twigroot}->descendants('dc:subject[@opf:scheme="' . $args{scheme} . '"]');
6994 foreach my $el (@elements) {
6995 $el->delete;
6996 $count++;
6997 }
6998 @elements = $self->{twigroot}->descendants('dc:Subject[@scheme="' . $args{scheme} . '"]');
6999 foreach my $el (@elements) {
7000 $el->delete;
7001 $count++;
7002 }
7003 @elements = $self->{twigroot}->descendants('dc:Subject[@opf:scheme="' . $args{scheme} . '"]');
7004 foreach my $el (@elements) {
7005 $el->delete;
7006 $count++;
7007 }
7008 }
7009  
7010 if($args{basiccode}) {
7011 @elements = $self->{twigroot}->descendants('dc:subject[@BASICCode="' . $args{id} . '"]');
7012 foreach my $el (@elements) {
7013 $el->delete;
7014 $count++;
7015 }
7016 @elements = $self->{twigroot}->descendants('dc:Subject[@BASICCode="' . $args{id} . '"]');
7017 foreach my $el (@elements) {
7018 $el->delete;
7019 $count++;
7020 }
7021 }
7022 debug(2,"DEBUG: Deleted ",$count," elements");
7023 return $count;
7024 }
7025  
7026  
7027 =head2 C<fix_creators()>
7028  
7029 Normalizes creator and contributor names and file-as attributes
7030  
7031 Names are normalized to 'First Last' format, while file-as attributes
7032 are normalized to 'Last, First' format.
7033  
7034 This can damage some unusual names that do not match standard
7035 capitalization formats, so it is not made part of L</fix_misc()>.
7036  
7037 =cut
7038  
7039 sub fix_creators :method {
7040 my $self = shift;
7041 my $subname = ( caller(0) )[3];
7042 croak($subname . "() called as a procedure") unless(ref $self);
7043 debug(2,"DEBUG[",$subname,"]");
7044 $self->twigcheck();
7045  
7046 my $twigroot = $self->{twigroot};
7047 my @elements = $twigroot->descendants(qr/dc:(creator|contributor)/ix);
7048 my $nameparse = Lingua::EN::NameParse->new(
7049 allow_reversed => 1,
7050 extended_titles => 1,
7051 force_case => 1,
7052 lc_prefix => 1,
7053 );
7054 foreach my $el (@elements) {
7055 my $fileas = $el->att('opf:file-as') || '';
7056 my $name = $el->text || '';
7057 my $fixed;
7058 $name = trim($name);
7059  
7060 if ( $nameparse->parse($name) ) {
7061 $self->add_warning(
7062 "failure while parsing name: ",
7063 {$nameparse->properties}->{non_matching});
7064 }
7065 else {
7066 $fixed = $nameparse->case_all;
7067 if($fixed and $strangenames{lc $fixed}) {
7068 $fixed = $strangenames{lc $fixed};
7069 }
7070 debug(2,"DEBUG: creator name '",$name,"' -> '",
7071 $fixed,"'");
7072 $el->set_text($fixed);
7073  
7074 $fixed = $nameparse->case_all_reversed;
7075 if($fixed and $strangefileas{lc $fixed}) {
7076 $fixed = $strangefileas{lc $fixed};
7077 }
7078 if($fixed) {
7079 debug(2,"DEBUG: creator file-as '",$fileas,"' -> '",
7080 $fixed,"'");
7081 $el->set_att('opf:file-as',$fixed);
7082 }
7083 else {
7084 debug(2,"DEBUG: removing empty creator file-as from creator '",
7085 $name,"'");
7086 $el->del_att('opf:file-as');
7087 }
7088 }
7089 }
7090 return;
7091 }
7092  
7093  
7094 =head2 C<fix_dates()>
7095  
7096 Standardizes all <dc:date> elements via fix_datestring(). Adds a
7097 warning to the object for each date that could not be fixed.
7098  
7099 Called from L</fix_misc()>.
7100  
7101 =cut
7102  
7103 sub fix_dates :method {
7104 my $self = shift;
7105 my $subname = ( caller(0) )[3];
7106 croak($subname . "() called as a procedure") unless(ref $self);
7107 debug(2,"DEBUG[",$subname,"]");
7108 $self->twigcheck();
7109  
7110 my @dates;
7111 my $newdate;
7112  
7113 @dates = $self->{twigroot}->descendants('dc:date');
7114 push(@dates,$self->{twigroot}->descendants('dc:Date'));
7115  
7116 foreach my $dcdate (@dates) {
7117 if(!$dcdate->text) {
7118 $self->add_warning(
7119 "WARNING: found dc:date with no value -- skipping");
7120 }
7121 else {
7122 $newdate = fix_datestring($dcdate->text);
7123 if(!$newdate) {
7124 $self->add_warning(
7125 sprintf("fixmisc(): can't deal with date '%s' -- skipping",
7126 $dcdate->text)
7127 );
7128 }
7129 elsif($dcdate->text ne $newdate) {
7130 debug(2,"DEBUG: setting date from '",$dcdate->text,
7131 "' to '",$newdate,"'");
7132 $dcdate->set_text($newdate);
7133 }
7134 }
7135 }
7136 return 1;
7137 }
7138  
7139  
7140 =head2 C<fix_guide()>
7141  
7142 Fixes problems related to the OPF guide elements, specifically:
7143  
7144 =over
7145  
7146 =item * Ensures the guide element exists
7147  
7148 =item * Moves all reference elements directly underneath the guide element
7149  
7150 =item * Finds nonstandard reference types and either converts them to
7151 standard or prefaces them with 'other.'
7152  
7153 =item * Finds reference elements with a href with only an anchor
7154 portion and assigns them to the first spine href. This only works if
7155 the spine is in working condition, so it may be wise to run
7156 L</fix_spine()> before C<fix_guide()> if the input is expected to be
7157 very badly broken.
7158  
7159 =back
7160  
7161 Logs a warning if a reference href is found that does not appear in
7162 the manifest.
7163  
7164 =cut
7165  
7166 sub fix_guide :method {
7167 my $self = shift;
7168 my $subname = ( caller(0) )[3];
7169 croak($subname . "() called as a procedure") unless(ref $self);
7170 debug(2,"DEBUG[",$subname,"]");
7171 $self->twigcheck();
7172  
7173 my $twigroot = $self->{twigroot};
7174 my $guide = $twigroot->first_descendant('guide');
7175 my $parent;
7176 my $href;
7177 my $type;
7178 my @spine;
7179  
7180 # If <guide> doesn't exist, create it
7181 unless($guide) {
7182 debug(1,"DEBUG: creating <guide>");
7183 $guide = $twigroot->insert_new_elt('last_child','guide');
7184 }
7185  
7186 # Make sure that the guide is a child of the twigroot,
7187 $parent = $guide->parent;
7188 if( $parent->cmp($twigroot) ) {
7189 debug(1,"DEBUG: moving <guide>");
7190 $guide->move('last_child',$twigroot);
7191 }
7192  
7193  
7194 my @elements = $twigroot->descendants(qr/^reference$/ix);
7195 foreach my $el (@elements) {
7196 $type = $el->att('type');
7197 if($referencetypes{$type}) {
7198 $el->set_att('type',$referencetypes{$type});
7199 }
7200 elsif($type !~ /^other./x) {
7201 $type = 'other.' . $type;
7202 $el->set_att('type',$type);
7203 }
7204  
7205 $href = $el->att('href');
7206 if (!$href) {
7207 # No href means it is broken.
7208 # Leave it alone, but log a warning
7209 $self->add_warning(
7210 "fix_guide(): <reference> with no href -- skipping");
7211 next;
7212 }
7213 if ($href =~ /^#/) {
7214 # Anchor-only href. Attempt to fix from the first
7215 # spine entry
7216 @spine = $self->spine;
7217 if (!@spine) {
7218 $self->add_warning(
7219 "fix_guide(): Cannot correct reference href '",$href,
7220 "', spine is empty");
7221 }
7222 elsif (!$spine[0]->{href}) {
7223 $self->add_warning(
7224 "fix_guide(): Cannot correct reference href '",$href,
7225 "', cannot find href for first spine entry");
7226 }
7227 else {
7228 debug(1,"DEBUG: correcting reference href from '",$href,
7229 "' to '",$spine[0]->{href} . $href,"'");
7230 $el->set_att('href',$spine[0]->{href} . $href);
7231 }
7232 }
7233 debug(3,"DEBUG: processing reference '",$href,"')");
7234 $el->move('last_child',$guide);
7235 } # foreach my $el (@elements)
7236  
7237 return 1;
7238 }
7239  
7240  
7241 =head2 C<fix_languages(%args)>
7242  
7243 Checks through the <dc:language> elements (case-insensitive) and
7244 removes any duplicates. If no <dc:language> elements are found, one
7245 is created.
7246  
7247 TODO: Also convert language names to IANA language and region codes.
7248  
7249 =head3 Arguments
7250  
7251 =over
7252  
7253 =item * C<default>
7254  
7255 The default language string to use when creating a new language
7256 element. If not specified, defaults to 'en'.
7257  
7258 =back
7259  
7260 =cut
7261  
7262 sub fix_languages :method {
7263 my ($self,%args) = @_;
7264 my $subname = ( caller(0) )[3];
7265 croak($subname . "() called as a procedure") unless(ref $self);
7266 debug(2,"DEBUG[",$subname,"]");
7267 $self->twigcheck();
7268  
7269 my %valid_args = (
7270 'default' => 1,
7271 );
7272 foreach my $arg (keys %args) {
7273 croak($subname,"(): invalid argument '",$arg,"'")
7274 if(!$valid_args{$arg});
7275 }
7276  
7277 my $twigroot = $self->{twigroot};
7278 my $defaultlang = $args{default} || 'en';
7279 my $langel;
7280 my @elements = $twigroot->descendants(qr/dc:language/ix);
7281 while($langel = shift(@elements) ) {
7282 foreach my $el (@elements) {
7283 $el->delete if(twigelt_detect_duplicate($el,$langel) );
7284 }
7285 }
7286  
7287 @elements = $self->languages;
7288 if(!@elements) {
7289 $self->set_language(text => $defaultlang);
7290 }
7291 return 1;
7292 }
7293  
7294  
7295 =head2 C<fix_links()>
7296  
7297 Checks through the links in the manifest and checks them for anything
7298 they might link to, adding anything missing to the manifest.
7299  
7300 A warning is added for every manifest item missing a href.
7301  
7302 If no <manifest> element exists directly underneath the <package>
7303 root, or <manifest> contains no items, the method logs a warning and
7304 returns undef. Otherwise, it returns 1.
7305  
7306 =cut
7307  
7308 sub fix_links :method {
7309 my $self = shift;
7310 my $subname = ( caller(0) )[3];
7311 croak($subname . "() called as a procedure") unless(ref $self);
7312 debug(2,"DEBUG[",$subname,"]");
7313 $self->twigcheck();
7314  
7315 my $twigroot = $self->{twigroot};
7316  
7317 my $manifest = $twigroot->first_child('manifest');
7318 my @unchecked;
7319  
7320 # The %links hash points a href to one of three values:
7321 # * undef : the link has not been checked at all
7322 # * 0 : the link has been checked and is not reachable
7323 # * 1 : the link has been checked and exists
7324 my %links;
7325 my @newlinks;
7326 my $href;
7327 my $mimetype;
7328  
7329 my %linking_mimetypes = (
7330 'text/html' => 1,
7331 'text/xhtml' => 1,
7332 'text/xml' => 1,
7333 'text/x-oeb1-document' => 1,
7334 'application/atom+xml' => 1,
7335 'application/xhtml+xml' => 1,
7336 'application/xml' => 1
7337 );
7338  
7339 if(!$manifest) {
7340 $self->add_warning(
7341 "fix_links(): no manifest found!"
7342 );
7343 return;
7344 }
7345  
7346 @unchecked = $self->manifest_hrefs;
7347 if(!@unchecked) {
7348 $self->add_warning(
7349 "fix_links(): empty manifest found!"
7350 );
7351 return;
7352 }
7353  
7354 # Initialize %links, so we don't try to add something already in
7355 # the manifest
7356 foreach my $mhref (@unchecked) {
7357 $mhref = uri_unescape($mhref);
7358 $links{$mhref} = undef unless(exists $links{$mhref});
7359 }
7360  
7361 while(@unchecked) {
7362 debug(3,"DEBUG: ",scalar(@unchecked),
7363 " items left to check at start of loop");
7364 $href = shift(@unchecked);
7365 $href = trim($href);
7366 $href = uri_unescape($href);
7367 debug(3,"DEBUG: checking '",$href,"'");
7368 next if(defined $links{$href});
7369  
7370 # Skip mailto: and news: links
7371 if($href =~ m#(mailto|news):#ix) {
7372 debug(1,"DEBUG: mailto link '",$href,"' skipped");
7373 $links{$href} = 0;
7374 next;
7375 }
7376  
7377 # Skip URIs for now
7378 if($href =~ m#^ \w+://#ix) {
7379 debug(1,"DEBUG: URI '",$href,"' skipped");
7380 $links{href} = 0;
7381 next;
7382 }
7383 if(! -f $href) {
7384 $self->add_warning(
7385 "fix_links(): '" . $href . "' not found"
7386 );
7387 $links{$href} = 0;
7388 next;
7389 }
7390  
7391 $mimetype = mimetype($href);
7392  
7393 if(!$linking_mimetypes{$mimetype}) {
7394 debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,
7395 "' -- not checking");
7396 $links{$href} = 1;
7397 next;
7398 }
7399  
7400 debug(1,"DEBUG: finding links in '",$href,"'");
7401 @newlinks = find_links($href);
7402 trim(@newlinks) if(@newlinks);
7403 $links{$href} = 1;
7404 foreach my $newlink (sort @newlinks) {
7405 # Skip mailto: and news: links
7406 if($newlink =~ m#(mailto|news):#ix) {
7407 debug(1,"DEBUG: mailto link '",$href,"' skipped");
7408 next;
7409 }
7410 # Skip URIs for now
7411 elsif($newlink =~ m#^ \w+://#ix) {
7412 debug(1,"DEBUG: URI '",$newlink,"' skipped");
7413 next;
7414 }
7415 elsif(!exists $links{$newlink}) {
7416 debug(2,"DEBUG: adding '",$newlink,"' to the manifest");
7417 push(@unchecked,$newlink);
7418 $self->add_item($newlink);
7419 $links{$newlink} = 1;
7420 }
7421 }
7422 debug(2,"DEBUG: ",scalar(@unchecked),
7423 " items left to check at end of loop");
7424 } # while(@unchecked)
7425 debug(2,"DEBUG[/",$subname,"]");
7426 return 1;
7427 }
7428  
7429 =head2 C<fix_manifest()>
7430  
7431 Finds all <item> elements and moves them underneath <manifest>,
7432 creating <manifest> if necessary.
7433  
7434 Logs a warning but continues if it finds an <item> with a missing id
7435 or href attribute. If both id and href attributes are missing, logs a
7436 warning, skips moving the item entirely (unless it was already
7437 underneath <manifest>, in which case it is moved to preserve its sort
7438 order along all other items under <manifest>), but otherwise
7439 continues.
7440  
7441 =cut
7442  
7443 sub fix_manifest :method {
7444 my $self = shift;
7445 my $subname = ( caller(0) )[3];
7446 croak($subname . "() called as a procedure") unless(ref $self);
7447 debug(2,"DEBUG[",$subname,"]");
7448 $self->twigcheck();
7449  
7450 my $twigroot = $self->{twigroot};
7451  
7452 my $spec = $self->spec || '';
7453 my $manifest = $twigroot->first_descendant('manifest');
7454 my @elements;
7455 my @extras;
7456 my $parent;
7457  
7458 my $href;
7459 my $id;
7460 my $type;
7461  
7462 # If <manifest> doesn't exist, create it
7463 if(! $manifest) {
7464 debug(1,"DEBUG: creating <manifest>");
7465 $manifest = $twigroot->insert_new_elt('last_child','manifest');
7466 }
7467  
7468 # Make sure that the manifest is the first child of the twigroot,
7469 # which should be <package>
7470 $parent = $manifest->parent;
7471 if($parent != $twigroot) {
7472 debug(1,"DEBUG: moving <manifest>");
7473 $manifest->move('first_child',$twigroot);
7474 }
7475  
7476 # Find and merge any other manifests
7477 @extras = $twigroot->descendants('manifest');
7478 shift @extras;
7479 foreach my $extra (@extras) {
7480 my @elements = $extra->children;
7481 foreach my $el (@elements) {
7482 debug(2,"DEBUG: moving <",$el->gi,"> into primary manifest");
7483 $el->move('last_child',$manifest);
7484 }
7485 $extra->delete;
7486 }
7487  
7488 @elements = $twigroot->descendants(qr/^item$/ix);
7489 foreach my $el (@elements) {
7490 $href = $el->att('href');
7491 $id = $el->id;
7492 $type = $el->att('media-type');
7493  
7494 # Convert to OPF2.0 document types if necessary
7495 if($spec eq 'OPF20') {
7496 if($type eq "text/x-oeb1-document") {
7497 $type = "application/xhtml+xml";
7498 $el->set_att('media-type',$type);
7499 }
7500 if($id eq 'ncx') {
7501 $type = 'application/x-dtbncx+xml';
7502 $el->set_att('media-type',$type);
7503 }
7504  
7505 }
7506  
7507 if(!$id) {
7508 if(!$href) {
7509 # No ID, no href, there's something very fishy here,
7510 # so log a warning.
7511 # If it is already underneath <manifest>, move it to
7512 # preserve sort order, but otherwise leave it alone
7513 $self->add_warning(
7514 "fix_manifest(): found item with no id or href"
7515 );
7516 debug(1,"fix_manifest(): found item with no id or href");
7517 if($el->parent == $manifest) {
7518 $el->move('last_child',$manifest);
7519 }
7520 else {
7521 print "DEBUG: skipping item with no id or href\n"
7522 if($debug);
7523 }
7524 next;
7525 } # if(!$href)
7526 # We have a href, but no ID. Log a warning, but move it anyway.
7527 $self->add_warning(
7528 'fix_manifest(): handling item with no ID! '
7529 . sprintf "(href='%s')",$href
7530 );
7531 debug(1,"DEBUG: processing item with no id (href='",$href,"')");
7532 $el->move('last_child',$manifest);
7533 } # if(!$id)
7534 if(!$href) {
7535 # We have an ID, but no href. Log a warning, but move it anyway.
7536 $self->add_warning(
7537 "fix_manifest(): item with id '" . $id . "' has no href!"
7538 );
7539 debug(1,"fix_manifest(): item with id '",$id,"' has no href!");
7540 $el->move('last_child',$manifest);
7541 }
7542 else {
7543 # We have an ID and a href
7544 debug(3,"DEBUG: processing item '",$id,"' (href='",$href,"')");
7545 $el->move('last_child',$manifest);
7546 }
7547 }
7548 return 1;
7549 }
7550  
7551 =head2 C<fix_metastructure_basic()>
7552  
7553 Verifies that <metadata> exists (creating it if necessary), and moves
7554 it to be the first child of <package>. If additional <metadata>
7555 elements exist, their children are moved into the first one found and
7556 then the extras are deleted.
7557  
7558 Used in L</fix_metastructure_oeb12()>, L</fix_packageid()>, and
7559 L</set_primary_author(%args)>.
7560  
7561 =cut
7562  
7563 sub fix_metastructure_basic :method {
7564 my $self = shift;
7565 my $subname = ( caller(0) )[3];
7566 croak($subname . "() called as a procedure") unless(ref $self);
7567 debug(3,"DEBUG[",$subname,"]");
7568 $self->twigcheck();
7569  
7570 my $twigroot = $self->{twigroot};
7571 my $metadata = $twigroot->first_descendant('metadata');
7572  
7573 my @extras = $twigroot->descendants('metadata');
7574 shift @extras;
7575  
7576 if(! $metadata) {
7577 debug(1,"DEBUG: creating <metadata>");
7578 $metadata = $twigroot->insert_new_elt('first_child','metadata');
7579 }
7580  
7581 foreach my $extra (@extras) {
7582 my @elements = $extra->children;
7583 foreach my $el (@elements) {
7584 debug(2,"DEBUG: moving <",$el->gi,"> into primary metadata");
7585 $el->move('last_child',$metadata);
7586 }
7587 $extra->delete;
7588 }
7589 debug(3,"DEBUG: moving <metadata> to be the first child of <package>");
7590 $metadata->move('first_child',$twigroot);
7591  
7592 if($metadata->att('xmlns:calibre')) {
7593 # xmlns:calibre isn't a real namespace; it's just there for
7594 # advertising, so remove it
7595 $metadata->del_att('xmlns:calibre');
7596 }
7597 return 1;
7598 }
7599  
7600  
7601 =head2 C<fix_metastructure_oeb12()>
7602  
7603 Verifies the existence of <metadata>, <dc-metadata>, and <x-metadata>,
7604 creating them as needed, and making sure that <metadata> is a child of
7605 <package>, while <dc-metadata> and <x-metadata> are children of
7606 <metadata>.
7607  
7608 Used in L</fix_oeb12()> and L</fix_mobi()>.
7609  
7610 =cut
7611  
7612 sub fix_metastructure_oeb12 :method {
7613 my $self = shift;
7614 my $subname = ( caller(0) )[3];
7615 croak($subname . "() called as a procedure") unless(ref $self);
7616 debug(3,"DEBUG[",$subname,"]");
7617 $self->twigcheck();
7618  
7619 my $twigroot = $self->{twigroot};
7620  
7621 my $metadata;
7622 my $dcmeta;
7623 my $xmeta;
7624 my $parent;
7625  
7626 # Start by forcing the basic <package><metadata> structure
7627 $self->fix_metastructure_basic;
7628 $metadata = $twigroot->first_child('metadata');
7629  
7630 # If <dc-metadata> doesn't exist, we'll have to create it.
7631 $dcmeta = $twigroot->first_descendant('dc-metadata');
7632 if(! $dcmeta) {
7633 debug(2,"DEBUG: creating <dc-metadata>");
7634 $dcmeta = $metadata->insert_new_elt('first_child','dc-metadata');
7635 }
7636  
7637 # Make sure that $dcmeta is a child of $metadata
7638 $parent = $dcmeta->parent;
7639 if($parent != $metadata) {
7640 debug(2,"DEBUG: moving <dc-metadata>");
7641 $dcmeta->move('first_child',$metadata);
7642 }
7643  
7644 # If <x-metadata> doesn't exist, create it
7645 $xmeta = $metadata->first_descendant('x-metadata');
7646 if(! $xmeta) {
7647 debug(2,"DEBUG: creating <x-metadata>");
7648 $xmeta = $metadata->insert_new_elt('last_child','x-metadata');
7649 }
7650  
7651 # Make sure that x-metadata is a child of metadata
7652 $parent = $xmeta->parent;
7653 if($parent != $metadata) {
7654 debug(2,"DEBUG: moving <x-metadata>");
7655 $xmeta->move('after',$dcmeta);
7656 }
7657 return 1;
7658 }
7659  
7660  
7661 =head2 C<fix_misc()>
7662  
7663 Fixes miscellaneous potential problems in OPF data. Specifically,
7664 this is a shortcut to calling L</delete_meta_filepos()>,
7665 L</fix_packageid()>, L</fix_dates()>, L</fix_languages()>,
7666 L</fix_publisher()>, L</fix_manifest()>, L</fix_spine()>,
7667 L</fix_subjects()>, L</fix_type()>, L</fix_guide()>, and
7668 L</fix_links()>.
7669  
7670 L</fix_creators()> is not run from this, as it carries a risk of taking
7671 a correct name and making it incorrect.
7672  
7673 The objective here is that you can run either C<fix_misc()> and either
7674 L</fix_oeb12()> or L</fix_opf20()> and a perfectly valid OPF file will
7675 result from only two calls.
7676  
7677 =cut
7678  
7679 sub fix_misc :method {
7680 my $self = shift;
7681 my $subname = ( caller(0) )[3];
7682 croak($subname . "() called as a procedure") unless(ref $self);
7683 debug(2,"DEBUG[",$subname,"]");
7684 $self->twigcheck();
7685  
7686 $self->delete_meta_filepos();
7687 $self->fix_packageid();
7688 $self->fix_dates();
7689 $self->fix_languages();
7690 $self->fix_publisher();
7691 $self->fix_manifest();
7692 $self->fix_spine();
7693 $self->fix_subjects();
7694 $self->fix_type();
7695 $self->fix_guide();
7696 $self->fix_links();
7697  
7698 debug(2,"DEBUG[/",$subname,"]");
7699 return 1;
7700 }
7701  
7702  
7703 =head2 C<fix_mobi()>
7704  
7705 Manipulates the twig to fix Mobipocket-specific issues
7706  
7707 =over
7708  
7709 =item * Force the OEB 1.2 structure (although not the namespace, DTD,
7710 or capitalization), so that <dc-metadata> and <x-metadata> are
7711 guaranteed to exist.
7712  
7713 =item * Find and move all Mobi-specific elements to <x-metadata>
7714  
7715 =item * If no <output> element exists, creates one for a utf-8 ebook
7716  
7717 =back
7718  
7719 Note that the forced creation of <output> will cause the OPF file to
7720 become noncompliant with IDPF specifications.
7721  
7722 =cut
7723  
7724 sub fix_mobi :method {
7725 my $self = shift;
7726 my $subname = ( caller(0) )[3];
7727 croak($subname . "() called as a procedure") unless(ref $self);
7728 debug(2,"DEBUG[",$subname,"]");
7729 $self->twigcheck();
7730  
7731 my $twigroot = $self->{twigroot};
7732  
7733 my %mobicontenttypes = (
7734 'text/x-oeb1-document' => 'text/x-oeb1-document',
7735 'application/x-mobipocket-subscription'
7736 => 'application/x-mobipocket-subscription',
7737 'application/x-mobipocket-subscription-feed'
7738 => 'application/x-mobipocket-subscription-feed',
7739 'application/x-mobipocket-subscription-magazine'
7740 => 'application/x-mobipocket-subscription-magazine',
7741 'image/gif' => 'image/gif',
7742 'application/msword' => 'application/msword',
7743 'application/vnd.ms-excel' => 'application/vnd.ms-excel',
7744 'application/vnd.ms-powerpoint' => 'application/vnd.ms-powerpoint',
7745 'text/plain' => 'text/plain',
7746 'text/html' => 'text/html',
7747 'application/vnd.mobipocket-game' => 'application/vnd.mobipocket-game',
7748 'application/vnd.mobipocket-franklin-ua-game'
7749 => 'application/vnd.mobipocket-franklin-ua-game'
7750 );
7751  
7752 my %mobiencodings = (
7753 'Windows-1252' => 'Windows-1252',
7754 'utf-8' => 'utf-8'
7755 );
7756  
7757 my @mobitags = (
7758 'output',
7759 'Adult',
7760 'Demo',
7761 'DefaultLookupIndex',
7762 'DictionaryInLanguage',
7763 'DictionaryOutLanguage',
7764 'DictionaryVeryShortName',
7765 'DatabaseName',
7766 'EmbeddedCover',
7767 'Review',
7768 'SRP',
7769 'Territory'
7770 );
7771  
7772 my $dcmeta;
7773 my $xmeta;
7774 my @elements;
7775 my $output;
7776  
7777  
7778 # Mobipocket currently requires that its custom elements be found
7779 # underneath <x-metadata>. Since the presence of <x-metadata>
7780 # requires that the Dublin Core tags be under <dc-metadata>, we
7781 # have to use at least the OEB1.2 structure (deprecated, but still
7782 # allowed in OPF2.0), though we don't have to convert everything.
7783 $self->fix_metastructure_oeb12();
7784 $dcmeta = $twigroot->first_descendant('dc-metadata');
7785 $xmeta = $twigroot->first_descendant('x-metadata');
7786  
7787 # If <x-metadata> doesn't exist, create it. Even if there are no
7788 # mobi-specific tags, this method will create at least one
7789 # (<output>) which will need it.
7790 if(!$xmeta) {
7791 debug(2,"DEBUG: creating <x-metadata>");
7792 $xmeta = $dcmeta->insert_new_elt('after','x-metadata')
7793 }
7794  
7795 foreach my $tag (@mobitags) {
7796 @elements = $twigroot->descendants($tag);
7797 next unless (@elements);
7798  
7799 # In theory, only one Mobipocket-specific element should ever
7800 # be present in a document. We'll deal with multiples anyway,
7801 # but send a warning.
7802 if(scalar(@elements) > 1) {
7803 $self->add_warning(
7804 'fix_mobi(): Found ' . scalar(@elements) . " '" . $tag .
7805 "' elements, but only one should exist."
7806 );
7807 }
7808  
7809 foreach my $el (@elements) {
7810 $el->move('last_child',$xmeta);
7811 }
7812 }
7813  
7814 $output = $xmeta->first_child('output');
7815 if($output) {
7816 my $encoding = $mobiencodings{$output->att('encoding')};
7817 my $contenttype = $mobicontenttypes{$output->att('content-type')};
7818  
7819 if($contenttype) {
7820 $output->set_att('encoding','utf-8') if(!$encoding);
7821 debug(2,"DEBUG: setting encoding only and returning");
7822 return 1;
7823 }
7824 }
7825 else {
7826 debug(1,"DEBUG: creating <output> under <x-metadata>");
7827 $output = $xmeta->insert_new_elt('last_child','output');
7828 }
7829  
7830  
7831 # At this stage, we definitely have <output> in the right place.
7832 # Set the attributes and return.
7833 $output->set_att('encoding' => 'utf-8',
7834 'content-type' => 'text/x-oeb1-document');
7835 debug(2,"DEBUG[/",$subname,"]");
7836 return 1;
7837 }
7838  
7839  
7840 =head2 C<fix_oeb12()>
7841  
7842 Modifies the OPF data to conform to the OEB 1.2 standard
7843  
7844 Specifically, this involves:
7845  
7846 =over
7847  
7848 =item * adding the OEB 1.2 doctype
7849  
7850 =item * removing OPF 2.0 version and namespace attributes
7851  
7852 =item * setting the OEB 1.2 namespace on <package>
7853  
7854 =item * moving all of the dc-metadata elements underneath an element
7855 with tag <dc-metadata>, which itself is forced to be underneath
7856 <metadata>, which is created if it doesn't exist.
7857  
7858 =item * moving any remaining tags underneath <x-metadata>, again
7859 forced to be under <metadata>
7860  
7861 =item * making the dc-metadata tags conform to the OEB v1.2 capitalization
7862  
7863 =back
7864  
7865 =cut
7866  
7867 sub fix_oeb12 :method {
7868 my $self = shift;
7869 my $subname = ( caller(0) )[3];
7870 croak($subname . "() called as a procedure") unless(ref $self);
7871 debug(2,"DEBUG[",$subname,"]");
7872 $self->twigcheck();
7873  
7874 my $twigroot = $self->{twigroot};
7875 my $metadata;
7876 my $dcmeta;
7877 my $xmeta;
7878 my @elements;
7879  
7880 # Verify and correct locations for <metadata>, <dc-metadata>, and
7881 # <x-metadata>, creating them as needed.
7882 $self->fix_metastructure_oeb12;
7883 $metadata = $twigroot->first_descendant('metadata');
7884 $dcmeta = $metadata->first_descendant('dc-metadata');
7885 $xmeta = $metadata->first_descendant('x-metadata');
7886  
7887 # Clobber metadata attributes 'xmlns:dc' and 'xmlns:opf'
7888 # used only in OPF2.0
7889 $metadata->del_atts('xmlns:dc','xmlns:opf');
7890  
7891 # Assign the DC namespace attribute to dc-metadata for OEB 1.2
7892 $dcmeta->set_att('xmlns:dc',"http://purl.org/dc/elements/1.1/");
7893  
7894 # Set the correct tag name and move it into <dc-metadata> in the
7895 # right order
7896 foreach my $dcel (keys %dcelements12) {
7897 @elements = $twigroot->descendants(qr/^$dcel$/ix);
7898 foreach my $el (@elements) {
7899 debug(3,"DEBUG: processing '",$el->gi,"'");
7900 croak("Found invalid DC element '",$el->gi,"'!")
7901 if(!$dcelements12{lc $el->gi});
7902 $el->set_gi($dcelements12{lc $el->gi});
7903 $el = twigelt_fix_oeb12_atts($el);
7904 $el->move('last_child',$dcmeta);
7905 }
7906 }
7907  
7908 # Handle non-DC metadata, deleting <x-metadata> if it isn't
7909 # needed.
7910 @elements = $metadata->children(qr/^(?!(?s:.*)-metadata)/x);
7911 if(@elements) {
7912 if($debug) {
7913 print {*STDERR} "DEBUG: extra metadata elements found: ";
7914 foreach my $el (@elements) { print {*STDERR} $el->gi," "; }
7915 print {*STDERR} "\n";
7916 }
7917 foreach my $el (@elements) {
7918 $el->move('last_child',$xmeta);
7919 }
7920 }
7921 @elements = $twigroot->children(qr/^meta$/ix);
7922 foreach my $el (@elements) {
7923 $el->set_gi(lc $el->gi);
7924 $el->move('last_child',$xmeta);
7925 }
7926 @elements = $xmeta->children;
7927 $xmeta->delete unless(@elements);
7928  
7929 # Delete Calibre advertisements in dc:Contributor elements
7930 @elements = $twigroot->descendants('dc:Contributor[string() =~ /calibre-ebook.com|calibre.kovidgoyal.net/]');
7931 foreach my $el (@elements) {
7932 $el->delete;
7933 }
7934  
7935 # Fix <manifest> and <spine>
7936 $self->fix_manifest;
7937 $self->fix_spine;
7938  
7939 # Set the OEB 1.2 doctype
7940 $self->{twig}->set_doctype('package',
7941 "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd",
7942 "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN");
7943  
7944 # Clean up <package>
7945 $twigroot->del_att('version');
7946 $twigroot->set_att(
7947 'xmlns' => 'http://openebook.org/namespaces/oeb-package/1.0/');
7948 $self->fix_packageid;
7949  
7950 $self->{spec} = $validspecs{'OEB12'};
7951 debug(2,"DEBUG[/",$subname,"]");
7952 return 1;
7953 }
7954  
7955  
7956 =head2 C<fix_oeb12_dcmetatags()>
7957  
7958 Makes a case-insensitive search for tags matching a known list of DC
7959 metadata elements and corrects the capitalization to the OEB 1.2
7960 standard. Also corrects 'dc:Copyrights' to 'dc:Rights'. See global
7961 variable $dcelements12.
7962  
7963 The L</fix_oeb12()> method does this also, but fix_oeb12_dcmetatags()
7964 is usable separately for the case where you want DC metadata elements
7965 with consistent tag names, but don't want them moved from wherever
7966 they are.
7967  
7968 =cut
7969  
7970 sub fix_oeb12_dcmetatags :method {
7971 my $self = shift;
7972 my $subname = ( caller(0) )[3];
7973 croak($subname . "() called as a procedure") unless(ref $self);
7974 debug(2,"DEBUG[",$subname,"]");
7975 $self->twigcheck();
7976  
7977 my $topelement = $self->{twigroot};
7978  
7979 my @elements;
7980  
7981 foreach my $dcmetatag (keys %dcelements12) {
7982 @elements = $topelement->descendants(qr/^$dcmetatag$/ix);
7983 foreach my $el (@elements) {
7984 $el->set_tag($dcelements12{lc $el->tag})
7985 if($dcelements12{lc $el->tag});
7986 }
7987 }
7988 return 1;
7989 }
7990  
7991  
7992 =head2 C<fix_opf20()>
7993  
7994 Modifies the OPF data to conform to the OPF 2.0 standard
7995  
7996 Specifically, this involves:
7997  
7998 =over
7999  
8000 =item * moving all of the dc-metadata and x-metadata elements directly
8001 underneath <metadata>
8002  
8003 =item * removing the <dc-metadata> and <x-metadata> elements themselves
8004  
8005 =item * lowercasing the dc-metadata tags (and fixing dc:copyrights to
8006 dc:rights)
8007  
8008 =item * setting namespaces on dc-metata OPF attributes
8009  
8010 =item * setting version and xmlns attributes on <package>
8011  
8012 =item * setting xmlns:dc and xmlns:opf on <metadata>
8013  
8014 =back
8015  
8016 =cut
8017  
8018 sub fix_opf20 :method {
8019 my $self = shift;
8020 my $subname = ( caller(0) )[3];
8021 croak($subname . "() called as a procedure") unless(ref $self);
8022 debug(2,"DEBUG[",$subname,"]");
8023 $self->twigcheck();
8024  
8025 # Ensure a sane structure
8026 $self->fix_metastructure_basic();
8027  
8028 # If there is an existing cover image, ensure it hits all standards
8029 my $coverimage = $self->coverimage;
8030 $self->set_cover('href' => $coverimage) if $coverimage;
8031  
8032 my $twigroot = $self->{twigroot};
8033 my $metadata = $twigroot->first_descendant('metadata');
8034 my @elements;
8035  
8036 # If <dc-metadata> exists, make sure that it is directly
8037 # underneath <metadata> so that its children will collapse to the
8038 # correct position, then erase it.
8039 @elements = $twigroot->descendants('dc-metadata');
8040 if(@elements) {
8041 foreach my $dcmeta (@elements) {
8042 debug(1,"DEBUG: moving <dc-metadata>");
8043 $dcmeta->move('first_child',$metadata);
8044 $dcmeta->erase;
8045 }
8046 }
8047  
8048 # If <x-metadata> exists, make sure that it is directly underneath
8049 # <metadata> so that its children will collapse to the correct
8050 # position, then erase it.
8051 @elements = $twigroot->descendants('x-metadata');
8052 if(@elements) {
8053 foreach my $xmeta (@elements) {
8054 debug(1,"DEBUG: moving <x-metadata>");
8055 $xmeta->move('last_child',$metadata);
8056 $xmeta->erase;
8057 }
8058 }
8059  
8060 # Delete any old OEB12 output elements
8061 @elements = $twigroot->descendants('output');
8062 foreach my $el (@elements) {
8063 $el->delete;
8064 }
8065  
8066 # For all DC elements at any location, set the correct tag name
8067 # and attribute namespace and move it directly under <metadata>
8068 foreach my $dcmetatag (keys %dcelements20) {
8069 @elements = $twigroot->descendants(qr/$dcmetatag/ix);
8070 foreach my $el (@elements) {
8071 debug(2,"DEBUG: checking DC element <",$el->gi,">");
8072 $el->set_gi($dcelements20{$dcmetatag});
8073 $el = twigelt_fix_opf20_atts($el);
8074 $el->move('last_child',$metadata);
8075 }
8076 }
8077  
8078 # Find any <meta> elements anywhere in the package and move them
8079 # under <metadata>. Force the tag to lowercase.
8080  
8081 @elements = $twigroot->descendants(qr/^meta$/ix);
8082 foreach my $el (@elements) {
8083 debug(2,'DEBUG: checking meta element <',$el->gi,
8084 ' name="',$el->att('name'),'">');
8085 $el->set_gi(lc $el->gi);
8086 $el->move('last_child',$metadata);
8087 }
8088  
8089 # Delete Calibre advertisements in dc:contributor elements
8090 @elements = $twigroot->descendants('dc:contributor[string() =~ /calibre-ebook.com|calibre.kovidgoyal.net/]');
8091 foreach my $el (@elements) {
8092 $el->delete;
8093 }
8094 # Delete Aspose.Words advertisements in dc:contributor elements
8095 @elements = $twigroot->descendants('dc:contributor[string() =~ /Aspose.Words/]');
8096 foreach my $el (@elements) {
8097 $el->delete;
8098 }
8099  
8100 # Fix the <package> attributes
8101 $twigroot->set_att('version' => '2.0',
8102 'xmlns' => 'http://www.idpf.org/2007/opf');
8103 $self->fix_packageid;
8104  
8105 # Fix the <metadata> attributes
8106 $metadata->set_att('xmlns:dc' => "http://purl.org/dc/elements/1.1/",
8107 'xmlns:opf' => "http://www.idpf.org/2007/opf",
8108 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance");
8109  
8110 # Fix <manifest> and <spine>
8111 $self->fix_manifest;
8112 $self->fix_spine;
8113  
8114 # Clobber the doctype, if present
8115 $self->{twig}->set_doctype(0,0,0,0);
8116  
8117 # Set the specification
8118 $self->{spec} = $validspecs{'OPF20'};
8119  
8120 debug(2,"DEBUG[/",$subname,"]");
8121 return 1;
8122 }
8123  
8124  
8125 =head2 C<fix_opf20_dcmetatags()>
8126  
8127 Makes a case-insensitive search for tags matching a known list of DC
8128 metadata elements and corrects the capitalization to the OPF 2.0
8129 standard. Also corrects 'dc:copyrights' to 'dc:rights'. See package
8130 variable %dcelements20.
8131  
8132 The L</fix_opf20()> method does this also, but
8133 C<fix_opf20_dcmetatags()> is usable separately for the case where you
8134 want DC metadata elements with consistent tag names, but don't want
8135 them moved from wherever they are.
8136  
8137 =cut
8138  
8139 sub fix_opf20_dcmetatags :method {
8140 my $self = shift;
8141 my $subname = ( caller(0) )[3];
8142 croak($subname . "() called as a procedure") unless(ref $self);
8143 debug(2,"DEBUG[",$subname,"]");
8144 $self->twigcheck();
8145  
8146 my $topelement = $self->{twigroot};
8147 my @elements;
8148  
8149 foreach my $dcmetatag (keys %dcelements20) {
8150 @elements = $topelement->descendants(qr/^$dcmetatag$/ix);
8151 foreach my $el (@elements) {
8152 $el->set_tag($dcelements20{lc $el->tag})
8153 if($dcelements20{lc $el->tag});
8154 }
8155 }
8156 return;
8157 }
8158  
8159  
8160 =head2 C<fix_packageid()>
8161  
8162 Checks the <package> element for the attribute 'unique-identifier',
8163 makes sure that it is mapped to a valid dc:identifier subelement, and
8164 if not, searches those subelements for an identifier to assign, or
8165 creates one if nothing can be found.
8166  
8167 Requires that <metadata> exist. Croaks if it doesn't. Run
8168 L</fix_oeb12()> or L</fix_opf20()> before calling this if the input
8169 might be very broken.
8170  
8171 =cut
8172  
8173 sub fix_packageid :method {
8174 my $self = shift;
8175 my $subname = ( caller(0) )[3];
8176 croak($subname . "() called as a procedure") unless(ref $self);
8177 debug(2,"DEBUG[",$subname,"]");
8178 $self->twigcheck();
8179  
8180 # Start by enforcing the basic structure needed
8181 $self->fix_metastructure_basic();
8182 my $twigroot = $self->{twigroot};
8183 my $packageid = $twigroot->att('unique-identifier');
8184  
8185 my $meta = $twigroot->first_child('metadata')
8186 or croak($subname,"(): metadata not found");
8187 my $element;
8188  
8189 if($packageid) {
8190 # Check that the ID maps to a valid identifier
8191 # If not, undefine it
8192 debug(2,"DEBUG: checking existing packageid '",$packageid,"'");
8193  
8194 # The twig ID handling system is unreliable, especially when
8195 # multiple twigs may be existing simultaneously. Use
8196 # XML::Twig->first_elt instead of XML::Twig->elt_id, even
8197 # though it is slower.
8198 #
8199 # As of Twig 3.32, this will cause 'uninitialized value'
8200 # warnings to be spewed for each time no descendants are
8201 # found.
8202 #$element = $self->{twig}->elt_id($packageid);
8203 $element = $self->{twig}->first_elt("*[\@id='$packageid']");
8204  
8205 if($element) {
8206 if(lc($element->tag) ne 'dc:identifier') {
8207 debug(1,"DEBUG: packageid '",$packageid,
8208 "' points to a non-identifier element ('",
8209 $element->tag,"')");
8210 debug(1,"DEBUG: undefining existing packageid '",
8211 $packageid,"'");
8212 undef($packageid);
8213 }
8214 elsif(!$element->text) {
8215 debug(1,"DEBUG: packageid '",$packageid,
8216 "' points to an empty identifier.");
8217 debug(1,"DEBUG: undefining existing packageid '",
8218 $packageid,"'");
8219 undef($packageid);
8220 }
8221 }
8222 else { undef($packageid); };
8223 }
8224  
8225 if(!$packageid) {
8226 # Search known IDs for a unique Package ID
8227 $packageid = $self->search_knownuids;
8228 }
8229  
8230 # If no unique ID found so far, start searching known schemes
8231 if(!$packageid) {
8232 $packageid = $self->search_knownuidschemes;
8233 }
8234  
8235 # And if we still don't have anything, we have to make one from
8236 # scratch using Data::UUID
8237 if(!$packageid) {
8238 debug(1,"DEBUG: creating new UUID");
8239 $element = twigelt_create_uuid();
8240 $element->paste('first_child',$meta);
8241 $packageid = 'UUID';
8242 }
8243  
8244 # At this point, we have a unique ID. Assign it to package
8245 $twigroot->set_att('unique-identifier',$packageid);
8246 debug(2,"[/",$subname,"]");
8247 return 1;
8248 }
8249  
8250  
8251 =head2 C<fix_publisher()>
8252  
8253 Standardizes publisher names in all dc:publisher entities, mapping
8254 known variants of a publisher's name to a canonical form via package
8255 variable %publishermap.
8256  
8257 Publisher entries with no text are deleted.
8258  
8259 =cut
8260  
8261 sub fix_publisher :method {
8262 my $self = shift;
8263 my $subname = ( caller(0) )[3];
8264 croak($subname . "() called as a procedure") unless(ref $self);
8265 debug(2,"DEBUG[",$subname,"]");
8266 $self->twigcheck();
8267  
8268 my @publishers = $self->twigroot->descendants(qr/^dc:publisher$/ix);
8269 foreach my $pub (@publishers) {
8270 debug(3,"Examining publisher entry in element '",$pub->gi,"'");
8271 if(!$pub->text) {
8272 debug(1,'Deleting empty publisher entry');
8273 $pub->delete;
8274 next;
8275 }
8276 elsif( $publishermap{lc $pub->text} &&
8277 ($publishermap{lc $pub->text} ne $pub->text) )
8278 {
8279 debug(1,"DEBUG: Changing publisher from '",$pub->text,"' to '",
8280 $publishermap{lc $pub->text},"'");
8281 $pub->set_text($publishermap{lc $pub->text});
8282 }
8283 }
8284 return 1;
8285 }
8286  
8287  
8288 =head2 C<fix_spine()>
8289  
8290 Fixes problems with the OPF spine, specifically:
8291  
8292 =over
8293  
8294 =item Moves all <itemref> elements underneath <spine>, creating
8295 <spine> if necessary.
8296  
8297 =back
8298  
8299 =cut
8300  
8301 sub fix_spine :method {
8302 my $self = shift;
8303 my $subname = ( caller(0) )[3];
8304 croak($subname . "() called as a procedure") unless(ref $self);
8305 debug(2,"DEBUG[",$subname,"]");
8306 $self->twigcheck();
8307  
8308 my $twigroot = $self->{twigroot};
8309 my $manifest = $twigroot->first_descendant('manifest');
8310 my $spine = $twigroot->first_descendant('spine');
8311 my @elements;
8312 my $parent;
8313  
8314 @elements = $twigroot->descendants(qr/^itemref$/ix);
8315 if(@elements) {
8316 # If <spine> doesn't exist, create it
8317 if(! $spine) {
8318 debug(1,"DEBUG: creating <spine>");
8319 $spine = $twigroot->insert_new_elt('last_child','spine');
8320 }
8321  
8322 # Make sure that the spine is a child of the twigroot,
8323 $parent = $spine->parent;
8324 if($parent != $twigroot) {
8325 debug(1,"DEBUG: moving <spine>");
8326 $spine->move('last_child',$twigroot);
8327 }
8328  
8329 # If an NCX item exists in the manifest, reference it as a
8330 # spine attribute
8331 if($manifest->has_child('@id="ncx"')) {
8332 $spine->set_att('toc' => 'ncx');
8333 }
8334  
8335 foreach my $el (@elements) {
8336 if(!$el->att('idref')) {
8337 # No idref means it is broken.
8338 # Leave it alone, but log a warning
8339 $self->add_warning(
8340 "fix_spine(): <itemref> with no idref -- skipping");
8341 next;
8342 }
8343 debug(3,"DEBUG: processing itemref '",$el->att('idref'),"')");
8344 $el->move('last_child',$spine);
8345 }
8346 }
8347 else {
8348 # No elements, delete spine if it exists
8349 $spine->delete if($spine);
8350 }
8351  
8352 return 1;
8353 }
8354  
8355  
8356 =head2 C<fix_subjects()>
8357  
8358 Deletes empty and duplicate subject elements and normalizes existing
8359 subject text against the known Library of Congress mappings.
8360  
8361 If $self->{erotic} is true, then the book will be treated as a
8362 work of erotic fiction and the subjects will go through preprocessing
8363 against the C<%sexcodes> package variable, normalizing matches and
8364 prepending 'FICTION / Erotica / ' (with a trailing space).
8365  
8366 This method is called as a component of C<fix_misc()>.
8367  
8368 =cut
8369  
8370 sub fix_subjects :method {
8371 my ($self) = @_;
8372 my $subname = ( caller(0) )[3];
8373 croak($subname . "() called as a procedure") unless(ref $self);
8374 debug(2,"DEBUG[",$subname,"]");
8375 $self->twigcheck();
8376  
8377 my $eroticaprefix = 'FICTION / Erotica / ';
8378  
8379 my $twigroot = $self->{twigroot};
8380 my $manifest = $twigroot->first_descendant('manifest');
8381 my $bisac;
8382 my $newsubject;
8383 my $text;
8384 my $newtext;
8385  
8386 $self->delete_subject('text' => '');
8387 my @elements = $self->{twigroot}->descendants(qr/^dc:subject$/ix);
8388 my %subjects_seen;
8389 foreach my $el (@elements) {
8390 # Matches to the list are done after stripping leading and
8391 # trailing whitespace, trailing periods, and removing
8392 # whitespace around '--', then converting ' - ' to '--' and
8393 # decoding entities.
8394 $text = trim $el->text;
8395 $text =~ s|\.\z||x;
8396 $text =~ s|\s* -- \s*|--|gx;
8397 $text =~ s|\s* - \s*|--|gx;
8398 $text =~ s|\s*—\s*|--|gx;
8399 # We can't normalize spaces around slashes -- they have
8400 # potentially distinct meanings
8401 #$text =~ s|\s* / \s*|/|gx;
8402 $text = decode_entities($text);
8403  
8404 # Sex code matches are case-sensitive
8405 if($self->{erotic}) {
8406 if($sexcodes{$text}) {
8407 $newtext = $eroticaprefix . $sexcodes{$text};
8408 debug(1,"DEBUG: normalizing ${text} to " . $newtext);
8409 if($subjects_seen{$newtext}) {
8410 $el->delete;
8411 }
8412 else {
8413 $el->set_text($newtext);
8414 $subjects_seen{$newtext} = 1;
8415 }
8416 }
8417 }
8418  
8419 # ... but all other normalizations are not.
8420 $text = lc $text;
8421 debug(1,"DEBUG: normalizing subject '",$text,"'");
8422  
8423 # TODO: check for BISACCODE property, convert it to both a
8424 # BISAC descriptor and a LoC subject, then remove it.
8425 if($el->att('BASICCode')) {
8426 $newsubject = $self->add_subject(text => $el->att('BASICCode'));
8427 $el->del_att('BASICCode');
8428 push(@elements,$newsubject);
8429 }
8430 if($bisacsubjects{$text}) {
8431 debug(1,"DEBUG: found BISAC: ",$text);
8432 $bisac = $bisacsubjects{$text};
8433 if($subjects_seen{$bisac}) {
8434 $el->delete;
8435 }
8436 else {
8437 $el->set_text($bisac);
8438 $subjects_seen{$bisac} = 1;
8439 }
8440 }
8441  
8442 # TODO: check for a BISAC code or descriptor in attribute as
8443 # well as text, normalize it to standard descriptor format, as
8444 # well as inserting an additional matching LoC subject if
8445 # present
8446 if($bisactolc{$text}) {
8447 $bisac = $bisactolc{$text};
8448 if(! $subjects_seen{$bisac}) {
8449 $self->add_subject(text => $bisac);
8450 }
8451 }
8452 elsif($lcsubjects{$text}) {
8453 $text = $lcsubjects{$text};
8454 $el->set_text($text);
8455 }
8456  
8457 if($subjects_seen{$text}) {
8458 $el->delete;
8459 }
8460 else {
8461 $subjects_seen{$text} = 1;
8462 }
8463 }
8464 return;
8465 }
8466  
8467  
8468 =head2 C<fix_type()>
8469  
8470 Normalizes <dc:type> elements against a limited list based on book types listed in Wikipedia.
8471  
8472 =cut
8473  
8474 sub fix_type :method {
8475 my ($self) = @_;
8476 my $subname = ( caller(0) )[3];
8477 croak($subname . "() called as a procedure") unless(ref $self);
8478 debug(2,"DEBUG[",$subname,"]");
8479 $self->twigcheck();
8480  
8481 my $twigroot = $self->{twigroot};
8482 my $manifest = $twigroot->first_descendant('manifest');
8483 my $text;
8484 my $type;
8485  
8486 my @elements = $self->{twigroot}->descendants(qr/^dc:type$/ix);
8487 foreach my $el (@elements) {
8488 # Matches to the list are done after stripping leading and
8489 # trailing whitespace, trailing periods, and removing
8490 # whitespace around '--' and '/'
8491 $text = lc trim $el->text;
8492 $text =~ s|\.\z||x;
8493 debug(2,"DEBUG: normalizing type '",$text,"'");
8494  
8495 if($booktypes{$text}) {
8496 $type = $booktypes{$text};
8497 $el->set_text($type);
8498 }
8499 else {
8500 debug(1,"WARNING: unknown book type '",$text,"'");
8501 }
8502 }
8503 return;
8504 }
8505  
8506  
8507 =head2 C<gen_epub(%args)>
8508  
8509 Creates a .epub format e-book. This will create (or overwrite) the
8510 files 'mimetype' and 'META-INF/container.xml' in the current
8511 directory, creating the subdirectory META-INF as needed.
8512  
8513 A NCX file will also be created if missing.
8514  
8515 =head3 Arguments
8516  
8517 This method can take two optional named arguments.
8518  
8519 =over
8520  
8521 =item C<filename>
8522  
8523 The filename of the .epub output file. If not specified, takes the
8524 base name of the opf file and adds a .epub extension.
8525  
8526 =item C<dir>
8527  
8528 The directory to output the .epub file. If not specified, uses the
8529 current working directory. If a specified directory does not exist,
8530 it will be created, or the method will croak.
8531  
8532 =back
8533  
8534 =head3 Example
8535  
8536 gen_epub(filename => 'mybook.epub',
8537 dir => '../epub_books');
8538  
8539 =cut
8540  
8541 sub gen_epub :method {
8542 my ($self,%args) = @_;
8543 my $subname = ( caller(0) )[3];
8544 croak($subname . "() called as a procedure") unless(ref $self);
8545 debug(2,"DEBUG[",$subname,"]");
8546  
8547 my %valid_args = (
8548 'filename' => 1,
8549 'dir' => 1,
8550 );
8551 foreach my $arg (keys %args) {
8552 croak($subname,"(): invalid argument '",$arg,"'")
8553 if(!$valid_args{$arg});
8554 }
8555  
8556 my $filename = $args{filename};
8557 my $dir = $args{dir};
8558 my $zip = Archive::Zip->new();
8559 my $member;
8560 my $cwd = usedir($self->{topdir});
8561  
8562 $self->gen_epub_files();
8563 if(! $self->{opffile} ) {
8564 $self->add_error(
8565 "Cannot create epub without an OPF (did you forget to init?)");
8566 debug(1,"Cannot create epub without an OPF");
8567 return;
8568 }
8569 if(! -f $self->opfpath) {
8570 $self->add_error(
8571 sprintf("OPF '%s' does not exist (did you forget to save?)",
8572 $self->opfpath)
8573 );
8574 debug(1,"OPF '",$self->opfpath,"' does not exist");
8575 return;
8576 }
8577  
8578 debug(3,"DEBUG: adding core metadata to zip archive");
8579 $member = $zip->addFile('mimetype');
8580 $member->desiredCompressionMethod(COMPRESSION_STORED);
8581  
8582 $member = $zip->addFile('META-INF/container.xml');
8583 $member->desiredCompressionLevel(9);
8584  
8585 $member = $zip->addFile($self->{opfsubdir} . '/' . $self->{opffile});
8586 $member->desiredCompressionLevel(9);
8587  
8588 debug(3,"DEBUG: adding manifest files to zip archive");
8589 foreach my $file ($self->manifest_hrefs()) {
8590 $file = uri_unescape($file);
8591 if(-f $self->{opfsubdir} . '/' . $file) {
8592 $member = $zip->addFile($self->{opfsubdir} . '/' . $file);
8593 $member->desiredCompressionLevel(9);
8594 }
8595 else { print STDERR "WARNING: ",$self->{opfsubdir} . '/' . $file," not found, skipping.\n"; }
8596 }
8597  
8598 if(! $filename) {
8599 $filename = basename($self->{topdir}) . '.epub';
8600 }
8601  
8602 if($dir) {
8603 unless(-d $dir) {
8604 mkpath($dir)
8605 or croak("Unable to create working directory '",$dir,"'!");
8606 }
8607 $filename = "$dir/$filename";
8608 }
8609  
8610 unless ( $zip->writeToFileNamed($filename) == AZ_OK ) {
8611 $self->add_error(
8612 sprintf("Failed to create epub as '%s'",$filename));
8613 debug(1,"Failed to create epub as '",$filename,"'");
8614 return;
8615 }
8616  
8617 usedir($cwd);
8618 return 1;
8619 }
8620  
8621  
8622 =head2 C<gen_epub_files()>
8623  
8624 Generates the C<mimetype> and C<META-INF/container.xml> files expected
8625 by a .epub container, but does not actually generate the .epub file
8626 itself. This will be called automatically by C<gen_epub>.
8627  
8628 The OPF will be normalized to the OPF 2.0 format.
8629  
8630 If no NCX element exists, it will also be created.
8631  
8632 =cut
8633  
8634 sub gen_epub_files :method {
8635 my $self = shift;
8636 my $subname = ( caller(0) )[3];
8637 croak($subname . "() called as a procedure") unless(ref $self);
8638 debug(2,"DEBUG[",$subname,"]");
8639  
8640 my $manifest = $self->{twigroot}->first_descendant('manifest');
8641  
8642 $self->fix_opf20();
8643 if( ! $manifest->first_child('item[@id="ncx"]') ) {
8644 $self->gen_ncx();
8645 }
8646 $self->save();
8647  
8648 # These two functions must happen from the top-level directory, not the OPF directory
8649 if($self->{opfsubdir} ne '.') {
8650 debug(3,"DEBUG: switching to ",$self->{topdir}," to generate EPUB metadata");
8651 my $cwd = usedir($self->{topdir});
8652 create_epub_mimetype();
8653 create_epub_container($self->{opfsubdir} . '/' . $self->{opffile});
8654 usedir($cwd);
8655 }
8656 else {
8657 create_epub_mimetype();
8658 create_epub_container($self->{opffile});
8659 }
8660  
8661 return 1;
8662 }
8663  
8664  
8665 =head2 C<gen_ncx($filename)>
8666  
8667 Creates a NCX-format table of contents from the package
8668 unique-identifier, the dc:title, dc:creator, and spine elements, and
8669 then add the NCX entry to the manifest if it is not already
8670 referenced.
8671  
8672 Adds an error and fails if any of those cannot be found. The first
8673 available dc:title is taken, but will prioritize dc:creator elements
8674 with opf:role="aut" over those with no role attribute (see
8675 twigelt_is_author() for details).
8676  
8677 WARNING: This method REQUIRES that the e-book be in OPF 2.0 format to
8678 function correctly. Call fix_opf20() before calling gen_ncx().
8679 gen_ncx() will log an error and fail if $self{spec} is not set to
8680 OPF20.
8681  
8682 =head3 Arguments
8683  
8684 =over
8685  
8686 =item $filename : The filename to save to. If not specified, will use
8687 'toc.ncx'.
8688  
8689 =back
8690  
8691 This method will overwrite any existing file.
8692  
8693 Returns a twig containing the NCX XML, or undef on failure.
8694  
8695 =cut
8696  
8697 sub gen_ncx :method {
8698 my ($self,$filename) = @_;
8699 my $subname = ( caller(0) )[3];
8700 croak($subname . "() called as a procedure") unless(ref $self);
8701 debug(2,"DEBUG[",$subname,"]");
8702 $self->twigcheck;
8703  
8704 $filename = 'toc.ncx' if(!$filename);
8705  
8706 my $cwd = usedir($self->opfdir);
8707 my $twigroot = $self->{twigroot};
8708 my $identifier = $self->identifier;
8709 my $element; # Generic element container
8710 my $parent; # Generic parent element container
8711 my $ncx; # NCX twig
8712 my $ncxroot; # NCX twig root <ncx>
8713 my $ncxitem; # manifest item pointing to the NCX document
8714 my $navmap; # NCX element <navMap>
8715 my $navpoint; # NCX element <navPoint>
8716 my %navpointorder; # Hash mapping playOrder to id
8717 my $navpointindex = 1; # playOrder number starting at 1
8718 my $title; # E-book title
8719 my $author; # E-book primary author
8720 my @spinelist; # List of hashrefs containing spine data
8721 my $manifest; # OPF manifest element
8722 my $spine; # OPF spine element
8723  
8724 if($self->{spec} ne 'OPF20') {
8725 $self->add_error(
8726 $subname . "(): specification is currently set to '"
8727 . $self->{spec} . "' -- need 'OPF20'"
8728 );
8729 debug(1,"DEBUG: gen_ncx() FAILED: wrong specification ('",
8730 $self->{spec},"')!");
8731 return;
8732 }
8733  
8734 if(!$identifier) {
8735 $self->add_error( $subname . "(): no unique-identifier found" );
8736 debug(1,"DEBUG: gen_ncx() FAILED: no unique-identifier!");
8737 return;
8738 }
8739  
8740 # Get the title
8741 $title = $self->title();
8742 if(!$title) {
8743 $self->add_error( $subname . "(): no title found" );
8744 debug(1,"DEBUG: gen_ncx() FAILED: no title!");
8745 return;
8746 }
8747  
8748 # Get the author
8749 $author = $self->primary_author();
8750 if(!$author) {
8751 $self->add_error( $subname . "(): no title found" );
8752 debug(1,"DEBUG: gen_ncx() FAILED: no title!");
8753 return;
8754 }
8755  
8756 # Get the spine list
8757 @spinelist = $self->spine();
8758 if(!@spinelist) {
8759 $self->add_error( $subname . "(): no spine found" );
8760 debug(1,"DEBUG: gen_ncx() FAILED: no spine!");
8761 return;
8762 }
8763  
8764 # Make sure the manifest element exists
8765 # (This should in theory never fail, since it is also checked by
8766 # spine() above)
8767 $manifest = $twigroot->first_descendant('manifest');
8768 if(!$manifest) {
8769 $self->add_error( $subname . "(): no manifest found" );
8770 debug(1,"DEBUG: gen_ncx() FAILED: no manifest!");
8771 return;
8772 }
8773  
8774 $ncx = XML::Twig->new(
8775 output_encoding => 'utf-8',
8776 pretty_print => 'record'
8777 );
8778  
8779 # <ncx>
8780 $element = XML::Twig::Elt->new('ncx');
8781 $element->set_att('xmlns' => 'http://www.daisy.org/z3986/2005/ncx/');
8782 $element->set_att('version' => '2005-1');
8783 $ncx->set_root($element);
8784 $ncxroot = $ncx->root;
8785  
8786 # <head>
8787 $parent = $ncxroot->insert_new_elt('first_child','head');
8788 $element = $parent->insert_new_elt('last_child','meta');
8789 $element->set_att(
8790 'name' => 'dtb:uid',
8791 'content' => $identifier
8792 );
8793  
8794 $element = $parent->insert_new_elt('last_child','meta');
8795 $element->set_att(
8796 'name' => 'dtb:depth',
8797 'content' => '1'
8798 );
8799 $element = $parent->insert_new_elt('last_child','meta');
8800 $element->set_att(
8801 'name' => 'dtb:totalPageCount',
8802 'content' => '0'
8803 );
8804  
8805 $element = $parent->insert_new_elt('last_child','meta');
8806 $element->set_att(
8807 'name' => 'dtb:maxPageNumber',
8808 'content' => '0'
8809 );
8810  
8811 # <docTitle>
8812 $parent = $parent->insert_new_elt('after','docTitle');
8813 $element = $parent->insert_new_elt('first_child','text');
8814 $element->set_text($title);
8815  
8816 # <navMap>
8817 $navmap = $parent->insert_new_elt('after','navMap');
8818  
8819 foreach my $spineitem (@spinelist) {
8820 # <navPoint>
8821 $navpoint = $navmap->insert_new_elt('last_child','navPoint');
8822 $navpoint->set_att('id' => $spineitem->{'id'},
8823 'playOrder' => $navpointindex);
8824 $navpointindex++;
8825  
8826 # <navLabel>
8827 $parent = $navpoint->insert_new_elt('last_child','navLabel');
8828 $element = $parent->insert_new_elt('last_child','text');
8829 $element->set_text($spineitem->{'id'});
8830  
8831 # <content>
8832 $element = $navpoint->insert_new_elt('last_child','content');
8833 $element->set_att('src' => $spineitem->{'href'});
8834 }
8835  
8836 # Backup existing file
8837 if(-e $filename) {
8838 rename($filename,"$filename.backup")
8839 or croak($subname,"(): could not backup ",$filename,"!");
8840 }
8841  
8842 # Twig handles utf-8 on its own. Setting binmode :utf8 here will
8843 # cause double-conversion.
8844 open(my $fh_ncx,'>',$filename)
8845 or croak($subname,"(): failed to open '",$filename,"' for writing!");
8846 $ncx->print(\*$fh_ncx);
8847 close($fh_ncx)
8848 or croak($subname,"(): failed to close '",$filename,"'!");
8849  
8850 # Search for existing NCX entries and modify the first one found,
8851 # creating a new one if there are no matches.
8852 $ncxitem = $manifest->first_child('item[@id="ncx"]');
8853 $ncxitem = $manifest->first_child("item[\@href='$filename']")
8854 if(!$ncxitem);
8855 $ncxitem = $manifest->first_child('item[@media-type="application/x-dtbncx+xml"]')
8856 if(!$ncxitem);
8857 $ncxitem = $manifest->insert_new_elt('first_child','item')
8858 if(!$ncxitem);
8859  
8860 $ncxitem->set_att(
8861 'id' => 'ncx',
8862 'href' => $filename,
8863 'media-type' => 'application/x-dtbncx+xml'
8864 );
8865  
8866 # Move the NCX item to the top of the manifest
8867 $ncxitem->move('first_child',$manifest);
8868  
8869 # Ensure that the spine references the NCX
8870 $spine = $twigroot->first_descendant('spine');
8871 $spine->set_att('toc' => 'ncx');
8872  
8873 usedir($cwd);
8874 return $ncx;
8875 }
8876  
8877  
8878 =head2 C<save()>
8879  
8880 Saves the OPF file to disk. Existing files are backed up to
8881 filename.backup.
8882  
8883 =cut
8884  
8885 sub save :method {
8886 my $self = shift;
8887 my $subname = ( caller(0) )[3];
8888 croak($subname . "() called as a procedure") unless(ref $self);
8889 debug(2,"DEBUG[",$subname,"]");
8890  
8891 croak($subname,"(): no opffile specified (did you forget to init?)")
8892 if(!$self->{opffile});
8893  
8894 my $fh_opf;
8895 my $cwd = usedir($self->opfdir);
8896 my $filename = $self->{opffile};
8897  
8898 # Backup existing file
8899 if(-e $filename) {
8900 rename($filename,"$filename.backup")
8901 or croak($subname,"(): could not backup ",$filename,"!");
8902 }
8903  
8904 # Update the last-modified timestamp as the very last thing before
8905 # saving if the output changed at all
8906 if($self->{twig}->sprint ne $self->{twig_unmodified}->sprint) {
8907 $self->set_timestamp();
8908 }
8909  
8910 if(!open($fh_opf,">:encoding(UTF-8)",$self->{opffile})) {
8911 add_error(sprintf("Could not open '%s' to save to!",$self->{opffile}));
8912 return;
8913 }
8914 $self->{twig}->print(\*$fh_opf);
8915  
8916 if(!close($fh_opf)) {
8917 add_error(sprintf("Failure while closing '%s'!",$self->{opffile}));
8918 return;
8919 }
8920  
8921 usedir($cwd);
8922 return 1;
8923 }
8924  
8925  
8926 =head2 C<set_adult($bool)>
8927  
8928 Sets the Mobipocket-specific <Adult> element, creating or deleting it
8929 as necessary. If C<$bool> is true, the text is set to 'yes'. If it
8930 is defined but false, any existing elements are deleted. If it is
8931 undefined, the method immediately returns.
8932  
8933 If a new element has to be created, L</fix_metastructure_oeb12> is
8934 called to ensure that <x-metadata> exists and the element is created
8935 under <x-metadata>, as Mobipocket elements are not recognized by
8936 Mobipocket's software when placed directly under <metadata>
8937  
8938 =cut
8939  
8940 sub set_adult :method {
8941 my $self = shift;
8942 my $adult = shift;
8943 my $subname = ( caller(0) )[3];
8944 croak($subname . "() called as a procedure") unless(ref $self);
8945 debug(2,"DEBUG[",$subname,"]");
8946 $self->twigcheck;
8947  
8948 return 1 unless(defined $adult);
8949  
8950 my $xmeta;
8951 my $element;
8952 my @elements;
8953  
8954 if($adult) {
8955 $element = $self->{twigroot}->first_descendant(qr/^adult$/ix);
8956 unless($element) {
8957 $self->fix_metastructure_oeb12();
8958 $xmeta = $self->{twigroot}->first_descendant('x-metadata');
8959 $element = $xmeta->insert_new_elt('last_child','Adult');
8960 }
8961 $element->set_text('yes');
8962 }
8963 else {
8964 @elements = $self->{twigroot}->descendants(qr/^adult$/ix);
8965 foreach my $el (@elements) {
8966 debug(2,"DEBUG: deleting <Adult> flag");
8967 $el->delete;
8968 }
8969 }
8970 return 1;
8971 }
8972  
8973  
8974 =head2 C<set_cover(%args)>
8975  
8976 Sets a cover image
8977  
8978 In OPF 2.0, this is done by setting both a <meta name="cover"> element
8979 and a guide <reference type="other.ms-coverimage-standard"> element
8980 (though some readers will also extract the first image found in the
8981 HTML of the <reference type="cover"> element, which this method will
8982 not handle).
8983  
8984 In OEB 1.2, this is done by setting the <EmbeddedCover> tag.
8985  
8986 If the filename is not currently listed as an item in the manifest, it
8987 is added.
8988  
8989 =head3 Arguments
8990  
8991 =over
8992  
8993 =item C<href>
8994  
8995 The filename of the image file to use. This is mandatory.
8996  
8997 =item C<id>
8998  
8999 The id attribute to assign to its item element
9000  
9001 =item C<spec>
9002  
9003 The specification to use, either OEB12 or OPF20. If this is left
9004 undefined, the current spec state will be checked, and if that is
9005 undefined, it will default to OPF20.
9006  
9007 =back
9008  
9009 =cut
9010  
9011 sub set_cover :method {
9012 my ($self,%args) = @_;
9013 my $subname = ( caller(0) )[3];
9014 croak($subname . "() called as a procedure") unless(ref $self);
9015 debug(2,"DEBUG[",$subname,"]");
9016 my %valid_args = (
9017 'href' => 1,
9018 'id' => 1,
9019 'spec' => 1,
9020 );
9021 foreach my $arg (keys %args) {
9022 croak($subname,"(): invalid argument '",$arg,"'")
9023 if(!$valid_args{$arg});
9024 }
9025  
9026 my $href = $args{href};
9027 my $newid = $args{id};
9028 my $spec = $args{spec};
9029 my $id;
9030 my $mimetype;
9031 my $manifest;
9032 my $guide;
9033 my $dcmeta;
9034 my $element;
9035  
9036 if(! $href) {
9037 $self->add_error($subname,"(): no href specified");
9038 return;
9039 }
9040 $mimetype = mimetype($href);
9041 if($mimetype !~ m#^image/#ix) {
9042 $self->add_warning(
9043 $subname,"(): ",$href,
9044 " does not appear to be an image (detected: ",$mimetype,")"
9045 );
9046 }
9047  
9048 if(! $spec) {
9049 $spec = $self->spec || 'OPF20';
9050 }
9051  
9052 # Ensure that there is a matching manifest item
9053 $manifest = $self->{twigroot}->first_child('manifest');
9054 $element = $manifest->first_child('item[@href="' . $href . '"]');
9055 if($element) {
9056 if($newid) {
9057 $element->set_id($newid);
9058 }
9059 }
9060 else {
9061 $element = $manifest->insert_new_elt('first_child','item');
9062 if ($newid) {
9063 $element->set_id($newid);
9064 }
9065 elsif ($self->{twig}->first_elt('*[@id="coverimage"]')) {
9066 $element->set_id(basename($href));
9067 }
9068 else {
9069 $element->set_id('coverimage');
9070 }
9071 $element->set_att('href',$href);
9072 $element->set_att('media-type',$mimetype);
9073 }
9074 $id = $element->id;
9075  
9076 if ($spec eq 'OPF20') {
9077 $self->fix_metastructure_basic;
9078 $self->fix_guide;
9079 $guide = $self->{twigroot}->first_child('guide');
9080 $element = $guide->first_child('reference[@type="other.ms-coverimage-standard"]');
9081 if ($element) {
9082 $element->set_att('href',$href);
9083 $element->set_att('title','Cover');
9084 }
9085 else {
9086 $element = $guide->insert_new_elt('last_child','reference');
9087 $element->set_att('href',$href);
9088 $element->set_att('title','Cover');
9089 $element->set_att('type','other.ms-coverimage-standard');
9090 }
9091 $self->set_meta('name' => 'cover',
9092 'content' => $href);
9093  
9094 # Now that the OPF 2.0 elements are set, we can delete the
9095 # OEB12 EmbeddedCover element
9096 $element = $self->{twigroot}->first_descendant('EmbeddedCover');
9097 if ($element) {
9098 debug(1,"deleting cover");
9099 $element->delete;
9100 }
9101 }
9102 elsif ($spec eq 'OEB12') {
9103 $self->fix_metastructure_oeb12;
9104 $dcmeta = $self->{twigroot}->first_child('dc-metadata');
9105 $element = $dcmeta->first_child('EmbeddedCover');
9106 if ($element) {
9107 $element->set_text($href);
9108 }
9109 else {
9110 $element = $dcmeta->insert_new_elt('last_child','EmbeddedCover');
9111 $element->set_text($href);
9112 }
9113 }
9114 else {
9115 self->add_error($subname,"(): unknown specification type: '",$spec,"'");
9116 }
9117 return;
9118 }
9119  
9120  
9121 =head2 C<set_date(%args)>
9122  
9123 Sets the date metadata for a given event. If more than one dc:date or
9124 dc:Date element is present with the specified event attribute, sets
9125 the first. If no dc:date element is present with the specified event
9126 attribute, a new element is created.
9127  
9128 If a <dc-metadata> element exists underneath <metadata>, the date
9129 element will be created underneath the <dc-metadata> in OEB 1.2
9130 format, otherwise the title element is created underneath <metadata>
9131 in OPF 2.0 format.
9132  
9133 Returns 1 on success, logs an error and returns undef if no text or
9134 event was specified.
9135  
9136 =head3 Arguments
9137  
9138 =over
9139  
9140 =item C<text>
9141  
9142 This specifies the description to use as the text of the element. If
9143 not specified, the method sets an error and returns undef.
9144  
9145 =item C<event>
9146  
9147 This optionally specifies the event attribute for the date. This
9148 attribute is not valid in OPF 3.0 (which only allows publication date
9149 in this element) and should no longer be used.
9150  
9151 =item C<id> (optional)
9152  
9153 This specifies the ID to set on the element. If set and the ID is
9154 already in use, a warning is logged and the ID is removed from the
9155 other location and assigned to the element.
9156  
9157 =back
9158  
9159 =cut
9160  
9161 sub set_date :method {
9162 my ($self,%args) = @_;
9163 my $subname = ( caller(0) )[3];
9164 croak($subname . "() called as a procedure") unless(ref $self);
9165 debug(2,"DEBUG[",$subname,"]");
9166 my %valid_args = (
9167 'text' => 1,
9168 'event' => 1,
9169 'id' => 1,
9170 );
9171 foreach my $arg (keys %args) {
9172 croak($subname,"(): invalid argument '",$arg,"'")
9173 if (!$valid_args{$arg});
9174 }
9175  
9176 my $text = $args{text};
9177 my $event = $args{event};
9178 my $newid = $args{id};
9179 unless($text) {
9180 $self->add_error($subname,"(): no text specified");
9181 return;
9182 }
9183  
9184 my $meta = $self->{twigroot}->first_child('metadata');
9185 my $dcmeta = $meta->first_child('dc-metadata');
9186 my $idelem;
9187 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
9188  
9189 $self->fix_metastructure_basic();
9190  
9191 my $element;
9192 if ($event) {
9193 $element = $self->{twigroot}->first_descendant(
9194 "dc:date[\@opf:event=~/$event/ix or \@event=~/$event/ix]");
9195 $element = $self->{twigroot}->first_descendant(
9196 "dc:Date[\@opf:event=~/$event/ix or \@event=~/$event/ix]")
9197 unless($element);
9198 }
9199 else {
9200 $element = $self->{twigroot}->first_descendant("dc:date");
9201 $element = $self->{twigroot}->first_descendant("dc:Date")
9202 unless($element);
9203 }
9204  
9205 if ($element) {
9206 $element->set_text($text);
9207 }
9208 elsif ($dcmeta) {
9209 $element = $dcmeta->insert_new_elt('last_child','dc:Date');
9210 $element->set_text($text);
9211 if ($event) {
9212 $element->set_att('event',$event);
9213 }
9214 }
9215 else {
9216 $element = $meta->insert_new_elt('last_child','dc:date');
9217 $element->set_text($text);
9218 if ($event) {
9219 $element->set_att('opf:event',$event);
9220 }
9221 }
9222  
9223 if ($idelem && $idelem->cmp($element) ) {
9224 $self->add_warning(
9225 $subname,"(): reassigning id '",$newid,
9226 "' from a '",$idelem->gi,"' element!"
9227 );
9228 $idelem->del_att('id');
9229 }
9230 $element->set_att('id' => $newid) if($newid);
9231 return 1;
9232 }
9233  
9234  
9235 =head2 set_description(%args)
9236  
9237 Sets the text and optionally ID of the first dc:description element
9238 found (case-insensitive). Creates the element if one did not exist.
9239 If a <dc-metadata> element exists underneath <metadata>, the
9240 description element will be created underneath the <dc-metadata> in
9241 OEB 1.2 format, otherwise the title element is created underneath
9242 <metadata> in OPF 2.0 format.
9243  
9244 Returns 1 on success, returns undef if no publisher was specified.
9245  
9246 =head3 Arguments
9247  
9248 C<set_description()> takes one required and one optional named argument
9249  
9250 =over
9251  
9252 =item C<text>
9253  
9254 This specifies the description to use as the text of the element. If
9255 not specified, the method returns undef.
9256  
9257 =item C<id> (optional)
9258  
9259 This specifies the ID to set on the element. If set and the ID is
9260 already in use, a warning is logged and the ID is removed from the
9261 other location and assigned to the element.
9262  
9263 =back
9264  
9265 =head3 Example
9266  
9267 $retval = $ebook->set_description('text' => 'A really good book',
9268 'id' => 'mydescid');
9269  
9270 =cut
9271  
9272 sub set_description :method {
9273 my ($self,%args) = @_;
9274 my $subname = ( caller(0) )[3];
9275 croak($subname . "() called as a procedure") unless(ref $self);
9276 debug(2,"DEBUG[",$subname,"]");
9277 my %valid_args = (
9278 'text' => 1,
9279 'id' => 1,
9280 );
9281 foreach my $arg (keys %args) {
9282 croak($subname,"(): invalid argument '",$arg,"'")
9283 if (!$valid_args{$arg});
9284 }
9285  
9286 my $text = $args{text};
9287 unless($text) {
9288 $self->add_error($subname,"(): no text specified");
9289 return;
9290 }
9291  
9292 $self->fix_metastructure_basic();
9293 my $element = $self->{twigroot}->first_descendant(qr/^dc:description$/ix);
9294 my $meta = $self->{twigroot}->first_child('metadata');
9295 my $dcmeta = $meta->first_child('dc-metadata');
9296  
9297 my $gi = ($dcmeta) ? 'dc:Description' : 'dc:description';
9298 $self->set_metadata(gi => $gi,
9299 text => $text,
9300 id => $args{id});
9301  
9302 return 1;
9303 }
9304  
9305  
9306 =head2 C<set_erotic($bool)>
9307  
9308 If C<$bool> is true, C<$self->{erotic}> is set to 1, otherwise this is
9309 set to 0.
9310  
9311 This will enable or disable special handling for erotic books, most
9312 notably in subject normalization.
9313  
9314 This is not related in any way to C<set_adult> which is a
9315 Mobipocket-specific flag.
9316  
9317 Returns 1 if no argument is given, 0 otherwise.
9318  
9319 =cut
9320  
9321 sub set_erotic :method {
9322 my ($self,$flag) = @_;
9323 my $subname = ( caller(0) )[3];
9324 croak($subname . "() called as a procedure") unless(ref $self);
9325 debug(2,"DEBUG[",$subname,"]");
9326  
9327 return 1 unless(defined $flag);
9328  
9329 if($flag) {
9330 $self->{erotic} = 1;
9331 }
9332 else {
9333 $self->{erotic} = 0;
9334 }
9335 return 0;
9336 }
9337  
9338  
9339 =head2 C<set_language(%args)>
9340  
9341 Sets the text and optionally the ID of the first dc:language element
9342 found (case-insensitive). Creates the element if one did not exist.
9343 If a <dc-metadata> element exists underneath <metadata>, the language
9344 element will be created underneath the <dc-metadata> in OEB 1.2
9345 format, otherwise the title element is created underneath <metadata>
9346 in OPF 2.0 format.
9347  
9348 Returns 1 on success, returns undef if no text was specified.
9349  
9350 =head3 Arguments
9351  
9352 =over
9353  
9354 =item C<text>
9355  
9356 This specifies the language set as the text of the element. If not
9357 specified, the method sets an error and returns undef. This should be
9358 an IANA language code, and it will be lowercased before it is set.
9359  
9360 =item C<id> (optional)
9361  
9362 This specifies the ID to set on the element. If set and the ID is
9363 already in use, a warning is logged and the ID is removed from the
9364 other location and assigned to the element.
9365  
9366 =back
9367  
9368 =head3 Example
9369  
9370 $retval = $ebook->set_language('text' => 'en-us',
9371 'id' => 'langid');
9372  
9373 =cut
9374  
9375 sub set_language :method {
9376 my ($self,%args) = @_;
9377 my $subname = ( caller(0) )[3];
9378 croak($subname . "() called as a procedure") unless(ref $self);
9379 debug(2,"DEBUG[",$subname,"]");
9380 my %valid_args = (
9381 'text' => 1,
9382 'id' => 1,
9383 );
9384 foreach my $arg (keys %args) {
9385 croak($subname,"(): invalid argument '",$arg,"'")
9386 if (!$valid_args{$arg});
9387 }
9388  
9389 my $text = lc($args{text});
9390 unless($text) {
9391 $self->add_error($subname,"(): no text specified");
9392 return;
9393 }
9394  
9395 $self->fix_metastructure_basic();
9396 my $element = $self->{twigroot}->first_descendant(qr/^dc:language$/ix);
9397 my $meta = $self->{twigroot}->first_child('metadata');
9398 my $dcmeta = $meta->first_child('dc-metadata');
9399  
9400 my $gi = ($dcmeta) ? 'dc:Language' : 'dc:language';
9401 $self->set_metadata(gi => $gi,
9402 text => $text,
9403 id => $args{id});
9404 return 1;
9405 }
9406  
9407  
9408 =head2 set_meta(%args)
9409  
9410 Sets a <meta> element in the <metadata> element area.
9411  
9412 =head3 Arguments
9413  
9414 =over
9415  
9416 =item C<name>
9417  
9418 The name attribute to use when finding or creating OPF 2.0 <meta>
9419 elements. Either this or the property attribute (below) must be
9420 specified, but specifying both is an error.
9421  
9422 =item C<content>
9423  
9424 The value of the content attribute to set on OPF 2.0 elements. If
9425 this value is empty or undefined, but C<name> is provided and matches
9426 an existing element, that element will be deleted.
9427  
9428 =item C<property>
9429  
9430 The property attribute to use when finding or creating OPF 3.0 <meta>
9431 elements. Either this or C<name> (above) must be specified, but
9432 specifying both is an error.
9433  
9434 =item C<refines>
9435  
9436 The refines attribute to use when finding or creating OPF 3.0 <meta>
9437 elements.
9438  
9439 =item C<scheme>
9440  
9441 The scheme attribute to use when creating or updating OPF 3.0 <meta>
9442 elements.
9443  
9444 =item C<text>
9445  
9446 The text set on OPF 3.0 <meta> elements. If this value is empty or
9447 undefined, but C<property> is provided and the combination of
9448 C<property> and C<refines> matches an existing element, that element
9449 will be deleted.
9450  
9451 =item C<lang>
9452  
9453 The xml:lang attribute to set. This is valid on both OPF 2 and OPF 3
9454 <meta> elements.
9455  
9456 =back
9457  
9458 =cut
9459  
9460 sub set_meta :method {
9461 my ($self, %args) = @_;
9462 my $subname = ( caller(0) )[3];
9463 croak($subname . "() called as a procedure") unless(ref $self);
9464 debug(3,"DEBUG[",$subname,"]");
9465 my %valid_args = (
9466 'name' => 1,
9467 'content' => 1,
9468 'property' => 1,
9469 'refines' => 1,
9470 'scheme' => 1,
9471 'text' => 1,
9472 'lang' => 1,
9473 );
9474 foreach my $arg (keys %args) {
9475 croak($subname,"(): invalid argument '",$arg,"'")
9476 if (!$valid_args{$arg});
9477 }
9478  
9479 my $name = $args{name};
9480 my $content = $args{content};
9481 my $property = $args{property};
9482 my $refines = $args{refines};
9483 my $scheme = $args{scheme};
9484 my $text = $args{text};
9485 my $lang = $args{lang};
9486 my $standard;
9487  
9488 if ($name) {
9489 if ($property) {
9490 $self->add_error($subname,"(): both name (OPF2) and property (OPF3) attributes specified for a meta tag");
9491 return;
9492 }
9493 $standard = 'OPF2';
9494 }
9495 else {
9496 if ($property) {
9497 $standard = 'OPF3';
9498 }
9499 else {
9500 $self->add_error($subname,"(): neither name (OPF2) nor property (OPF3) attributes specified for a meta tag");
9501 return;
9502 }
9503 }
9504  
9505 $self->fix_metastructure_basic();
9506 my $metadata = $self->{twigroot}->first_child('metadata');
9507 my $element;
9508  
9509 if ($standard eq 'OPF2') {
9510 $element = $metadata->first_descendant('meta[@name="' . $name . '"]');
9511  
9512 if ($element) {
9513 if (! $content) {
9514 debug(2,"DEBUG: deleting <meta name='",$name,"'>");
9515 $element->delete;
9516 }
9517 else {
9518 debug(2,"DEBUG: updating <meta name='",$name,"'>");
9519 $element->set_att('content',$content);
9520 if ($lang) {
9521 $element->set_att('xml:lang',$lang);
9522 }
9523 }
9524 }
9525 else {
9526 if ($content) {
9527 debug(2,"DEBUG: creating <meta name='",$name,"'>");
9528 $element = $metadata->insert_new_elt('last_child','meta');
9529 $element->set_att('name',$name);
9530 $element->set_att('content',$content);
9531 }
9532 }
9533 }
9534 elsif ($standard eq 'OPF3') {
9535 if ($refines) {
9536 $element = $metadata->first_descendant(
9537 'meta[@property="' . $property . '" and @refines="' . $refines . '"]');
9538 }
9539 else {
9540 $element = $metadata->first_descendant(
9541 'meta[@property="' . $property . '"]');
9542 }
9543 if ($element) {
9544 if (! $text) {
9545 debug(2,"DEBUG: deleting meta property='",$property,"'>");
9546 $element->delete;
9547 }
9548 else {
9549 debug(2,"DEBUG: updating <meta property='",$property,"'>");
9550 $element->set_text($text);
9551 }
9552 if ($scheme) {
9553 $element->set_att('scheme',$scheme);
9554 }
9555 if ($lang) {
9556 $element->set_att('xml:lang',$lang);
9557 }
9558 }
9559 else {
9560 if ($text) {
9561 debug(2,"DEBUG: creating <meta property='",$property,"'>");
9562 $element = $metadata->insert_new_elt('last_child','meta');
9563 $element->set_att('property',$property);
9564 if ($refines) {
9565 $element->set_att('refines',$refines);
9566 }
9567 if ($scheme) {
9568 $element->set_att('scheme',$scheme);
9569 }
9570 if ($lang) {
9571 $element->set_att('xml:lang',$lang);
9572 }
9573 $element->set_text($text);
9574 }
9575 }
9576 }
9577 else {
9578 croak($subname,"(): unknown standard '${standard}'! (This should be impossible!)");
9579 }
9580  
9581 return;
9582 }
9583  
9584  
9585 =head2 set_metadata(%args)
9586  
9587 Sets the text and optionally the ID of the first specified element
9588 type found (case-insensitive). Creates the element if one did not
9589 exist (with the exact capitalization specified).
9590  
9591 If a <dc-metadata> element exists underneath <metadata>, the language
9592 element will be created underneath the <dc-metadata> and any standard
9593 attributes will be created in OEB 1.2 format, otherwise the element is
9594 created underneath <metadata> in OPF 2.0 format.
9595  
9596 Returns 1 on success, returns undef if no gi or if no text was specified.
9597  
9598 =cut
9599  
9600 =head3 Arguments
9601  
9602 =over
9603  
9604 =item C<gi>
9605  
9606 The generic identifier (tag) of the metadata element to alter or
9607 create. If not specified, the method sets an error and returns undef.
9608  
9609 =item C<parent>
9610  
9611 The generic identifier (tag) of the parent to use for any newly
9612 created element. If not specified, defaults to 'dc-metadata' if
9613 'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.
9614  
9615 A newly created element will be created under the first element found
9616 with this gi. A modified element will be moved under the first
9617 element found with this gi.
9618  
9619 Newly created elements will use OPF 2.0 attribute names if the parent
9620 is 'metadata' and OEB 1.2 attribute names otherwise.
9621  
9622 =item C<text>
9623  
9624 This specifies the element text to set. If not specified, the method
9625 sets an error and returns undef.
9626  
9627 =item C<id> (optional)
9628  
9629 This specifies the ID to set on the element. If set and the ID is
9630 already in use, a warning is logged and the ID is removed from the
9631 other location and assigned to the element.
9632  
9633 =item C<fileas> (optional)
9634  
9635 This specifies the file-as attribute to set on the element.
9636  
9637 =item C<role> (optional)
9638  
9639 This specifies the role attribute to set on the element.
9640  
9641 =item C<scheme> (optional)
9642  
9643 This specifies the scheme attribute to set on the element.
9644  
9645 =back
9646  
9647 =head3 Example
9648  
9649 $retval = $ebook->set_metadata(gi => 'AuthorNonstandard',
9650 text => 'Element Text',
9651 id => 'customid',
9652 fileas => 'Text, Element',
9653 role => 'xxx',
9654 scheme => 'code');
9655  
9656 =cut
9657  
9658 sub set_metadata :method {
9659 my ($self,%args) = @_;
9660 my $subname = ( caller(0) )[3];
9661 croak($subname . "() called as a procedure") unless(ref $self);
9662 debug(3,"DEBUG[",$subname,"]");
9663 my %valid_args = (
9664 'gi' => 1,
9665 'parent' => 1,
9666 'text' => 1,
9667 'id' => 1,
9668 'fileas' => 1,
9669 'role' => 1,
9670 'scheme' => 1,
9671 );
9672 foreach my $arg (keys %args) {
9673 croak($subname,"(): invalid argument '",$arg,"'")
9674 if(!$valid_args{$arg});
9675 }
9676  
9677 my $gi = $args{gi};
9678 unless($gi) {
9679 $self->add_error($subname,"(): no gi specified");
9680 return;
9681 }
9682  
9683 my $text = $args{text};
9684 unless($text) {
9685 $self->add_error($subname,"(): no text specified");
9686 return;
9687 }
9688  
9689 my $newid = $args{id};
9690 my $idelem;
9691 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
9692  
9693 my $element = $self->{twigroot}->first_descendant(qr/^ $gi $/ix);
9694 my $meta;
9695 my $dcmeta;
9696 my $parent;
9697 my %dcatts;
9698  
9699 $self->fix_metastructure_basic();
9700 $parent = $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
9701 if($args{parent});
9702 $meta = $self->{twigroot}->first_child('metadata');
9703 $dcmeta = $meta->first_child('dc-metadata');
9704 $parent = $parent || $dcmeta || $meta;
9705 if($parent->gi eq 'metadata') {
9706 %dcatts = (
9707 'file-as' => 'opf:file-as',
9708 'role' => 'opf:role',
9709 'scheme' => 'opf:scheme',
9710 );
9711 }
9712 else {
9713 %dcatts = (
9714 'file-as' => 'file-as',
9715 'role' => 'role',
9716 'scheme' => 'scheme'
9717 );
9718 }
9719  
9720  
9721 if($element) {
9722 debug(2,"DEBUG: updating '",$gi,"'");
9723 if($element->att('opf:file-as') && $args{fileas}) {
9724 debug(3,"DEBUG: setting opf:file-as '",$args{fileas},"'");
9725 $element->set_att('opf:file-as',$args{fileas});
9726 }
9727 elsif($args{fileas}) {
9728 debug(3,"DEBUG: setting file-as '",$args{fileas},"'");
9729 $element->set_att('file-as',$args{fileas});
9730 }
9731 if($element->att('opf:role') && $args{role}) {
9732 debug(3,"DEBUG: setting opf:role '",$args{role},"'");
9733 $element->set_att('opf:role',$args{role});
9734 }
9735 elsif($args{role}) {
9736 debug(3,"DEBUG: setting role '",$args{role},"'");
9737 $element->set_att('role',$args{role});
9738 }
9739 if($element->att('opf:scheme') && $args{scheme}) {
9740 debug(3,"DEBUG: setting opf:scheme '",$args{scheme},"'");
9741 $element->set_att('opf:scheme',$args{scheme});
9742 }
9743 elsif($args{scheme}) {
9744 debug(3,"DEBUG: setting scheme '",$args{scheme},"'");
9745 $element->set_att('scheme',$args{scheme});
9746 }
9747 debug(3,"DEBUG: setting text");
9748 $element->set_text($text);
9749  
9750 unless($element->parent->gi eq $parent->gi) {
9751 debug(2,"DEBUG: moving <",$element->gi,"> under <",
9752 $parent->gi,">");
9753 $element->move('last_child',$parent);
9754 }
9755 }
9756 else {
9757 debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
9758 $element = $parent->insert_new_elt('last_child',$gi);
9759 $element->set_att($dcatts{'file-as'},$args{fileas})
9760 if($args{fileas});
9761 $element->set_att($dcatts{'role'},$args{role})
9762 if($args{role});
9763 $element->set_att($dcatts{'scheme'},$args{scheme})
9764 if($args{scheme});
9765 $element->set_text($text);
9766 }
9767  
9768 if($idelem && $idelem->cmp($element) ) {
9769 $self->add_warning(
9770 $subname,"(): reassigning id '",$newid,
9771 "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
9772 );
9773 $idelem->del_att('id');
9774 }
9775 $element->set_att('id' => $newid) if($newid);
9776 return 1;
9777 }
9778  
9779  
9780 =head2 set_opffile($filename)
9781  
9782 Sets the filename used to store the OPF metadata.
9783  
9784 Returns 1 on success; sets an error message and returns undef if no
9785 filename was specified.
9786  
9787 =cut
9788  
9789 sub set_opffile :method {
9790 my ($self,$filename) = @_;
9791 my $subname = ( caller(0) )[3];
9792 croak($subname . "() called as a procedure") unless(ref $self);
9793 debug(2,"DEBUG[",$subname,"]");
9794  
9795 unless($filename) {
9796 debug(1,$subname,"(): no filename specified!");
9797 $self->add_warning($subname,"(): no filename specified!");
9798 return;
9799 }
9800 $self->{opffile} = $filename;
9801 return 1;
9802 }
9803  
9804  
9805 =head2 set_retailprice(%args)
9806  
9807 Sets the Mobipocket-specific <SRP> element (Suggested Retail Price),
9808 creating or deleting it as necessary.
9809  
9810 If a new element has to be created, L</fix_metastructure_oeb12> is
9811 called to ensure that <x-metadata> exists and the element is created
9812 under <x-metadata>, as Mobipocket elements are not recognized by
9813 Mobipocket's software when placed directly under <metadata>
9814  
9815 =head3 Arguments
9816  
9817 =over
9818  
9819 =item * C<text>
9820  
9821 The price to set as the text of the element. If this is undefined,
9822 the method sets an error and returns undef. If it is set but false,
9823 any existing <SRP> element is deleted.
9824  
9825 =item * C<currency> (optional)
9826  
9827 The value to set on the 'Currency' attribute. If not provided,
9828 defaults to 'USD' (US Dollars)
9829  
9830 =back
9831  
9832 =cut
9833  
9834 sub set_retailprice :method {
9835 my ($self,%args) = @_;
9836 my $subname = ( caller(0) )[3];
9837 croak($subname . "() called as a procedure") unless(ref $self);
9838 debug(2,"DEBUG[",$subname,"]");
9839 $self->twigcheck;
9840  
9841 my %valid_args = (
9842 'text' => 1,
9843 'currency' => 1,
9844 );
9845  
9846 foreach my $arg (keys %args) {
9847 croak($subname,"(): invalid argument '",$arg,"'")
9848 if(!$valid_args{$arg});
9849 }
9850 unless(defined $args{text}) {
9851 $self->add_error($subname,"(): text not defined");
9852 return;
9853 }
9854  
9855 my $xmeta;
9856 my $element;
9857 my @elements;
9858  
9859 if($args{text}) {
9860 $element = $self->{twigroot}->first_descendant(qr/^ SRP $/ix);
9861 unless($element) {
9862 $self->fix_metastructure_oeb12();
9863 $xmeta = $self->{twigroot}->first_descendant('x-metadata');
9864 $element = $xmeta->insert_new_elt('last_child','SRP');
9865 }
9866 $element->set_text($args{text});
9867 $element->set_att('Currency',$args{currency}) if($args{currency});
9868 }
9869 else {
9870 @elements = $self->{twigroot}->descendants(qr/^ SRP $/ix);
9871 foreach my $el (@elements) {
9872 debug(2,"DEBUG: deleting <SRP>");
9873 $el->delete;
9874 }
9875 }
9876 return 1;
9877 }
9878  
9879  
9880 =head2 set_primary_author(%args)
9881  
9882 Sets the text, id, file-as, and role attributes of the primary author
9883 element (see L</primary_author()> for details on how this is found),
9884 or if no primary author exists, creates a new element containing the
9885 information.
9886  
9887 This method calls L</fix_metastructure_basic()> to enforce the
9888 presence of the <metadata> element. When creating a new element, the
9889 method will use the OEB 1.2 element name and create the element
9890 underneath <dc-metadata> if an existing <dc-metadata> element is found
9891 underneath <metadata>. If no existing <dc-metadata> element is found,
9892 the new element will be created with the OPF 2.0 element name directly
9893 underneath <metadata>. Regardless, it is probably a good idea to call
9894 L</fix_oeb12()> or L</fix_opf20()> after calling this method to ensure
9895 a consistent scheme.
9896  
9897 =head3 Arguments
9898  
9899 Three optional named arguments can be passed:
9900  
9901 =over
9902  
9903 =item * C<text>
9904  
9905 Specifies the author text to set. If omitted and a primary author
9906 element exists, the text will be left as is; if omitted and a primary
9907 author element cannot be found, an error message will be generated and
9908 the method will return undef.
9909  
9910 =item * C<fileas>
9911  
9912 Specifies the 'file-as' attribute to set. If omitted and a primary
9913 author element exists, any existing attribute will be left untouched;
9914 if omitted and a primary author element cannot be found, the newly
9915 created element will not have this attribute.
9916  
9917 =item * C<id>
9918  
9919 Specifies the 'id' attribute to set. If this is specified, and the id
9920 is already in use, a warning will be added but the method will
9921 continue, removing the id attribute from the element that previously
9922 contained it.
9923  
9924 If this is omitted and a primary author element exists, any existing
9925 id will be left untouched; if omitted and a primary author element
9926 cannot be found, the newly created element will not have an id set.
9927  
9928 =back
9929  
9930 If called with no arguments, the only effect this method has is to
9931 enforce that either an 'opf:role' or 'role' attribute is set to 'aut'
9932 on the primary author element.
9933  
9934 =head3 Return values
9935  
9936 Returns 1 if successful, returns undef and sets an error message if
9937 the author argument is missing and no primary author element was
9938 found.
9939  
9940 =cut
9941  
9942 sub set_primary_author :method {
9943 my ($self,%args) = @_;
9944 my $subname = ( caller(0) )[3];
9945 croak($subname . "() called as a procedure") unless(ref $self);
9946 debug(2,"DEBUG[",$subname,"]");
9947 my %valid_args = (
9948 'text' => 1,
9949 'fileas' => 1,
9950 'id' => 1,
9951 );
9952 foreach my $arg (keys %args) {
9953 croak($subname,"(): invalid argument '",$arg,"'")
9954 if(!$valid_args{$arg});
9955 }
9956  
9957 my $twigroot = $self->{twigroot};
9958 $self->fix_metastructure_basic();
9959 my $meta = $twigroot->first_child('metadata');
9960 my $dcmeta = $meta->first_child('dc-metadata');
9961 my $element;
9962 my $newauthor = $args{text};
9963 my $newfileas = $args{fileas};
9964 my $newid = $args{id};
9965 my $idelem;
9966 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
9967  
9968 $element = $twigroot->first_descendant(\&twigelt_is_author);
9969 $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
9970  
9971 unless($element) {
9972 unless($newauthor) {
9973 add_error(
9974 $subname,
9975 "(): cannot create a new author element when the author is not specified");
9976 return;
9977 }
9978 if($dcmeta) {
9979 $element = $dcmeta->insert_new_elt('last_child','dc:Creator');
9980 $element->set_att('role' => 'aut');
9981 $element->set_att('file-as' => $newfileas) if($newfileas);
9982 }
9983 else {
9984 $element = $meta->insert_new_elt('last_child','dc:creator');
9985 $element->set_att('opf:role' => 'aut');
9986 $element->set_att('opf:file-as' => $newfileas) if($newfileas);
9987 }
9988 } # unless($element)
9989 $element->set_text($newauthor);
9990  
9991 if($idelem && $idelem->cmp($element) ) {
9992 $self->add_warning(
9993 $subname,"(): reassigning id '",$newid,
9994 "' from a '",$idelem->gi,"' element!"
9995 );
9996 $idelem->del_att('id');
9997 }
9998 $element->set_att('id' => $newid) if($newid);
9999 return 1;
10000 }
10001  
10002  
10003 =head2 C<set_publisher(%args)>
10004  
10005 Sets the text and optionally the ID of the first dc:publisher element
10006 found (case-insensitive). Creates the element if one did not exist.
10007 If a <dc-metadata> element exists underneath <metadata>, the publisher
10008 element will be created underneath the <dc-metadata> in OEB 1.2
10009 format, otherwise the title element is created underneath <metadata>
10010 in OPF 2.0 format.
10011  
10012 Returns 1 on success, returns undef if no publisher was specified.
10013  
10014 =head3 Arguments
10015  
10016 C<set_publisher()> takes one required and one optional named argument
10017  
10018 =over
10019  
10020 =item C<text>
10021  
10022 This specifies the publisher name to set as the text of the element.
10023 If not specified, the method returns undef.
10024  
10025 =item C<id> (optional)
10026  
10027 This specifies the ID to set on the element. If set and the ID is
10028 already in use, a warning is logged and the ID is removed from the
10029 other location and assigned to the element.
10030  
10031 =back
10032  
10033 =head3 Example
10034  
10035 $retval = $ebook->set_publisher('text' => 'My Publishing House',
10036 'id' => 'mypubid');
10037  
10038 =cut
10039  
10040 sub set_publisher :method {
10041 my ($self,%args) = @_;
10042 my $subname = ( caller(0) )[3];
10043 croak($subname . "() called as a procedure") unless(ref $self);
10044 debug(2,"DEBUG[",$subname,"]");
10045 my %valid_args = (
10046 'text' => 1,
10047 'id' => 1,
10048 );
10049 foreach my $arg (keys %args) {
10050 croak($subname,"(): invalid argument '",$arg,"'")
10051 if(!$valid_args{$arg});
10052 }
10053  
10054 my $publisher = $args{text};
10055 return unless($publisher);
10056  
10057 my $newid = $args{id};
10058 my $idelem;
10059 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10060  
10061 $self->fix_metastructure_basic();
10062 my $element = $self->{twigroot}->first_descendant(qr/^dc:publisher$/ix);
10063 my $meta = $self->{twigroot}->first_child('metadata');
10064 my $dcmeta = $meta->first_child('dc-metadata');
10065  
10066 if(!$element && $dcmeta) {
10067 $element = $dcmeta->insert_new_elt('last_child','dc:Publisher');
10068 }
10069 elsif(!$element) {
10070 $element = $meta->insert_new_elt('last_child','dc:publisher');
10071 }
10072 $element->set_text($publisher);
10073 if($idelem && $idelem->cmp($element) ) {
10074 $self->add_warning(
10075 $subname,"(): reassigning id '",$newid,
10076 "' from a '",$idelem->gi,"' element!"
10077 );
10078 $idelem->del_att('id');
10079 }
10080 $element->set_att('id' => $newid) if($newid);
10081 return 1;
10082 }
10083  
10084  
10085 =head2 set_review(%args)
10086  
10087 Sets the text and optionally ID of the first <Review> element found
10088 (case-insensitive), creating the element if one did not exist.
10089  
10090 This is a Mobipocket-specific element and if it needs to be created it
10091 will always be created under <x-metadata> with
10092 L</fix_metastructure_oeb12()> called to ensure that <x-metadata>
10093 exists.
10094  
10095 Returns 1 on success, returns undef if no review text was specified
10096  
10097 =head3 Arguments
10098  
10099 =over
10100  
10101 =item C<text>
10102  
10103 This specifies the description to use as the text of the element. If
10104 not specified, the method returns undef.
10105  
10106 =item C<id> (optional)
10107  
10108 This specifies the ID to set on the element. If set and the ID is
10109 already in use, a warning is logged and the ID is removed from the
10110 other location and assigned to the element.
10111  
10112 =back
10113  
10114 =head3 Example
10115  
10116 $retval = $ebook->set_review('text' => 'This book is perfect!',
10117 'id' => 'revid');
10118  
10119 =cut
10120  
10121 sub set_review :method {
10122 my ($self,%args) = @_;
10123 my $subname = ( caller(0) )[3];
10124 croak($subname . "() called as a procedure") unless(ref $self);
10125 debug(2,"DEBUG[",$subname,"]");
10126 my %valid_args = (
10127 'text' => 1,
10128 'id' => 1,
10129 );
10130 foreach my $arg (keys %args) {
10131 croak($subname,"(): invalid argument '",$arg,"'")
10132 if(!$valid_args{$arg});
10133 }
10134  
10135 my $text = $args{text};
10136 unless($text) {
10137 $self->add_error($subname,"(): no text specified");
10138 return;
10139 }
10140  
10141 $self->fix_metastructure_oeb12();
10142 $self->set_metadata(gi => 'Review',
10143 parent => 'x-metadata',
10144 text => $args{text},
10145 id => $args{id});
10146  
10147 return 1;
10148 }
10149  
10150  
10151 =head2 C<set_rights(%args)>
10152  
10153 Sets the text of the first dc:rights or dc:copyrights element found
10154 (case-insensitive). If the element found has the gi of dc:copyrights,
10155 it will be changed to dc:rights. This is to correct certain
10156 noncompliant Mobipocket files.
10157  
10158 Creates the element if one did not exist. If a <dc-metadata> element
10159 exists underneath <metadata>, the title element will be created
10160 underneath the <dc-metadata> in OEB 1.2 format, otherwise the title
10161 element is created underneath <metadata> in OPF 2.0 format.
10162  
10163 Returns 1 on success, returns undef if no rights string was specified.
10164  
10165 =head3 Arguments
10166  
10167 =over
10168  
10169 =item * C<text>
10170  
10171 This specifies the text of the element. If not specified, the method
10172 returns undef.
10173  
10174 =item * C<id> (optional)
10175  
10176 This specifies the ID to set on the element. If set and the ID is
10177 already in use, a warning is logged but the method continues anyway.
10178  
10179 =back
10180  
10181 =cut
10182  
10183 sub set_rights :method {
10184 my ($self,%args) = @_;
10185 my $subname = ( caller(0) )[3];
10186 croak($subname . "() called as a procedure") unless(ref $self);
10187 debug(2,"DEBUG[",$subname,"]");
10188 my %valid_args = (
10189 'text' => 1,
10190 'id' => 1,
10191 );
10192 foreach my $arg (keys %args) {
10193 croak($subname,"(): invalid argument '",$arg,"'")
10194 if(!$valid_args{$arg});
10195 }
10196 my $rights = $args{text};
10197 return unless($rights);
10198 my $newid = $args{id};
10199 my $idelem;
10200 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10201  
10202 $self->fix_metastructure_basic();
10203 my $element = $self->{twigroot}->first_descendant(qr/^dc:(copy)?rights$/ix);
10204 my $meta = $self->{twigroot}->first_child('metadata');
10205 my $dcmeta = $meta->first_child('dc-metadata');
10206 my $parent = $dcmeta || $meta;
10207  
10208 $element ||= $parent->insert_new_elt('last_child','dc:rights');
10209 $element->set_text($rights);
10210 $element->set_gi('dc:Rights') if($element->gi eq 'dc:Copyrights');
10211 $element->set_gi('dc:rights') if($element->gi eq 'dc:copyrights');
10212 if($idelem && $idelem->cmp($element) ) {
10213 $self->add_warning(
10214 $subname,"(): reassigning id '",$newid,
10215 "' from a '",$idelem->gi,"' element!"
10216 );
10217 $idelem->del_att('id');
10218 }
10219 $element->set_att('id' => $newid) if($newid);
10220 return 1;
10221 }
10222  
10223  
10224 =head2 C<set_spec($spec)>
10225  
10226 Sets the OEB specification to match when modifying OPF data.
10227 Allowable values are 'OEB12', 'OPF20', and 'MOBI12'.
10228  
10229 Returns 1 if successful; returns undef and sets an error message if an
10230 unknown specification was set.
10231  
10232 =cut
10233  
10234 sub set_spec :method {
10235 my ($self,$spec) = @_;
10236 my $subname = ( caller(0) )[3];
10237 croak($subname . "() called as a procedure") unless(ref $self);
10238 debug(2,"DEBUG[",$subname,"]");
10239  
10240 unless($validspecs{$spec}) {
10241 $self->add_error($subname,"(): invalid specification '",$spec,"'");
10242 return;
10243 }
10244 $self->{spec} = $validspecs{$spec};
10245 return 1;
10246 }
10247  
10248  
10249 =head2 C<set_timestamp()>
10250  
10251 Sets the <meta property="dcterms:modified"> element to the current
10252 timestamp and removes duplicate or nonstandard timestamps.
10253  
10254 =cut
10255  
10256 sub set_timestamp :method {
10257 my ($self) = @_;
10258 my $subname = ( caller(0) )[3];
10259 croak($subname . "() called as a procedure") unless(ref $self);
10260 debug(2,"DEBUG[",$subname,"]");
10261  
10262 my @timestamps;
10263 my $twigroot = $self->{twigroot};
10264 my $time = Date::Manip::Date->new();
10265  
10266 @timestamps = $twigroot->descendants(
10267 'meta[@property="dcterms:modified" or @name="calibre:timestamp"]');
10268 foreach my $timestamp (@timestamps) {
10269 $timestamp->delete;
10270 }
10271 @timestamps = $twigroot->descendants(
10272 'dc:date[@opf:event="modification" or @event="modification"]');
10273 foreach my $timestamp (@timestamps) {
10274 $timestamp->delete;
10275 }
10276 $time->parse('now');
10277 $self->set_meta('property' => 'dcterms:modified',
10278 'text' => $time->printf('%O') );
10279 return;
10280 }
10281  
10282  
10283 =head2 C<set_title(%args)>
10284  
10285 Sets the text or id of the first dc:title element found
10286 (case-insensitive). Creates the element if one did not exist. If a
10287 <dc-metadata> element exists underneath <metadata>, the title element
10288 will be created underneath the <dc-metadata> in OEB 1.2 format,
10289 otherwise the title element is created underneath <metadata> in OPF
10290 2.0 format.
10291  
10292 =head3 Arguments
10293  
10294 set_title() takes two optional named arguments. If neither is
10295 specified, the method will do nothing.
10296  
10297 =over
10298  
10299 =item * C<text>
10300  
10301 This specifies the text of the element. If not specified, and no
10302 title element is found, an error will be set and the method will
10303 return undef -- set_title() will refuse to create a dc:title element
10304 with no text.
10305  
10306 =item * C<id>
10307  
10308 This specifies the ID to set on the element. If set and the ID is
10309 already in use, a warning is logged but the method continues anyway.
10310  
10311 =back
10312  
10313 =cut
10314  
10315 sub set_title :method {
10316 my ($self,%args) = @_;
10317 my $subname = ( caller(0) )[3];
10318 croak($subname . "() called as a procedure") unless(ref $self);
10319 debug(2,"DEBUG[",$subname,"]");
10320  
10321 my %valid_args = (
10322 'text' => 1,
10323 'id' => 1,
10324 );
10325 foreach my $arg (keys %args) {
10326 croak($subname,"(): invalid argument '",$arg,"'")
10327 if(!$valid_args{$arg});
10328 }
10329 my $title = $args{text};
10330 my $newid = $args{id};
10331 my $idelem;
10332 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10333  
10334 $self->fix_metastructure_basic();
10335 my $element = $self->{twigroot}->first_descendant(qr/^dc:title$/ix);
10336 my $meta = $self->{twigroot}->first_child('metadata');
10337 my $dcmeta = $meta->first_child('dc-metadata');
10338 my $parent = $dcmeta || $meta;
10339 unless($element) {
10340 unless($title) {
10341 add_error($subname,
10342 "(): no title specified, but no existing title found");
10343 return;
10344 }
10345 $element = $parent->insert_new_elt('last_child','dc:title');
10346 }
10347 $element->set_text($title) if($title);
10348  
10349 if($idelem && $idelem->cmp($element) ) {
10350 $self->add_warning(
10351 $subname,"(): reassigning id '",$newid,
10352 "' from a '",$idelem->gi,"' element!"
10353 );
10354 $idelem->del_att('id');
10355 }
10356 $element->set_att('id' => $newid) if($newid);
10357 return 1;
10358 }
10359  
10360  
10361 =head2 C<set_type(%args)>
10362  
10363 Sets the text and optionally the ID of the first dc:type element
10364 found (case-insensitive). Creates the element if one did not exist.
10365 If a <dc-metadata> element exists underneath <metadata>, the publisher
10366 element will be created underneath the <dc-metadata> in OEB 1.2
10367 format, otherwise the title element is created underneath <metadata>
10368 in OPF 2.0 format.
10369  
10370 Returns 1 on success, returns undef if no publisher was specified.
10371  
10372 =head3 Arguments
10373  
10374 C<set_type()> takes one required and one optional named argument
10375  
10376 =over
10377  
10378 =item C<text>
10379  
10380 This specifies the publisher name to set as the text of the element.
10381 If not specified, the method returns undef.
10382  
10383 =item C<id> (optional)
10384  
10385 This specifies the ID to set on the element. If set and the ID is
10386 already in use, a warning is logged and the ID is removed from the
10387 other location and assigned to the element.
10388  
10389 =back
10390  
10391 =head3 Example
10392  
10393 $retval = $ebook->set_type('text' => 'Short Story',
10394 'id' => 'mytypeid');
10395  
10396 =cut
10397  
10398 sub set_type :method {
10399 my ($self,%args) = @_;
10400 my $subname = ( caller(0) )[3];
10401 croak($subname . "() called as a procedure") unless(ref $self);
10402 debug(2,"DEBUG[",$subname,"]");
10403 my %valid_args = (
10404 'text' => 1,
10405 'id' => 1,
10406 );
10407 foreach my $arg (keys %args) {
10408 croak($subname,"(): invalid argument '",$arg,"'")
10409 if(!$valid_args{$arg});
10410 }
10411  
10412 my $text = $args{text};
10413 return unless($text);
10414  
10415 my $newid = $args{id};
10416 my $idelem;
10417 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10418  
10419 $self->fix_metastructure_basic();
10420 my $element = $self->{twigroot}->first_descendant(qr/^dc:type$/ix);
10421 my $meta = $self->{twigroot}->first_child('metadata');
10422 my $dcmeta = $meta->first_child('dc-metadata');
10423  
10424 if(!$element && $dcmeta) {
10425 $element = $dcmeta->insert_new_elt('last_child','dc:Type');
10426 }
10427 elsif(!$element) {
10428 $element = $meta->insert_new_elt('last_child','dc:type');
10429 }
10430 $element->set_text($text);
10431 if($idelem && $idelem->cmp($element) ) {
10432 $self->add_warning(
10433 $subname,"(): reassigning id '",$newid,
10434 "' from a '",$idelem->gi,"' element!"
10435 );
10436 $idelem->del_att('id');
10437 }
10438 $element->set_att('id' => $newid) if($newid);
10439 return 1;
10440 }
10441  
10442  
10443 ################################
10444 ########## PROCEDURES ##########
10445 ################################
10446  
10447 =head1 PROCEDURES
10448  
10449 All procedures are exportable, but none are exported by default. All
10450 procedures can be exported by using the ":all" tag.
10451  
10452  
10453 =head2 C<_lc>
10454  
10455 Wrapper for CORE::lc to get around the fact that builtins can't be
10456 used in dispatch tables prior to Perl 5.16.
10457  
10458 WARNING: this procedure may disappear once Perl 5.16 is standard on
10459 all systems in common use! For that reason, this is not exportable.
10460  
10461 =cut
10462  
10463 sub _lc {
10464 my ($string) = @_;
10465 return lc $string;
10466 }
10467  
10468  
10469 =head2 C<_uc>
10470  
10471 Wrapper for CORE::uc to get around the fact that builtins can't be
10472 used in dispatch tables prior to Perl 5.16.
10473  
10474 WARNING: this procedure may disappear once Perl 5.16 is standard on
10475 all systems in common use! For that reason, this is not exportable.
10476  
10477 =cut
10478  
10479 sub _uc {
10480 my ($string) = @_;
10481 return uc $string;
10482 }
10483  
10484  
10485 =head2 C<capitalize($string)>
10486  
10487 Capitalizes the first letter of each word in $string.
10488  
10489 Returns the corrected string.
10490  
10491 =cut
10492  
10493 sub capitalize {
10494 my ($string) = @_;
10495 $string =~ s/(?<=\w)(.)/\l$1/gx;
10496 return $string;
10497 }
10498  
10499  
10500 =head2 C<clean_filename($string)>
10501  
10502 Takes an input string and cleans out any characters that would not be
10503 valid in a filename.
10504  
10505 Returns the cleaned string.
10506  
10507 =cut
10508  
10509 sub clean_filename {
10510 my ($string) = @_;
10511 $string =~ s/[^A-Za-z0-9_ \-\.]//g;
10512 return $string;
10513 }
10514  
10515  
10516 =head2 C<create_epub_container($opffile)>
10517  
10518 Creates the XML file META-INF/container.xml pointing to the
10519 specified OPF file.
10520  
10521 Creates the META-INF directory if necessary. Will destroy any
10522 non-directory file named 'META-INF' in the current directory. If
10523 META-INF/container.xml already exists, it will rename that file to
10524 META-INF/container.xml.backup.
10525  
10526 =head3 Arguments
10527  
10528 =over
10529  
10530 =item $opffile
10531  
10532 The OPF filename (and path, if necessary) to use in the container. If
10533 not specified, looks for a sole OPF file in the current working
10534 directory. Fails if more than one is found.
10535  
10536 =back
10537  
10538 =head3 Return values
10539  
10540 =over
10541  
10542 =item Returns a twig representing the container data if successful, undef
10543 otherwise
10544  
10545 =back
10546  
10547 =cut
10548  
10549 sub create_epub_container {
10550 my ($opffile) = @_;
10551 my $subname = ( caller(0) )[3];
10552 debug(2,"DEBUG[",$subname,"]");
10553  
10554 my $twig;
10555 my $twigroot;
10556 my $rootfiles;
10557 my $element;
10558 my $fh_container;
10559  
10560 if($opffile eq '') { return; }
10561  
10562 if(-e 'META-INF') {
10563 if(! -d 'META-INF') {
10564 unlink('META-INF') or return;
10565 mkdir('META-INF') or return;
10566 }
10567 }
10568 else { mkdir('META-INF') or return; }
10569  
10570 $twig = XML::Twig->new(
10571 output_encoding => 'utf-8',
10572 pretty_print => 'record'
10573 );
10574  
10575 $element = XML::Twig::Elt->new('container');
10576 $element->set_att('version' => '1.0',
10577 'xmlns' => 'urn:oasis:names:tc:opendocument:xmlns:container');
10578 $twig->set_root($element);
10579 $twigroot = $twig->root;
10580  
10581 $rootfiles = $twigroot->insert_new_elt('first_child','rootfiles');
10582 $element = $rootfiles->insert_new_elt('first_child','rootfile');
10583 $element->set_att('full-path',$opffile);
10584 $element->set_att('media-type','application/oebps-package+xml');
10585  
10586  
10587 # Backup existing file
10588 if(-e 'META-INF/container.xml') {
10589 rename('META-INF/container.xml','META-INF/container.xml.backup')
10590 or croak($subname,"(): could not backup container.xml!");
10591 }
10592  
10593 open($fh_container,'>:encoding(UTF-8)','META-INF/container.xml')
10594 or croak($subname,"(): could not write to 'META-INF/container.xml'\n");
10595 $twig->print(\*$fh_container);
10596 close($fh_container)
10597 or croak($subname,"(): could not close 'META-INF/container.xml'\n");
10598 return $twig;
10599 }
10600  
10601  
10602 =head2 C<create_epub_mimetype()>
10603  
10604 Creates a file named 'mimetype' in the current working directory
10605 containing 'application/epub+zip' (no trailing newline)
10606  
10607 Destroys and overwrites that file if it exists.
10608  
10609 Returns the mimetype string if successful, undef otherwise.
10610  
10611 =cut
10612  
10613 sub create_epub_mimetype {
10614 my $subname = ( caller(0) )[3];
10615 debug(2,"DEBUG[",$subname,"]");
10616  
10617 my $mimetype = "application/epub+zip";
10618 my $fh_mimetype;
10619  
10620 open($fh_mimetype,">",'mimetype') or return;
10621 print {*$fh_mimetype} $mimetype;
10622 close($fh_mimetype) or croak($subname,"(): failed to close filehandle [$!]");
10623  
10624 return $mimetype;
10625 }
10626  
10627  
10628 =head2 C<debug($level,@message)>
10629  
10630 Prints a debugging message to C<STDERR> if package variable C<$debug>
10631 is greater than or equal to C<$level>. A trailing newline is
10632 appended, and should not be part of @message.
10633  
10634 Returns true or dies.
10635  
10636 =cut
10637  
10638 sub debug {
10639 my ($level,@message) = @_;
10640 my $subname = ( caller(0) )[3];
10641 croak($subname,"(): no debugging level specified") unless($level);
10642 croak($subname,"(): invalid debugging level '",$level,"'")
10643 unless( $level =~ /^\d$/ );
10644 croak($subname,"(): no message specified") unless(@message);
10645 print {*STDERR} @message,"\n" if($debug >= $level);
10646 return 1;
10647 }
10648  
10649  
10650 =head2 C<excerpt_line($text)>
10651  
10652 Takes as an argument a list of text pieces that will be joined. If
10653 the joined length is less than 70, all of the joined text is returned.
10654  
10655 If the joined length is greater than 70, the return string is the
10656 first 30 characters followed by C<' [...] '> followed by the last 30
10657 characters.
10658  
10659 =cut
10660  
10661 sub excerpt_line {
10662 my @parts = @_;
10663 my $subname = ( caller(0) )[3];
10664 my $text = join('',@parts);
10665 if(length($text) > 70)
10666 {
10667 $text =~ /^ (.{30}) .*? (.{30}) $/sx;
10668 return ($1 . ' [...] ' . $2);
10669 }
10670 else { return $text; }
10671 }
10672  
10673  
10674 =head2 C<find_in_path($pattern,@extradirs)>
10675  
10676 Searches through C<$ENV{PATH}> (and optionally any additional
10677 directories specified in C<@extradirs>) for the first regular file
10678 matching C<$pattern>. C<$pattern> itself can take two forms: if
10679 passed a C<qr//> regular expression, that expression is used directly.
10680 If passed any other string, that string will be used for a
10681 case-insensitive exact match where the extension '.bat', '.com', or
10682 '.exe' is optional (i.e. the final pattern will be
10683 C<qr/^ $pattern (\.bat|\.com|\.exe)? $/ix>).
10684  
10685 Returns the first match found, or undef if there were no matches or if
10686 no pattern was specified.
10687  
10688 =cut
10689  
10690 sub find_in_path {
10691 my ($pattern,@extradirs) = @_;
10692 return unless($pattern);
10693 my $subname = ( caller(0) )[3];
10694 debug(3,"DEBUG[",$subname,"]");
10695  
10696 my $regexp;
10697 my @dirs;
10698 my $fh_dir;
10699 my @filelist;
10700 my $envsep = ':';
10701 my $filesep = '/';
10702 if($OSNAME eq 'MSWin32') {
10703 $envsep = ';';
10704 $filesep = "\\";
10705 }
10706  
10707 if(ref($pattern) eq 'Regexp') { $regexp = $pattern; }
10708 else { $regexp = qr/^ $pattern (\.bat|\.com|\.exe)? $/ix; }
10709  
10710 @dirs = split(/$envsep/,$ENV{PATH});
10711 unshift(@dirs,@extradirs) if(@extradirs);
10712 foreach my $dir (@dirs) {
10713 if(-d $dir) {
10714 if(opendir($fh_dir,$dir)) {
10715 @filelist = grep { /$regexp/ } readdir($fh_dir);
10716 @filelist = grep { -f "$dir/$_" } @filelist;
10717 closedir($fh_dir);
10718  
10719 if(@filelist) { return $dir . $filesep . $filelist[0]; }
10720 }
10721 }
10722 }
10723 return;
10724 }
10725  
10726 =head2 C<find_links($filename)>
10727  
10728 Searches through a file for href and src attributes, and returns a
10729 list of unique links with any named anchors removed
10730 (e.g. 'myfile.html#part7' returns as just 'myfile.html'). If no links
10731 are found, or the file does not exist, returns undef.
10732  
10733 Does not check to see if the links are local. Requires that links be
10734 surrounded by double quotes, not single or left bare. Assumes that
10735 any link will not be broken across multiple lines, so it will (for
10736 example) fail to find:
10737  
10738 <img src=
10739 "myfile.jpg">
10740  
10741 though it can find:
10742  
10743 <img
10744 src="myfile.jpg">
10745  
10746 This also does not distinguish between local files and remote links.
10747  
10748 =cut
10749  
10750 sub find_links {
10751 my ($filename) = @_;
10752 return unless(-f $filename);
10753 my $subname = ( caller(0) )[3];
10754 debug(3,"DEBUG[",$subname,"]");
10755  
10756 my $fh;
10757 my %linkhash;
10758 my @links;
10759  
10760 my $subdir = dirname($filename);
10761 if($subdir eq '.') {
10762 $subdir = '';
10763 }
10764 else {
10765 $subdir = $subdir . '/';
10766 }
10767  
10768 open($fh,'<:raw',$filename)
10769 or croak($subname,"(): unable to open '",$filename,"'\n");
10770  
10771 while(<$fh>) {
10772 @links = /(?:href|src) \s* = \s* "
10773 ([^">]+)/gix;
10774 foreach my $link (@links) {
10775 # Perform URI decoding
10776 $link = uri_unescape($link);
10777  
10778 # Strip off any named anchors
10779 $link =~ s/#.*$//;
10780 next unless $link;
10781  
10782 # Skip links that begin with backwards directory traversal
10783 next if $link =~ m#^\.\./.*$#;
10784  
10785 # Strip javascript: hrefs
10786 next if $link =~ m#javascript:#;
10787  
10788 # Baen HTML sources in particular may contain javascript
10789 # href generators
10790 next if $link =~ /\+ /;
10791  
10792 # If the link is not a URI and we are in a subdirectory
10793 # relative to the OPF, ensure that subdirectory is placed
10794 # as a prefix.
10795 if($subdir and $link !~ m#^ \w+://#ix) {
10796 $link = $subdir . $link;
10797 }
10798 debug(2, "DEBUG: found link '",$link,"'");
10799 $linkhash{$link}++;
10800 }
10801 }
10802 if(%linkhash) { return keys(%linkhash); }
10803 else { return; }
10804 }
10805  
10806  
10807 =head2 C<find_opffile()>
10808  
10809 Attempts to locate an OPF file, first by calling
10810 L</get_container_rootfile()> to check the contents of
10811 C<META-INF/container.xml>, and then by looking for a single file with
10812 the extension C<.opf> in the current working directory.
10813  
10814 Returns the filename of the OPF file, or undef if nothing was found.
10815  
10816 =cut
10817  
10818 sub find_opffile {
10819 my $subname = ( caller(0) )[3];
10820 my $opffile = get_container_rootfile();
10821  
10822 if(!$opffile) {
10823 my @candidates = glob("*.opf");
10824 if(scalar(@candidates) > 1) {
10825 debug(1,"DEBUG: Multiple OPF files found, but no container",
10826 " to specify which one to choose!");
10827 return;
10828 }
10829 if(scalar(@candidates) < 1) {
10830 debug(1,"DEBUG: No OPF files found!");
10831 return;
10832 }
10833 $opffile = $candidates[0];
10834 }
10835 return $opffile;
10836 }
10837  
10838  
10839 =head2 C<fix_datestring($datestring)>
10840  
10841 Takes a date string and attempts to convert it to the limited subset
10842 of ISO8601 allowed by the OPF standard (YYYY, YYYY-MM, or YYYY-MM-DD).
10843  
10844 In the special case of finding MM/DD/YYYY, it assumes that it was a
10845 Mobipocket-mangled date, and not only converts it, but will strip the
10846 day information if the day is '01', and both the month and day
10847 information if both month and day are '01'. This is because
10848 Mobipocket Creator enforces a complete MM/DD/YYYY even if the month
10849 and day aren't known, and it is common practice to use 01 for an
10850 unknown value.
10851  
10852 =head3 Arguments
10853  
10854 =over
10855  
10856 =item $datestring
10857  
10858 A date string in a format recognizable by Date::Manip
10859  
10860 =back
10861  
10862 =head3 Returns $fixeddate
10863  
10864 =over
10865  
10866 =item $fixeddate : the corrected string, or undef on failure
10867  
10868 =back
10869  
10870 =cut
10871  
10872 sub fix_datestring {
10873 my ($datestring) = @_;
10874 return unless($datestring);
10875 my $subname = ( caller(0) )[3];
10876 debug(2,"DEBUG[",$subname,"]");
10877  
10878 my $date;
10879 my ($year,$month,$day);
10880 my $fixeddate;
10881  
10882 $_ = $datestring;
10883  
10884 debug(3,"DEBUG: checking M(M)/D(D)/YYYY");
10885 if(( ($month,$day,$year) = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/x ) == 3) {
10886 # We have a XX/XX/XXXX datestring
10887 debug(3,"DEBUG: found '",$month,"/",$day,"/",$year,"'");
10888 ($year,$month,$day) = ymd_validate($year,$month,$day);
10889 if($year) {
10890 $fixeddate = $year;
10891 $fixeddate .= sprintf("-%02u",$month)
10892 unless( ($month == 1) && ($day == 1) );
10893 $fixeddate .= sprintf("-%02u",$day) unless($day == 1);
10894 debug(3,"DEBUG: returning '",$fixeddate,"'");
10895 return $fixeddate;
10896 }
10897 }
10898  
10899 debug(3,"DEBUG: checking M(M)/YYYY");
10900 if(( ($month,$year) = /^(\d{1,2})\/(\d{4})$/x ) == 2) {
10901 # We have a XX/XXXX datestring
10902 debug(3,"DEBUG: found '",$month,"/",$year,"'");
10903 if($month <= 12) {
10904 # We probably have MM/YYYY
10905 $fixeddate = sprintf("%04u-%02u",$year,$month);
10906 debug(3,"DEBUG: returning '",$fixeddate,"'");
10907 return $fixeddate;
10908 }
10909 }
10910  
10911 # These regexps will reduce '2009-xx-01' to just 2009
10912 # We don't want this, so don't use them.
10913 # ($year,$month,$day) = /(\d{4})-?(\d{2})?-?(\d{2})?/;
10914 # ($year,$month,$day) = /(\d{4})(?:-?(\d{2})-?(\d{2}))?/;
10915  
10916 # Force exact match)
10917 debug(3,"DEBUG: checking YYYY-MM-DD");
10918 ($year,$month,$day) = /^(\d{4})-(\d{2})-(\d{2})$/x;
10919 ($year,$month,$day) = ymd_validate($year,$month,$day);
10920  
10921 if(!$year) {
10922 debug(3,"DEBUG: checking YYYYMMDD");
10923 ($year,$month,$day) = /^(\d{4})(\d{2})(\d{2})$/x;
10924 ($year,$month,$day) = ymd_validate($year,$month,$day);
10925 }
10926  
10927 if(!$year) {
10928 debug(3,"DEBUG: checking YYYY-M(M)");
10929 ($year,$month) = /^(\d{4})-(\d{1,2})$/x;
10930 ($year,$month) = ymd_validate($year,$month,undef);
10931 }
10932  
10933 if(!$year) {
10934 debug(3,"DEBUG: checking YYYY");
10935 ($year) = /^(\d{4})$/x;
10936 }
10937  
10938 # At this point, we've exhausted all of the common cases. We use
10939 # Date::Manip to hit all of the unlikely ones as well. This comes
10940 # with a drawback: Date::Manip doesn't distinguish between 2008
10941 # and 2008-01-01, but we should have covered that above.
10942 #
10943 # Note that Date::Manip will die on MS Windows system unless the
10944 # TZ environment variable is set in a specific manner.
10945 # See:
10946 # http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES
10947  
10948 if(!$year) {
10949 $date = ParseDate($datestring);
10950 $year = UnixDate($date,"%Y");
10951 $month = UnixDate($date,"%m");
10952 $day = UnixDate($date,"%d");
10953 debug(2,"DEBUG: Date::Manip found '",UnixDate($date,"%Y-%m-%d"),"'");
10954 }
10955  
10956 if($year) {
10957 # If we still have a $year, $month and $day either don't exist
10958 # or are plausibly valid.
10959 print {*STDERR} "DEBUG: found year=",$year," " if($debug >= 2);
10960 $fixeddate = sprintf("%04u",$year);
10961 if($month) {
10962 print {*STDERR} "month=",$month," " if($debug >= 2);
10963 $fixeddate .= sprintf("-%02u",$month);
10964 if($day) {
10965 print {*STDERR} "day=",$day if($debug >= 2);
10966 $fixeddate .= sprintf("-%02u",$day);
10967 }
10968 }
10969 print {*STDERR} "\n" if($debug >= 2);
10970 debug(2,"DEBUG: returning '",$fixeddate,"'");
10971 return $fixeddate if($fixeddate);
10972 }
10973  
10974 if(!$year) {
10975 debug(3,"fix_date: didn't find a valid date in '",$datestring,"'!");
10976 return;
10977 }
10978 elsif($debug) {
10979 print {*STDERR} "DEBUG: found ",sprintf("04u",$year);
10980 print {*STDERR} sprintf("-02u",$month) if($month);
10981 print {*STDERR} sprintf("-02u",$day),"\n" if($day);
10982 }
10983  
10984 $fixeddate = sprintf("%04u",$year);
10985 $fixeddate .= sprintf("-%02u-%02u",$month,$day);
10986 return $fixeddate;
10987 }
10988  
10989  
10990 =head2 C<get_container_rootfile($container)>
10991  
10992 Opens and parses an OPS/epub container, extracting the 'full-path'
10993 attribute of element 'rootfile'
10994  
10995 =head3 Arguments
10996  
10997 =over
10998  
10999 =item $container
11000  
11001 The OPS container to parse. Defaults to 'META-INF/container.xml'
11002  
11003 =back
11004  
11005 =head3 Return values
11006  
11007 =over
11008  
11009 =item Returns a string containing the rootfile on success, undef on failure.
11010  
11011 =back
11012  
11013 =cut
11014  
11015 sub get_container_rootfile {
11016 my ($container) = @_;
11017 my $subname = ( caller(0) )[3];
11018 debug(2,"DEBUG[",$subname,"]");
11019  
11020 my $twig = XML::Twig->new();
11021 my $rootfile;
11022 my $retval = undef;
11023  
11024 $container = 'META-INF/container.xml' if(! $container);
11025  
11026 if(-f $container) {
11027 $twig->parsefile($container) or return;
11028 $rootfile = $twig->root->first_descendant('rootfile');
11029 return unless($rootfile);
11030 $retval = $rootfile->att('full-path');
11031 }
11032 return $retval;
11033 }
11034  
11035  
11036 =head2 C<hashvalue_key_self(\%hash, $modifier)>
11037  
11038 Takes as an argument a hash reference and an optional modifier and
11039 inserts a new key for every value in that hash if no such key already
11040 exists.
11041  
11042 If the modifer is set to 'lc' or 'uc', the value is either lowercased
11043 or uppercased respectively before it is used as a key.
11044  
11045 Croaks if the first argument is not a hashref, or if an invalid
11046 modifier string is used.
11047  
11048 =cut
11049  
11050 sub hashvalue_key_self {
11051 my ($hashref, $modifier) = @_;
11052 my $subname = ( caller(0) )[3];
11053 debug(4,"DEBUG[",$subname,"]");
11054  
11055 if (not $hashref or not ref($hashref)) {
11056 croak($subname,"(): first argument is not a reference");
11057 }
11058 elsif (!UNIVERSAL::isa($hashref,'HASH')) {
11059 croak($subname,"(): first argument is not a hashref");
11060 }
11061  
11062 my %modifier_dispatch = (
11063 'lc' => \&_lc,
11064 'uc' => \&_uc,
11065 );
11066  
11067 if ($modifier and not $modifier_dispatch{$modifier}) {
11068 croak($subname,"(): ",$modifier," is not a valid modifier string");
11069 }
11070  
11071 foreach my $value (values %{$hashref}) {
11072 my $key;
11073 if($modifier) {
11074 $key = $modifier_dispatch{$modifier}($value);
11075 }
11076 else {
11077 $key = $value;
11078 }
11079 if (! $hashref->{$key}) {
11080 $hashref->{$key} = $value;
11081 }
11082 }
11083 return;
11084 }
11085  
11086  
11087 =head2 C<hexstring($bindata)>
11088  
11089 Takes as an argument a scalar containing a sequence of binary bytes.
11090 Returns a string converting each octet of the data to its two-digit
11091 hexadecimal equivalent. There is no leading "0x" on the string.
11092  
11093 =cut
11094  
11095 sub hexstring {
11096 my $data = shift;
11097 my $subname = ( caller(0) )[3];
11098 debug(4,"DEBUG[",$subname,"]");
11099  
11100 croak($subname,"(): no data provided")
11101 unless($data);
11102  
11103 my $byte;
11104 my $retval = '';
11105 my $pos = 0;
11106  
11107 while($pos < length($data)) {
11108 $byte = unpack("C",substr($data,$pos,1));
11109 $retval .= sprintf("%02x",$byte);
11110 $pos++;
11111 }
11112 return $retval;
11113 }
11114  
11115  
11116 =head2 C<print_memory($label)>
11117  
11118 Checks /proc/$PID/statm and prints out a line to STDERR showing the
11119 current memory usage. This is a debugging tool that will likely fail
11120 to do anything useful on a system without a /proc system compatible
11121 with Linux.
11122  
11123 =head3 Arguments
11124  
11125 =over
11126  
11127 =item $label
11128  
11129 If defined, will be output along with the memory usage.
11130  
11131 =back
11132  
11133 Returns 1 on success, undef otherwise.
11134  
11135 =cut
11136  
11137 sub print_memory {
11138 my ($label) = @_;
11139 my $subname = ( caller(0) )[3];
11140 debug(2,"DEBUG[",$subname,"]");
11141  
11142 my @mem;
11143 my $fh_procstatm;
11144  
11145 if(!open($fh_procstatm,"<","/proc/$$/statm")) {
11146 print "[",$label,"]: " if(defined $label);
11147 print "Couldn't open /proc/$$/statm [$!]\n";
11148 return;
11149 }
11150  
11151 @mem = split(/\s+/,<$fh_procstatm>);
11152 close($fh_procstatm);
11153  
11154 # @mem[0]*4 = size (kb)
11155 # @mem[1]*4 = resident (kb)
11156 # @mem[2]*4 = shared (kb)
11157 # @mem[3] = trs
11158 # @mem[4] = lrs
11159 # @mem[5] = drs
11160 # @mem[6] = dt
11161  
11162 print "Current memory usage";
11163 print " [".$label."]" if(defined $label);
11164 print ": size=",$mem[0]*4,"k";
11165 print " resident=",$mem[1]*4,"k";
11166 print " shared=",$mem[2]*4,"k\n";
11167 return 1;
11168 }
11169  
11170  
11171  
11172 =head2 C<split_metadata($metahtmlfile, $metafile)>
11173  
11174 Takes a psuedo-HTML containing one or more <metadata>...</metadata>
11175 blocks and splits out the metadata blocks into an XML file ready to be
11176 used as an OPF document. The input HTML file is rewritten without the
11177 metadata.
11178  
11179 If $metafile (or the temporary HTML-only file created during the
11180 split) already exists, it will be moved to filename.backup.
11181  
11182 =head3 Arguments
11183  
11184 =over
11185  
11186 =item C<$metahtmlfile>
11187  
11188 The filename of the pseudo-HTML file
11189  
11190 =item C<$metafile> (optional)
11191  
11192 The filename to write out any extracted metadata. If not specified,
11193 will default to the basename of $metahtmlfile with '.opf' appended.
11194  
11195 =back
11196  
11197 Returns the filename the metadata was written to, or undef if no
11198 metadata was found.
11199  
11200 =cut
11201  
11202 sub split_metadata {
11203 my ($metahtmlfile,$metafile) = @_;
11204 my $subname = ( caller(0) )[3];
11205 debug(2,"DEBUG[",$subname,"]");
11206  
11207 croak($subname,"(): no input file specified")
11208 if(!$metahtmlfile);
11209  
11210 croak($subname,"(): input file has zero size")
11211 if(-z $metahtmlfile);
11212  
11213 my @metablocks;
11214 my @guideblocks;
11215 my $htmlfile;
11216  
11217 my ($filebase,$filedir,$fileext);
11218 my ($fh_metahtml,$fh_meta,$fh_html);
11219  
11220 ($filebase,$filedir,$fileext) = fileparse($metahtmlfile,'\.\w+$');
11221 $metafile = $filedir . $filebase . ".opf" if(!$metafile);
11222 $htmlfile = $filedir . $filebase . "-html.html";
11223  
11224 debug(2,"DEBUG: metahtml='",$metahtmlfile,"' meta='",$metafile,
11225 " html='",$htmlfile,"'");
11226  
11227 # Move existing output files to avoid overwriting them
11228 if(-f $metafile) {
11229 debug(3, "DEBUG: moving metafile '",$metafile,"'");
11230 croak ($subname,"(): output file '",$metafile,
11231 "' exists and could not be moved!")
11232 if(! rename($metafile,"$metafile.backup") );
11233 }
11234 if(-f $htmlfile) {
11235 debug(3, "DEBUG: moving htmlfile '",$htmlfile,"'");
11236 croak ($subname,"(): output file '",$htmlfile,
11237 "' exists and could not be moved!")
11238 if(! rename($htmlfile,"$metafile.backup") );
11239 }
11240  
11241 debug(2," splitting '",$metahtmlfile,"'");
11242 open($fh_metahtml,"<:raw",$metahtmlfile)
11243 or croak($subname,"(): Failed to open '",$metahtmlfile,"' for reading!");
11244 open($fh_meta,">:raw",$metafile)
11245 or croak($subname,"(): Failed to open '",$metafile,"' for writing!");
11246 open($fh_html,">:raw",$htmlfile)
11247 or croak($subname,"(): Failed to open '",$htmlfile,"' for writing!");
11248  
11249  
11250 # Preload the return value with the OPF headers
11251 print $fh_meta $utf8xmldec,$oeb12doctype,"<package>\n";
11252 #print $fh_meta $utf8xmldec,$opf20package;
11253  
11254 # Finding and removing all of the metadata requires that the
11255 # entire thing be handled as one slurped string, so temporarily
11256 # undefine the perl delimiter
11257 #
11258 # Since multiple <metadata> sections may be present, cannot use
11259 # </metadata> as a delimiter.
11260 local $/;
11261 while(<$fh_metahtml>) {
11262 s/\sfilepos=\d+//gix;
11263 (@metablocks) = m#(<metadata>.*</metadata>)#gisx;
11264 (@guideblocks) = m#(<guide>.*</guide>)#gisx;
11265 last unless(@metablocks || @guideblocks);
11266 print {*$fh_meta} @metablocks,"\n" if(@metablocks);
11267 print {*$fh_meta} @guideblocks,"\n" if(@guideblocks);
11268 s#<metadata>.*</metadata>##gisx;
11269 s#<guide>.*</guide>##gisx;
11270 print {*$fh_html} $_,"\n";
11271 }
11272 print $fh_meta "</package>\n";
11273  
11274 close($fh_html)
11275 or croak($subname,"(): Failed to close '",$htmlfile,"'!");
11276 close($fh_meta)
11277 or croak($subname,"(): Failed to close '",$metafile,"'!");
11278 close($fh_metahtml)
11279 or croak($subname,"(): Failed to close '",$metahtmlfile,"'!");
11280  
11281 if( (-z $htmlfile) && (-z $metafile) ) {
11282 croak($subname,"(): ended up with no text in any output file",
11283 " -- bailing out!");
11284 }
11285  
11286 # It is very unlikely that split_metadata will be called twice
11287 # from the same program, so undef all capture variables reclaim
11288 # the memory. Just going out of scope will not necessarily do
11289 # this.
11290 undef(@metablocks);
11291 undef(@guideblocks);
11292 undef($_);
11293  
11294 if(-z $htmlfile) {
11295 debug(1,"split_metadata(): HTML has zero size.",
11296 " Not replacing original.");
11297 unlink($htmlfile);
11298 }
11299 else {
11300 rename($htmlfile,$metahtmlfile)
11301 or croak("split_metadata(): Failed to rename ",$htmlfile,
11302 " to ",$metahtmlfile,"!\n");
11303 }
11304  
11305 if(-z $metafile) {
11306 croak($subname,
11307 "(): unable to remove empty output file '",$metafile,"'!")
11308 if(! unlink($metafile) );
11309 return;
11310 }
11311 return $metafile;
11312 }
11313  
11314  
11315 =head2 C<split_pre($htmlfile,$outfilebase)>
11316  
11317 Splits <pre>...</pre> blocks out of a source HTML file into their own
11318 separate HTML files including required headers. Each block will be
11319 written to its own file following the naming format
11320 C<$outfilebase-###.html>, where ### is a three-digit number beginning
11321 at 001 and incrementing for each block found. If C<$outfilebase> is
11322 not specified, it defaults to the basename of C<$htmlfile> with
11323 "-pre-###.html" appended. The
11324  
11325 Returns a list containing all filenames created.
11326  
11327 =cut
11328  
11329 sub split_pre {
11330 my ($htmlfile,$outfilebase) = @_;
11331 my $subname = ( caller(0) )[3];
11332 debug(2,"DEBUG[",$subname,"]");
11333  
11334 croak($subname,"(): no input file specified")
11335 if(!$htmlfile);
11336  
11337 my ($filebase,$filedir,$fileext);
11338 my ($fh_html,$fh_htmlout,$fh_pre);
11339 my $htmloutfile;
11340 my @preblocks;
11341 my @prefiles = ();
11342 my $prefile;
11343 my $count = 0;
11344  
11345 my $htmlheader = <<'END';
11346 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
11347 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
11348 <html>
11349 <head>
11350 <title></title>
11351 </head>
11352 <body>
11353 END
11354  
11355 ($filebase,$filedir,$fileext) = fileparse($htmlfile,'\.\w+$');
11356 $outfilebase = "$filebase-pre" if(!$outfilebase);
11357 $htmloutfile = "$filebase-nopre.html";
11358  
11359 open($fh_html,"<:raw",$htmlfile)
11360 or croak($subname,"(): Failed to open '",$htmlfile,"' for reading!");
11361 open($fh_htmlout,">:raw",$htmloutfile)
11362 or croak($subname,"(): Failed to open '",$htmloutfile,"' for writing!");
11363  
11364 local $/;
11365 while(<$fh_html>)
11366 {
11367 (@preblocks) = /(<pre>.*?<\/pre>)/gisx;
11368 last unless(@preblocks);
11369  
11370 foreach my $pre (@preblocks)
11371 {
11372 $count++;
11373 debug(1,"DEBUG: split_pre() splitting block ",
11374 sprintf("%03d",$count));
11375 $prefile = sprintf("%s-%03d.html",$outfilebase,$count);
11376 if(-f $prefile)
11377 {
11378 rename($prefile,"$prefile.backup")
11379 or croak("Unable to rename '",$prefile,
11380 "' to '",$prefile,".backup'");
11381 }
11382 open($fh_pre,">:raw",$prefile)
11383 or croak("Unable to open '",$prefile,"' for writing!");
11384 print {*$fh_pre} $utf8xmldec;
11385 print {*$fh_pre} $htmlheader,"\n";
11386 print {*$fh_pre} $pre,"\n";
11387 print {*$fh_pre} "</body>\n</html>\n";
11388 close($fh_pre) or croak("Unable to close '",$prefile,"'!");
11389 push @prefiles,$prefile;
11390 }
11391 s/(<pre>.*?<\/pre>)//gisx;
11392 print {*$fh_htmlout} $_,"\n";
11393 close($fh_htmlout)
11394 or croak($subname,"(): Failed to close '",$htmloutfile,"'!");
11395 rename($htmloutfile,$htmlfile)
11396 or croak($subname,"(): Failed to rename '",$htmloutfile,"' to '",
11397 $htmlfile,"'!");
11398 }
11399 return @prefiles;
11400 }
11401  
11402  
11403 =head2 C<strip_script(%args)>
11404  
11405 Strips any <script>...</script> blocks out of a HTML file.
11406  
11407 =head3 Arguments
11408  
11409 =over
11410  
11411 =item C<infile>
11412  
11413 Specifies the input file. If not specified, the sub croaks.
11414  
11415 =item C<outfile>
11416  
11417 Specifies the output file. If not specified, it defaults to C<infile>
11418 (i.e. the input file is overwritten).
11419  
11420 =item C<noscript>
11421  
11422 If set to true, the sub will strip <noscript>...</noscript> blocks as
11423 well.
11424  
11425 =back
11426  
11427 =cut
11428  
11429 sub strip_script {
11430 my %args = @_;
11431 my $subname = ( caller(0) )[3];
11432 debug(2,"DEBUG[",$subname,"]");
11433  
11434 croak($subname,"(): no input file specified")
11435 if(!$args{infile});
11436  
11437 my %valid_args = (
11438 'infile' => 1,
11439 'outfile' => 1,
11440 'noscript' => 1,
11441 );
11442 foreach my $arg (keys %args) {
11443 croak($subname,"(): invalid argument '",$arg,"'")
11444 if(!$valid_args{$arg});
11445 }
11446  
11447 my $infile = $args{infile};
11448 my $outfile = $args{outfile};
11449 $outfile = $infile unless($outfile);
11450  
11451 my ($fh_in,$fh_out);
11452 my $html;
11453 local $/;
11454  
11455 open($fh_in,"<:raw",$infile)
11456 or croak($subname,"(): Failed to open '",$infile,"' for reading!\n");
11457 $html = <$fh_in>;
11458 close($fh_in)
11459 or croak($subname,"(): Failed to close '",$infile,"'!\n");
11460  
11461 $html =~ s#<script>.*?</script>\n?##gix;
11462 $html =~ s#<noscript>.*?</noscript>\n?##gix
11463 if($args{noscript});
11464  
11465 open($fh_out,">:raw",$outfile)
11466 or croak($subname,"(): Failed to open '",$outfile,"' for writing!\n");
11467 print {*$fh_out} $html;
11468 close($fh_out)
11469 or croak($subname,"(): Failed to close '",$outfile,"'!\n");
11470  
11471 return 1;
11472 }
11473  
11474  
11475 =head2 C<system_result($caller,$retval,@syscmd)>
11476  
11477 Checks the result of a system call and croak on failure with an
11478 appropriate message. For this to work, it MUST be used as the line
11479 immediately following the system command.
11480  
11481 =head3 Arguments
11482  
11483 =over
11484  
11485 =item $caller
11486  
11487 The calling function (used in output message)
11488  
11489 =item $retval
11490  
11491 The return value of the system command
11492  
11493 =item @syscmd
11494  
11495 The array passed to the system call
11496  
11497 =back
11498  
11499 =head3 Return Values
11500  
11501 Returns 0 on success
11502  
11503 Croaks on failure.
11504  
11505 =cut
11506  
11507 sub system_result {
11508 my ($caller,$retval,@syscmd) = @_;
11509  
11510 if ( ($CHILD_ERROR >> 8) == 0 ) {
11511 return 0;
11512 }
11513 elsif ($CHILD_ERROR == -1) {
11514 croak($caller," child failed to execute (ERRNO=",$ERRNO,"):\n ",
11515 join(' ',@syscmd),"\n")
11516 }
11517 elsif ($CHILD_ERROR & 127) {
11518 my $withcoredump = ($CHILD_ERROR & 128) ? 'with' : 'without';
11519 croak($caller," child died with signal ",($CHILD_ERROR & 127)," ",
11520 $withcoredump," coredump:\n ",join(' ',@syscmd),"\n");
11521 }
11522 else {
11523 croak($caller," child exited with value ",$CHILD_ERROR >> 8,":\n ",
11524 join(' ',@syscmd),"\n")
11525 }
11526 }
11527  
11528  
11529 =head2 C<system_tidy_xhtml($infile,$outfile)>
11530  
11531 Runs tidy on a XHTML file semi-safely (using a secondary file)
11532  
11533 Converts HTML to XHTML if necessary
11534  
11535 =head3 Arguments
11536  
11537 =over
11538  
11539 =item $infile
11540  
11541 The filename to tidy
11542  
11543 =item $outfile
11544  
11545 The filename to use for tidy output if the safety condition to
11546 overwrite the input file isn't met.
11547  
11548 Defaults to C<infile-tidy.ext> if not specified.
11549  
11550 =back
11551  
11552 =head3 Global variables used
11553  
11554 =over
11555  
11556 =item $tidycmd
11557  
11558 the location of the tidy executable
11559  
11560 =item $tidyxhtmlerrors
11561  
11562 the filename to use to output errors
11563  
11564 =item $tidysafety
11565  
11566 the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)
11567  
11568 =back
11569  
11570 =head3 Return Values
11571  
11572 Returns the return value from tidy
11573  
11574 =over
11575  
11576 =item 0 - no errors
11577  
11578 =item 1 - warnings only
11579  
11580 =item 2 - errors
11581  
11582 =item Dies horribly if the return value is unexpected
11583  
11584 =back
11585  
11586 =cut
11587  
11588 sub system_tidy_xhtml {
11589 my ($infile,$outfile) = @_;
11590 my $retval;
11591  
11592 croak("system_tidy_xhtml called with no input file") if(!$infile);
11593 if(!$outfile)
11594 {
11595 my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
11596 $outfile = $filebase . "-tidy" . $fileext;
11597 }
11598 croak("system_tidy_xhtml called with no output file") if(!$outfile);
11599  
11600 $retval = system($tidycmd,
11601 '-q','-utf8','--tidy-mark','no',
11602 '--wrap','0',
11603 '--clean','yes',
11604 '-asxhtml',
11605 '--output-xhtml','yes',
11606 '--add-xml-decl','yes',
11607 '--doctype','auto',
11608 '-f',$tidyxhtmlerrors,
11609 '-o',$outfile,
11610 $infile);
11611  
11612 # Some systems may return a two-byte code, so deal with that first
11613 if($retval >= 256) { $retval = $retval >> 8 };
11614 if($retval == 0)
11615 {
11616 rename($outfile,$infile) if($tidysafety < 4);
11617 unlink($tidyxhtmlerrors);
11618 }
11619 elsif($retval == 1)
11620 {
11621 rename($outfile,$infile) if($tidysafety < 3);
11622 unlink($tidyxhtmlerrors) if($tidysafety < 2);
11623 }
11624 elsif($retval == 2)
11625 {
11626 print {*STDERR} "WARNING: Tidy errors encountered. Check ",$tidyxhtmlerrors,"\n"
11627 if($tidysafety > 0);
11628 unlink($tidyxhtmlerrors) if($tidysafety < 1);
11629 }
11630 else
11631 {
11632 # Something unexpected happened (program crash, sigint, other)
11633 croak("Tidy did something unexpected (return value=",$retval,
11634 "). Check all output.");
11635 }
11636 return $retval;
11637 }
11638  
11639  
11640 =head2 C<system_tidy_xml($infile,$outfile)>
11641  
11642 Runs tidy on an XML file semi-safely (using a secondary file)
11643  
11644 =head3 Arguments
11645  
11646 =over
11647  
11648 =item C<$infile>
11649  
11650 The filename to tidy
11651  
11652 =item C<$outfile> (optional)
11653  
11654 The filename to use for tidy output if the safety condition to
11655 overwrite the input file isn't met.
11656  
11657 Defaults to C<infile-tidy.ext> if not specified.
11658  
11659 =back
11660  
11661 =head3 Global variables used
11662  
11663 =over
11664  
11665 =item C<$tidycmd>
11666  
11667 the name of the tidy executable
11668  
11669 =item C<$tidyxmlerrors>
11670  
11671 the filename to use to output errors
11672  
11673 =item C<$tidysafety>
11674  
11675 the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)
11676  
11677 =back
11678  
11679 =head3 Return values
11680  
11681 Returns the return value from tidy
11682  
11683 =over
11684  
11685 =item 0 - no errors
11686  
11687 =item 1 - warnings only
11688  
11689 =item 2 - errors
11690  
11691 =item Dies horribly if the return value is unexpected
11692  
11693 =back
11694  
11695 =cut
11696  
11697 sub system_tidy_xml {
11698 my ($infile,$outfile) = @_;
11699 my $retval;
11700  
11701 croak("system_tidy_xml called with no input file") if(!$infile);
11702  
11703 if (!$outfile) {
11704 my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
11705 $outfile = $filebase . "-tidy" . $fileext;
11706 }
11707 croak("system_tidy_xml called with no output file") if(!$outfile);
11708  
11709 $retval = system($tidycmd,
11710 '-q','-utf8','--tidy-mark','no',
11711 '--wrap','0',
11712 '-xml',
11713 '--add-xml-decl','yes',
11714 '-f',$tidyxmlerrors,
11715 '-o',$outfile,
11716 $infile);
11717  
11718 # Some systems may return a two-byte code, so deal with that first
11719 if ($retval >= 256) {
11720 $retval = $retval >> 8;
11721 }
11722 ;
11723 if ($retval == 0) {
11724 rename($outfile,$infile) if($tidysafety < 4);
11725 unlink($tidyxmlerrors);
11726 }
11727 elsif ($retval == 1) {
11728 rename($outfile,$infile) if($tidysafety < 3);
11729 unlink($tidyxmlerrors) if($tidysafety < 2);
11730 }
11731 elsif ($retval == 2) {
11732 print STDERR "WARNING: Tidy errors encountered. Check ",$tidyxmlerrors,"\n"
11733 if ($tidysafety > 0);
11734 unlink($tidyxmlerrors) if($tidysafety < 1);
11735 }
11736 else {
11737 # Something unexpected happened (program crash, sigint, other)
11738 croak("Tidy did something unexpected (return value=",$retval,
11739 "). Check all output.");
11740 }
11741 return $retval;
11742 }
11743  
11744  
11745 =head2 C<trim>
11746  
11747 Removes any whitespace characters from the beginning or end of every
11748 string in @list (also works on scalars).
11749  
11750 trim; # trims $_ inplace
11751 $new = trim; # trims (and returns) a copy of $_
11752 trim $str; # trims $str inplace
11753 $new = trim $str; # trims (and returns) a copy of $str
11754 trim @list; # trims @list inplace
11755 @new = trim @list; # trims (and returns) a copy of @list
11756  
11757 This was shamelessly copied from japhy's example at perlmonks.org:
11758  
11759 http://www.perlmonks.org/?node_id=36684
11760  
11761 If needed for large lists, it would probably be better to use
11762 String::Strip.
11763  
11764 =cut
11765  
11766 sub trim { ## no critic
11767 ## no critic
11768 # PerlCritic is turned off here, as this is unusual code
11769 # deliberately bending rules.
11770 @_ = $_ if not @_ and defined wantarray;
11771 @_ = @_ if defined wantarray;
11772 for ( @_ ? @_ : $_ ) { s/^\s+//, s/\s+$// }
11773 return wantarray ? @_ : $_[ 0 ] if defined wantarray;
11774 }
11775  
11776  
11777 =head2 C<twigelt_create_uuid($gi)>
11778  
11779 Creates an unlinked element with the specified gi (tag), and then
11780 assigns it the id and scheme attributes 'UUID'.
11781  
11782 =head3 Arguments
11783  
11784 =over
11785  
11786 =item $gi : The gi (tag) to use for the element
11787  
11788 Default: 'dc:identifier'
11789  
11790 =back
11791  
11792 Returns the element.
11793  
11794 =cut
11795  
11796 sub twigelt_create_uuid {
11797 my ($gi) = @_;
11798 my $subname = ( caller(0) )[3];
11799 debug(2,"DEBUG[",$subname,"]");
11800 my $element;
11801  
11802 if(!$gi) { $gi = 'dc:identifier'; }
11803  
11804 my $uuidgen = Data::UUID->new();
11805 $element = XML::Twig::Elt->new($gi);
11806 $element->set_id('UUID');
11807 $element->set_att('scheme' => 'UUID');
11808 $element->set_text($uuidgen->create_str());
11809 return $element;
11810 }
11811  
11812  
11813 =head2 C<twigelt_detect_duplicate($element1, $element2)>
11814  
11815 Takes two twig elements and returns 1 if they have the same GI (tag),
11816 text, and attributes, but are not actually the same element. The GI
11817 comparison is case-insensitive. The others are case-sensitive.
11818  
11819 Returns 0 otherwise.
11820  
11821 Croaks if passed anything but twig elements.
11822  
11823 =cut
11824  
11825 sub twigelt_detect_duplicate {
11826 my ($element1,$element2) = @_;
11827 my $subname = ( caller(0) )[3];
11828 debug(3,"DEBUG[",$subname,"]");
11829  
11830 croak($subname,"(): arguments must be XML::Twig::Elt objects")
11831 unless( $element1->isa('XML::Twig::Elt')
11832 && $element2->isa('XML::Twig::Elt') );
11833  
11834 my (%atts1, %atts2);
11835  
11836 unless($element1->cmp($element2)) {
11837 debug(3," both elements have the same position");
11838 return 0;
11839 }
11840  
11841 unless( lc($element1->gi) eq lc($element2->gi) ) {
11842 debug(3," elements have different GIs");
11843 return 0;
11844 }
11845  
11846 unless($element1->text eq $element2->text) {
11847 debug(3," elements have different text");
11848 return 0;
11849 }
11850  
11851 %atts1 = %{$element1->atts};
11852 %atts2 = %{$element2->atts};
11853  
11854 my $attkeys1 = join('',sort keys %atts1);
11855 my $attkeys2 = join('',sort keys %atts2);
11856  
11857 unless($attkeys1 eq $attkeys2) {
11858 debug(3," elements have different attributes");
11859 return 0;
11860 }
11861  
11862 foreach my $att (keys %atts1) {
11863 unless($element1->att($att) eq $element2->att($att)) {
11864 debug(3," elements have different values for attribute '",
11865 $att,"'");
11866 return 0;
11867 }
11868 }
11869 debug(3," elements are duplicates of each other!");
11870 return 1;
11871 }
11872  
11873 =head2 C<twigelt_fix_oeb12_atts($element)>
11874  
11875 Checks the attributes in a twig element to see if they match OPF names
11876 with an opf: namespace, and if so, removes the namespace. Used by the
11877 fix_oeb12() method.
11878  
11879 Takes as a sole argument a twig element.
11880  
11881 Returns that element with the modified attributes, or undef if the
11882 element didn't exist. Returns an unmodified element if both att and
11883 opf:att exist.
11884  
11885 =cut
11886  
11887 sub twigelt_fix_oeb12_atts {
11888 my ($element) = @_;
11889 return unless($element);
11890 my $subname = ( caller(0) )[3];
11891 debug(3,"DEBUG[",$subname,"]");
11892  
11893 my %opfatts_no_ns = (
11894 "opf:role" => "role",
11895 "opf:file-as" => "file-as",
11896 "opf:scheme" => "scheme",
11897 "opf:event" => "event"
11898 );
11899  
11900 foreach my $att ($element->att_names)
11901 {
11902 debug(3,"DEBUG: checking attribute '",$att,"'");
11903 if($opfatts_no_ns{$att})
11904 {
11905 # If the opf:att attribute properly exists already, do nothing.
11906 if($element->att($opfatts_no_ns{$att}))
11907 {
11908 debug(1,"DEBUG: found both '",$att,"' and '",
11909 $opfatts_no_ns{$att},"' -- skipping.");
11910 next;
11911 }
11912 debug(1,"DEBUG: changing attribute '",$att,"' => '",
11913 $opfatts_no_ns{$att},"'");
11914 $element->change_att_name($att,$opfatts_no_ns{$att});
11915 }
11916 }
11917 return $element;
11918 }
11919  
11920  
11921 =head2 C<twigelt_fix_opf20_atts($element)>
11922  
11923 Checks the attributes in a twig element to see if they match OPF
11924 names, and if so, prepends the OPF namespace. Used by the fix_opf20()
11925 method.
11926  
11927 Takes as a sole argument a twig element.
11928  
11929 Returns that element with the modified attributes, or undef if the
11930 element didn't exist.
11931  
11932 =cut
11933  
11934 sub twigelt_fix_opf20_atts {
11935 my ($element) = @_;
11936 return unless($element);
11937 my $subname = ( caller(0) )[3];
11938 debug(3,"DEBUG[",$subname,"]");
11939  
11940 my %opfatts_ns = (
11941 "role" => "opf:role",
11942 "file-as" => "opf:file-as",
11943 "scheme" => "opf:scheme",
11944 "event" => "opf:event"
11945 );
11946  
11947 foreach my $att ($element->att_names)
11948 {
11949 debug(2,"DEBUG: checking attribute '",$att,"'");
11950 if($opfatts_ns{$att})
11951 {
11952 # If the opf:att attribute properly exists already, do nothing.
11953 if($element->att($opfatts_ns{$att}))
11954 {
11955 debug(1,"DEBUG: found both '",$att,"' and '",
11956 $opfatts_ns{$att},"' -- skipping.");
11957 next;
11958 }
11959 debug(1,"DEBUG: changing attribute '",$att,"' => '",
11960 $opfatts_ns{$att},"'");
11961 $element->change_att_name($att,$opfatts_ns{$att});
11962 }
11963 }
11964 return $element;
11965 }
11966  
11967  
11968 =head2 C<twigelt_is_author($element)>
11969  
11970 Takes as an argument a twig element. Returns true if the element is a
11971 dc:creator (case-insensitive) with either a opf:role="aut" or
11972 role="aut" attribute defined. Returns undef otherwise, and also if
11973 the element has no text.
11974  
11975 Croaks if fed no argument, or fed an argument that isn't a twig
11976 element.
11977  
11978 Intended to be used as a twig search condition.
11979  
11980 =head3 Example
11981  
11982 my @elements = $ebook->twigroot->descendants(\&twigelt_is_author);
11983  
11984 =cut
11985  
11986 sub twigelt_is_author {
11987 my ($element) = @_;
11988 my $subname = ( caller(0) )[3];
11989 debug(3,"DEBUG[",$subname,"]");
11990  
11991 croak($subname,"(): no element provided") unless($element);
11992  
11993 my $ref = ref($element) || '';
11994  
11995 croak($subname,"(): argument was of type '",$ref,
11996 "', needs to be 'XML::Twig::Elt' or a subclass")
11997 unless($element->isa('XML::Twig::Elt'));
11998  
11999 return if( (lc $element->gi) ne 'dc:creator');
12000 return unless($element->text);
12001  
12002 my $role = $element->att('opf:role') || $element->att('role');
12003 return unless($role);
12004  
12005 return 1 if($role eq 'aut');
12006 return;
12007 }
12008  
12009  
12010 =head2 C<twigelt_is_isbn($element)>
12011  
12012 Takes as an argument a twig element. Returns true if the element is a
12013 dc:identifier (case-insensitive) where any of the id, opf:scheme, or
12014 scheme attributes start with 'isbn', '-isbn', 'eisbn', or 'e-isbn'
12015 (again case-insensitive).
12016  
12017 Returns undef otherwise, and also if the element has no text.
12018  
12019 Croaks if fed no argument, or fed an argument that isn't a twig
12020 element.
12021  
12022 Intended to be used as a twig search condition.
12023  
12024 =head3 Example
12025  
12026 my @elements = $ebook->twigroot->descendants(\&twigelt_is_isbn);
12027  
12028 =cut
12029  
12030 sub twigelt_is_isbn {
12031 my ($element) = @_;
12032 my $subname = ( caller(0) )[3];
12033 debug(3,"DEBUG[",$subname,"]");
12034  
12035 croak($subname,"(): no element provided") unless($element);
12036  
12037 my $ref = ref($element) || '';
12038 my $id;
12039 my $scheme;
12040  
12041 croak($subname,"(): argument was of type '",$ref,
12042 "', needs to be 'XML::Twig::Elt' or a subclass")
12043 unless($element->isa('XML::Twig::Elt'));
12044  
12045 return if( (lc $element->gi) ne 'dc:identifier');
12046 return unless($element->text);
12047  
12048 $id = $element->id || '';
12049 return 1 if($id =~ /^e?-?isbn/ix);
12050  
12051 $scheme = $element->att('opf:scheme') || '';
12052 return 1 if($scheme =~ /^e?-?isbn/ix);
12053 $scheme = $element->att('scheme') || '';
12054 return 1 if($scheme =~ /^e?-?isbn/ix);
12055 return;
12056 }
12057  
12058  
12059 =head2 C<twigelt_is_knownuid($element)>
12060  
12061 Takes as an argument a twig element. Returns true if the element is a
12062 dc:identifier (case-insensitive) element with an C<id> attribute
12063 matching the known IDs of proper unique identifiers suitable for a
12064 package-id (also case-insensitive). Returns undef otherwise.
12065  
12066 Croaks if fed no argument, or fed an argument that isn't a twig element.
12067  
12068 Intended to be used as a twig search condition.
12069  
12070 =head3 Example
12071  
12072 my @elements = $ebook->twigroot->descendants(\&twigelt_is_knownuid);
12073  
12074 =cut
12075  
12076 sub twigelt_is_knownuid {
12077 my ($element) = @_;
12078 my $subname = ( caller(0) )[3];
12079 debug(3,"DEBUG[",$subname,"]");
12080  
12081 croak($subname,"(): no element provided") unless($element);
12082  
12083 my $ref = ref($element) || '';
12084  
12085 croak($subname,"(): argument was of type '",$ref,
12086 "', needs to be 'XML::Twig::Elt' or a subclass")
12087 unless($element->isa('XML::Twig::Elt'));
12088  
12089 return if( (lc $element->gi) ne 'dc:identifier');
12090 my $id = $element->id;
12091 return unless($id);
12092  
12093 my %knownuids = (
12094 'package-id' => 56,
12095 'overdriveguid' => 48,
12096 'guid' => 40,
12097 'uuid' => 32,
12098 'uid' => 24,
12099 'calibre_id' => 16,
12100 'fwid' => 8,
12101 );
12102  
12103 if($knownuids{lc $id})
12104 {
12105 # debug(2,"DEBUG: '",$element->gi,"' has known UID '",$id,"'");
12106 return 1;
12107 }
12108 return;
12109 }
12110  
12111  
12112 =head2 C<usedir($dir)>
12113  
12114 Changes the current working directory to the one specified, creating
12115 it if necessary.
12116  
12117 Returns the current working directory before the change. If no
12118 directory is specified, returns the current working directory without
12119 changing anything.
12120  
12121 Croaks on any failure.
12122  
12123 =cut
12124  
12125 sub usedir {
12126 my ($dir) = @_;
12127 my $subname = ( caller(0) )[3];
12128 debug(2,"DEBUG[",$subname,"]: $dir");
12129  
12130 my $cwd = getcwd();
12131 return $cwd unless($dir);
12132  
12133 unless(-d $dir) {
12134 debug(2," Creating directory '",$dir,"'");
12135 mkpath($dir)
12136 or croak("Unable to create output directory '",$dir,"'!\n");
12137 }
12138 chdir($dir)
12139 or croak("Unable to change working directory to '",$dir,"'!\n");
12140 return $cwd;
12141 }
12142  
12143  
12144 =head2 C<userconfigdir()>
12145  
12146 Returns the directory in which user configuration files and helper
12147 programs are expected to be found, creating that directory if it does
12148 not exist. Typically, this directory is C<"$ENV{HOME}/.ebooktools">,
12149 but on MSWin32 systems if that directory does not already exist,
12150 C<"$ENV{USERPROFILE}/ApplicationData/EBook-Tools"> is returned (and
12151 potentially created) instead.
12152  
12153 If C<$ENV{HOME}> (and C<$ENV{USERPROFILE}> on MSWin32) are either not
12154 set or do not point to a directory, the sub returns undef.
12155  
12156 =cut
12157  
12158 sub userconfigdir {
12159 my $subname = ( caller(0) )[3];
12160 debug(3,"DEBUG[",$subname,"]");
12161  
12162 my $dir;
12163  
12164 if(-d $ENV{HOME}) {
12165 $dir = $ENV{HOME} . '/.ebooktools';
12166 }
12167  
12168 if($OSNAME eq 'MSWin32') {
12169 if(not -d $dir and -d $ENV{USERPROFILE}) {
12170 $dir = $ENV{USERPROFILE} . '\Application Data\EBook-Tools';
12171 }
12172 }
12173 if($dir) {
12174 if(! -d $dir) {
12175 mkpath($dir)
12176 or croak($subname,
12177 "(): unable to create configuration directory '",
12178 $dir,"'!\n");
12179 }
12180 return $dir;
12181 }
12182 else { return; }
12183 }
12184  
12185  
12186 =head2 C<ymd_validate($year,$month,$day)>
12187  
12188 Make sure month and day have valid values. Return the passed values
12189 if they are, return 3 undefs if not. Testing of month or day can be
12190 skipped by passing undef in that spot.
12191  
12192 =cut
12193  
12194 sub ymd_validate {
12195 my ($year,$month,$day) = @_;
12196  
12197 return (undef,undef,undef) unless($year);
12198  
12199 if($month) {
12200 return (undef,undef,undef) if($month > 12);
12201 if($day) {
12202 if(!eval { timelocal(0,0,0,$day,$month-1,$year); }) {
12203 debug(1,"DEBUG: timelocal validation failed for year=",
12204 $year," month=",$month," day=",$day);
12205 return (undef,undef,undef);
12206 }
12207 }
12208 return ($year,$month,$day);
12209 }
12210  
12211 # We don't have a month. If we *do* have a day, the result is
12212 # broken, so send back the undefs.
12213 return (undef,undef,undef) if($day);
12214 return ($year,undef,undef);
12215 }
12216  
12217  
12218 ########## END CODE ##########
12219  
12220 =head1 BUGS AND LIMITATIONS
12221  
12222 =over
12223  
12224 =item * fix_links() could be improved to download remote URIs instead
12225 of ignoring them.
12226  
12227 =item * fix_links() needs to check the <reference> links under <guide>
12228  
12229 =item * fix_links() needs to be redone with HTML::TreeBuilder or
12230 Mojo::DOM to avoid the weakness with newlines between attribute names
12231 and values
12232  
12233 =item * Need to implement fix_tours() that should collect the related
12234 elements and delete the parent if none are found. Empty <tours>
12235 elements aren't allowed.
12236  
12237 =item * fix_languages() needs to convert language names into IANA
12238 language codes.
12239  
12240 =item * set_language() should add a warning if the text isn't a valid
12241 IANA language code.
12242  
12243 =item * NCX generation only generates from the spine. It should be
12244 possible to use a TOC html file for generation instead. In the long
12245 term, it should be possible to generate one from the headers and
12246 anchors in arbitrary HTML files.
12247  
12248 =item * It might be better to use sysread / index / substr / syswrite in
12249 &split_metadata to handle the split in 10k chunks, to avoid massive
12250 memory usage on large files.
12251  
12252 This may not be worth the effort, since the average size for most
12253 books is less than 500k, and the largest books are rarely over 10M.
12254  
12255 =item * The only generator is currently for .epub books. PDF,
12256 PalmDoc, Mobipocket, Plucker, and iSiloX are eventually planned.
12257  
12258 =item * Although I like keeping warnings associated with the ebook
12259 object, it may be better to throw exceptions on errors and catch them
12260 later. This probably won't be implemented until it bites someone who
12261 complains, though.
12262  
12263 =item * Unit tests are incomplete
12264  
12265 =back
12266  
12267 =head1 AUTHOR
12268  
12269 Zed Pobre <zed@debian.org>
12270  
12271 =head1 LICENSE AND COPYRIGHT
12272  
12273 Copyright 2008-2013 Zed Pobre
12274  
12275 Licensed to the public under the terms of the GNU GPL, version 2
12276  
12277 =cut
12278  
12279 1;
« Tools/Unpack.pm ↑ Summary