blib/lib/EBook/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
« blib/lib/EBook/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.2");
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 10 ▶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 'romantic' => 'Romantic',
4218 'non-con' => 'NonConsensual', # At least one of the parties is not participating willfully
4219 'nonconsensual' => 'NonConsensual',
4220 'pedo' => 'Pedophilia', # An adult initiating sexual contact with a
4221 # pre-pubescent child (boy or girl, 12 or under)
4222 'pedophilia' => 'Pedophilia',
4223 'lolita' => 'Lolita', # A pre-pubescent child (boy or girl, 12 or
4224 # younger) initiates sexual contact with an adult
4225 'reluc' => 'Reluctant', # Start as non consentual and then the non
4226 # consenting party participates willingly
4227 'reluctant' => 'Reluctant',
4228 'rape' => 'Rape', # Stories with violent rape
4229 'coer' => 'Coercion', # Not exactly blackmail, but applying different
4230 # kinds of pressure to force into the act.
4231 'coercion' => 'Coercion',
4232 'Blkm' => 'Blackmail', # Blackmailing somebody to force them into the sex act depicted
4233 'blackmail' => 'Blackmail',
4234 'mc' => 'Mind Control', # Stories where one party somehow controls another's mind
4235 'mind control' => 'Mind Control',
4236 'MindControl' => 'Mind Control',
4237 'Mindcontrol' => 'Mind Control',
4238 'mindcontrol' => 'Mind Control',
4239 'hypno' => 'Hypnosis', # One party using hypnosis for sexual purposes
4240 'hypnosis' => 'Hypnosis',
4241 'dru' => 'Drunk/Drugged', # One party at least is drunk or drugged and
4242 # participates while under the influence without really knowing
4243 'drunk/drugged' => 'Drunk/Drugged',
4244 'Drunk' => 'Drunk/Drugged',
4245 'drunk' => 'Drunk/Drugged',
4246 'Drugged' => 'Drunk/Drugged',
4247 'drugged' => 'Drunk/Drugged',
4248 'mag' => 'Magic', # Contains magic and supernatural phenomenons
4249 'slave' => 'Slavery', # Slavery, sexual or otherwise
4250 'Slave' => 'Slavery',
4251 'slavery' => 'Slavery',
4252  
4253 # Sexual Orientations
4254 'gay' => 'Gay', # Self Explanatory
4255 'les' => 'Lesbian', # Self Explanatory
4256 'Les' => 'Lesbian',
4257 'lesbian' => 'Lesbian',
4258 'bi' => 'BiSexual', # Self Explanatory
4259 'Bisexual' => 'BiSexual',
4260 'bisexual' => 'BiSexual',
4261 'het' => 'Heterosexual', # Self Explanatory
4262 'hetero' => 'Heterosexual',
4263 'heterosexual' => 'Heterosexual',
4264 'tg' => 'TransGender', # Gender crossing (note that code 'trans' refers to transformation)
4265 'Transgender' => 'TransGender',
4266 'transgender' => 'TransGender',
4267 'cd' => 'CrossDressing', # Men dressing as women and in women clothing, also vice-versa
4268 'Crossdressing' => 'CrossDressing',
4269 'crossdressing' => 'CrossDressing',
4270 'Crossdress' => 'CrossDressing',
4271 'crossdress' => 'CrossDressing',
4272 'herm' => 'Hermaphrodite', # Person having both male and female genitalia
4273 'hermaphrodite' => 'Hermaphrodite',
4274 'shem' => 'Shemale', # Trans women with male genitalia and female
4275 'shemale' => 'Shemale', # breasts from breast augmentation and/or use of hormones
4276  
4277 # Story Types
4278 'fict' => 'Fiction', # Fictitious story, not true
4279 'fiction' => 'Fiction',
4280 'true' => 'True Story', # A true story, according to the author.
4281 'hiFant' => 'High Fantasy', # High Fantasy, sword and sorcery and such
4282 'fanfic' => 'Fan Fiction', # A story using characters from movies, TV shows or Comics
4283 'celeb' => 'Celebrity', # A story about a real life celebrity, the
4284 # story is fictional of course.
4285 'ScFi' => 'Science Fiction', # Science Fiction
4286 'Scifi' => 'Science Fiction',
4287 'scifi' => 'Science Fiction',
4288 'TimeTr' => 'Time Travel', # Science Fiction involving travel through time
4289 'robot' => 'Robot', # Humans having relations, sexual or otherwise,
4290 # with non-biological entities (mechanical
4291 # robots or full blown androids)
4292 'PostApoc' => 'Post Apocalypse', # Post Apocalyptic world.
4293 'hist' => 'Historical', # Story that is set in past history, mostly
4294 # related to famous people and events.
4295 'horror' => 'Horror', # Horror Elements in the story, erotic or otherwise.
4296 'humor' => 'Humor', # Contains humor or the story is a spoof
4297 'tears' => 'Tear Jerker', # Sad story or containing sad moments
4298 'superhero' => 'Superhero', # Story contains Super Hero/Heroine
4299 'ESP' => 'Extra Sensory Perception', # Perceiving things by means other
4300 # than the known senses, e.g. by telepathy or clairvoyance.
4301 'Zoo' => 'Zoophilia ', # Different from bestiality, it's about
4302 # relationships between humans and animals, not just sex.
4303 'space' => 'Space', # Story set in outer space
4304 'myst' => 'Mystery', # A suspensful story about a mystery
4305 'sport' => 'Sports', # A story with a sports theme
4306 'west' => 'Western', # Set in the old US west
4307 'doover' => 'DoOver', # Getting to do one's life all over again
4308  
4309 # Paranormal
4310 'paranormal' => 'Paranormal', # Ghosts, angels, spirits, poltergeists, etc
4311 'vamp' => 'Vampires', # Vampires in the story
4312 'vampire' => 'Vampires',
4313 'vampires' => 'Vampires',
4314 'furry' => 'Furry', # Anthropomorphic animals or 'taurs' (animal
4315 # bodies with anthropomorphic torsos) it also
4316 # includes other forms such as dragons.
4317 'non-anthro' => 'non-anthro', # Animal in form with human level
4318 # intelligence, e.g. Werewolves
4319 'were' => 'Were animal', # A human that can turn into an animal temporarily.
4320 'zom' => 'Zombies', # Zombies in the story
4321  
4322 # Couples
4323 'cheat' => 'Cheating', # One party is cheating on their spouse
4324 'cheating' => 'Cheating',
4325 'wife' => 'Slut Wife', # Slutty wife
4326 'wimp' => 'Wimp Husband', # Husband does not stand up for himself when
4327 # faced with a cheating wife
4328 'cuckold' => 'Cuckold', # When man is being forced to accept
4329 # his wife's cheating against his will.
4330 'watch' => 'Wife Watching', # Man enjoys watching his wife getting fucked
4331 'reven' => 'Revenge', # One party gets revenge for spouse's cheating
4332  
4333 # Incest
4334 'inc' => 'Incest', # sex between the members of the same family
4335 'incest' => 'Incest',
4336 'mother' => 'Mother', # Self Explanatory
4337 'son' => 'Son', # Self Explanatory
4338 'bro' => 'Brother', # Self Explanatory
4339 'brother' => 'Brother',
4340 'sis' => 'Sister', # Self Explanatory
4341 'fath' => 'Father', # Self Explanatory
4342 'father' => 'Father',
4343 'dau' => 'Daughter', # Self Explanatory
4344 'daughter' => 'Daughter',
4345 'cous' => 'Cousins', # Self Explanatory
4346 'cousin' => 'Cousins',
4347 'cousins' => 'Cousins',
4348 'grand' => 'Grand Parent', # Self Explanatory
4349 'Grandfather' => 'Grand Parent',
4350 'grandfather' => 'Grand Parent',
4351 'Grandmother' => 'Grand Parent',
4352 'grandmother' => 'Grand Parent',
4353 'Grandparent' => 'Grand Parent',
4354 'grandparent' => 'Grand Parent',
4355 'grand parent' => 'Grand Parent',
4356 'unc' => 'Uncle', # Self Explanatory
4357 'uncle' => 'Uncle',
4358 'niece' => 'Niece', # Self Explanatory
4359 'aunt' => 'Aunt', # Self Explanatory
4360 'neph' => 'Nephew', # Self Explanatory
4361 'nephew' => 'Nephew',
4362 'in-law' => 'InLaws', # Self Explanatory
4363 'inlaw' => 'InLaws',
4364 'inlaws' => 'InLaws',
4365 'Inlaws' => 'InLaws',
4366  
4367 # BDSM Elements
4368 'BDSM' => 'BDSM', # Bondage and/or SadoMasochism
4369 'D/S' => 'DomSub', # Story about domination, being sexual or otherwise
4370 'Mdom' => 'MaleDom', # Male Dominant
4371 'mdom' => 'MaleDom',
4372 'Fdom' => 'FemaleDom', # Female Dominant
4373 'fdom' => 'FemaleDom',
4374 'span' => 'Spanking', # Somebody gets spanked in the story, willingly or unwillingly
4375 'spank' => 'Spanking',
4376 'spanking' => 'Spanking',
4377 'rough' => 'Rough', # Rough sex
4378 'lght' => 'Light Bond', # Light Bondage, usually consensual and for
4379 # experimentation at the request of the one of the parties
4380 'humil' => 'Humiliation', # Degradation of somebody in the story and/or
4381 'Humil' => 'Humiliation', # humiliating them publicly
4382 'sad' => 'Sadistic', # Somebody inflicting pain, physical or mental, for the hell of it
4383 'sadism' => 'Sadistic',
4384 'Sadism' => 'Sadistic',
4385 'tort' => 'Torture', # Self Explanatory
4386 'torture' => 'Torture',
4387 'snuff' => 'Snuff', # Killing being done during the act of sex.
4388 # (Non-sexual murder is in violent)
4389  
4390 # Groups
4391 'swing' => 'Swinging', # Trading Sexual Partners
4392 'swingers' => 'Swinging',
4393 'swinging' => 'Swinging',
4394 'gang' => 'Gang Bang', # Multiple men fucking same woman
4395 'GangBang' => 'Gang Bang',
4396 'Gangbang' => 'Gang Bang',
4397 'gangbang' => 'Gang Bang',
4398 'group' => 'Group Sex', # Multiple couples in the same place or a threesome
4399 'orgy' => 'Orgy', # Everybody is Fucking everybody in a group
4400 'harem' => 'Harem', # There is a harem involved in the story.
4401 'poly' => 'Polygamy/Polyamory', # Multiple spouses or partners (multiple men or multiple women)
4402 'polygamy' => 'Polygamy/Polyamory',
4403 'Polygamy' => 'Polygamy/Polyamory',
4404 'polyamory' => 'Polygamy/Polyamory',
4405 'Polyamory' => 'Polygamy/Polyamory',
4406  
4407 # Interracial Elements
4408 'interr' => 'Interracial', # Sexual partners of different races
4409 'Interr' => 'Interracial',
4410 'interrracial' => 'Interracial',
4411 'WC' => 'White Couple', # Self Explanatory
4412 'BC' => 'Black Couple', # Self Explanatory
4413 'BF' => 'Black Female', # Self Explanatory
4414 'BM' => 'Black Male', # Self Explanatory
4415 'WM' => 'White Male', # Self Explanatory
4416 'WF' => 'White Female', # Self Explanatory
4417 'OM' => 'Oriental Male', # Self Explanatory
4418 'OF' => 'Oriental Female', # Self Explanatory
4419 'HM' => 'Hispanic Male', # Self Explanatory
4420 'HF' => 'Hispanic Female', # Self Explanatory
4421  
4422 # Sexual Activities
4423 '1st' => 'First', # One of the parties having sex is a virgin
4424 'first' => 'First', # One of the parties having sex is a virgin
4425 'safe' => 'Safe Sex', # Sex with proper protection
4426 'Safe' => 'Safe Sex',
4427 'oral' => 'Oral Sex', # Self Explanatory
4428 'anal' => 'Anal Sex', # Self Explanatory
4429 'mastrb' => 'Masturbation', # Self pleasuring, could be alone or while
4430 # with somebody else but no intercourse
4431 'masturbation' => 'Masturbation',
4432 'pett' => 'Petting', # Feeling up and such
4433 'petting' => 'Petting',
4434 'fist' => 'Fisting', # Hand and arm or foot insertion
4435 'Fist' => 'Fisting',
4436 'toys' => 'Sex Toys', # Sex with the help of sex toys, such as dildos and vibrators
4437 'Toys' => 'Sex Toys',
4438 'beast' => 'Bestiality', # Sex with animals
4439 'bestiality' => 'Bestiality',
4440 'squirt' => 'Squirting', # Female Ejaculation
4441 'squirting' => 'Squirting',
4442 'food' => 'Food', # Sex where food is involved, like doing it to
4443 # a pie or shoving a carrot
4444 'lac' => 'Lactation', # Drinking and playing with human milk
4445 'lact' => 'Lactation',
4446 'lactation' => 'Lactation',
4447 'ws' => 'Water Sports', # Peeing on each other
4448 'golden shower' => 'Water Sports',
4449 'enem' => 'Enema', # Getting an enema as a sexual thing
4450 'scat' => 'Scatology', # Playing with feces
4451 'preg' => 'Pregnancy', # Somebody gets pregnant in the story
4452 'Preg' => 'Pregnancy',
4453 'creampie' => 'Cream Pie', # Somebody licks a pussy full of cum
4454 'necro' => 'Necrophilia', # Sex with a corpse
4455 'Necro' => 'Necrophilia',
4456 'fart' => 'Flatulence', # Flatulence as a sexual fetish
4457 'spit' => 'Spitting', # Spitting as a sexual fetish
4458 'exhib' => 'Exhibitionism', # Enjoyment of self exposure
4459 'Exhib' => 'Exhibitionism',
4460 'voy' => 'Voyeurism', # Enjoyment of watching other people without their knowledge
4461 'Voy' => 'Voyeurism',
4462 'voyeur' => 'Voyeurism',
4463 'Voyeur' => 'Voyeurism',
4464 'DP' => 'Double Penetration', # Simultaneous Anal and Vaginal Penetration
4465 'dp' => 'Double Penetration',
4466  
4467 # Fetishes
4468 'size' => 'Size', # Where the size of the sex parts (penis,
4469 # breasts, toys) plays a major role in the story
4470 'doct' => 'Doctor/Nurse', # Medical Fetish, Doctor or Nurse Play a prominent role in the story
4471 'BBW' => 'BBW', # Big Beautiful Woman. Loving Big Women
4472 'feet' => 'Foot Fetish', # Foot fetish
4473 'legs' => 'Leg Fetish', # Leg fetish, often with stockings, garters and heels.
4474 'hairy' => 'Hairy Fetish', # with hairy men/women
4475 'mod' => 'Body Modification', # Erotic body modification, including
4476 # piercings and tattoos, plays a prominent role.
4477 'amput' => 'Amputee', # Sex with an amputee
4478 'needles' => 'Needles', # Includes injections and play or permanent piercings.
4479 'teach' => 'Teacher/Student', # Teacher/student relations
4480 'bbsit' => 'Babysitter', # Sex with babysitters fetish
4481 'BBr' => 'Big Breasts', # Women with Big Breasts
4482 'clergy' => 'Clergy', # Involving members of the clergy (Priest, Bishops, nuns)
4483 'menses' => 'Menstrual Play', # Sex play with a woman who's on menstrual cycle
4484 'Menses' => 'Menstrual Play',
4485 'menstruation' => 'Menstrual Play',
4486 'Menstruation' => 'Menstrual Play',
4487 'public' => 'Public Sex', # Sexual events taking place in public
4488 'Public' => 'Public Sex',
4489  
4490 # Other
4491 'slow' => 'Slow', # There is a story and plot development before
4492 # any sex occurs. Not a stroke story.
4493 'clas' => 'Novel-Classic', # An old classic novel that is now in the public domain
4494 'bknk' => 'Novel-Pocketbook', # An old published pocketbook novel that
4495 # is not in circulation any more and the
4496 # publisher has gone under, so it's not going to be published again
4497 'caution' => 'Caution', # Story contains something that can't be
4498 # classified but requires caution on the reader's part
4499 '2nd' => '2nd POV', # Story written from the 2nd person POV
4500 'violent' => 'Violent', # Violence in the story, not necessarily of sexual nature
4501 'work' => 'Workplace', # Story centres around a workplace setting
4502 'workplace' => 'Workplace',
4503 'sch' => 'School', # Mostly in an educational setting (high-school, college, University)
4504 'school' => 'School',
4505 'college' => 'School',
4506 'trans' => 'Transformation', # Un-natural physical transformation
4507 'prost' => 'Prostitution', # Prostitution elements
4508 'nud' => 'Nudism', # Features scenes set in a naturist/nudist environment
4509 'nudism' => 'Nudism',
4510 'nudist' => 'Nudism',
4511 'Mil' => 'Military', # Story in a Military setting
4512 'military' => 'Military',
4513 'pornThea' => 'Porn Theatre', # Story has events in a porn theatre or Adult bookstore
4514 'cf' => 'Cat-Fighting', # Women having a cat fight
4515 'catfight' => 'Cat-Fighting',
4516 'cannib' => 'Cannibalism', # Self explanatory
4517 'cannibalism' => 'Cannibalism',
4518 );
4519 hashvalue_key_self(\%sexcodes);
4520  
4521 our %strangenames = (
4522 'brian d foy' => 'brian d foy',
4523 'brian d. foy' => 'brian d foy',
4524 );
4525  
4526 our %strangefileas = (
4527 'foy, brian d' => 'd foy, brian',
4528 'foy, brian d.' => 'd foy, brian',
4529 );
4530  
4531 our %validspecs = (
4532 'OEB12' => 'OEB12',
4533 'OPF20' => 'OPF20',
4534 'MOBI12' => 'MOBI12',
4535 );
4536  
4537  
4538 #####################################################
4539 ########## CONSTRUCTORS AND INITIALIZATION ##########
4540 #####################################################
4541  
4542 my %rwfields = (
4543 'opffile' => 'string', # OPF filename (with no path)
4544 'opfsubdir' => 'string', # Subdirectory name where opffile is found
4545 'erotic' => 'scalar', # Enable special handling for erotic fiction
4546 'spec' => 'string',
4547 );
4548 my %rofields = (
4549 'topdir' => 'string', # Top-level directory of the unpacked book
4550 'twig' => 'scalar',
4551 'twig_unmodified' => 'scalar',
4552 'twigroot' => 'scalar',
4553 'errors' => 'arrayref',
4554 'warnings' => 'arrayref',
4555 );
4556 my %privatefields = (
4557 );
4558  
4559 # A simple 'use fields' will not work here: use takes place inside
4560 # BEGIN {}, so the @...fields variables won't exist.
4561 require fields;
4562 fields->import(
4563 keys(%rwfields),keys(%rofields),keys(%privatefields)
4564 );
4565  
4566  
4567 =head1 CONSTRUCTORS AND INITIALIZATION
4568  
4569 =head2 C<new($filename)>
4570  
4571 Instantiates a new EBook::Tools object. If C<$filename> is specified,
4572 it will also immediately initialize itself via the C<init> method.
4573  
4574 =cut
4575  
4576 sub new {
4577 my ($self,$filename) = @_;
4578 my $class = ref($self) || $self;
4579 my $subname = (caller(0))[3];
4580 debug(2,"DEBUG[",$subname,"]");
4581 my $bisg = EBook::Tools::BISG->new();
4582  
4583 $self = fields::new($class);
4584  
4585 if($filename) {
4586 debug(2,"DEBUG: new object from '",$filename,"'");
4587 $self->init($filename);
4588 }
4589 return $self;
4590 }
4591  
4592  
4593 =head2 C<init($filename)>
4594  
4595 Initializes the object from an existing OPF file. If C<$filename> is
4596 specified and exists, the OEB object will be set to read and write to
4597 that file before attempting to initialize. Otherwise, if the object
4598 currently points to an OPF file it will use that name. If there is no
4599 OPF filename data, and C<$filename> was not specified, it will make a
4600 last-ditch attempt to find an OPF file first by looking in
4601 META-INF/container.xml, and if nothing is found there, by looking in
4602 the current directory for a single OPF file.
4603  
4604 If no such files or found (or more than one is found), the
4605 initialization croaks.
4606  
4607 =cut
4608  
4609 sub init :method {
4610 my ($self,$filename) = @_;
4611 my $fh_opffile;
4612 my $opfstring;
4613 my $subname = (caller(0))[3];
4614 croak($subname . "() called as a procedure") unless(ref $self);
4615 debug(2,"DEBUG[",$subname,"]");
4616  
4617 $self->{topdir} = getcwd();
4618  
4619 if($filename) { $self->{opffile} = $filename; }
4620  
4621 if(!$self->{opffile})
4622 {
4623 $opfstring = find_opffile();
4624 $self->{opffile} = $opfstring if($opfstring);
4625 }
4626  
4627 if(!$self->{opffile})
4628 {
4629 croak($subname,"(): Unable to find an OPF file to work with!\n");
4630 }
4631  
4632 if(! -f $self->{opffile})
4633 {
4634 croak($subname,"(): '",$self->{opffile},
4635 "' does not exist or is not a regular file!")
4636 }
4637  
4638 if(-z $self->{opffile})
4639 {
4640 croak("OPF file '",$self->{opffile},"' has zero size!");
4641 }
4642  
4643 # At this point, we have definitely found an OPF file to work
4644 # with, but it might not be in the top level directory, and with
4645 # the exception of final book construction and EPUB metadata, we
4646 # want to be in the directory of the OPF.
4647 $self->{opfsubdir} = dirname($self->{opffile});
4648 $self->{opffile} = basename($self->{opffile});
4649 usedir($self->opfdir);
4650  
4651 debug(2,"DEBUG: init using '",$self->{opfsubdir},"/",$self->{opffile},"'");
4652  
4653 # Initialize the twig before use
4654 $self->{twig} = XML::Twig->new(
4655 keep_atts_order => 1,
4656 output_encoding => 'utf-8',
4657 pretty_print => 'record'
4658 );
4659  
4660 # Initialize a second copy to be used to check for changes
4661 $self->{twig_unmodified} = XML::Twig->new(
4662 keep_atts_order => 1,
4663 output_encoding => 'utf-8',
4664 pretty_print => 'record'
4665 );
4666  
4667 # Read and decode entities before parsing to avoid parsing errors
4668 open($fh_opffile,'<:encoding(:UTF-8)',$self->{opffile})
4669 or croak($subname,"(): failed to open '",$self->{opffile},
4670 "' for reading!");
4671 read($fh_opffile,$opfstring,-s $self->opffile)
4672 or croak($subname,"(): failed to read from '",$self->{opffile},"'!");
4673 close($fh_opffile)
4674 or croak($subname,"(): failed to close '",$self->{opffile},"'!");
4675  
4676 # We use _decode_entities and the custom hash to decode, but also
4677 # see below for the regexp
4678 _decode_entities($opfstring,\%nonxmlentity2char);
4679  
4680 # This runs decode_entities on the substring containing just the
4681 # entity for every entity *except* the 5 predefined internal
4682 # entities. It seems to be about the same speed as running
4683 # _decode_entities on a small file, but having the hash map as a
4684 # package variable has additional utility, so that technique gets
4685 # used instead.
4686 # $opfstring =~
4687 # s/(&
4688 # (?! (?:lt|gt|quot|apos|amp);
4689 # )\w+;
4690 # )
4691 # / decode_entities($1) /gex;
4692  
4693 $self->{twig}->parse($opfstring);
4694 $self->{twig_unmodified}->parse($opfstring);
4695 $self->{twigroot} = $self->{twig}->root;
4696 $self->opf_namespace;
4697 $self->twigcheck;
4698 debug(2,"DEBUG[/",$subname,"]");
4699 return $self;
4700 }
4701  
4702  
4703 =head2 C<init_blank(%args)>
4704  
4705 Initializes an object containing nothing more than the basic OPF
4706 framework, suitable for adding new documents when creating an e-book
4707 from scratch.
4708  
4709 =head3 Arguments
4710  
4711 C<init_blank> takes up to three optional named arguments:
4712  
4713 =over
4714  
4715 =item C<opffile>
4716  
4717 This specifies the OPF filename to use. If not specified, defaults to
4718 'content.opf'
4719  
4720 =item C<author>
4721  
4722 This specifies the content of the initial dc:creator element. If not
4723 specified, defaults to "Unknown Author".
4724  
4725 =item C<title>
4726  
4727 This specifies the content of the initial dc:title element. If not
4728 specified, defaults to "Unknown Title".
4729  
4730 =back
4731  
4732 =head3 Example
4733  
4734 init_blank('opffile' => 'newfile.opf',
4735 'title' => 'The Great Unknown');
4736  
4737 =cut
4738  
4739 sub init_blank :method {
4740 my ($self,%args) = @_;
4741 my $subname = ( caller(0) )[3];
4742 croak($subname . "() called as a procedure") unless(ref $self);
4743 debug(2,"DEBUG[",$subname,"]");
4744  
4745  
4746 my %valid_args = (
4747 'opffile' => 1,
4748 'author' => 1,
4749 'title' => 1,
4750 );
4751 foreach my $arg (keys %args) {
4752 croak($subname,"(): invalid argument '",$arg,"'")
4753 if(!$valid_args{$arg});
4754 }
4755  
4756 $args{opffile} ||= "content.opf";
4757  
4758 my $author = $args{author} || 'Unknown Author';
4759 my $title = $args{title} || 'Unknown Title';
4760 my $metadata;
4761 my $element;
4762  
4763 $self->{topdir} = getcwd();
4764 $self->{opfsubdir} = '.';
4765 $self->{opffile} = $args{opffile};
4766 $self->{twig} = XML::Twig->new(
4767 keep_atts_order => 1,
4768 output_encoding => 'utf-8',
4769 pretty_print => 'record'
4770 );
4771 $self->{twig_unmodified} = XML::Twig->new(
4772 keep_atts_order => 1,
4773 output_encoding => 'utf-8',
4774 pretty_print => 'record'
4775 );
4776  
4777 $element = XML::Twig::Elt->new('package');
4778 $self->{twig}->set_root($element);
4779 $self->{twig_unmodified}->set_root($element);
4780 $self->{twigroot} = $self->{twig}->root;
4781 $metadata = $self->{twigroot}->insert_new_elt('first_child','metadata');
4782  
4783 # dc:identifier
4784 $self->fix_packageid;
4785  
4786 # dc:title
4787 $element = $metadata->insert_new_elt('last_child','dc:title');
4788 $element->set_text($title);
4789  
4790 # dc:creator (author)
4791 $element = $metadata->insert_new_elt('last_child','dc:creator');
4792 $element->set_att('opf:role','aut');
4793 $element->set_text($author);
4794  
4795 $self->fix_opf20;
4796 return 1;
4797 }
4798  
4799  
4800 ######################################
4801 ########## ACCESSOR METHODS ##########
4802 ######################################
4803  
4804 =head1 ACCESSOR METHODS
4805  
4806 The following methods return data deeper in the structure than the
4807 auto-accessors, but still do not modify any object data or files.
4808  
4809  
4810 =head2 C<adult()>
4811  
4812 Returns the text of the Mobipocket-specific <Adult> element, if it
4813 exists. Expected values are 'yes' and undef.
4814  
4815 =cut
4816  
4817 sub adult :method {
4818 my $self = shift;
4819 my $subname = ( caller(0) )[3];
4820 croak($subname . "() called as a procedure") unless(ref $self);
4821 debug(2,"DEBUG[",$subname,"]");
4822 $self->twigcheck;
4823  
4824 my $twigroot = $self->{twigroot};
4825  
4826 my $element = $twigroot->first_descendant(qr/^adult$/ix);
4827 return unless($element);
4828  
4829 if($element->text) { return $element->text; }
4830 else { return; }
4831 }
4832  
4833  
4834 =head2 C<contributor_list()>
4835  
4836 Returns a list containing the text of all dc:contributor elements
4837 (case-insensitive) or undef if none are found.
4838  
4839 In scalar context, returns the first contributor, not the last.
4840  
4841 =cut
4842  
4843 sub contributor_list :method {
4844 my $self = shift;
4845 my $subname = ( caller(0) )[3];
4846 croak($subname . "() called as a procedure") unless(ref $self);
4847 debug(2,"DEBUG[",$subname,"]");
4848 $self->twigcheck;
4849  
4850 my @retval = ();
4851 my $twigroot = $self->{twigroot};
4852  
4853 my @elements = $twigroot->descendants(qr/dc:contributor/ix);
4854 return unless(@elements);
4855  
4856 foreach my $el (@elements)
4857 {
4858 push(@retval,$el->text) if($el->text);
4859 }
4860 return unless(@retval);
4861 if(wantarray) { return @retval; }
4862 else { return $retval[0]; }
4863 }
4864  
4865  
4866 =head2 C<coverimage()>
4867  
4868 Returns the href to the cover image, or undef if none is found.
4869  
4870 Checks the following in order:
4871  
4872 =over
4873  
4874 =item <reference type="other.ms-coverimage-standard">
4875  
4876 =item <EmbeddedCover>
4877  
4878 =item <meta name="cover"> (as href)
4879  
4880 =item <meta name="cover"> (as item id)
4881  
4882 =back
4883  
4884 =cut
4885  
4886 sub coverimage :method {
4887 my ($self) = @_;
4888 my $subname = ( caller(0) )[3];
4889 croak($subname . "() called as a procedure") unless(ref $self);
4890 debug(2,"DEBUG[",$subname,"]");
4891 $self->twigcheck();
4892  
4893 my $twigroot = $self->{twigroot};
4894 my $element;
4895 my $href;
4896 my $id;
4897  
4898 $element = $twigroot->first_descendant('reference[@type="other.ms-coverimage-standard"]');
4899 $href = $element->att('href') if $element;
4900 return $href if $href;
4901  
4902 $element = $twigroot->first_descendant('EmbeddedCover');
4903 $href = $element->text if $element;
4904 return $href if $href;
4905  
4906 $element = $twigroot->first_descendant('meta[@name="cover"]');
4907 if($element) {
4908 if(-f $element->att('content')) {
4909 return $element->att('content');
4910 }
4911 $id = $element->att('content');
4912 $element = $twigroot->first_descendant("item[\@id='${id}']");
4913 $href = $element->att('href') if $element;
4914 return $href if $href;
4915 }
4916 return;
4917 }
4918  
4919  
4920 =head2 C<date_list(%args)>
4921  
4922 Returns the text of all dc:date elements (case-insensitive) matching
4923 the specified attributes.
4924  
4925 In scalar context, returns the first match, not the last.
4926  
4927 Returns undef if no matches are found.
4928  
4929 =head3 Arguments
4930  
4931 =over
4932  
4933 =item * C<id> - 'id' attribute that must be matched exactly for the
4934 result to be added to the list
4935  
4936 =item * C<event> 'opf:event' or 'event' attribute that must be
4937 matched exactly for the result to be added to the list
4938  
4939 =back
4940  
4941 If both arguments are specified a value is added to the list if it
4942 matches either one (i.e. the logic is OR).
4943  
4944 =cut
4945  
4946 sub date_list :method {
4947 my ($self,%args) = @_;
4948 my %valid_args = (
4949 'id' => 1,
4950 'event' => 1,
4951 );
4952 my $subname = ( caller(0) )[3];
4953 croak($subname . "() called as a procedure") unless(ref $self);
4954 debug(2,"DEBUG[",$subname,"]");
4955 $self->twigcheck();
4956 foreach my $arg (keys %args) {
4957 croak($subname,"(): invalid argument '",$arg,"'")
4958 if(!$valid_args{$arg});
4959 }
4960  
4961 my @elements = $self->{twigroot}->descendants(qr/^ dc:date $/ix);
4962 my @list = ();
4963 my $id;
4964 my $scheme;
4965 foreach my $el (@elements) {
4966 if($args{id}) {
4967 $id = $el->att('id') || '';
4968 if($id eq $args{id}) {
4969 push(@list,$el->text);
4970 next;
4971 }
4972 }
4973 if($args{event}) {
4974 $scheme = $el->att('opf:event') || $el->att('event') || '';
4975 if($scheme eq $args{event}) {
4976 push(@list,$el->text);
4977 next;
4978 }
4979 }
4980 next if($args{id} || $args{event});
4981 push(@list,$el->text);
4982 }
4983 return unless(@list);
4984 if(wantarray) { return @list; }
4985 else { return $list[0]; }
4986 }
4987  
4988  
4989 =head2 C<description()>
4990  
4991 Returns the description of the e-book, if set, or undef otherwise.
4992  
4993 =cut
4994  
4995 sub description :method {
4996 my $self = shift;
4997 my $subname = ( caller(0) )[3];
4998 croak($subname . "() called as a procedure") unless(ref $self);
4999 debug(2,"DEBUG[",$subname,"]");
5000 $self->twigcheck;
5001  
5002 my $twigroot = $self->{twigroot};
5003  
5004 my $element = $twigroot->first_descendant(qr/^dc:description$/ix);
5005 return unless($element);
5006  
5007 if($element->text) { return $element->text; }
5008 else { return; }
5009 }
5010  
5011  
5012 =head2 C<element_list(%args)>
5013  
5014 Returns a list containing the text values of all elements matching the
5015 specified criteria.
5016  
5017 =head3 Arguments
5018  
5019 =over
5020  
5021 =item * C<cond>
5022  
5023 The L<XML::Twig> search condition used to find the elements.
5024 Typically this is just the GI (tag) of the element you wish to find,
5025 but it can also be a C<qr//> expression, coderef, or anything else
5026 that XML::Twig can work with. See the XML::Twig documentation for
5027 details.
5028  
5029 If this is not specified, an error is added and the method returns
5030 undef.
5031  
5032 =item * C<id> (optional)
5033  
5034 'id' attribute that must be matched exactly for the
5035 result to be added to the list
5036  
5037 =item * C<scheme> (optional)
5038  
5039 'opf:scheme' or 'scheme' attribute that must be
5040 matched exactly for the result to be added to the list
5041  
5042 =item * C<event> (optional)
5043  
5044 'opf:event' or 'event' attribute that must be matched exactly for the
5045 result to be added to the list
5046  
5047 =back
5048  
5049 If more than one of the arguments C<id>, C<scheme>, or C<event> are
5050 specified a value is added to the list if it matches any one (i.e. the
5051 logic is OR).
5052  
5053 =cut
5054  
5055 sub element_list :method {
5056 my ($self,%args) = @_;
5057 my %valid_args = (
5058 'cond' => 1,
5059 'id' => 1,
5060 'scheme' => 1,
5061 );
5062 my $subname = ( caller(0) )[3];
5063 croak($subname . "() called as a procedure") unless(ref $self);
5064 debug(2,"DEBUG[",$subname,"]");
5065 $self->twigcheck();
5066 foreach my $arg (keys %args) {
5067 croak($subname,"(): invalid argument '",$arg,"'")
5068 if(!$valid_args{$arg});
5069 }
5070 unless($args{cond}) {
5071 $self->add_error($subname,"(): no search condition specified");
5072 return;
5073 }
5074  
5075 my @elements = $self->{twigroot}->descendants($args{cond});
5076 my @list = ();
5077 my $id;
5078 my $scheme;
5079 foreach my $el (@elements) {
5080 if($args{id}) {
5081 $id = $el->att('id') || '';
5082 if($id eq $args{id}) {
5083 push(@list,$el->text);
5084 next;
5085 }
5086 }
5087 if($args{event}) {
5088 $scheme = $el->att('opf:event') || $el->att('event') || '';
5089 if($scheme eq $args{event}) {
5090 push(@list,$el->text);
5091 next;
5092 }
5093 }
5094 if($args{scheme}) {
5095 $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
5096 if($scheme eq $args{scheme}) {
5097 push(@list,$el->text);
5098 next;
5099 }
5100 }
5101 next if($args{id} || $args{event} || $args{scheme});
5102 push(@list,$el->text);
5103 }
5104 return unless(@list);
5105 if(wantarray) { return @list; }
5106 else { return $list[0]; }
5107 }
5108  
5109  
5110 =head2 C<errors()>
5111  
5112 Returns an arrayref containing any generated error messages.
5113  
5114 =cut
5115  
5116 sub errors :method {
5117 my $self = shift;
5118 my $subname = ( caller(0) )[3];
5119 croak($subname . "() called as a procedure") unless(ref $self);
5120 debug(2,"DEBUG[",$subname,"]");
5121 return $self->{errors};
5122 }
5123  
5124  
5125 =head2 C<identifier()>
5126  
5127 Returns the text of the dc:identifier element pointed to by the
5128 'unique-identifier' attribute of the root 'package' element, or undef
5129 if it could not be located.
5130  
5131 =cut
5132  
5133 sub identifier :method {
5134 my $self = shift;
5135 my $subname = ( caller(0) )[3];
5136 croak($subname . "() called as a procedure") unless(ref $self);
5137 debug(2,"DEBUG[",$subname,"]");
5138 $self->twigcheck;
5139  
5140 my $identid = $self->{twigroot}->att('unique-identifier');
5141 return unless($identid);
5142  
5143 my $identifier = $self->{twig}->first_elt("*[\@id='$identid']");
5144 return unless($identifier);
5145  
5146 my $idtext = $identifier->text;
5147 return unless($idtext);
5148  
5149 return($idtext);
5150 }
5151  
5152  
5153 =head2 C<isbn_list(%args)>
5154  
5155 Returns a list of all ISBNs matching the specified attributes. See
5156 L</twigelt_is_isbn()> for a detailed description of how the ISBN
5157 elements are found.
5158  
5159 Returns undef if no matches are found.
5160  
5161 In scalar context returns the first match, not the last.
5162  
5163 See also L</isbns(%args)>.
5164  
5165 =head3 Arguments
5166  
5167 =over
5168  
5169 =item * C<id> (optional)
5170  
5171 'id' attribute that must be matched exactly for the
5172 result to be added to the list
5173  
5174 =item * C<scheme> (optional)
5175  
5176 'opf:scheme' or 'scheme' attribute that must be
5177 matched exactly for the result to be added to the list
5178  
5179 =back
5180  
5181 If both arguments are specified a value is added to the list if it
5182 matches either one (i.e. the logic is OR).
5183  
5184 =cut
5185  
5186 sub isbn_list :method {
5187 my ($self,%args) = @_;
5188 my %valid_args = (
5189 'id' => 1,
5190 'scheme' => 1,
5191 );
5192 my $subname = ( caller(0) )[3];
5193 croak($subname . "() called as a procedure") unless(ref $self);
5194 debug(2,"DEBUG[",$subname,"]");
5195 $self->twigcheck();
5196 foreach my $arg (keys %args) {
5197 croak($subname,"(): invalid argument '",$arg,"'")
5198 if(!$valid_args{$arg});
5199 }
5200  
5201 my @list = $self->element_list(cond => \&twigelt_is_isbn,
5202 %args);
5203 return unless(@list);
5204 if(wantarray) { return @list; }
5205 else { return $list[0]; }
5206 }
5207  
5208  
5209 =head2 C<isbns(%args)>
5210  
5211 Returns all of the ISBN identifiers matching the specificied
5212 attributes as a list of hashrefs, with one hash per ISBN identifier
5213 presented in the order that the identifiers are found. The hash keys
5214 are 'id' (containing the value of the 'id' attribute), 'scheme'
5215 (containing the value of either the 'opf:scheme' or 'scheme'
5216 attribute, whichever is found first), and 'isbn' (containing the text
5217 of the element).
5218  
5219 If no entries are found, returns undef.
5220  
5221 In scalar context returns the first match, not the last.
5222  
5223 See also L</isbn_list(%args)>.
5224  
5225 =head3 Arguments
5226  
5227 C<isbns()> takes two optional named arguments:
5228  
5229 =over
5230  
5231 =item * C<id> - 'id' attribute that must be matched exactly for the
5232 result to be added to the list
5233  
5234 =item * C<scheme> - 'opf:scheme' or 'scheme' attribute that must be
5235 matched exactly for the result to be added to the list
5236  
5237 =back
5238  
5239 If both arguments are specified a value is added to the list if it
5240 matches either one (i.e. the logic is OR).
5241  
5242 =cut
5243  
5244 sub isbns :method {
5245 my ($self,%args) = @_;
5246 my %valid_args = (
5247 'id' => 1,
5248 'scheme' => 1,
5249 );
5250 my $subname = ( caller(0) )[3];
5251 croak($subname . "() called as a procedure") unless(ref $self);
5252 debug(2,"DEBUG[",$subname,"]");
5253 $self->twigcheck();
5254 foreach my $arg (keys %args) {
5255 croak($subname,"(): invalid argument '",$arg,"'")
5256 if(!$valid_args{$arg});
5257 }
5258  
5259 my @elements = $self->{twigroot}->descendants(\&twigelt_is_isbn);
5260 my @list = ();
5261 my $id;
5262 my $scheme;
5263 foreach my $el (@elements) {
5264 if($args{id}) {
5265 $id = $el->att('id') || '';
5266 if($id eq $args{id}) {
5267 push(@list,
5268 {
5269 'isbn' => $el->text,
5270 'id' => $el->att('id'),
5271 'scheme' => $el->att('scheme'),
5272 });
5273 next;
5274 }
5275 }
5276 if($args{scheme}) {
5277 $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
5278 if($scheme eq $args{scheme}) {
5279 push(@list,
5280 {
5281 'isbn' => $el->text,
5282 'id' => $el->att('id'),
5283 'scheme' => $el->att('scheme'),
5284 });
5285 next;
5286 }
5287 }
5288 next if($args{id} || $args{scheme});
5289 $scheme = $el->att('opf:scheme') || $el->att('scheme');
5290 push(@list,
5291 {
5292 'isbn' => $el->text,
5293 'id' => $el->att('id'),
5294 'scheme' => $scheme,
5295 });
5296 }
5297 return unless(@list);
5298 if(wantarray) { return @list; }
5299 else { return $list[0]; }
5300 }
5301  
5302  
5303 =head2 C<languages()>
5304  
5305 Returns a list containing the text of all dc:language
5306 (case-insensitive) entries, or undef if none are found.
5307  
5308 In scalar context returns the first match, not the last.
5309  
5310 =cut
5311  
5312 sub languages :method {
5313 my $self = shift;
5314 my $subname = ( caller(0) )[3];
5315 croak($subname . "() called as a procedure") unless(ref $self);
5316 debug(2,"DEBUG[",$subname,"]");
5317 $self->twigcheck;
5318  
5319 my @retval = ();
5320 my @elements = $self->{twigroot}->descendants(qr/^dc:language$/ix);
5321 foreach my $el (@elements) {
5322 push(@retval,$el->text) if($el->text);
5323 }
5324 return unless(@retval);
5325 if(wantarray) { return @retval; }
5326 else { return $retval[0]; }
5327 }
5328  
5329  
5330 =head2 C<manifest(%args)>
5331  
5332 Returns all of the items in the manifest as a list of hashrefs, with
5333 one hash per manifest item in the order that they appear, where the
5334 hash keys are 'id', 'href', and 'media-type', each returning the
5335 appropriate attribute, if any.
5336  
5337 In scalar context, returns the first match, not the last.
5338  
5339 =head3 Arguments
5340  
5341 C<manifest()> takes four optional named arguments:
5342  
5343 =over
5344  
5345 =item * C<id> - 'id' attribute to match
5346  
5347 =item * C<href> - 'href' attribute to match
5348  
5349 =item * C<mtype> - 'media-type' attribute to match
5350  
5351 =item * C<logic> - logic to use (valid values are 'and' or 'or', default: 'and')
5352  
5353 =back
5354  
5355 If any of the named arguments are specified, C<manifest()> will return
5356 only items matching the specified criteria. This is an exact
5357 case-sensitive match, but it can (especially in the case of mtype)
5358 still return multiple elements.
5359  
5360 =head3 Return values
5361  
5362 Returns undef if there is no <manifest> element directly underneath
5363 <package>, or if <manifest> contains no items.
5364  
5365 =head3 See also
5366  
5367 L</manifest_hrefs()>, L</spine()>
5368  
5369 =head3 Example
5370  
5371 @manifest = $ebook->manifest(id => 'ncx',
5372 mtype => 'text/xml',
5373 logic => 'or');
5374  
5375 =cut
5376  
5377 sub manifest :method {
5378 my ($self,%args) = @_;
5379 my %valid_args = (
5380 'id' => 1,
5381 'href' => 1,
5382 'mtype' => 1,
5383 'logic' => 1
5384 );
5385 my %valid_logic = (
5386 'and' => 1,
5387 'or' => 1
5388 );
5389 my $subname = ( caller(0) )[3];
5390 croak($subname . "() called as a procedure") unless(ref $self);
5391 debug(2,"DEBUG[",$subname,"]");
5392 $self->twigcheck();
5393  
5394 foreach my $arg (keys %args) {
5395 croak($subname,"(): invalid argument '",$arg,"'")
5396 if(!$valid_args{$arg});
5397 }
5398 if($args{logic}) {
5399 croak($subname,
5400 "(): logic must be 'and' or 'or' (got '",$args{logic},"')")
5401 if(!$valid_logic{$args{logic}});
5402 }
5403 else { $args{logic} = 'and'; }
5404  
5405 debug(1,"DEBUG: manifest() called with '",join(" ",keys(%args)),"'");
5406  
5407 my @elements;
5408 my @retarray;
5409 my $cond;
5410  
5411 if($args{id})
5412 {
5413 debug(1,"DEBUG: manifest searching on id");
5414 $cond = "item[\@id='$args{id}'";
5415 }
5416 if($args{href})
5417 {
5418 debug(1,"DEBUG: manifest searching on href");
5419 if($cond) { $cond .= " $args{logic} \@href='$args{href}'"; }
5420 else { $cond = "item[\@href='$args{href}'"; }
5421 }
5422 if($args{mtype})
5423 {
5424 debug(1,"DEBUG: manifest searching on mtype");
5425 if($cond) { $cond .= " $args{logic} \@media-type='$args{mtype}'"; }
5426 else { $cond = "item[\@media-type='$args{mtype}'"; }
5427 }
5428 if($cond) { $cond .= "]"; }
5429 else { $cond = "item"; }
5430  
5431 my $manifest = $self->{twigroot}->first_child('manifest');
5432 return unless($manifest);
5433  
5434 debug(1,"DEBUG: manifest search condition = '",$cond,"'");
5435 @elements = $manifest->children($cond);
5436 return unless(@elements);
5437  
5438 foreach my $el (@elements)
5439 {
5440 push(@retarray,
5441 {
5442 'id' => $el->id,
5443 'href' => $el->att('href'),
5444 'media-type' => $el->att('media-type')
5445 });
5446 }
5447 if(wantarray) { return @retarray; }
5448 else { return $retarray[0]; }
5449 }
5450  
5451  
5452 =head2 C<manifest_hrefs()>
5453  
5454 Returns a list of all of the hrefs in the current OPF manifest, or the
5455 empty list if none are found.
5456  
5457 In scalar context returns the first href, not the last.
5458  
5459 See also: C<manifest()>, C<spine_idrefs()>
5460  
5461 =cut
5462  
5463 sub manifest_hrefs :method {
5464 my $self = shift;
5465 my $subname = ( caller(0) )[3];
5466 croak($subname . "() called as a procedure") unless(ref $self);
5467 debug(2,"DEBUG[",$subname,"]");
5468 $self->twigcheck();
5469  
5470 my @items;
5471 my $href;
5472 my $manifest;
5473 my $mimetype;
5474 my @retval = ();
5475  
5476 $manifest = $self->{twigroot}->first_child('manifest');
5477 if(! $manifest) { return @retval; }
5478  
5479 @items = $manifest->descendants('item');
5480 foreach my $item (@items) {
5481 $href = $item->att('href');
5482 if($href) {
5483 $mimetype = mimetype($href) || "UNKNOWN";
5484 debug(3,"DEBUG: '",$href,"' has mime-type '",$mimetype,"'");
5485 push(@retval,$href);
5486 }
5487 }
5488 debug(2,"DEBUG[/",$subname,"]");
5489 if(wantarray) { return @retval; }
5490 else { return $retval[0]; }
5491 }
5492  
5493  
5494 =head2 C<opf_namespace()>
5495  
5496 Some OPF generators explicity assign 'opf:' in the gi as a prefix on
5497 OPF elements. This makes later parsing more complex and is
5498 unnecessary, so this is stripped before any parsing takes place.
5499  
5500 =cut
5501  
5502 sub opf_namespace :method {
5503 my $self = shift;
5504 my $subname = ( caller(0) )[3];
5505 croak($subname . "() called as a procedure") unless(ref $self);
5506 debug(3,"DEBUG[",$subname,"]");
5507  
5508 my @elements = $self->{twig}->descendants(qr/^opf:/ix);
5509 foreach my $el (@elements)
5510 {
5511 my $gi = $el->gi;
5512 $gi =~ s/^opf:(.*)/$1/ix;
5513 $el->set_gi($gi);
5514 }
5515 return;
5516 }
5517  
5518  
5519 =head2 C<opfdir()>
5520  
5521 Returns the full filesystem path to the directory where the OPF
5522 metadata file will be stored, or undef if either the top-level
5523 directory or the OPF subdirectory is not found.
5524  
5525 =cut
5526  
5527 sub opfdir :method {
5528 my $self = shift;
5529 my $subname = ( caller(0) )[3];
5530 croak($subname . "() called as a procedure") unless(ref $self);
5531 debug(3,"DEBUG[",$subname,"]");
5532 return unless($self->{topdir});
5533 return unless($self->{opfsubdir});
5534  
5535 if($self->{opfsubdir} eq '.') {
5536 return $self->{topdir};
5537 }
5538 return $self->{topdir} . '/' . $self->{opfsubdir};
5539 }
5540  
5541  
5542 =head2 C<opffile()>
5543  
5544 Returns the name of the file where the OPF metadata will be stored or
5545 undef if no value is found..
5546  
5547 =cut
5548  
5549 sub opffile :method {
5550 my $self = shift;
5551 my $subname = ( caller(0) )[3];
5552 croak($subname . "() called as a procedure") unless(ref $self);
5553 debug(3,"DEBUG[",$subname,"]");
5554 return unless($self->{opffile});
5555 return $self->{opffile};
5556 }
5557  
5558  
5559 =head2 C<opfpath()>
5560  
5561 Returns the full filesystem path to the file where the OPF metadata
5562 will be stored or undef if either the top level directory or the OPF
5563 filename is not found.
5564  
5565 =cut
5566  
5567 sub opfpath :method {
5568 my $self = shift;
5569 my $subname = ( caller(0) )[3];
5570 croak($subname . "() called as a procedure") unless(ref $self);
5571 debug(3,"DEBUG[",$subname,"]");
5572 return unless($self->{topdir});
5573 return unless($self->{opfsubdir});
5574 return unless($self->{opffile});
5575  
5576 return $self->{topdir} . '/' . $self->{opfsubdir} . '/' . $self->{opffile};
5577 }
5578  
5579  
5580 =head2 C<primary_author()>
5581  
5582 Finds the primary author of the book, defined as the first
5583 'dc:creator' entry (case-insensitive) where either the attribute
5584 opf:role="aut" or role="aut", or the first 'dc:creator' entry if no
5585 entries with either attribute can be found. Entries must actually
5586 have text to be considered.
5587  
5588 In list context, returns a two-item list, the first of which is the
5589 text of the entry (the author name), and the second element of which
5590 is the value of the 'opf:file-as' or 'file-as' attribute (where
5591 'opf:file-as' is given precedence if both are present).
5592  
5593 In scalar context, returns the text of the entry (the author name).
5594  
5595 If no entries are found, returns undef.
5596  
5597 Uses L</twigelt_is_author()> in the first half of the search.
5598  
5599 =head3 Example
5600  
5601 my ($fileas, $author) = $ebook->primary_author;
5602 my $author = $ebook->primary_author;
5603  
5604 =cut
5605  
5606 sub primary_author :method {
5607 my $self = shift;
5608 my $subname = ( caller(0) )[3];
5609 croak($subname . "() called as a procedure") unless(ref $self);
5610 debug(2,"DEBUG[",$subname,"]");
5611  
5612 my $twigroot = $self->{twigroot};
5613 my $element;
5614 my $fileas;
5615  
5616 $element = $twigroot->first_descendant(\&twigelt_is_author);
5617 $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
5618 if(! $element) {
5619 carp("## WARNING: no dc:creator elements found!");
5620 return;
5621 }
5622 if(! $element->text) {
5623 carp("## WARNING: dc:creator element is empty!");
5624 return;
5625 }
5626 $fileas = $element->att('opf:file-as');
5627 $fileas = $element->att('file-as') unless($fileas);
5628 if(wantarray) { return ($element->text, $fileas); }
5629 else { return $element->text; }
5630 }
5631  
5632  
5633 =head2 C<print_errors()>
5634  
5635 Prints the current list of errors to STDERR.
5636  
5637 =cut
5638  
5639 sub print_errors :method {
5640 my $self = shift;
5641 my $subname = ( caller(0) )[3];
5642 croak($subname . "() called as a procedure") unless(ref $self);
5643 debug(2,"DEBUG[",$subname,"]");
5644  
5645 my $errorref = $self->{errors};
5646  
5647 if(!$self->errors) {
5648 debug(1,"DEBUG: no errors found!");
5649 return 1;
5650 }
5651  
5652  
5653 foreach my $error (@$errorref) {
5654 print "ERROR: ",$error,"\n";
5655 }
5656 return 1;
5657 }
5658  
5659  
5660 =head2 C<print_warnings()>
5661  
5662 Prints the current list of warnings to STDERR.
5663  
5664 =cut
5665  
5666 sub print_warnings :method {
5667 my $self = shift;
5668 my $subname = ( caller(0) )[3];
5669 croak($subname . "() called as a procedure") unless(ref $self);
5670 debug(2,"DEBUG[",$subname,"]");
5671  
5672 my $warningref = $self->{warnings};
5673  
5674 if(!$self->warnings) {
5675 debug(2,"DEBUG: no warnings found!");
5676 return 1;
5677 }
5678  
5679 foreach my $warning (@$warningref) {
5680 print "WARNING: ",$warning,"\n";
5681 }
5682 return 1;
5683 }
5684  
5685  
5686 =head2 C<print_opf()>
5687  
5688 Prints the OPF file to the default filehandle
5689  
5690 =cut
5691  
5692 sub print_opf :method {
5693 my $self = shift;
5694 my $filehandle = shift;
5695 my $subname = ( caller(0) )[3];
5696 croak($subname . "() called as a procedure") unless(ref $self);
5697 debug(2,"DEBUG[",$subname,"]");
5698  
5699 if(defined $filehandle) { $self->{twig}->print($filehandle); }
5700 else { $self->{twig}->print; }
5701 return 1;
5702 }
5703  
5704  
5705 =head2 C<publishers()>
5706  
5707 Returns a list containing the text of all dc:publisher
5708 (case-insensitive) entries, or undef if none are found.
5709  
5710 In scalar context returns the first match, not the last.
5711  
5712 =cut
5713  
5714 sub publishers :method {
5715 my $self = shift;
5716 my $subname = ( caller(0) )[3];
5717 croak($subname . "() called as a procedure") unless(ref $self);
5718 debug(2,"DEBUG[",$subname,"]");
5719 $self->twigcheck;
5720  
5721 my @pubs = ();
5722 my @elements = $self->{twigroot}->descendants(qr/^dc:publisher$/ix);
5723 foreach my $el (@elements) {
5724 push(@pubs,$el->text) if($el->text);
5725 }
5726 return unless(@pubs);
5727 if(wantarray) { return @pubs; }
5728 else { return $pubs[0]; }
5729 }
5730  
5731  
5732 =head2 C<retailprice()>
5733  
5734 Returns a two-scalar list, the first scalar being the text of the
5735 Mobipocket-specific <SRP> element, if it exists, and the second being
5736 the 'Currency' attribute of that element, if it exists.
5737  
5738 In scalar context, returns just the text (price).
5739  
5740 Returns undef if the SRP element is not found.
5741  
5742 =cut
5743  
5744 sub retailprice :method {
5745 my $self = shift;
5746 my $subname = ( caller(0) )[3];
5747 croak($subname . "() called as a procedure") unless(ref $self);
5748 debug(2,"DEBUG[",$subname,"]");
5749 $self->twigcheck;
5750  
5751 my $twigroot = $self->{twigroot};
5752  
5753 my $element = $twigroot->first_descendant(qr/^ SRP $/ix);
5754 return unless($element);
5755 if(wantarray) { return ($element->text,$element->att('Currency')); }
5756 else { return $element->text };
5757 }
5758  
5759  
5760 =head2 C<review()>
5761  
5762 Returns the text of the Mobipocket-specific <Review> element, if it
5763 exists. Returns undef if one is not found.
5764  
5765 =cut
5766  
5767 sub review :method {
5768 my $self = shift;
5769 my $subname = ( caller(0) )[3];
5770 croak($subname . "() called as a procedure") unless(ref $self);
5771 debug(2,"DEBUG[",$subname,"]");
5772 $self->twigcheck;
5773  
5774 my $twigroot = $self->{twigroot};
5775  
5776 my $element = $twigroot->first_descendant(qr/^review$/ix);
5777 return unless($element);
5778 return $element->text;
5779 }
5780  
5781  
5782 =head2 C<< rights('id' => 'identifier') >>
5783  
5784 Returns a list containing the text of all of dc:rights or
5785 dc:copyrights (case-insensitive) entries in the e-book, or undef if
5786 none are found.
5787  
5788 In scalar context returns the first match, not the last.
5789  
5790 If the optional named argument 'id' is specified, it will only return
5791 entries where the id attribute matches the specified identifier.
5792 Although this still returns a list, if more than one entry is found, a
5793 warning is logged.
5794  
5795 Note that dc:copyrights is not a valid Dublin Core element -- it is
5796 included only because some broken Mobipocket books use it.
5797  
5798 =cut
5799  
5800 sub rights :method {
5801 my ($self,%args) = @_;
5802 my $subname = ( caller(0) )[3];
5803 croak($subname . "() called as a procedure") unless(ref $self);
5804 debug(2,"DEBUG[",$subname,"]");
5805 $self->twigcheck;
5806  
5807 my %valid_args = (
5808 'id' => 1,
5809 );
5810 foreach my $arg (keys %args)
5811 {
5812 croak($subname,"(): invalid argument '",$arg,"'")
5813 if(!$valid_args{$arg});
5814 }
5815  
5816  
5817 my @rights = ();
5818 my $id = $args{id};
5819 my @elements = $self->{twigroot}->descendants(qr/^dc:(copy)?rights$/ix);
5820  
5821 foreach my $element (@elements)
5822 {
5823 if($id)
5824 {
5825 next if($element->att('id') ne $id);
5826 push @rights,$element->text if($element->text);
5827 }
5828 else { push @rights,$element->text if($element->text); }
5829 }
5830  
5831 if($id)
5832 {
5833 add_warning($subname
5834 . "(): More than one rights entry found with id '"
5835 . $id ."'" )
5836 if(scalar(@rights) > 1);
5837 }
5838 return unless(@rights);
5839 if(wantarray) { return @rights; }
5840 else { return $rights[0]; }
5841 }
5842  
5843  
5844 =head2 C<search_knownuids()>
5845  
5846 Searches the OPF twig for the first dc:identifier (case-insensitive)
5847 element with an ID matching known UID IDs.
5848  
5849 Returns the ID if a match is found, undef otherwise
5850  
5851 =cut
5852  
5853 sub search_knownuids :method {
5854 my $self = shift;
5855 my $subname = ( caller(0) )[3];
5856 croak($subname . "() called as a procedure") unless(ref $self);
5857 debug(2,"DEBUG[",$subname,"]");
5858  
5859 my @elements;
5860  
5861 @elements = $self->{twigroot}->descendants(\&twigelt_is_knownuid);
5862 return unless(@elements);
5863 debug(1,"DEBUG: found known UID '",$elements[0]->id,"'");
5864 return $elements[0]->id;
5865 }
5866  
5867  
5868 =head2 C<search_knownuidschemes()>
5869  
5870 Searches descendants of the OPF twig element for the first
5871 <dc:identifier> or <dc:Identifier> subelement with the attribute
5872 'scheme' or 'opf:scheme' matching a known list of schemes for unique
5873 IDs
5874  
5875 NOTE: this is NOT a case-insensitive search! If you have to deal with
5876 really bizarre input, make sure that you run L</fix_oeb12()> or
5877 L</fix_opf20()> before calling L</fix_packageid()> or L</fix_misc()>.
5878  
5879 Returns the ID if a match is found, undef otherwise.
5880  
5881 =cut
5882  
5883 sub search_knownuidschemes :method {
5884 my ($self,$gi) = @_;
5885 if(!$gi) { $gi = 'dc:identifier'; }
5886 my $subname = ( caller(0) )[3];
5887 croak($subname . "() called as a procedure") unless(ref $self);
5888 debug(2,"DEBUG[",$subname,"]");
5889 $self->twigcheck;
5890  
5891 my $topelement = $self->{twigroot};
5892  
5893 my @knownuidschemes = (
5894 'GUID',
5895 'UUID',
5896 'FWID',
5897 );
5898  
5899 # Creating a regexp to search on works, but doesn't let you
5900 # specify priority. For that, you really do have to loop.
5901 # my $schemeregexp = "(" . join('|',@knownuidschemes) . ")";
5902  
5903 my @elems;
5904 my $id;
5905  
5906 my $retval = undef;
5907  
5908 foreach my $scheme (@knownuidschemes) {
5909 debug(2,"DEBUG: searching for scheme='",$scheme,"'");
5910 @elems = $topelement->descendants(
5911 "dc:identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
5912 );
5913 push @elems, $topelement->descendants(
5914 "dc:Identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
5915 );
5916 foreach my $elem (@elems) {
5917 debug(2,"DEBUG: working on scheme '",$scheme,"'");
5918 if(defined $elem) {
5919 if($scheme eq 'FWID') {
5920 # Fictionwise has a screwy output that sets the ID
5921 # equal to the text. Fix the ID to just be 'FWID'
5922 debug(1,"DEBUG: fixing FWID");
5923 $elem->set_id('FWID');
5924 }
5925  
5926 $id = $elem->id;
5927 unless(defined $id) {
5928 debug(1,"DEBUG: assigning ID from scheme '",$scheme,"'");
5929 $id = uc($scheme);
5930 $elem->set_id($id);
5931 }
5932 $retval = $id;
5933 debug(1,"DEBUG: found Package ID: ",$id);
5934 last;
5935 } # if(defined $elem)
5936 } # foreach my $elem (@elems)
5937 last if(defined $retval);
5938 }
5939 debug(2,"[/",$subname,"]");
5940 return $retval;
5941 }
5942  
5943  
5944 =head2 C<spec()>
5945  
5946 Returns the version of the OEB specification currently in use. Valid
5947 values are C<OEB12> and C<OPF20>. This value will default to undef
5948 until C<fix_oeb12> or C<fix_opf20> is called, as there is no way for
5949 the object to know what specification is being conformed to (if any)
5950 until it attempts to enforce it.
5951  
5952 =cut
5953  
5954 sub spec :method {
5955 my $self = shift;
5956 my $subname = ( caller(0) )[3];
5957 croak($subname . "() called as a procedure") unless(ref $self);
5958 debug(2,"DEBUG[",$subname,"]");
5959 return $self->{spec};
5960 }
5961  
5962  
5963 =head2 C<spine()>
5964  
5965 Returns all of the manifest items referenced in the spine as a list of
5966 hashrefs, with one hash per manifest item in the order that they
5967 appear, where the hash keys are 'id', 'href', and 'media-type', each
5968 returning the appropriate attribute, if any.
5969  
5970 In scalar context, returns the first item, not the last.
5971  
5972 Returns undef if there is no <spine> element directly underneath
5973 <package>, or if <spine> contains no itemrefs. If <spine> exists, but
5974 <manifest> does not, or a spine itemref exists but points an ID not
5975 found in the manifest, spine() logs an error and returns undef.
5976  
5977 See also: L</spine_idrefs()>, L</manifest()>
5978  
5979 =cut
5980  
5981 sub spine :method {
5982 my $self = shift;
5983 my $subname = ( caller(0) )[3];
5984 croak($subname . "() called as a procedure") unless(ref $self);
5985 debug(2,"DEBUG[",$subname,"]");
5986 $self->twigcheck();
5987  
5988 my $spine = $self->{twigroot}->first_child('spine');
5989 return unless($spine);
5990 my @spinerefs;
5991 my $idref;
5992 my $element;
5993 my @retarray;
5994  
5995 my $manifest = $self->{twigroot}->first_child('manifest');
5996 if(!$manifest)
5997 {
5998 $self->add_error(
5999 $subname . "(): <spine> found without <manifest>"
6000 );
6001 debug(1,"DEBUG: <spine> found without <manifest>!");
6002 return;
6003 }
6004  
6005 @spinerefs = $spine->children('itemref');
6006 return unless(@spinerefs);
6007  
6008 foreach my $spineref (@spinerefs)
6009 {
6010 $idref = $spineref->att('idref');
6011 if(!$idref)
6012 {
6013 $self->add_warning(
6014 $subname . "(): <itemref> found with no idref -- skipping"
6015 );
6016 debug(1,"DEBUG: <itemref> found with no idref -- skipping");
6017 next;
6018 }
6019 $element = $manifest->first_child("item[\@id='$idref']");
6020 if(!$element)
6021 {
6022 $self->add_error(
6023 $subname ."(): id '" . $idref . "' not found in manifest!"
6024 );
6025 debug(1,"DEBUG: id '",$idref," not found in manifest!");
6026 return;
6027 }
6028 push(@retarray,
6029 {
6030 'id' => $element->id,
6031 'href' => $element->att('href'),
6032 'media-type' => $element->att('media-type')
6033 });
6034 }
6035 if(wantarray) { return @retarray; }
6036 else { return $retarray[0]; }
6037 }
6038  
6039  
6040 =head2 C<spine_idrefs()>
6041  
6042 Returns a list of all of the idrefs in the current OPF spine, or the
6043 empty list if none are found.
6044  
6045 In scalar context, returns the first idref, not the last.
6046  
6047 See also: L</spine()>, L</manifest_hrefs()>
6048  
6049 =cut
6050  
6051 sub spine_idrefs :method {
6052 my $self = shift;
6053 my $subname = ( caller(0) )[3];
6054 croak($subname . "() called as a procedure") unless(ref $self);
6055 debug(2,"DEBUG[",$subname,"]");
6056 $self->twigcheck();
6057  
6058 my $spine = $self->{twigroot}->first_child('spine');;
6059 my @retval = ();
6060 my @itemrefs;
6061 my $idref;
6062  
6063 if(! $spine) { return @retval; }
6064  
6065 @itemrefs = $spine->children('itemref');
6066 foreach my $item (@itemrefs) {
6067 $idref = $item->att('idref');
6068 push(@retval,$idref) if($idref);
6069 }
6070 if(wantarray) { return @retval; }
6071 else { return $retval[0]; }
6072 }
6073  
6074  
6075 =head2 C<subject_list()>
6076  
6077 Returns a list containing the text of all dc:subject elements or undef
6078 if none are found.
6079  
6080 In scalar context, returns the first subject, not the last.
6081  
6082 =cut
6083  
6084 sub subject_list :method {
6085 my $self = shift;
6086 my $subname = ( caller(0) )[3];
6087 croak($subname . "() called as a procedure") unless(ref $self);
6088 debug(2,"DEBUG[",$subname,"]");
6089 $self->twigcheck;
6090  
6091 my @retval = ();
6092 my $twigroot = $self->{twigroot};
6093  
6094 my @subjects = $twigroot->descendants(qr/dc:subject/ix);
6095 return unless(@subjects);
6096  
6097 foreach my $subject (@subjects) {
6098 push(@retval,$subject->text) if($subject->text);
6099 }
6100 return unless(@retval);
6101 if(wantarray) { return @retval; }
6102 else { return $retval[0]; }
6103 }
6104  
6105  
6106 =head2 C<title()>
6107  
6108 Returns the title of the e-book, or undef if no dc:title element
6109 (case-insensitive) exists. If a dc:title element exists, but contains
6110 no text, returns an empty string.
6111  
6112 =cut
6113  
6114 sub title :method {
6115 my $self = shift;
6116 my $subname = ( caller(0) )[3];
6117 croak($subname . "() called as a procedure") unless(ref $self);
6118 debug(2,"DEBUG[",$subname,"]");
6119 $self->twigcheck;
6120  
6121 my $twigroot = $self->{twigroot};
6122 my $retval;
6123  
6124 my $element = $twigroot->first_descendant(qr/^dc:title$/ix);
6125 return unless($element);
6126 $retval = $element->text || '';
6127 $retval = trim($retval);
6128 return $retval;
6129 }
6130  
6131  
6132 =head2 C<twig()>
6133  
6134 Returns the raw L<XML::Twig> object used to store the OPF metadata.
6135  
6136 Although this twig can be manipulated via the standard XML::Twig
6137 methods, doing so requires caution and is not recommended. In
6138 particular, changing the root element from here will cause the
6139 EBook::Tools internal twig and twigroot attributes to become unlinked
6140 and the result of any subsequent action is not defined.
6141  
6142 =cut
6143  
6144 sub twig :method {
6145 my $self = shift;
6146 my $subname = ( caller(0) )[3];
6147 croak($subname . "() called as a procedure") unless(ref $self);
6148 debug(2,"DEBUG[",$subname,"]");
6149 return $self->{twig};
6150 }
6151  
6152  
6153 =head2 C<twigcheck()>
6154  
6155 Croaks showing the calling location unless C<$self> has both a twig and a
6156 twigroot, and the twigroot is <package>. Used as a sanity check for
6157 methods that use twig or twigroot.
6158  
6159 =cut
6160  
6161 sub twigcheck :method {
6162 my $self = shift;
6163 my $subname = ( caller(0) )[3];
6164 croak($subname . "() called as a procedure") unless(ref $self);
6165 debug(3,"DEBUG[",$subname,"]");
6166  
6167 my @calledfrom = caller(1);
6168 croak("twigcheck called from unknown location") if(!@calledfrom);
6169  
6170 croak($calledfrom[3],"(): undefined twig")
6171 if(!$self->{twig});
6172 croak($calledfrom[3],"(): twig isn't a XML::Twig")
6173 if( (ref $self->{twig}) ne 'XML::Twig' );
6174 croak($calledfrom[3],"(): twig root missing")
6175 if(!$self->{twigroot});
6176 croak($calledfrom[3],"(): twig root isn't a XML::Twig::Elt")
6177 if( (ref $self->{twigroot}) ne 'XML::Twig::Elt' );
6178 croak($calledfrom[3],"(): twig root is '" . $self->{twigroot}->gi
6179 . "' (needs to be 'package')")
6180 if($self->{twigroot}->gi ne 'package');
6181 debug(3,"DEBUG[/",$subname,"]");
6182 return 1;
6183 }
6184  
6185  
6186 =head2 C<twigroot()>
6187  
6188 Returns the raw L<XML::Twig> root element used to store the OPF
6189 metadata.
6190  
6191 This twig element can be manipulated via the standard XML::Twig::Elt
6192 methods, but care should be taken not to attempt to cut this element
6193 from its twig as doing so will cause the EBook::Tools internal twig
6194 and twigroot attributes to become unlinked and the result of any
6195 subsequent action is not defined.
6196  
6197 =cut
6198  
6199 sub twigroot :method {
6200 my $self = shift;
6201 my $subname = ( caller(0) )[3];
6202 croak($subname . "() called as a procedure") unless(ref $self);
6203 debug(2,"DEBUG[",$subname,"]");
6204 return $self->{twigroot};
6205 }
6206  
6207  
6208 =head2 C<warnings()>
6209  
6210 Returns an arrayref containing any generated warning messages.
6211  
6212 =cut
6213  
6214 sub warnings :method {
6215 my $self = shift;
6216 my $subname = ( caller(0) )[3];
6217 croak($subname . "() called as a procedure") unless(ref $self);
6218 debug(2,"DEBUG[",$subname,"]");
6219 return $self->{warnings};
6220 }
6221  
6222  
6223 ######################################
6224 ########## MODIFIER METHODS ##########
6225 ######################################
6226  
6227 =head1 MODIFIER METHODS
6228  
6229 Unless otherwise specified, all modifier methods return undef if an
6230 error was added to the error list, and true otherwise (even if a
6231 warning was added to the warning list).
6232  
6233  
6234 =head2 C<add_document($href,$id,$mediatype)>
6235  
6236 Adds a document to the OPF manifest and spine, creating <manifest> and
6237 <spine> if necessary. To add an item only to the OPF manifest, see
6238 add_item().
6239  
6240 =head3 Arguments
6241  
6242 =over
6243  
6244 =item C<$href>
6245  
6246 The href to the document in question. Usually, this is just a
6247 filename (or relative path and filename) of a file in the current
6248 working directory. If you are planning to eventually generate a .epub
6249 book, all hrefs MUST be in or below the current working directory.
6250  
6251 The method returns undef if $href is not defined or empty.
6252  
6253 =item C<$id>
6254  
6255 The XML ID to use. If not specified, defaults to the href with
6256 invalid characters removed.
6257  
6258 This must be unique not only to the manifest list, but to every
6259 element in the OPF file. If a duplicate ID exists, the method sets an
6260 error and returns undef.
6261  
6262 =item C<$mediatype> (optional)
6263  
6264 The mime type of the document. If not specified, will attempt to
6265 autodetect the mime type, and if that fails, will default to
6266 'application/xhtml+xml'.
6267  
6268 =back
6269  
6270 =cut
6271  
6272 sub add_document :method {
6273 my ($self,$href,$id,$mediatype) = @_;
6274 my $subname = (caller(0))[3];
6275 croak($subname . "() called as a procedure") unless(ref $self);
6276 debug(2,"DEBUG[",$subname,"]");
6277 $self->twigcheck();
6278  
6279 $href = trim($href);
6280 return unless($href);
6281  
6282 my $twig = $self->{twig};
6283 my $topelement = $self->{twigroot};
6284 my $element;
6285  
6286 $id = $href unless($id);
6287 $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
6288 $id =~ s/^[.\d -]+//gx; # Delete all nonvalid XML 1.0 namestartchars
6289  
6290 $element = $twig->first_elt("*[\@id='$id']");
6291 if($element)
6292 {
6293 $self->add_error(
6294 $subname . "(): ID '" . $id . "' already exists"
6295 . " (in a '" . $element->gi ."' tag)"
6296 );
6297 return;
6298 }
6299  
6300 if(!$mediatype)
6301 {
6302 my $mimetype = mimetype($href);
6303 if($mimetype) { $mediatype = $mimetype; }
6304 else { $mediatype = "application/xhtml+xml"; }
6305 debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,"'");
6306 }
6307  
6308 my $manifest = $topelement->first_child('manifest');
6309 $manifest = $topelement->insert_new_elt('last_child','manifest')
6310 if(!$manifest);
6311 my $spine = $topelement->first_child('spine');
6312 $spine = $topelement->insert_new_elt('last_child','spine')
6313 if(!$spine);
6314  
6315 my $item = $manifest->insert_new_elt('last_child','item');
6316 $item->set_id($id);
6317 $item->set_att(
6318 'href' => $href,
6319 'media-type' => $mediatype
6320 );
6321  
6322 my $itemref = $spine->insert_new_elt('last_child','itemref');
6323 $itemref->set_att('idref' => $id);
6324  
6325 return 1;
6326 }
6327  
6328  
6329 =head2 C<add_error(@errors)>
6330  
6331 Adds @errors to the list of object errors. Each member of
6332 @errors should be a string containing the entire text of the
6333 error, with no ending newline.
6334  
6335 SEE ALSO: L</add_warning()>, L</clear_errors()>, L</clear_warnerr()>
6336  
6337 =cut
6338  
6339 sub add_error :method {
6340 my ($self,@newerror) = @_;
6341 my $subname = (caller(0))[3];
6342 croak($subname . "() called as a procedure") unless(ref $self);
6343 debug(3,"DEBUG[",$subname,"]");
6344  
6345 my $currenterrors;
6346 $currenterrors = $self->{errors} if($self->{errors});
6347  
6348 if(@newerror) {
6349 my $error = join('',@newerror);
6350 debug(1,"ERROR: ",$error);
6351 push(@$currenterrors,$error);
6352 }
6353 $self->{errors} = $currenterrors;
6354 return 1;
6355 }
6356  
6357  
6358 =head2 C<add_identifier(%args)>
6359  
6360 Creates a new dc:identifier element containing the specified text, id,
6361 and scheme.
6362  
6363 If a <dc-metadata> element exists underneath <metadata>, the
6364 identifier element will be created underneath the <dc-metadata> in OEB
6365 1.2 format, otherwise the title element is created underneath
6366 <metadata> in OPF 2.0 format.
6367  
6368 Returns the twig element containing the new identifier.
6369  
6370 =head3 Arguments
6371  
6372 C<add_identifier()> takes three named arguments, one mandatory, two
6373 optional.
6374  
6375 =over
6376  
6377 =item * C<text> - the text of the identifier. This is mandatory, and
6378 the method croaks if it is not present.
6379  
6380 =item * C<scheme> - 'opf:scheme' or 'scheme' attribute to be added (optional)
6381  
6382 =item * C<id> - 'id' attribute to be added. If this is specified, and
6383 the id is already in use, a warning will be added but the method will
6384 continue, removing the id attribute from the element that previously
6385 contained it.
6386  
6387 =back
6388  
6389 =cut
6390  
6391 sub add_identifier :method {
6392 my ($self,%args) = @_;
6393 my %valid_args = (
6394 'text' => 1,
6395 'id' => 1,
6396 'scheme' => 1,
6397 );
6398 my $subname = ( caller(0) )[3];
6399 croak($subname . "() called as a procedure") unless(ref $self);
6400 debug(2,"DEBUG[",$subname,"]");
6401 $self->twigcheck();
6402 foreach my $arg (keys %args) {
6403 croak($subname,"(): invalid argument '",$arg,"'")
6404 if(!$valid_args{$arg});
6405 }
6406 croak($subname,"(): identifier text not specified")
6407 unless($args{text});
6408  
6409 $self->fix_metastructure_basic();
6410 my $meta = $self->{twigroot}->first_child('metadata');
6411 my $dcmeta = $meta->first_child('dc-metadata');
6412 my $element;
6413 my $idelem;
6414 my $newid = $args{id};
6415 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
6416  
6417 if($dcmeta) {
6418 $element = $dcmeta->insert_new_elt('last_child','dc:Identifier');
6419 $element->set_att('scheme' => $args{scheme}) if($args{scheme});
6420 }
6421 else {
6422 $element = $meta->insert_new_elt('last_child','dc:identifier');
6423 $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
6424 }
6425 $element->set_text($args{text});
6426  
6427 if($idelem && $idelem->cmp($element) ) {
6428 $self->add_warning(
6429 $subname,"(): reassigning id '",$newid,
6430 "' from a '",$idelem->gi,"' element!"
6431 );
6432 $idelem->del_att('id');
6433 }
6434 $element->set_att('id' => $newid) if($newid);
6435  
6436 return $element;
6437 }
6438  
6439  
6440 =head2 C<add_item($href,$id,$mediatype)>
6441  
6442 Adds a document to the OPF manifest (but not spine), creating
6443 <manifest> if necessary. To add an item only to both the OPF manifest
6444 and spine, see add_document().
6445  
6446 =head3 Arguments
6447  
6448 =over
6449  
6450 =item C<$href>
6451  
6452 The href to the document in question. Usually, this is just a
6453 filename (or relative path and filename) of a file in the current
6454 working directory. If you are planning to eventually generate a .epub
6455 book, all hrefs MUST be in or below the current working directory.
6456  
6457 =item C<$id>
6458  
6459 The XML ID to use. If not specified, defaults to the href with all
6460 nonword characters removed.
6461  
6462 This must be unique not only to the manifest list, but to every
6463 element in the OPF file. If a duplicate ID exists, the method sets an
6464 error and returns undef.
6465  
6466 =item C<$mediatype> (optional)
6467  
6468 The mime type of the document. If not specified, will attempt to
6469 autodetect the mime type, and if that fails, will set an error and
6470 return undef.
6471  
6472 =back
6473  
6474 =cut
6475  
6476 sub add_item :method {
6477 my ($self,$href,$id,$mediatype) = @_;
6478 my $subname = (caller(0))[3];
6479 croak($subname . "() called as a procedure") unless(ref $self);
6480 debug(2,"DEBUG[",$subname,"]");
6481 $self->twigcheck();
6482  
6483 $href = trim($href);
6484 return unless($href);
6485  
6486 my $twig = $self->{twig};
6487 my $topelement = $self->{twigroot};
6488 my $element;
6489  
6490 $id = $href unless($id);
6491 $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
6492 if($id =~ /^[.\d -]+/x) {
6493 # We're starting with a nonvalid XML 1.0 namestartchar, so
6494 # prefix with id_
6495 $id = 'id_' . $id;
6496 }
6497  
6498 $element = $twig->first_elt("*[\@id='$id']");
6499 if($element) {
6500 $self->add_error(
6501 $subname . "(): ID '" . $id . "' already exists"
6502 . " (in a '" . $element->gi ."' tag)"
6503 );
6504 debug(2,"DEBUG[/",$subname,"]");
6505 return;
6506 }
6507  
6508 if(!$mediatype) {
6509 my $mimetype = mimetype($href);
6510 if($mimetype) { $mediatype = $mimetype; }
6511 else { $mediatype = "application/xhtml+xml"; }
6512 debug(2,"DEBUG: '",$href,"' has mimetype '",$mediatype,"'");
6513 }
6514  
6515 my $manifest = $self->{twigroot}->first_child('manifest');
6516 $manifest = $topelement->insert_new_elt('last_child','manifest')
6517 if(!$manifest);
6518  
6519 debug(2,"DEBUG: adding item '",$id,"': '",$href,"'");
6520 my $item = $manifest->insert_new_elt('last_child','item');
6521 $item->set_id($id);
6522 $item->set_att(
6523 'href' => $href,
6524 'media-type' => $mediatype
6525 );
6526  
6527 debug(3,"DEBUG[/",$subname,"]");
6528 return 1;
6529 }
6530  
6531  
6532 =head2 add_metadata(%args)
6533  
6534 Creates a metadata element with the specified text, attributes, and parent.
6535  
6536 If a <dc-metadata> element exists underneath <metadata>, the language
6537 element will be created underneath the <dc-metadata> and any standard
6538 attributes will be created in OEB 1.2 format, otherwise the element is
6539 created underneath <metadata> in OPF 2.0 format.
6540  
6541 Returns 1 on success, returns undef if no gi or if no text was specified.
6542  
6543 =cut
6544  
6545 =head3 Arguments
6546  
6547 =over
6548  
6549 =item C<gi>
6550  
6551 The generic identifier (tag) of the metadata element to alter or
6552 create. If not specified, the method sets an error and returns undef.
6553  
6554 =item C<parent>
6555  
6556 The generic identifier (tag) of the parent to use for any newly
6557 created element. If not specified, defaults to 'dc-metadata' if
6558 'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.
6559  
6560 A newly created element will be created under the first element found
6561 with this gi. A modified element will be moved under the first
6562 element found with this gi.
6563  
6564 Newly created elements will use OPF 2.0 attribute names if the parent
6565 is 'metadata' and OEB 1.2 attribute names otherwise.
6566  
6567 =item C<text>
6568  
6569 This specifies the element text to set. If not specified, the method
6570 sets an error and returns undef.
6571  
6572 =item C<id> (optional)
6573  
6574 This specifies the ID to set on the element. If set and the ID is
6575 already in use, a warning is logged and the ID is removed from the
6576 other location and assigned to the element.
6577  
6578 =item C<fileas> (optional)
6579  
6580 This specifies the file-as attribute to set on the element.
6581  
6582 =item C<role> (optional)
6583  
6584 This specifies the role attribute to set on the element.
6585  
6586 =item C<scheme> (optional)
6587  
6588 This specifies the scheme attribute to set on the element.
6589  
6590 =back
6591  
6592 =head3 Example
6593  
6594 $retval = $ebook->add_metadata(gi => 'AuthorNonstandard',
6595 text => 'Element Text',
6596 id => 'customid',
6597 fileas => 'Text, Element',
6598 role => 'xxx',
6599 scheme => 'code');
6600  
6601 =cut
6602  
6603 sub add_metadata :method {
6604 my ($self,%args) = @_;
6605 my $subname = ( caller(0) )[3];
6606 croak($subname . "() called as a procedure") unless(ref $self);
6607 debug(3,"DEBUG[",$subname,"]");
6608 my %valid_args = (
6609 'gi' => 1,
6610 'parent' => 1,
6611 'text' => 1,
6612 'id' => 1,
6613 'fileas' => 1,
6614 'role' => 1,
6615 'scheme' => 1,
6616 );
6617 foreach my $arg (keys %args) {
6618 croak($subname,"(): invalid argument '",$arg,"'")
6619 if(!$valid_args{$arg});
6620 }
6621  
6622 my $gi = $args{gi};
6623 unless($gi) {
6624 $self->add_error($subname,"(): no gi specified");
6625 return;
6626 }
6627  
6628 my $text = $args{text};
6629 unless($text) {
6630 $self->add_error($subname,"(): no text specified");
6631 return;
6632 }
6633  
6634 my $newid = $args{id};
6635 my $idelem;
6636 my $element;
6637 my $meta;
6638 my $dcmeta;
6639 my $parent;
6640 my %dcatts;
6641  
6642 $self->fix_metastructure_basic();
6643 $parent = $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
6644 if($args{parent});
6645 $meta = $self->{twigroot}->first_child('metadata');
6646 $dcmeta = $meta->first_child('dc-metadata');
6647 $parent = $parent || $dcmeta || $meta;
6648 if($parent->gi eq 'metadata') {
6649 %dcatts = (
6650 'file-as' => 'opf:file-as',
6651 'role' => 'opf:role',
6652 'scheme' => 'opf:scheme',
6653 );
6654 }
6655 else {
6656 %dcatts = (
6657 'file-as' => 'file-as',
6658 'role' => 'role',
6659 'scheme' => 'scheme'
6660 );
6661 }
6662  
6663 debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
6664 $element = $parent->insert_new_elt('last_child',$gi);
6665 $element->set_att($dcatts{'file-as'},$args{fileas})
6666 if($args{fileas});
6667 $element->set_att($dcatts{'role'},$args{role})
6668 if($args{role});
6669 $element->set_att($dcatts{'scheme'},$args{scheme})
6670 if($args{scheme});
6671 $element->set_text($text);
6672  
6673 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
6674 if($idelem && $idelem->cmp($element) ) {
6675 $self->add_warning(
6676 $subname,"(): reassigning id '",$newid,
6677 "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
6678 );
6679 $idelem->del_att('id');
6680 }
6681 $element->set_att('id' => $newid) if($newid);
6682 return 1;
6683 }
6684  
6685  
6686 =head2 C<add_subject(%args)>
6687  
6688 Creates a new dc:subject element containing the specified text, code,
6689 and id.
6690  
6691 If a <dc-metadata> element exists underneath <metadata>, the
6692 subject element will be created underneath the <dc-metadata> in OEB
6693 1.2 format, otherwise the title element is created underneath
6694 <metadata> in OPF 2.0 format.
6695  
6696 Returns the twig element containing the new subject.
6697  
6698 =head3 Arguments
6699  
6700 C<add_subject()> takes four named arguments, one mandatory, three
6701 optional.
6702  
6703 =over
6704  
6705 =item * C<text> - the text of the subject. This is mandatory, and
6706 the method croaks if it is not present.
6707  
6708 =item * C<scheme> (optional) - 'opf:scheme' or 'scheme' attribute to
6709 be added. Be warned that neither the OEB 1.2 nor the OPF 2.0
6710 specifications allow a scheme to be added to this element, so if this
6711 is specified, the resulting OPF file will fail to validate against
6712 either standard.
6713  
6714 =item * C<basiccode> (optional) - 'BASICCode' attribute to be added.
6715 Be warned that this is a Mobipocket-specific attribute that does not
6716 exist in either the OEB 1.2 nor the OPF 2.0 specifications, so if this
6717 is specified, the resulting OPF file will fail to validate against
6718 either standard.
6719  
6720 =item * C<id> (optional) - 'id' attribute to be added. If this is
6721 specified, and the id is already in use, a warning will be added but
6722 the method will continue, removing the id attribute from the element
6723 that previously contained it.
6724  
6725 =back
6726  
6727 =cut
6728  
6729 sub add_subject :method {
6730 my ($self,%args) = @_;
6731 my %valid_args = (
6732 'text' => 1,
6733 'id' => 1,
6734 'scheme' => 1,
6735 'basiccode' => 1,
6736 );
6737 my $subname = ( caller(0) )[3];
6738 croak($subname . "() called as a procedure") unless(ref $self);
6739 debug(2,"DEBUG[",$subname,"]");
6740 $self->twigcheck();
6741 foreach my $arg (keys %args) {
6742 croak($subname,"(): invalid argument '",$arg,"'")
6743 if(!$valid_args{$arg});
6744 }
6745 croak($subname,"(): subject text not specified")
6746 unless($args{text});
6747  
6748 $self->fix_metastructure_basic();
6749 my $meta = $self->{twigroot}->first_child('metadata');
6750 my $dcmeta = $meta->first_child('dc-metadata');
6751 my $element;
6752 my $idelem;
6753 my $newid = $args{id};
6754 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
6755  
6756 if($dcmeta) {
6757 $element = $dcmeta->first_child('dc:Subject[string()="' . $args{text} . '"]');
6758 if(! $element) {
6759 $element = $dcmeta->insert_new_elt('last_child','dc:Subject');
6760 }
6761 $element->set_att('scheme' => $args{scheme}) if($args{scheme});
6762 }
6763 else {
6764 $element = $meta->first_child('dc:subject[string()="' . $args{text} . '"]');
6765 if(! $element) {
6766 $element = $meta->insert_new_elt('last_child','dc:subject');
6767 }
6768 $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
6769 }
6770 $element->set_text($args{text});
6771 $element->set_att('BASICCode' => $args{basiccode}) if($args{basiccode});
6772  
6773 if($idelem && $idelem->cmp($element) ) {
6774 $self->add_warning(
6775 $subname,"(): reassigning id '",$newid,
6776 "' from a '",$idelem->gi,"' element!"
6777 );
6778 $idelem->del_att('id');
6779 }
6780 $element->set_att('id' => $newid) if($newid);
6781  
6782 return $element;
6783 }
6784  
6785  
6786 =head2 C<add_warning(@newwarning)>
6787  
6788 Joins @newwarning to a single string and adds it to the list of object
6789 warnings. The warning should not end with a newline newline.
6790  
6791 SEE ALSO: L</add_error()>, L</clear_warnings()>, L</clear_warnerr()>
6792  
6793 =cut
6794  
6795 sub add_warning :method {
6796 my ($self,@newwarning) = @_;
6797 my $subname = (caller(0))[3];
6798 croak($subname . "() called as a procedure") unless(ref $self);
6799 debug(3,"DEBUG[",$subname,"]");
6800  
6801 my @currentwarnings;
6802 @currentwarnings = @{$self->{warnings}} if($self->{warnings});
6803  
6804 if (@newwarning) {
6805 my $warning = join('',@newwarning);
6806 debug(1,"WARNING: ",$warning);
6807 push(@currentwarnings,$warning);
6808 }
6809 $self->{warnings} = \@currentwarnings;
6810  
6811 debug(3,"DEBUG[/",$subname,"]");
6812 return 1;
6813 }
6814  
6815  
6816 =head2 C<clear_errors()>
6817  
6818 Clear the current list of errors
6819  
6820 =cut
6821  
6822 sub clear_errors :method {
6823 my $self = shift;
6824 my $subname = ( caller(0) )[3];
6825 croak($subname . "() called as a procedure") unless(ref $self);
6826 debug(2,"DEBUG[",$subname,"]");
6827  
6828 $self->{errors} = ();
6829 return 1;
6830 }
6831  
6832  
6833 =head2 C<clear_warnerr()>
6834  
6835 Clear both the error and warning lists
6836  
6837 =cut
6838  
6839 sub clear_warnerr :method {
6840 my $self = shift;
6841 my $subname = ( caller(0) )[3];
6842 croak($subname . "() called as a procedure") unless(ref $self);
6843 debug(2,"DEBUG[",$subname,"]");
6844  
6845 $self->{errors} = ();
6846 $self->{warnings} = ();
6847 return 1;
6848 }
6849  
6850  
6851 =head2 C<clear_warnings()>
6852  
6853 Clear the current list of warnings
6854  
6855 =cut
6856  
6857 sub clear_warnings :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->{warnings} = ();
6864 return 1;
6865 }
6866  
6867  
6868 =head2 C<delete_meta_filepos()>
6869  
6870 Deletes metadata elements with the attribute 'filepos' underneath
6871 the given parent element
6872  
6873 These are secondary metadata elements included in the output from
6874 mobi2html may that are not used.
6875  
6876 =cut
6877  
6878 sub delete_meta_filepos :method {
6879 my $self = shift;
6880 my $subname = ( caller(0) )[3];
6881 croak($subname . "() called as a procedure") unless(ref $self);
6882 debug(2,"DEBUG[",$subname,"]");
6883 $self->twigcheck();
6884  
6885 my @elements = $self->{twigroot}->descendants('metadata[@filepos]');
6886 foreach my $el (@elements) {
6887 $el->delete;
6888 }
6889 return 1;
6890 }
6891  
6892  
6893 =head2 C<delete_subject(%args)>
6894  
6895 Deletes dc:subject and dc:Subject elements based on text content or
6896 the id, scheme, or basiccode attributes. Matches are case-sensitive.
6897  
6898 Specifying multiple arguments will delete subject matching any of them.
6899  
6900 This has the same potential arguments as add_subject.
6901  
6902 Returns the count of elements deleted.
6903  
6904 =cut
6905  
6906 sub delete_subject :method {
6907 my ($self,%args) = @_;
6908 my %valid_args = (
6909 'text' => 1,
6910 'id' => 1,
6911 'scheme' => 1,
6912 'basiccode' => 1,
6913 );
6914 my $subname = ( caller(0) )[3];
6915 croak($subname . "() called as a procedure") unless(ref $self);
6916 debug(2,"DEBUG[",$subname,"]");
6917 $self->twigcheck();
6918 foreach my $arg (keys %args) {
6919 croak($subname,"(): invalid argument '",$arg,"'")
6920 if(!$valid_args{$arg});
6921 }
6922  
6923 my @elements;
6924 my $count = 0;
6925  
6926 if(defined $args{text}) {
6927 @elements = $self->{twigroot}->descendants('dc:subject[text()="' . $args{text} . '"]');
6928 foreach my $el (@elements) {
6929 $el->delete;
6930 $count++;
6931 }
6932 @elements = $self->{twigroot}->descendants('dc:Subject[text()="' . $args{text} . '"]');
6933 foreach my $el (@elements) {
6934 $el->delete;
6935 $count++;
6936 }
6937 }
6938  
6939 if($args{id}) {
6940 @elements = $self->{twigroot}->descendants('dc:subject[@id="' . $args{id} . '"]');
6941 foreach my $el (@elements) {
6942 $el->delete;
6943 $count++;
6944 }
6945 @elements = $self->{twigroot}->descendants('dc:Subject[@id="' . $args{id} . '"]');
6946 foreach my $el (@elements) {
6947 $el->delete;
6948 $count++;
6949 }
6950 }
6951  
6952 if($args{scheme}) {
6953 @elements = $self->{twigroot}->descendants('dc:subject[@scheme="' . $args{scheme} . '"]');
6954 foreach my $el (@elements) {
6955 $el->delete;
6956 $count++;
6957 }
6958 @elements = $self->{twigroot}->descendants('dc:subject[@opf:scheme="' . $args{scheme} . '"]');
6959 foreach my $el (@elements) {
6960 $el->delete;
6961 $count++;
6962 }
6963 @elements = $self->{twigroot}->descendants('dc:Subject[@scheme="' . $args{scheme} . '"]');
6964 foreach my $el (@elements) {
6965 $el->delete;
6966 $count++;
6967 }
6968 @elements = $self->{twigroot}->descendants('dc:Subject[@opf:scheme="' . $args{scheme} . '"]');
6969 foreach my $el (@elements) {
6970 $el->delete;
6971 $count++;
6972 }
6973 }
6974  
6975 if($args{basiccode}) {
6976 @elements = $self->{twigroot}->descendants('dc:subject[@BASICCode="' . $args{id} . '"]');
6977 foreach my $el (@elements) {
6978 $el->delete;
6979 $count++;
6980 }
6981 @elements = $self->{twigroot}->descendants('dc:Subject[@BASICCode="' . $args{id} . '"]');
6982 foreach my $el (@elements) {
6983 $el->delete;
6984 $count++;
6985 }
6986 }
6987 debug(2,"DEBUG: Deleted ",$count," elements");
6988 return $count;
6989 }
6990  
6991  
6992 =head2 C<fix_creators()>
6993  
6994 Normalizes creator and contributor names and file-as attributes
6995  
6996 Names are normalized to 'First Last' format, while file-as attributes
6997 are normalized to 'Last, First' format.
6998  
6999 This can damage some unusual names that do not match standard
7000 capitalization formats, so it is not made part of L</fix_misc()>.
7001  
7002 =cut
7003  
7004 sub fix_creators :method {
7005 my $self = shift;
7006 my $subname = ( caller(0) )[3];
7007 croak($subname . "() called as a procedure") unless(ref $self);
7008 debug(2,"DEBUG[",$subname,"]");
7009 $self->twigcheck();
7010  
7011 my $twigroot = $self->{twigroot};
7012 my @elements = $twigroot->descendants(qr/dc:(creator|contributor)/ix);
7013 my $nameparse = Lingua::EN::NameParse->new(
7014 allow_reversed => 1,
7015 extended_titles => 1,
7016 force_case => 1,
7017 lc_prefix => 1,
7018 );
7019 foreach my $el (@elements) {
7020 my $fileas = $el->att('opf:file-as') || '';
7021 my $name = $el->text || '';
7022 my $fixed;
7023 $name = trim($name);
7024  
7025 if ( $nameparse->parse($name) ) {
7026 $self->add_warning(
7027 "failure while parsing name: ",
7028 {$nameparse->properties}->{non_matching});
7029 }
7030 else {
7031 $fixed = $nameparse->case_all;
7032 if($fixed and $strangenames{lc $fixed}) {
7033 $fixed = $strangenames{lc $fixed};
7034 }
7035 debug(2,"DEBUG: creator name '",$name,"' -> '",
7036 $fixed,"'");
7037 $el->set_text($fixed);
7038  
7039 $fixed = $nameparse->case_all_reversed;
7040 if($fixed and $strangefileas{lc $fixed}) {
7041 $fixed = $strangefileas{lc $fixed};
7042 }
7043 if($fixed) {
7044 debug(2,"DEBUG: creator file-as '",$fileas,"' -> '",
7045 $fixed,"'");
7046 $el->set_att('opf:file-as',$fixed);
7047 }
7048 else {
7049 debug(2,"DEBUG: removing empty creator file-as from creator '",
7050 $name,"'");
7051 $el->del_att('opf:file-as');
7052 }
7053 }
7054 }
7055 return;
7056 }
7057  
7058  
7059 =head2 C<fix_dates()>
7060  
7061 Standardizes all <dc:date> elements via fix_datestring(). Adds a
7062 warning to the object for each date that could not be fixed.
7063  
7064 Called from L</fix_misc()>.
7065  
7066 =cut
7067  
7068 sub fix_dates :method {
7069 my $self = shift;
7070 my $subname = ( caller(0) )[3];
7071 croak($subname . "() called as a procedure") unless(ref $self);
7072 debug(2,"DEBUG[",$subname,"]");
7073 $self->twigcheck();
7074  
7075 my @dates;
7076 my $newdate;
7077  
7078 @dates = $self->{twigroot}->descendants('dc:date');
7079 push(@dates,$self->{twigroot}->descendants('dc:Date'));
7080  
7081 foreach my $dcdate (@dates) {
7082 if(!$dcdate->text) {
7083 $self->add_warning(
7084 "WARNING: found dc:date with no value -- skipping");
7085 }
7086 else {
7087 $newdate = fix_datestring($dcdate->text);
7088 if(!$newdate) {
7089 $self->add_warning(
7090 sprintf("fixmisc(): can't deal with date '%s' -- skipping",
7091 $dcdate->text)
7092 );
7093 }
7094 elsif($dcdate->text ne $newdate) {
7095 debug(2,"DEBUG: setting date from '",$dcdate->text,
7096 "' to '",$newdate,"'");
7097 $dcdate->set_text($newdate);
7098 }
7099 }
7100 }
7101 return 1;
7102 }
7103  
7104  
7105 =head2 C<fix_guide()>
7106  
7107 Fixes problems related to the OPF guide elements, specifically:
7108  
7109 =over
7110  
7111 =item * Ensures the guide element exists
7112  
7113 =item * Moves all reference elements directly underneath the guide element
7114  
7115 =item * Finds nonstandard reference types and either converts them to
7116 standard or prefaces them with 'other.'
7117  
7118 =item * Finds reference elements with a href with only an anchor
7119 portion and assigns them to the first spine href. This only works if
7120 the spine is in working condition, so it may be wise to run
7121 L</fix_spine()> before C<fix_guide()> if the input is expected to be
7122 very badly broken.
7123  
7124 =back
7125  
7126 Logs a warning if a reference href is found that does not appear in
7127 the manifest.
7128  
7129 =cut
7130  
7131 sub fix_guide :method {
7132 my $self = shift;
7133 my $subname = ( caller(0) )[3];
7134 croak($subname . "() called as a procedure") unless(ref $self);
7135 debug(2,"DEBUG[",$subname,"]");
7136 $self->twigcheck();
7137  
7138 my $twigroot = $self->{twigroot};
7139 my $guide = $twigroot->first_descendant('guide');
7140 my $parent;
7141 my $href;
7142 my $type;
7143 my @spine;
7144  
7145 # If <guide> doesn't exist, create it
7146 unless($guide) {
7147 debug(1,"DEBUG: creating <guide>");
7148 $guide = $twigroot->insert_new_elt('last_child','guide');
7149 }
7150  
7151 # Make sure that the guide is a child of the twigroot,
7152 $parent = $guide->parent;
7153 if( $parent->cmp($twigroot) ) {
7154 debug(1,"DEBUG: moving <guide>");
7155 $guide->move('last_child',$twigroot);
7156 }
7157  
7158  
7159 my @elements = $twigroot->descendants(qr/^reference$/ix);
7160 foreach my $el (@elements) {
7161 $type = $el->att('type');
7162 if($referencetypes{$type}) {
7163 $el->set_att('type',$referencetypes{$type});
7164 }
7165 elsif($type !~ /^other./x) {
7166 $type = 'other.' . $type;
7167 $el->set_att('type',$type);
7168 }
7169  
7170 $href = $el->att('href');
7171 if (!$href) {
7172 # No href means it is broken.
7173 # Leave it alone, but log a warning
7174 $self->add_warning(
7175 "fix_guide(): <reference> with no href -- skipping");
7176 next;
7177 }
7178 if ($href =~ /^#/) {
7179 # Anchor-only href. Attempt to fix from the first
7180 # spine entry
7181 @spine = $self->spine;
7182 if (!@spine) {
7183 $self->add_warning(
7184 "fix_guide(): Cannot correct reference href '",$href,
7185 "', spine is empty");
7186 }
7187 elsif (!$spine[0]->{href}) {
7188 $self->add_warning(
7189 "fix_guide(): Cannot correct reference href '",$href,
7190 "', cannot find href for first spine entry");
7191 }
7192 else {
7193 debug(1,"DEBUG: correcting reference href from '",$href,
7194 "' to '",$spine[0]->{href} . $href,"'");
7195 $el->set_att('href',$spine[0]->{href} . $href);
7196 }
7197 }
7198 debug(3,"DEBUG: processing reference '",$href,"')");
7199 $el->move('last_child',$guide);
7200 } # foreach my $el (@elements)
7201  
7202 return 1;
7203 }
7204  
7205  
7206 =head2 C<fix_languages(%args)>
7207  
7208 Checks through the <dc:language> elements (case-insensitive) and
7209 removes any duplicates. If no <dc:language> elements are found, one
7210 is created.
7211  
7212 TODO: Also convert language names to IANA language and region codes.
7213  
7214 =head3 Arguments
7215  
7216 =over
7217  
7218 =item * C<default>
7219  
7220 The default language string to use when creating a new language
7221 element. If not specified, defaults to 'en'.
7222  
7223 =back
7224  
7225 =cut
7226  
7227 sub fix_languages :method {
7228 my ($self,%args) = @_;
7229 my $subname = ( caller(0) )[3];
7230 croak($subname . "() called as a procedure") unless(ref $self);
7231 debug(2,"DEBUG[",$subname,"]");
7232 $self->twigcheck();
7233  
7234 my %valid_args = (
7235 'default' => 1,
7236 );
7237 foreach my $arg (keys %args) {
7238 croak($subname,"(): invalid argument '",$arg,"'")
7239 if(!$valid_args{$arg});
7240 }
7241  
7242 my $twigroot = $self->{twigroot};
7243 my $defaultlang = $args{default} || 'en';
7244 my $langel;
7245 my @elements = $twigroot->descendants(qr/dc:language/ix);
7246 while($langel = shift(@elements) ) {
7247 foreach my $el (@elements) {
7248 $el->delete if(twigelt_detect_duplicate($el,$langel) );
7249 }
7250 }
7251  
7252 @elements = $self->languages;
7253 if(!@elements) {
7254 $self->set_language(text => $defaultlang);
7255 }
7256 return 1;
7257 }
7258  
7259  
7260 =head2 C<fix_links()>
7261  
7262 Checks through the links in the manifest and checks them for anything
7263 they might link to, adding anything missing to the manifest.
7264  
7265 A warning is added for every manifest item missing a href.
7266  
7267 If no <manifest> element exists directly underneath the <package>
7268 root, or <manifest> contains no items, the method logs a warning and
7269 returns undef. Otherwise, it returns 1.
7270  
7271 =cut
7272  
7273 sub fix_links :method {
7274 my $self = shift;
7275 my $subname = ( caller(0) )[3];
7276 croak($subname . "() called as a procedure") unless(ref $self);
7277 debug(2,"DEBUG[",$subname,"]");
7278 $self->twigcheck();
7279  
7280 my $twigroot = $self->{twigroot};
7281  
7282 my $manifest = $twigroot->first_child('manifest');
7283 my @unchecked;
7284  
7285 # The %links hash points a href to one of three values:
7286 # * undef : the link has not been checked at all
7287 # * 0 : the link has been checked and is not reachable
7288 # * 1 : the link has been checked and exists
7289 my %links;
7290 my @newlinks;
7291 my $href;
7292 my $mimetype;
7293  
7294 my %linking_mimetypes = (
7295 'text/html' => 1,
7296 'text/xhtml' => 1,
7297 'text/xml' => 1,
7298 'text/x-oeb1-document' => 1,
7299 'application/atom+xml' => 1,
7300 'application/xhtml+xml' => 1,
7301 'application/xml' => 1
7302 );
7303  
7304 if(!$manifest) {
7305 $self->add_warning(
7306 "fix_links(): no manifest found!"
7307 );
7308 return;
7309 }
7310  
7311 @unchecked = $self->manifest_hrefs;
7312 if(!@unchecked) {
7313 $self->add_warning(
7314 "fix_links(): empty manifest found!"
7315 );
7316 return;
7317 }
7318  
7319 # Initialize %links, so we don't try to add something already in
7320 # the manifest
7321 foreach my $mhref (@unchecked) {
7322 $mhref = uri_unescape($mhref);
7323 $links{$mhref} = undef unless(exists $links{$mhref});
7324 }
7325  
7326 while(@unchecked) {
7327 debug(3,"DEBUG: ",scalar(@unchecked),
7328 " items left to check at start of loop");
7329 $href = shift(@unchecked);
7330 $href = trim($href);
7331 $href = uri_unescape($href);
7332 debug(3,"DEBUG: checking '",$href,"'");
7333 next if(defined $links{$href});
7334  
7335 # Skip mailto: and news: links
7336 if($href =~ m#(mailto|news):#ix) {
7337 debug(1,"DEBUG: mailto link '",$href,"' skipped");
7338 $links{$href} = 0;
7339 next;
7340 }
7341  
7342 # Skip URIs for now
7343 if($href =~ m#^ \w+://#ix) {
7344 debug(1,"DEBUG: URI '",$href,"' skipped");
7345 $links{href} = 0;
7346 next;
7347 }
7348 if(! -f $href) {
7349 $self->add_warning(
7350 "fix_links(): '" . $href . "' not found"
7351 );
7352 $links{$href} = 0;
7353 next;
7354 }
7355  
7356 $mimetype = mimetype($href);
7357  
7358 if(!$linking_mimetypes{$mimetype}) {
7359 debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,
7360 "' -- not checking");
7361 $links{$href} = 1;
7362 next;
7363 }
7364  
7365 debug(1,"DEBUG: finding links in '",$href,"'");
7366 @newlinks = find_links($href);
7367 trim(@newlinks) if(@newlinks);
7368 $links{$href} = 1;
7369 foreach my $newlink (sort @newlinks) {
7370 # Skip mailto: and news: links
7371 if($newlink =~ m#(mailto|news):#ix) {
7372 debug(1,"DEBUG: mailto link '",$href,"' skipped");
7373 next;
7374 }
7375 # Skip URIs for now
7376 elsif($newlink =~ m#^ \w+://#ix) {
7377 debug(1,"DEBUG: URI '",$newlink,"' skipped");
7378 next;
7379 }
7380 elsif(!exists $links{$newlink}) {
7381 debug(2,"DEBUG: adding '",$newlink,"' to the manifest");
7382 push(@unchecked,$newlink);
7383 $self->add_item($newlink);
7384 $links{$newlink} = 1;
7385 }
7386 }
7387 debug(2,"DEBUG: ",scalar(@unchecked),
7388 " items left to check at end of loop");
7389 } # while(@unchecked)
7390 debug(2,"DEBUG[/",$subname,"]");
7391 return 1;
7392 }
7393  
7394 =head2 C<fix_manifest()>
7395  
7396 Finds all <item> elements and moves them underneath <manifest>,
7397 creating <manifest> if necessary.
7398  
7399 Logs a warning but continues if it finds an <item> with a missing id
7400 or href attribute. If both id and href attributes are missing, logs a
7401 warning, skips moving the item entirely (unless it was already
7402 underneath <manifest>, in which case it is moved to preserve its sort
7403 order along all other items under <manifest>), but otherwise
7404 continues.
7405  
7406 =cut
7407  
7408 sub fix_manifest :method {
7409 my $self = shift;
7410 my $subname = ( caller(0) )[3];
7411 croak($subname . "() called as a procedure") unless(ref $self);
7412 debug(2,"DEBUG[",$subname,"]");
7413 $self->twigcheck();
7414  
7415 my $twigroot = $self->{twigroot};
7416  
7417 my $spec = $self->spec || '';
7418 my $manifest = $twigroot->first_descendant('manifest');
7419 my @elements;
7420 my @extras;
7421 my $parent;
7422  
7423 my $href;
7424 my $id;
7425 my $type;
7426  
7427 # If <manifest> doesn't exist, create it
7428 if(! $manifest) {
7429 debug(1,"DEBUG: creating <manifest>");
7430 $manifest = $twigroot->insert_new_elt('last_child','manifest');
7431 }
7432  
7433 # Make sure that the manifest is the first child of the twigroot,
7434 # which should be <package>
7435 $parent = $manifest->parent;
7436 if($parent != $twigroot) {
7437 debug(1,"DEBUG: moving <manifest>");
7438 $manifest->move('first_child',$twigroot);
7439 }
7440  
7441 # Find and merge any other manifests
7442 @extras = $twigroot->descendants('manifest');
7443 shift @extras;
7444 foreach my $extra (@extras) {
7445 my @elements = $extra->children;
7446 foreach my $el (@elements) {
7447 debug(2,"DEBUG: moving <",$el->gi,"> into primary manifest");
7448 $el->move('last_child',$manifest);
7449 }
7450 $extra->delete;
7451 }
7452  
7453 @elements = $twigroot->descendants(qr/^item$/ix);
7454 foreach my $el (@elements) {
7455 $href = $el->att('href');
7456 $id = $el->id;
7457 $type = $el->att('media-type');
7458  
7459 # Convert to OPF2.0 document types if necessary
7460 if($spec eq 'OPF20') {
7461 if($type eq "text/x-oeb1-document") {
7462 $type = "application/xhtml+xml";
7463 $el->set_att('media-type',$type);
7464 }
7465 if($id eq 'ncx') {
7466 $type = 'application/x-dtbncx+xml';
7467 $el->set_att('media-type',$type);
7468 }
7469  
7470 }
7471  
7472 if(!$id) {
7473 if(!$href) {
7474 # No ID, no href, there's something very fishy here,
7475 # so log a warning.
7476 # If it is already underneath <manifest>, move it to
7477 # preserve sort order, but otherwise leave it alone
7478 $self->add_warning(
7479 "fix_manifest(): found item with no id or href"
7480 );
7481 debug(1,"fix_manifest(): found item with no id or href");
7482 if($el->parent == $manifest) {
7483 $el->move('last_child',$manifest);
7484 }
7485 else {
7486 print "DEBUG: skipping item with no id or href\n"
7487 if($debug);
7488 }
7489 next;
7490 } # if(!$href)
7491 # We have a href, but no ID. Log a warning, but move it anyway.
7492 $self->add_warning(
7493 'fix_manifest(): handling item with no ID! '
7494 . sprintf "(href='%s')",$href
7495 );
7496 debug(1,"DEBUG: processing item with no id (href='",$href,"')");
7497 $el->move('last_child',$manifest);
7498 } # if(!$id)
7499 if(!$href) {
7500 # We have an ID, but no href. Log a warning, but move it anyway.
7501 $self->add_warning(
7502 "fix_manifest(): item with id '" . $id . "' has no href!"
7503 );
7504 debug(1,"fix_manifest(): item with id '",$id,"' has no href!");
7505 $el->move('last_child',$manifest);
7506 }
7507 else {
7508 # We have an ID and a href
7509 debug(3,"DEBUG: processing item '",$id,"' (href='",$href,"')");
7510 $el->move('last_child',$manifest);
7511 }
7512 }
7513 return 1;
7514 }
7515  
7516 =head2 C<fix_metastructure_basic()>
7517  
7518 Verifies that <metadata> exists (creating it if necessary), and moves
7519 it to be the first child of <package>. If additional <metadata>
7520 elements exist, their children are moved into the first one found and
7521 then the extras are deleted.
7522  
7523 Used in L</fix_metastructure_oeb12()>, L</fix_packageid()>, and
7524 L</set_primary_author(%args)>.
7525  
7526 =cut
7527  
7528 sub fix_metastructure_basic :method {
7529 my $self = shift;
7530 my $subname = ( caller(0) )[3];
7531 croak($subname . "() called as a procedure") unless(ref $self);
7532 debug(3,"DEBUG[",$subname,"]");
7533 $self->twigcheck();
7534  
7535 my $twigroot = $self->{twigroot};
7536 my $metadata = $twigroot->first_descendant('metadata');
7537  
7538 my @extras = $twigroot->descendants('metadata');
7539 shift @extras;
7540  
7541 if(! $metadata) {
7542 debug(1,"DEBUG: creating <metadata>");
7543 $metadata = $twigroot->insert_new_elt('first_child','metadata');
7544 }
7545  
7546 foreach my $extra (@extras) {
7547 my @elements = $extra->children;
7548 foreach my $el (@elements) {
7549 debug(2,"DEBUG: moving <",$el->gi,"> into primary metadata");
7550 $el->move('last_child',$metadata);
7551 }
7552 $extra->delete;
7553 }
7554 debug(3,"DEBUG: moving <metadata> to be the first child of <package>");
7555 $metadata->move('first_child',$twigroot);
7556  
7557 if($metadata->att('xmlns:calibre')) {
7558 # xmlns:calibre isn't a real namespace; it's just there for
7559 # advertising, so remove it
7560 $metadata->del_att('xmlns:calibre');
7561 }
7562 return 1;
7563 }
7564  
7565  
7566 =head2 C<fix_metastructure_oeb12()>
7567  
7568 Verifies the existence of <metadata>, <dc-metadata>, and <x-metadata>,
7569 creating them as needed, and making sure that <metadata> is a child of
7570 <package>, while <dc-metadata> and <x-metadata> are children of
7571 <metadata>.
7572  
7573 Used in L</fix_oeb12()> and L</fix_mobi()>.
7574  
7575 =cut
7576  
7577 sub fix_metastructure_oeb12 :method {
7578 my $self = shift;
7579 my $subname = ( caller(0) )[3];
7580 croak($subname . "() called as a procedure") unless(ref $self);
7581 debug(3,"DEBUG[",$subname,"]");
7582 $self->twigcheck();
7583  
7584 my $twigroot = $self->{twigroot};
7585  
7586 my $metadata;
7587 my $dcmeta;
7588 my $xmeta;
7589 my $parent;
7590  
7591 # Start by forcing the basic <package><metadata> structure
7592 $self->fix_metastructure_basic;
7593 $metadata = $twigroot->first_child('metadata');
7594  
7595 # If <dc-metadata> doesn't exist, we'll have to create it.
7596 $dcmeta = $twigroot->first_descendant('dc-metadata');
7597 if(! $dcmeta) {
7598 debug(2,"DEBUG: creating <dc-metadata>");
7599 $dcmeta = $metadata->insert_new_elt('first_child','dc-metadata');
7600 }
7601  
7602 # Make sure that $dcmeta is a child of $metadata
7603 $parent = $dcmeta->parent;
7604 if($parent != $metadata) {
7605 debug(2,"DEBUG: moving <dc-metadata>");
7606 $dcmeta->move('first_child',$metadata);
7607 }
7608  
7609 # If <x-metadata> doesn't exist, create it
7610 $xmeta = $metadata->first_descendant('x-metadata');
7611 if(! $xmeta) {
7612 debug(2,"DEBUG: creating <x-metadata>");
7613 $xmeta = $metadata->insert_new_elt('last_child','x-metadata');
7614 }
7615  
7616 # Make sure that x-metadata is a child of metadata
7617 $parent = $xmeta->parent;
7618 if($parent != $metadata) {
7619 debug(2,"DEBUG: moving <x-metadata>");
7620 $xmeta->move('after',$dcmeta);
7621 }
7622 return 1;
7623 }
7624  
7625  
7626 =head2 C<fix_misc()>
7627  
7628 Fixes miscellaneous potential problems in OPF data. Specifically,
7629 this is a shortcut to calling L</delete_meta_filepos()>,
7630 L</fix_packageid()>, L</fix_dates()>, L</fix_languages()>,
7631 L</fix_publisher()>, L</fix_manifest()>, L</fix_spine()>,
7632 L</fix_subjects()>, L</fix_type()>, L</fix_guide()>, and
7633 L</fix_links()>.
7634  
7635 L</fix_creators()> is not run from this, as it carries a risk of taking
7636 a correct name and making it incorrect.
7637  
7638 The objective here is that you can run either C<fix_misc()> and either
7639 L</fix_oeb12()> or L</fix_opf20()> and a perfectly valid OPF file will
7640 result from only two calls.
7641  
7642 =cut
7643  
7644 sub fix_misc :method {
7645 my $self = shift;
7646 my $subname = ( caller(0) )[3];
7647 croak($subname . "() called as a procedure") unless(ref $self);
7648 debug(2,"DEBUG[",$subname,"]");
7649 $self->twigcheck();
7650  
7651 $self->delete_meta_filepos();
7652 $self->fix_packageid();
7653 $self->fix_dates();
7654 $self->fix_languages();
7655 $self->fix_publisher();
7656 $self->fix_manifest();
7657 $self->fix_spine();
7658 $self->fix_subjects();
7659 $self->fix_type();
7660 $self->fix_guide();
7661 $self->fix_links();
7662  
7663 debug(2,"DEBUG[/",$subname,"]");
7664 return 1;
7665 }
7666  
7667  
7668 =head2 C<fix_mobi()>
7669  
7670 Manipulates the twig to fix Mobipocket-specific issues
7671  
7672 =over
7673  
7674 =item * Force the OEB 1.2 structure (although not the namespace, DTD,
7675 or capitalization), so that <dc-metadata> and <x-metadata> are
7676 guaranteed to exist.
7677  
7678 =item * Find and move all Mobi-specific elements to <x-metadata>
7679  
7680 =item * If no <output> element exists, creates one for a utf-8 ebook
7681  
7682 =back
7683  
7684 Note that the forced creation of <output> will cause the OPF file to
7685 become noncompliant with IDPF specifications.
7686  
7687 =cut
7688  
7689 sub fix_mobi :method {
7690 my $self = shift;
7691 my $subname = ( caller(0) )[3];
7692 croak($subname . "() called as a procedure") unless(ref $self);
7693 debug(2,"DEBUG[",$subname,"]");
7694 $self->twigcheck();
7695  
7696 my $twigroot = $self->{twigroot};
7697  
7698 my %mobicontenttypes = (
7699 'text/x-oeb1-document' => 'text/x-oeb1-document',
7700 'application/x-mobipocket-subscription'
7701 => 'application/x-mobipocket-subscription',
7702 'application/x-mobipocket-subscription-feed'
7703 => 'application/x-mobipocket-subscription-feed',
7704 'application/x-mobipocket-subscription-magazine'
7705 => 'application/x-mobipocket-subscription-magazine',
7706 'image/gif' => 'image/gif',
7707 'application/msword' => 'application/msword',
7708 'application/vnd.ms-excel' => 'application/vnd.ms-excel',
7709 'application/vnd.ms-powerpoint' => 'application/vnd.ms-powerpoint',
7710 'text/plain' => 'text/plain',
7711 'text/html' => 'text/html',
7712 'application/vnd.mobipocket-game' => 'application/vnd.mobipocket-game',
7713 'application/vnd.mobipocket-franklin-ua-game'
7714 => 'application/vnd.mobipocket-franklin-ua-game'
7715 );
7716  
7717 my %mobiencodings = (
7718 'Windows-1252' => 'Windows-1252',
7719 'utf-8' => 'utf-8'
7720 );
7721  
7722 my @mobitags = (
7723 'output',
7724 'Adult',
7725 'Demo',
7726 'DefaultLookupIndex',
7727 'DictionaryInLanguage',
7728 'DictionaryOutLanguage',
7729 'DictionaryVeryShortName',
7730 'DatabaseName',
7731 'EmbeddedCover',
7732 'Review',
7733 'SRP',
7734 'Territory'
7735 );
7736  
7737 my $dcmeta;
7738 my $xmeta;
7739 my @elements;
7740 my $output;
7741  
7742  
7743 # Mobipocket currently requires that its custom elements be found
7744 # underneath <x-metadata>. Since the presence of <x-metadata>
7745 # requires that the Dublin Core tags be under <dc-metadata>, we
7746 # have to use at least the OEB1.2 structure (deprecated, but still
7747 # allowed in OPF2.0), though we don't have to convert everything.
7748 $self->fix_metastructure_oeb12();
7749 $dcmeta = $twigroot->first_descendant('dc-metadata');
7750 $xmeta = $twigroot->first_descendant('x-metadata');
7751  
7752 # If <x-metadata> doesn't exist, create it. Even if there are no
7753 # mobi-specific tags, this method will create at least one
7754 # (<output>) which will need it.
7755 if(!$xmeta) {
7756 debug(2,"DEBUG: creating <x-metadata>");
7757 $xmeta = $dcmeta->insert_new_elt('after','x-metadata')
7758 }
7759  
7760 foreach my $tag (@mobitags) {
7761 @elements = $twigroot->descendants($tag);
7762 next unless (@elements);
7763  
7764 # In theory, only one Mobipocket-specific element should ever
7765 # be present in a document. We'll deal with multiples anyway,
7766 # but send a warning.
7767 if(scalar(@elements) > 1) {
7768 $self->add_warning(
7769 'fix_mobi(): Found ' . scalar(@elements) . " '" . $tag .
7770 "' elements, but only one should exist."
7771 );
7772 }
7773  
7774 foreach my $el (@elements) {
7775 $el->move('last_child',$xmeta);
7776 }
7777 }
7778  
7779 $output = $xmeta->first_child('output');
7780 if($output) {
7781 my $encoding = $mobiencodings{$output->att('encoding')};
7782 my $contenttype = $mobicontenttypes{$output->att('content-type')};
7783  
7784 if($contenttype) {
7785 $output->set_att('encoding','utf-8') if(!$encoding);
7786 debug(2,"DEBUG: setting encoding only and returning");
7787 return 1;
7788 }
7789 }
7790 else {
7791 debug(1,"DEBUG: creating <output> under <x-metadata>");
7792 $output = $xmeta->insert_new_elt('last_child','output');
7793 }
7794  
7795  
7796 # At this stage, we definitely have <output> in the right place.
7797 # Set the attributes and return.
7798 $output->set_att('encoding' => 'utf-8',
7799 'content-type' => 'text/x-oeb1-document');
7800 debug(2,"DEBUG[/",$subname,"]");
7801 return 1;
7802 }
7803  
7804  
7805 =head2 C<fix_oeb12()>
7806  
7807 Modifies the OPF data to conform to the OEB 1.2 standard
7808  
7809 Specifically, this involves:
7810  
7811 =over
7812  
7813 =item * adding the OEB 1.2 doctype
7814  
7815 =item * removing OPF 2.0 version and namespace attributes
7816  
7817 =item * setting the OEB 1.2 namespace on <package>
7818  
7819 =item * moving all of the dc-metadata elements underneath an element
7820 with tag <dc-metadata>, which itself is forced to be underneath
7821 <metadata>, which is created if it doesn't exist.
7822  
7823 =item * moving any remaining tags underneath <x-metadata>, again
7824 forced to be under <metadata>
7825  
7826 =item * making the dc-metadata tags conform to the OEB v1.2 capitalization
7827  
7828 =back
7829  
7830 =cut
7831  
7832 sub fix_oeb12 :method {
7833 my $self = shift;
7834 my $subname = ( caller(0) )[3];
7835 croak($subname . "() called as a procedure") unless(ref $self);
7836 debug(2,"DEBUG[",$subname,"]");
7837 $self->twigcheck();
7838  
7839 my $twigroot = $self->{twigroot};
7840 my $metadata;
7841 my $dcmeta;
7842 my $xmeta;
7843 my @elements;
7844  
7845 # Verify and correct locations for <metadata>, <dc-metadata>, and
7846 # <x-metadata>, creating them as needed.
7847 $self->fix_metastructure_oeb12;
7848 $metadata = $twigroot->first_descendant('metadata');
7849 $dcmeta = $metadata->first_descendant('dc-metadata');
7850 $xmeta = $metadata->first_descendant('x-metadata');
7851  
7852 # Clobber metadata attributes 'xmlns:dc' and 'xmlns:opf'
7853 # used only in OPF2.0
7854 $metadata->del_atts('xmlns:dc','xmlns:opf');
7855  
7856 # Assign the DC namespace attribute to dc-metadata for OEB 1.2
7857 $dcmeta->set_att('xmlns:dc',"http://purl.org/dc/elements/1.1/");
7858  
7859 # Set the correct tag name and move it into <dc-metadata> in the
7860 # right order
7861 foreach my $dcel (keys %dcelements12) {
7862 @elements = $twigroot->descendants(qr/^$dcel$/ix);
7863 foreach my $el (@elements) {
7864 debug(3,"DEBUG: processing '",$el->gi,"'");
7865 croak("Found invalid DC element '",$el->gi,"'!")
7866 if(!$dcelements12{lc $el->gi});
7867 $el->set_gi($dcelements12{lc $el->gi});
7868 $el = twigelt_fix_oeb12_atts($el);
7869 $el->move('last_child',$dcmeta);
7870 }
7871 }
7872  
7873 # Handle non-DC metadata, deleting <x-metadata> if it isn't
7874 # needed.
7875 @elements = $metadata->children(qr/^(?!(?s:.*)-metadata)/x);
7876 if(@elements) {
7877 if($debug) {
7878 print {*STDERR} "DEBUG: extra metadata elements found: ";
7879 foreach my $el (@elements) { print {*STDERR} $el->gi," "; }
7880 print {*STDERR} "\n";
7881 }
7882 foreach my $el (@elements) {
7883 $el->move('last_child',$xmeta);
7884 }
7885 }
7886 @elements = $twigroot->children(qr/^meta$/ix);
7887 foreach my $el (@elements) {
7888 $el->set_gi(lc $el->gi);
7889 $el->move('last_child',$xmeta);
7890 }
7891 @elements = $xmeta->children;
7892 $xmeta->delete unless(@elements);
7893  
7894 # Delete Calibre advertisements in dc:Contributor elements
7895 @elements = $twigroot->descendants('dc:Contributor[string() =~ /calibre-ebook.com|calibre.kovidgoyal.net/]');
7896 foreach my $el (@elements) {
7897 $el->delete;
7898 }
7899  
7900 # Fix <manifest> and <spine>
7901 $self->fix_manifest;
7902 $self->fix_spine;
7903  
7904 # Set the OEB 1.2 doctype
7905 $self->{twig}->set_doctype('package',
7906 "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd",
7907 "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN");
7908  
7909 # Clean up <package>
7910 $twigroot->del_att('version');
7911 $twigroot->set_att(
7912 'xmlns' => 'http://openebook.org/namespaces/oeb-package/1.0/');
7913 $self->fix_packageid;
7914  
7915 $self->{spec} = $validspecs{'OEB12'};
7916 debug(2,"DEBUG[/",$subname,"]");
7917 return 1;
7918 }
7919  
7920  
7921 =head2 C<fix_oeb12_dcmetatags()>
7922  
7923 Makes a case-insensitive search for tags matching a known list of DC
7924 metadata elements and corrects the capitalization to the OEB 1.2
7925 standard. Also corrects 'dc:Copyrights' to 'dc:Rights'. See global
7926 variable $dcelements12.
7927  
7928 The L</fix_oeb12()> method does this also, but fix_oeb12_dcmetatags()
7929 is usable separately for the case where you want DC metadata elements
7930 with consistent tag names, but don't want them moved from wherever
7931 they are.
7932  
7933 =cut
7934  
7935 sub fix_oeb12_dcmetatags :method {
7936 my $self = shift;
7937 my $subname = ( caller(0) )[3];
7938 croak($subname . "() called as a procedure") unless(ref $self);
7939 debug(2,"DEBUG[",$subname,"]");
7940 $self->twigcheck();
7941  
7942 my $topelement = $self->{twigroot};
7943  
7944 my @elements;
7945  
7946 foreach my $dcmetatag (keys %dcelements12) {
7947 @elements = $topelement->descendants(qr/^$dcmetatag$/ix);
7948 foreach my $el (@elements) {
7949 $el->set_tag($dcelements12{lc $el->tag})
7950 if($dcelements12{lc $el->tag});
7951 }
7952 }
7953 return 1;
7954 }
7955  
7956  
7957 =head2 C<fix_opf20()>
7958  
7959 Modifies the OPF data to conform to the OPF 2.0 standard
7960  
7961 Specifically, this involves:
7962  
7963 =over
7964  
7965 =item * moving all of the dc-metadata and x-metadata elements directly
7966 underneath <metadata>
7967  
7968 =item * removing the <dc-metadata> and <x-metadata> elements themselves
7969  
7970 =item * lowercasing the dc-metadata tags (and fixing dc:copyrights to
7971 dc:rights)
7972  
7973 =item * setting namespaces on dc-metata OPF attributes
7974  
7975 =item * setting version and xmlns attributes on <package>
7976  
7977 =item * setting xmlns:dc and xmlns:opf on <metadata>
7978  
7979 =back
7980  
7981 =cut
7982  
7983 sub fix_opf20 :method {
7984 my $self = shift;
7985 my $subname = ( caller(0) )[3];
7986 croak($subname . "() called as a procedure") unless(ref $self);
7987 debug(2,"DEBUG[",$subname,"]");
7988 $self->twigcheck();
7989  
7990 # Ensure a sane structure
7991 $self->fix_metastructure_basic();
7992  
7993 # If there is an existing cover image, ensure it hits all standards
7994 my $coverimage = $self->coverimage;
7995 $self->set_cover('href' => $coverimage) if $coverimage;
7996  
7997 my $twigroot = $self->{twigroot};
7998 my $metadata = $twigroot->first_descendant('metadata');
7999 my @elements;
8000  
8001 # If <dc-metadata> exists, make sure that it is directly
8002 # underneath <metadata> so that its children will collapse to the
8003 # correct position, then erase it.
8004 @elements = $twigroot->descendants('dc-metadata');
8005 if(@elements) {
8006 foreach my $dcmeta (@elements) {
8007 debug(1,"DEBUG: moving <dc-metadata>");
8008 $dcmeta->move('first_child',$metadata);
8009 $dcmeta->erase;
8010 }
8011 }
8012  
8013 # If <x-metadata> exists, make sure that it is directly underneath
8014 # <metadata> so that its children will collapse to the correct
8015 # position, then erase it.
8016 @elements = $twigroot->descendants('x-metadata');
8017 if(@elements) {
8018 foreach my $xmeta (@elements) {
8019 debug(1,"DEBUG: moving <x-metadata>");
8020 $xmeta->move('last_child',$metadata);
8021 $xmeta->erase;
8022 }
8023 }
8024  
8025 # Delete any old OEB12 output elements
8026 @elements = $twigroot->descendants('output');
8027 foreach my $el (@elements) {
8028 $el->delete;
8029 }
8030  
8031 # For all DC elements at any location, set the correct tag name
8032 # and attribute namespace and move it directly under <metadata>
8033 foreach my $dcmetatag (keys %dcelements20) {
8034 @elements = $twigroot->descendants(qr/$dcmetatag/ix);
8035 foreach my $el (@elements) {
8036 debug(2,"DEBUG: checking DC element <",$el->gi,">");
8037 $el->set_gi($dcelements20{$dcmetatag});
8038 $el = twigelt_fix_opf20_atts($el);
8039 $el->move('last_child',$metadata);
8040 }
8041 }
8042  
8043 # Find any <meta> elements anywhere in the package and move them
8044 # under <metadata>. Force the tag to lowercase.
8045  
8046 @elements = $twigroot->descendants(qr/^meta$/ix);
8047 foreach my $el (@elements) {
8048 debug(2,'DEBUG: checking meta element <',$el->gi,
8049 ' name="',$el->att('name'),'">');
8050 $el->set_gi(lc $el->gi);
8051 $el->move('last_child',$metadata);
8052 }
8053  
8054 # Delete Calibre advertisements in dc:contributor elements
8055 @elements = $twigroot->descendants('dc:contributor[string() =~ /calibre-ebook.com|calibre.kovidgoyal.net/]');
8056 foreach my $el (@elements) {
8057 $el->delete;
8058 }
8059 # Delete Aspose.Words advertisements in dc:contributor elements
8060 @elements = $twigroot->descendants('dc:contributor[string() =~ /Aspose.Words/]');
8061 foreach my $el (@elements) {
8062 $el->delete;
8063 }
8064  
8065 # Fix the <package> attributes
8066 $twigroot->set_att('version' => '2.0',
8067 'xmlns' => 'http://www.idpf.org/2007/opf');
8068 $self->fix_packageid;
8069  
8070 # Fix the <metadata> attributes
8071 $metadata->set_att('xmlns:dc' => "http://purl.org/dc/elements/1.1/",
8072 'xmlns:opf' => "http://www.idpf.org/2007/opf",
8073 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance");
8074  
8075 # Fix <manifest> and <spine>
8076 $self->fix_manifest;
8077 $self->fix_spine;
8078  
8079 # Clobber the doctype, if present
8080 $self->{twig}->set_doctype(0,0,0,0);
8081  
8082 # Set the specification
8083 $self->{spec} = $validspecs{'OPF20'};
8084  
8085 debug(2,"DEBUG[/",$subname,"]");
8086 return 1;
8087 }
8088  
8089  
8090 =head2 C<fix_opf20_dcmetatags()>
8091  
8092 Makes a case-insensitive search for tags matching a known list of DC
8093 metadata elements and corrects the capitalization to the OPF 2.0
8094 standard. Also corrects 'dc:copyrights' to 'dc:rights'. See package
8095 variable %dcelements20.
8096  
8097 The L</fix_opf20()> method does this also, but
8098 C<fix_opf20_dcmetatags()> is usable separately for the case where you
8099 want DC metadata elements with consistent tag names, but don't want
8100 them moved from wherever they are.
8101  
8102 =cut
8103  
8104 sub fix_opf20_dcmetatags :method {
8105 my $self = shift;
8106 my $subname = ( caller(0) )[3];
8107 croak($subname . "() called as a procedure") unless(ref $self);
8108 debug(2,"DEBUG[",$subname,"]");
8109 $self->twigcheck();
8110  
8111 my $topelement = $self->{twigroot};
8112 my @elements;
8113  
8114 foreach my $dcmetatag (keys %dcelements20) {
8115 @elements = $topelement->descendants(qr/^$dcmetatag$/ix);
8116 foreach my $el (@elements) {
8117 $el->set_tag($dcelements20{lc $el->tag})
8118 if($dcelements20{lc $el->tag});
8119 }
8120 }
8121 return;
8122 }
8123  
8124  
8125 =head2 C<fix_packageid()>
8126  
8127 Checks the <package> element for the attribute 'unique-identifier',
8128 makes sure that it is mapped to a valid dc:identifier subelement, and
8129 if not, searches those subelements for an identifier to assign, or
8130 creates one if nothing can be found.
8131  
8132 Requires that <metadata> exist. Croaks if it doesn't. Run
8133 L</fix_oeb12()> or L</fix_opf20()> before calling this if the input
8134 might be very broken.
8135  
8136 =cut
8137  
8138 sub fix_packageid :method {
8139 my $self = shift;
8140 my $subname = ( caller(0) )[3];
8141 croak($subname . "() called as a procedure") unless(ref $self);
8142 debug(2,"DEBUG[",$subname,"]");
8143 $self->twigcheck();
8144  
8145 # Start by enforcing the basic structure needed
8146 $self->fix_metastructure_basic();
8147 my $twigroot = $self->{twigroot};
8148 my $packageid = $twigroot->att('unique-identifier');
8149  
8150 my $meta = $twigroot->first_child('metadata')
8151 or croak($subname,"(): metadata not found");
8152 my $element;
8153  
8154 if($packageid) {
8155 # Check that the ID maps to a valid identifier
8156 # If not, undefine it
8157 debug(2,"DEBUG: checking existing packageid '",$packageid,"'");
8158  
8159 # The twig ID handling system is unreliable, especially when
8160 # multiple twigs may be existing simultaneously. Use
8161 # XML::Twig->first_elt instead of XML::Twig->elt_id, even
8162 # though it is slower.
8163 #
8164 # As of Twig 3.32, this will cause 'uninitialized value'
8165 # warnings to be spewed for each time no descendants are
8166 # found.
8167 #$element = $self->{twig}->elt_id($packageid);
8168 $element = $self->{twig}->first_elt("*[\@id='$packageid']");
8169  
8170 if($element) {
8171 if(lc($element->tag) ne 'dc:identifier') {
8172 debug(1,"DEBUG: packageid '",$packageid,
8173 "' points to a non-identifier element ('",
8174 $element->tag,"')");
8175 debug(1,"DEBUG: undefining existing packageid '",
8176 $packageid,"'");
8177 undef($packageid);
8178 }
8179 elsif(!$element->text) {
8180 debug(1,"DEBUG: packageid '",$packageid,
8181 "' points to an empty identifier.");
8182 debug(1,"DEBUG: undefining existing packageid '",
8183 $packageid,"'");
8184 undef($packageid);
8185 }
8186 }
8187 else { undef($packageid); };
8188 }
8189  
8190 if(!$packageid) {
8191 # Search known IDs for a unique Package ID
8192 $packageid = $self->search_knownuids;
8193 }
8194  
8195 # If no unique ID found so far, start searching known schemes
8196 if(!$packageid) {
8197 $packageid = $self->search_knownuidschemes;
8198 }
8199  
8200 # And if we still don't have anything, we have to make one from
8201 # scratch using Data::UUID
8202 if(!$packageid) {
8203 debug(1,"DEBUG: creating new UUID");
8204 $element = twigelt_create_uuid();
8205 $element->paste('first_child',$meta);
8206 $packageid = 'UUID';
8207 }
8208  
8209 # At this point, we have a unique ID. Assign it to package
8210 $twigroot->set_att('unique-identifier',$packageid);
8211 debug(2,"[/",$subname,"]");
8212 return 1;
8213 }
8214  
8215  
8216 =head2 C<fix_publisher()>
8217  
8218 Standardizes publisher names in all dc:publisher entities, mapping
8219 known variants of a publisher's name to a canonical form via package
8220 variable %publishermap.
8221  
8222 Publisher entries with no text are deleted.
8223  
8224 =cut
8225  
8226 sub fix_publisher :method {
8227 my $self = shift;
8228 my $subname = ( caller(0) )[3];
8229 croak($subname . "() called as a procedure") unless(ref $self);
8230 debug(2,"DEBUG[",$subname,"]");
8231 $self->twigcheck();
8232  
8233 my @publishers = $self->twigroot->descendants(qr/^dc:publisher$/ix);
8234 foreach my $pub (@publishers) {
8235 debug(3,"Examining publisher entry in element '",$pub->gi,"'");
8236 if(!$pub->text) {
8237 debug(1,'Deleting empty publisher entry');
8238 $pub->delete;
8239 next;
8240 }
8241 elsif( $publishermap{lc $pub->text} &&
8242 ($publishermap{lc $pub->text} ne $pub->text) )
8243 {
8244 debug(1,"DEBUG: Changing publisher from '",$pub->text,"' to '",
8245 $publishermap{lc $pub->text},"'");
8246 $pub->set_text($publishermap{lc $pub->text});
8247 }
8248 }
8249 return 1;
8250 }
8251  
8252  
8253 =head2 C<fix_spine()>
8254  
8255 Fixes problems with the OPF spine, specifically:
8256  
8257 =over
8258  
8259 =item Moves all <itemref> elements underneath <spine>, creating
8260 <spine> if necessary.
8261  
8262 =back
8263  
8264 =cut
8265  
8266 sub fix_spine :method {
8267 my $self = shift;
8268 my $subname = ( caller(0) )[3];
8269 croak($subname . "() called as a procedure") unless(ref $self);
8270 debug(2,"DEBUG[",$subname,"]");
8271 $self->twigcheck();
8272  
8273 my $twigroot = $self->{twigroot};
8274 my $manifest = $twigroot->first_descendant('manifest');
8275 my $spine = $twigroot->first_descendant('spine');
8276 my @elements;
8277 my $parent;
8278  
8279 @elements = $twigroot->descendants(qr/^itemref$/ix);
8280 if(@elements) {
8281 # If <spine> doesn't exist, create it
8282 if(! $spine) {
8283 debug(1,"DEBUG: creating <spine>");
8284 $spine = $twigroot->insert_new_elt('last_child','spine');
8285 }
8286  
8287 # Make sure that the spine is a child of the twigroot,
8288 $parent = $spine->parent;
8289 if($parent != $twigroot) {
8290 debug(1,"DEBUG: moving <spine>");
8291 $spine->move('last_child',$twigroot);
8292 }
8293  
8294 # If an NCX item exists in the manifest, reference it as a
8295 # spine attribute
8296 if($manifest->has_child('@id="ncx"')) {
8297 $spine->set_att('toc' => 'ncx');
8298 }
8299  
8300 foreach my $el (@elements) {
8301 if(!$el->att('idref')) {
8302 # No idref means it is broken.
8303 # Leave it alone, but log a warning
8304 $self->add_warning(
8305 "fix_spine(): <itemref> with no idref -- skipping");
8306 next;
8307 }
8308 debug(3,"DEBUG: processing itemref '",$el->att('idref'),"')");
8309 $el->move('last_child',$spine);
8310 }
8311 }
8312 else {
8313 # No elements, delete spine if it exists
8314 $spine->delete if($spine);
8315 }
8316  
8317 return 1;
8318 }
8319  
8320  
8321 =head2 C<fix_subjects()>
8322  
8323 Deletes empty and duplicate subject elements and normalizes existing
8324 subject text against the known Library of Congress mappings.
8325  
8326 If $self->{erotic} is true, then the book will be treated as a
8327 work of erotic fiction and the subjects will go through preprocessing
8328 against the C<%sexcodes> package variable, normalizing matches and
8329 prepending 'FICTION / Erotica / ' (with a trailing space).
8330  
8331 This method is called as a component of C<fix_misc()>.
8332  
8333 =cut
8334  
8335 sub fix_subjects :method {
8336 my ($self) = @_;
8337 my $subname = ( caller(0) )[3];
8338 croak($subname . "() called as a procedure") unless(ref $self);
8339 debug(2,"DEBUG[",$subname,"]");
8340 $self->twigcheck();
8341  
8342 my $eroticaprefix = 'FICTION / Erotica / ';
8343  
8344 my $twigroot = $self->{twigroot};
8345 my $manifest = $twigroot->first_descendant('manifest');
8346 my $bisac;
8347 my $newsubject;
8348 my $text;
8349  
8350 $self->delete_subject('text' => '');
8351 my @elements = $self->{twigroot}->descendants(qr/^dc:subject$/ix);
8352 my %subjects_seen;
8353 foreach my $el (@elements) {
8354 # Matches to the list are done after stripping leading and
8355 # trailing whitespace, trailing periods, and removing
8356 # whitespace around '--', then converting ' - ' to '--' and
8357 # decoding entities.
8358 $text = trim $el->text;
8359 $text =~ s|\.\z||x;
8360 $text =~ s|\s* -- \s*|--|gx;
8361 $text =~ s|\s* - \s*|--|gx;
8362 $text =~ s|\s*—\s*|--|gx;
8363 # We can't normalize spaces around slashes -- they have
8364 # potentially distinct meanings
8365 #$text =~ s|\s* / \s*|/|gx;
8366 $text = decode_entities($text);
8367  
8368 # Sex code matches are case-sensitive
8369 if($self->{erotic}) {
8370 if($sexcodes{$text}) {
8371 debug(1,"DEBUG: normalizing ${text} to " . $eroticaprefix . $sexcodes{$text});
8372 $el->set_text($eroticaprefix . $sexcodes{$text});
8373 }
8374 }
8375  
8376 # ... but all other normalizations are not.
8377 $text = lc $text;
8378 debug(1,"DEBUG: normalizing subject '",$text,"'");
8379  
8380 # TODO: check for BISACCODE property, convert it to both a
8381 # BISAC descriptor and a LoC subject, then remove it.
8382 if($el->att('BASICCode')) {
8383 $newsubject = $self->add_subject(text => $el->att('BASICCode'));
8384 $el->del_att('BASICCode');
8385 push(@elements,$newsubject);
8386 }
8387 if($bisacsubjects{$text}) {
8388 debug(1,"DEBUG: found BISAC: ",$text);
8389 $bisac = $bisacsubjects{$text};
8390 if($subjects_seen{$bisac}) {
8391 $el->delete;
8392 }
8393 else {
8394 $el->set_text($bisac);
8395 $subjects_seen{$bisac} = 1;
8396 }
8397 }
8398  
8399 # TODO: check for a BISAC code or descriptor in attribute as
8400 # well as text, normalize it to standard descriptor format, as
8401 # well as inserting an additional matching LoC subject if
8402 # present
8403 if($bisactolc{$text}) {
8404 $bisac = $bisactolc{$text};
8405 if(! $subjects_seen{$bisac}) {
8406 $self->add_subject(text => $bisac);
8407 }
8408 }
8409 elsif($lcsubjects{$text}) {
8410 $text = $lcsubjects{$text};
8411 $el->set_text($text);
8412 }
8413  
8414 if($subjects_seen{$text}) {
8415 $el->delete;
8416 }
8417 else {
8418 $subjects_seen{$text} = 1;
8419 }
8420 }
8421 return;
8422 }
8423  
8424  
8425 =head2 C<fix_type()>
8426  
8427 Normalizes <dc:type> elements against a limited list based on book types listed in Wikipedia.
8428  
8429 =cut
8430  
8431 sub fix_type :method {
8432 my ($self) = @_;
8433 my $subname = ( caller(0) )[3];
8434 croak($subname . "() called as a procedure") unless(ref $self);
8435 debug(2,"DEBUG[",$subname,"]");
8436 $self->twigcheck();
8437  
8438 my $twigroot = $self->{twigroot};
8439 my $manifest = $twigroot->first_descendant('manifest');
8440 my $text;
8441 my $type;
8442  
8443 my @elements = $self->{twigroot}->descendants(qr/^dc:type$/ix);
8444 foreach my $el (@elements) {
8445 # Matches to the list are done after stripping leading and
8446 # trailing whitespace, trailing periods, and removing
8447 # whitespace around '--' and '/'
8448 $text = lc trim $el->text;
8449 $text =~ s|\.\z||x;
8450 debug(2,"DEBUG: normalizing type '",$text,"'");
8451  
8452 if($booktypes{$text}) {
8453 $type = $booktypes{$text};
8454 $el->set_text($type);
8455 }
8456 else {
8457 debug(1,"WARNING: unknown book type '",$text,"'");
8458 }
8459 }
8460 return;
8461 }
8462  
8463  
8464 =head2 C<gen_epub(%args)>
8465  
8466 Creates a .epub format e-book. This will create (or overwrite) the
8467 files 'mimetype' and 'META-INF/container.xml' in the current
8468 directory, creating the subdirectory META-INF as needed.
8469  
8470 A NCX file will also be created if missing.
8471  
8472 =head3 Arguments
8473  
8474 This method can take two optional named arguments.
8475  
8476 =over
8477  
8478 =item C<filename>
8479  
8480 The filename of the .epub output file. If not specified, takes the
8481 base name of the opf file and adds a .epub extension.
8482  
8483 =item C<dir>
8484  
8485 The directory to output the .epub file. If not specified, uses the
8486 current working directory. If a specified directory does not exist,
8487 it will be created, or the method will croak.
8488  
8489 =back
8490  
8491 =head3 Example
8492  
8493 gen_epub(filename => 'mybook.epub',
8494 dir => '../epub_books');
8495  
8496 =cut
8497  
8498 sub gen_epub :method {
8499 my ($self,%args) = @_;
8500 my $subname = ( caller(0) )[3];
8501 croak($subname . "() called as a procedure") unless(ref $self);
8502 debug(2,"DEBUG[",$subname,"]");
8503  
8504 my %valid_args = (
8505 'filename' => 1,
8506 'dir' => 1,
8507 );
8508 foreach my $arg (keys %args) {
8509 croak($subname,"(): invalid argument '",$arg,"'")
8510 if(!$valid_args{$arg});
8511 }
8512  
8513 my $filename = $args{filename};
8514 my $dir = $args{dir};
8515 my $zip = Archive::Zip->new();
8516 my $member;
8517 my $cwd = usedir($self->{topdir});
8518  
8519 $self->gen_epub_files();
8520 if(! $self->{opffile} ) {
8521 $self->add_error(
8522 "Cannot create epub without an OPF (did you forget to init?)");
8523 debug(1,"Cannot create epub without an OPF");
8524 return;
8525 }
8526 if(! -f $self->opfpath) {
8527 $self->add_error(
8528 sprintf("OPF '%s' does not exist (did you forget to save?)",
8529 $self->opfpath)
8530 );
8531 debug(1,"OPF '",$self->opfpath,"' does not exist");
8532 return;
8533 }
8534  
8535 debug(3,"DEBUG: adding core metadata to zip archive");
8536 $member = $zip->addFile('mimetype');
8537 $member->desiredCompressionMethod(COMPRESSION_STORED);
8538  
8539 $member = $zip->addFile('META-INF/container.xml');
8540 $member->desiredCompressionLevel(9);
8541  
8542 $member = $zip->addFile($self->{opfsubdir} . '/' . $self->{opffile});
8543 $member->desiredCompressionLevel(9);
8544  
8545 debug(3,"DEBUG: adding manifest files to zip archive");
8546 foreach my $file ($self->manifest_hrefs()) {
8547 $file = uri_unescape($file);
8548 if(-f $self->{opfsubdir} . '/' . $file) {
8549 $member = $zip->addFile($self->{opfsubdir} . '/' . $file);
8550 $member->desiredCompressionLevel(9);
8551 }
8552 else { print STDERR "WARNING: ",$self->{opfsubdir} . '/' . $file," not found, skipping.\n"; }
8553 }
8554  
8555 if(! $filename) {
8556 $filename = basename($self->{topdir}) . '.epub';
8557 }
8558  
8559 if($dir) {
8560 unless(-d $dir) {
8561 mkpath($dir)
8562 or croak("Unable to create working directory '",$dir,"'!");
8563 }
8564 $filename = "$dir/$filename";
8565 }
8566  
8567 unless ( $zip->writeToFileNamed($filename) == AZ_OK ) {
8568 $self->add_error(
8569 sprintf("Failed to create epub as '%s'",$filename));
8570 debug(1,"Failed to create epub as '",$filename,"'");
8571 return;
8572 }
8573  
8574 usedir($cwd);
8575 return 1;
8576 }
8577  
8578  
8579 =head2 C<gen_epub_files()>
8580  
8581 Generates the C<mimetype> and C<META-INF/container.xml> files expected
8582 by a .epub container, but does not actually generate the .epub file
8583 itself. This will be called automatically by C<gen_epub>.
8584  
8585 The OPF will be normalized to the OPF 2.0 format.
8586  
8587 If no NCX element exists, it will also be created.
8588  
8589 =cut
8590  
8591 sub gen_epub_files :method {
8592 my $self = shift;
8593 my $subname = ( caller(0) )[3];
8594 croak($subname . "() called as a procedure") unless(ref $self);
8595 debug(2,"DEBUG[",$subname,"]");
8596  
8597 my $manifest = $self->{twigroot}->first_descendant('manifest');
8598  
8599 $self->fix_opf20();
8600 if( ! $manifest->first_child('item[@id="ncx"]') ) {
8601 $self->gen_ncx();
8602 }
8603 $self->save();
8604  
8605 # These two functions must happen from the top-level directory, not the OPF directory
8606 if($self->{opfsubdir} ne '.') {
8607 debug(3,"DEBUG: switching to ",$self->{topdir}," to generate EPUB metadata");
8608 my $cwd = usedir($self->{topdir});
8609 create_epub_mimetype();
8610 create_epub_container($self->{opfsubdir} . '/' . $self->{opffile});
8611 usedir($cwd);
8612 }
8613 else {
8614 create_epub_mimetype();
8615 create_epub_container($self->{opffile});
8616 }
8617  
8618 return 1;
8619 }
8620  
8621  
8622 =head2 C<gen_ncx($filename)>
8623  
8624 Creates a NCX-format table of contents from the package
8625 unique-identifier, the dc:title, dc:creator, and spine elements, and
8626 then add the NCX entry to the manifest if it is not already
8627 referenced.
8628  
8629 Adds an error and fails if any of those cannot be found. The first
8630 available dc:title is taken, but will prioritize dc:creator elements
8631 with opf:role="aut" over those with no role attribute (see
8632 twigelt_is_author() for details).
8633  
8634 WARNING: This method REQUIRES that the e-book be in OPF 2.0 format to
8635 function correctly. Call fix_opf20() before calling gen_ncx().
8636 gen_ncx() will log an error and fail if $self{spec} is not set to
8637 OPF20.
8638  
8639 =head3 Arguments
8640  
8641 =over
8642  
8643 =item $filename : The filename to save to. If not specified, will use
8644 'toc.ncx'.
8645  
8646 =back
8647  
8648 This method will overwrite any existing file.
8649  
8650 Returns a twig containing the NCX XML, or undef on failure.
8651  
8652 =cut
8653  
8654 sub gen_ncx :method {
8655 my ($self,$filename) = @_;
8656 my $subname = ( caller(0) )[3];
8657 croak($subname . "() called as a procedure") unless(ref $self);
8658 debug(2,"DEBUG[",$subname,"]");
8659 $self->twigcheck;
8660  
8661 $filename = 'toc.ncx' if(!$filename);
8662  
8663 my $cwd = usedir($self->opfdir);
8664 my $twigroot = $self->{twigroot};
8665 my $identifier = $self->identifier;
8666 my $element; # Generic element container
8667 my $parent; # Generic parent element container
8668 my $ncx; # NCX twig
8669 my $ncxroot; # NCX twig root <ncx>
8670 my $ncxitem; # manifest item pointing to the NCX document
8671 my $navmap; # NCX element <navMap>
8672 my $navpoint; # NCX element <navPoint>
8673 my %navpointorder; # Hash mapping playOrder to id
8674 my $navpointindex = 1; # playOrder number starting at 1
8675 my $title; # E-book title
8676 my $author; # E-book primary author
8677 my @spinelist; # List of hashrefs containing spine data
8678 my $manifest; # OPF manifest element
8679 my $spine; # OPF spine element
8680  
8681 if($self->{spec} ne 'OPF20') {
8682 $self->add_error(
8683 $subname . "(): specification is currently set to '"
8684 . $self->{spec} . "' -- need 'OPF20'"
8685 );
8686 debug(1,"DEBUG: gen_ncx() FAILED: wrong specification ('",
8687 $self->{spec},"')!");
8688 return;
8689 }
8690  
8691 if(!$identifier) {
8692 $self->add_error( $subname . "(): no unique-identifier found" );
8693 debug(1,"DEBUG: gen_ncx() FAILED: no unique-identifier!");
8694 return;
8695 }
8696  
8697 # Get the title
8698 $title = $self->title();
8699 if(!$title) {
8700 $self->add_error( $subname . "(): no title found" );
8701 debug(1,"DEBUG: gen_ncx() FAILED: no title!");
8702 return;
8703 }
8704  
8705 # Get the author
8706 $author = $self->primary_author();
8707 if(!$author) {
8708 $self->add_error( $subname . "(): no title found" );
8709 debug(1,"DEBUG: gen_ncx() FAILED: no title!");
8710 return;
8711 }
8712  
8713 # Get the spine list
8714 @spinelist = $self->spine();
8715 if(!@spinelist) {
8716 $self->add_error( $subname . "(): no spine found" );
8717 debug(1,"DEBUG: gen_ncx() FAILED: no spine!");
8718 return;
8719 }
8720  
8721 # Make sure the manifest element exists
8722 # (This should in theory never fail, since it is also checked by
8723 # spine() above)
8724 $manifest = $twigroot->first_descendant('manifest');
8725 if(!$manifest) {
8726 $self->add_error( $subname . "(): no manifest found" );
8727 debug(1,"DEBUG: gen_ncx() FAILED: no manifest!");
8728 return;
8729 }
8730  
8731 $ncx = XML::Twig->new(
8732 output_encoding => 'utf-8',
8733 pretty_print => 'record'
8734 );
8735  
8736 # <ncx>
8737 $element = XML::Twig::Elt->new('ncx');
8738 $element->set_att('xmlns' => 'http://www.daisy.org/z3986/2005/ncx/');
8739 $element->set_att('version' => '2005-1');
8740 $ncx->set_root($element);
8741 $ncxroot = $ncx->root;
8742  
8743 # <head>
8744 $parent = $ncxroot->insert_new_elt('first_child','head');
8745 $element = $parent->insert_new_elt('last_child','meta');
8746 $element->set_att(
8747 'name' => 'dtb:uid',
8748 'content' => $identifier
8749 );
8750  
8751 $element = $parent->insert_new_elt('last_child','meta');
8752 $element->set_att(
8753 'name' => 'dtb:depth',
8754 'content' => '1'
8755 );
8756 $element = $parent->insert_new_elt('last_child','meta');
8757 $element->set_att(
8758 'name' => 'dtb:totalPageCount',
8759 'content' => '0'
8760 );
8761  
8762 $element = $parent->insert_new_elt('last_child','meta');
8763 $element->set_att(
8764 'name' => 'dtb:maxPageNumber',
8765 'content' => '0'
8766 );
8767  
8768 # <docTitle>
8769 $parent = $parent->insert_new_elt('after','docTitle');
8770 $element = $parent->insert_new_elt('first_child','text');
8771 $element->set_text($title);
8772  
8773 # <navMap>
8774 $navmap = $parent->insert_new_elt('after','navMap');
8775  
8776 foreach my $spineitem (@spinelist) {
8777 # <navPoint>
8778 $navpoint = $navmap->insert_new_elt('last_child','navPoint');
8779 $navpoint->set_att('id' => $spineitem->{'id'},
8780 'playOrder' => $navpointindex);
8781 $navpointindex++;
8782  
8783 # <navLabel>
8784 $parent = $navpoint->insert_new_elt('last_child','navLabel');
8785 $element = $parent->insert_new_elt('last_child','text');
8786 $element->set_text($spineitem->{'id'});
8787  
8788 # <content>
8789 $element = $navpoint->insert_new_elt('last_child','content');
8790 $element->set_att('src' => $spineitem->{'href'});
8791 }
8792  
8793 # Backup existing file
8794 if(-e $filename) {
8795 rename($filename,"$filename.backup")
8796 or croak($subname,"(): could not backup ",$filename,"!");
8797 }
8798  
8799 # Twig handles utf-8 on its own. Setting binmode :utf8 here will
8800 # cause double-conversion.
8801 open(my $fh_ncx,'>',$filename)
8802 or croak($subname,"(): failed to open '",$filename,"' for writing!");
8803 $ncx->print(\*$fh_ncx);
8804 close($fh_ncx)
8805 or croak($subname,"(): failed to close '",$filename,"'!");
8806  
8807 # Search for existing NCX entries and modify the first one found,
8808 # creating a new one if there are no matches.
8809 $ncxitem = $manifest->first_child('item[@id="ncx"]');
8810 $ncxitem = $manifest->first_child("item[\@href='$filename']")
8811 if(!$ncxitem);
8812 $ncxitem = $manifest->first_child('item[@media-type="application/x-dtbncx+xml"]')
8813 if(!$ncxitem);
8814 $ncxitem = $manifest->insert_new_elt('first_child','item')
8815 if(!$ncxitem);
8816  
8817 $ncxitem->set_att(
8818 'id' => 'ncx',
8819 'href' => $filename,
8820 'media-type' => 'application/x-dtbncx+xml'
8821 );
8822  
8823 # Move the NCX item to the top of the manifest
8824 $ncxitem->move('first_child',$manifest);
8825  
8826 # Ensure that the spine references the NCX
8827 $spine = $twigroot->first_descendant('spine');
8828 $spine->set_att('toc' => 'ncx');
8829  
8830 usedir($cwd);
8831 return $ncx;
8832 }
8833  
8834  
8835 =head2 C<save()>
8836  
8837 Saves the OPF file to disk. Existing files are backed up to
8838 filename.backup.
8839  
8840 =cut
8841  
8842 sub save :method {
8843 my $self = shift;
8844 my $subname = ( caller(0) )[3];
8845 croak($subname . "() called as a procedure") unless(ref $self);
8846 debug(2,"DEBUG[",$subname,"]");
8847  
8848 croak($subname,"(): no opffile specified (did you forget to init?)")
8849 if(!$self->{opffile});
8850  
8851 my $fh_opf;
8852 my $cwd = usedir($self->opfdir);
8853 my $filename = $self->{opffile};
8854  
8855 # Backup existing file
8856 if(-e $filename) {
8857 rename($filename,"$filename.backup")
8858 or croak($subname,"(): could not backup ",$filename,"!");
8859 }
8860  
8861 # Update the last-modified timestamp as the very last thing before
8862 # saving if the output changed at all
8863 if($self->{twig}->sprint ne $self->{twig_unmodified}->sprint) {
8864 $self->set_timestamp();
8865 }
8866  
8867 if(!open($fh_opf,">:encoding(UTF-8)",$self->{opffile})) {
8868 add_error(sprintf("Could not open '%s' to save to!",$self->{opffile}));
8869 return;
8870 }
8871 $self->{twig}->print(\*$fh_opf);
8872  
8873 if(!close($fh_opf)) {
8874 add_error(sprintf("Failure while closing '%s'!",$self->{opffile}));
8875 return;
8876 }
8877  
8878 usedir($cwd);
8879 return 1;
8880 }
8881  
8882  
8883 =head2 C<set_adult($bool)>
8884  
8885 Sets the Mobipocket-specific <Adult> element, creating or deleting it
8886 as necessary. If C<$bool> is true, the text is set to 'yes'. If it
8887 is defined but false, any existing elements are deleted. If it is
8888 undefined, the method immediately returns.
8889  
8890 If a new element has to be created, L</fix_metastructure_oeb12> is
8891 called to ensure that <x-metadata> exists and the element is created
8892 under <x-metadata>, as Mobipocket elements are not recognized by
8893 Mobipocket's software when placed directly under <metadata>
8894  
8895 =cut
8896  
8897 sub set_adult :method {
8898 my $self = shift;
8899 my $adult = shift;
8900 my $subname = ( caller(0) )[3];
8901 croak($subname . "() called as a procedure") unless(ref $self);
8902 debug(2,"DEBUG[",$subname,"]");
8903 $self->twigcheck;
8904  
8905 return 1 unless(defined $adult);
8906  
8907 my $xmeta;
8908 my $element;
8909 my @elements;
8910  
8911 if($adult) {
8912 $element = $self->{twigroot}->first_descendant(qr/^adult$/ix);
8913 unless($element) {
8914 $self->fix_metastructure_oeb12();
8915 $xmeta = $self->{twigroot}->first_descendant('x-metadata');
8916 $element = $xmeta->insert_new_elt('last_child','Adult');
8917 }
8918 $element->set_text('yes');
8919 }
8920 else {
8921 @elements = $self->{twigroot}->descendants(qr/^adult$/ix);
8922 foreach my $el (@elements) {
8923 debug(2,"DEBUG: deleting <Adult> flag");
8924 $el->delete;
8925 }
8926 }
8927 return 1;
8928 }
8929  
8930  
8931 =head2 C<set_cover(%args)>
8932  
8933 Sets a cover image
8934  
8935 In OPF 2.0, this is done by setting both a <meta name="cover"> element
8936 and a guide <reference type="other.ms-coverimage-standard"> element
8937 (though some readers will also extract the first image found in the
8938 HTML of the <reference type="cover"> element, which this method will
8939 not handle).
8940  
8941 In OEB 1.2, this is done by setting the <EmbeddedCover> tag.
8942  
8943 If the filename is not currently listed as an item in the manifest, it
8944 is added.
8945  
8946 =head3 Arguments
8947  
8948 =over
8949  
8950 =item C<href>
8951  
8952 The filename of the image file to use. This is mandatory.
8953  
8954 =item C<id>
8955  
8956 The id attribute to assign to its item element
8957  
8958 =item C<spec>
8959  
8960 The specification to use, either OEB12 or OPF20. If this is left
8961 undefined, the current spec state will be checked, and if that is
8962 undefined, it will default to OPF20.
8963  
8964 =back
8965  
8966 =cut
8967  
8968 sub set_cover :method {
8969 my ($self,%args) = @_;
8970 my $subname = ( caller(0) )[3];
8971 croak($subname . "() called as a procedure") unless(ref $self);
8972 debug(2,"DEBUG[",$subname,"]");
8973 my %valid_args = (
8974 'href' => 1,
8975 'id' => 1,
8976 'spec' => 1,
8977 );
8978 foreach my $arg (keys %args) {
8979 croak($subname,"(): invalid argument '",$arg,"'")
8980 if(!$valid_args{$arg});
8981 }
8982  
8983 my $href = $args{href};
8984 my $newid = $args{id};
8985 my $spec = $args{spec};
8986 my $id;
8987 my $mimetype;
8988 my $manifest;
8989 my $guide;
8990 my $dcmeta;
8991 my $element;
8992  
8993 if(! $href) {
8994 $self->add_error($subname,"(): no href specified");
8995 return;
8996 }
8997 $mimetype = mimetype($href);
8998 if($mimetype !~ m#^image/#ix) {
8999 $self->add_warning(
9000 $subname,"(): ",$href,
9001 " does not appear to be an image (detected: ",$mimetype,")"
9002 );
9003 }
9004  
9005 if(! $spec) {
9006 $spec = $self->spec || 'OPF20';
9007 }
9008  
9009 # Ensure that there is a matching manifest item
9010 $manifest = $self->{twigroot}->first_child('manifest');
9011 $element = $manifest->first_child('item[@href="' . $href . '"]');
9012 if($element) {
9013 if($newid) {
9014 $element->set_id($newid);
9015 }
9016 }
9017 else {
9018 $element = $manifest->insert_new_elt('first_child','item');
9019 if ($newid) {
9020 $element->set_id($newid);
9021 }
9022 elsif ($self->{twig}->first_elt('*[@id="coverimage"]')) {
9023 $element->set_id(basename($href));
9024 }
9025 else {
9026 $element->set_id('coverimage');
9027 }
9028 $element->set_att('href',$href);
9029 $element->set_att('media-type',$mimetype);
9030 }
9031 $id = $element->id;
9032  
9033 if ($spec eq 'OPF20') {
9034 $self->fix_metastructure_basic;
9035 $self->fix_guide;
9036 $guide = $self->{twigroot}->first_child('guide');
9037 $element = $guide->first_child('reference[@type="other.ms-coverimage-standard"]');
9038 if ($element) {
9039 $element->set_att('href',$href);
9040 $element->set_att('title','Cover');
9041 }
9042 else {
9043 $element = $guide->insert_new_elt('last_child','reference');
9044 $element->set_att('href',$href);
9045 $element->set_att('title','Cover');
9046 $element->set_att('type','other.ms-coverimage-standard');
9047 }
9048 $self->set_meta('name' => 'cover',
9049 'content' => $href);
9050  
9051 # Now that the OPF 2.0 elements are set, we can delete the
9052 # OEB12 EmbeddedCover element
9053 $element = $self->{twigroot}->first_descendant('EmbeddedCover');
9054 if ($element) {
9055 debug(1,"deleting cover");
9056 $element->delete;
9057 }
9058 }
9059 elsif ($spec eq 'OEB12') {
9060 $self->fix_metastructure_oeb12;
9061 $dcmeta = $self->{twigroot}->first_child('dc-metadata');
9062 $element = $dcmeta->first_child('EmbeddedCover');
9063 if ($element) {
9064 $element->set_text($href);
9065 }
9066 else {
9067 $element = $dcmeta->insert_new_elt('last_child','EmbeddedCover');
9068 $element->set_text($href);
9069 }
9070 }
9071 else {
9072 self->add_error($subname,"(): unknown specification type: '",$spec,"'");
9073 }
9074 return;
9075 }
9076  
9077  
9078 =head2 C<set_date(%args)>
9079  
9080 Sets the date metadata for a given event. If more than one dc:date or
9081 dc:Date element is present with the specified event attribute, sets
9082 the first. If no dc:date element is present with the specified event
9083 attribute, a new element is created.
9084  
9085 If a <dc-metadata> element exists underneath <metadata>, the date
9086 element will be created underneath the <dc-metadata> in OEB 1.2
9087 format, otherwise the title element is created underneath <metadata>
9088 in OPF 2.0 format.
9089  
9090 Returns 1 on success, logs an error and returns undef if no text or
9091 event was specified.
9092  
9093 =head3 Arguments
9094  
9095 =over
9096  
9097 =item C<text>
9098  
9099 This specifies the description to use as the text of the element. If
9100 not specified, the method sets an error and returns undef.
9101  
9102 =item C<event>
9103  
9104 This optionally specifies the event attribute for the date. This
9105 attribute is not valid in OPF 3.0 (which only allows publication date
9106 in this element) and should no longer be used.
9107  
9108 =item C<id> (optional)
9109  
9110 This specifies the ID to set on the element. If set and the ID is
9111 already in use, a warning is logged and the ID is removed from the
9112 other location and assigned to the element.
9113  
9114 =back
9115  
9116 =cut
9117  
9118 sub set_date :method {
9119 my ($self,%args) = @_;
9120 my $subname = ( caller(0) )[3];
9121 croak($subname . "() called as a procedure") unless(ref $self);
9122 debug(2,"DEBUG[",$subname,"]");
9123 my %valid_args = (
9124 'text' => 1,
9125 'event' => 1,
9126 'id' => 1,
9127 );
9128 foreach my $arg (keys %args) {
9129 croak($subname,"(): invalid argument '",$arg,"'")
9130 if (!$valid_args{$arg});
9131 }
9132  
9133 my $text = $args{text};
9134 my $event = $args{event};
9135 my $newid = $args{id};
9136 unless($text) {
9137 $self->add_error($subname,"(): no text specified");
9138 return;
9139 }
9140  
9141 my $meta = $self->{twigroot}->first_child('metadata');
9142 my $dcmeta = $meta->first_child('dc-metadata');
9143 my $idelem;
9144 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
9145  
9146 $self->fix_metastructure_basic();
9147  
9148 my $element;
9149 if ($event) {
9150 $element = $self->{twigroot}->first_descendant(
9151 "dc:date[\@opf:event=~/$event/ix or \@event=~/$event/ix]");
9152 $element = $self->{twigroot}->first_descendant(
9153 "dc:Date[\@opf:event=~/$event/ix or \@event=~/$event/ix]")
9154 unless($element);
9155 }
9156 else {
9157 $element = $self->{twigroot}->first_descendant("dc:date");
9158 $element = $self->{twigroot}->first_descendant("dc:Date")
9159 unless($element);
9160 }
9161  
9162 if ($element) {
9163 $element->set_text($text);
9164 }
9165 elsif ($dcmeta) {
9166 $element = $dcmeta->insert_new_elt('last_child','dc:Date');
9167 $element->set_text($text);
9168 if ($event) {
9169 $element->set_att('event',$event);
9170 }
9171 }
9172 else {
9173 $element = $meta->insert_new_elt('last_child','dc:date');
9174 $element->set_text($text);
9175 if ($event) {
9176 $element->set_att('opf:event',$event);
9177 }
9178 }
9179  
9180 if ($idelem && $idelem->cmp($element) ) {
9181 $self->add_warning(
9182 $subname,"(): reassigning id '",$newid,
9183 "' from a '",$idelem->gi,"' element!"
9184 );
9185 $idelem->del_att('id');
9186 }
9187 $element->set_att('id' => $newid) if($newid);
9188 return 1;
9189 }
9190  
9191  
9192 =head2 set_description(%args)
9193  
9194 Sets the text and optionally ID of the first dc:description element
9195 found (case-insensitive). Creates the element if one did not exist.
9196 If a <dc-metadata> element exists underneath <metadata>, the
9197 description element will be created underneath the <dc-metadata> in
9198 OEB 1.2 format, otherwise the title element is created underneath
9199 <metadata> in OPF 2.0 format.
9200  
9201 Returns 1 on success, returns undef if no publisher was specified.
9202  
9203 =head3 Arguments
9204  
9205 C<set_description()> takes one required and one optional named argument
9206  
9207 =over
9208  
9209 =item C<text>
9210  
9211 This specifies the description to use as the text of the element. If
9212 not specified, the method returns undef.
9213  
9214 =item C<id> (optional)
9215  
9216 This specifies the ID to set on the element. If set and the ID is
9217 already in use, a warning is logged and the ID is removed from the
9218 other location and assigned to the element.
9219  
9220 =back
9221  
9222 =head3 Example
9223  
9224 $retval = $ebook->set_description('text' => 'A really good book',
9225 'id' => 'mydescid');
9226  
9227 =cut
9228  
9229 sub set_description :method {
9230 my ($self,%args) = @_;
9231 my $subname = ( caller(0) )[3];
9232 croak($subname . "() called as a procedure") unless(ref $self);
9233 debug(2,"DEBUG[",$subname,"]");
9234 my %valid_args = (
9235 'text' => 1,
9236 'id' => 1,
9237 );
9238 foreach my $arg (keys %args) {
9239 croak($subname,"(): invalid argument '",$arg,"'")
9240 if (!$valid_args{$arg});
9241 }
9242  
9243 my $text = $args{text};
9244 unless($text) {
9245 $self->add_error($subname,"(): no text specified");
9246 return;
9247 }
9248  
9249 $self->fix_metastructure_basic();
9250 my $element = $self->{twigroot}->first_descendant(qr/^dc:description$/ix);
9251 my $meta = $self->{twigroot}->first_child('metadata');
9252 my $dcmeta = $meta->first_child('dc-metadata');
9253  
9254 my $gi = ($dcmeta) ? 'dc:Description' : 'dc:description';
9255 $self->set_metadata(gi => $gi,
9256 text => $text,
9257 id => $args{id});
9258  
9259 return 1;
9260 }
9261  
9262  
9263 =head2 C<set_erotic($bool)>
9264  
9265 If C<$bool> is true, C<$self->{erotic}> is set to 1, otherwise this is
9266 set to 0.
9267  
9268 This will enable or disable special handling for erotic books, most
9269 notably in subject normalization.
9270  
9271 This is not related in any way to C<set_adult> which is a
9272 Mobipocket-specific flag.
9273  
9274 Returns 1 if no argument is given, 0 otherwise.
9275  
9276 =cut
9277  
9278 sub set_erotic :method {
9279 my ($self,$flag) = @_;
9280 my $subname = ( caller(0) )[3];
9281 croak($subname . "() called as a procedure") unless(ref $self);
9282 debug(2,"DEBUG[",$subname,"]");
9283  
9284 return 1 unless(defined $flag);
9285  
9286 if($flag) {
9287 $self->{erotic} = 1;
9288 }
9289 else {
9290 $self->{erotic} = 0;
9291 }
9292 return 0;
9293 }
9294  
9295  
9296 =head2 C<set_language(%args)>
9297  
9298 Sets the text and optionally the ID of the first dc:language element
9299 found (case-insensitive). Creates the element if one did not exist.
9300 If a <dc-metadata> element exists underneath <metadata>, the language
9301 element will be created underneath the <dc-metadata> in OEB 1.2
9302 format, otherwise the title element is created underneath <metadata>
9303 in OPF 2.0 format.
9304  
9305 Returns 1 on success, returns undef if no text was specified.
9306  
9307 =head3 Arguments
9308  
9309 =over
9310  
9311 =item C<text>
9312  
9313 This specifies the language set as the text of the element. If not
9314 specified, the method sets an error and returns undef. This should be
9315 an IANA language code, and it will be lowercased before it is set.
9316  
9317 =item C<id> (optional)
9318  
9319 This specifies the ID to set on the element. If set and the ID is
9320 already in use, a warning is logged and the ID is removed from the
9321 other location and assigned to the element.
9322  
9323 =back
9324  
9325 =head3 Example
9326  
9327 $retval = $ebook->set_language('text' => 'en-us',
9328 'id' => 'langid');
9329  
9330 =cut
9331  
9332 sub set_language :method {
9333 my ($self,%args) = @_;
9334 my $subname = ( caller(0) )[3];
9335 croak($subname . "() called as a procedure") unless(ref $self);
9336 debug(2,"DEBUG[",$subname,"]");
9337 my %valid_args = (
9338 'text' => 1,
9339 'id' => 1,
9340 );
9341 foreach my $arg (keys %args) {
9342 croak($subname,"(): invalid argument '",$arg,"'")
9343 if (!$valid_args{$arg});
9344 }
9345  
9346 my $text = lc($args{text});
9347 unless($text) {
9348 $self->add_error($subname,"(): no text specified");
9349 return;
9350 }
9351  
9352 $self->fix_metastructure_basic();
9353 my $element = $self->{twigroot}->first_descendant(qr/^dc:language$/ix);
9354 my $meta = $self->{twigroot}->first_child('metadata');
9355 my $dcmeta = $meta->first_child('dc-metadata');
9356  
9357 my $gi = ($dcmeta) ? 'dc:Language' : 'dc:language';
9358 $self->set_metadata(gi => $gi,
9359 text => $text,
9360 id => $args{id});
9361 return 1;
9362 }
9363  
9364  
9365 =head2 set_meta(%args)
9366  
9367 Sets a <meta> element in the <metadata> element area.
9368  
9369 =head3 Arguments
9370  
9371 =over
9372  
9373 =item C<name>
9374  
9375 The name attribute to use when finding or creating OPF 2.0 <meta>
9376 elements. Either this or the property attribute (below) must be
9377 specified, but specifying both is an error.
9378  
9379 =item C<content>
9380  
9381 The value of the content attribute to set on OPF 2.0 elements. If
9382 this value is empty or undefined, but C<name> is provided and matches
9383 an existing element, that element will be deleted.
9384  
9385 =item C<property>
9386  
9387 The property attribute to use when finding or creating OPF 3.0 <meta>
9388 elements. Either this or C<name> (above) must be specified, but
9389 specifying both is an error.
9390  
9391 =item C<refines>
9392  
9393 The refines attribute to use when finding or creating OPF 3.0 <meta>
9394 elements.
9395  
9396 =item C<scheme>
9397  
9398 The scheme attribute to use when creating or updating OPF 3.0 <meta>
9399 elements.
9400  
9401 =item C<text>
9402  
9403 The text set on OPF 3.0 <meta> elements. If this value is empty or
9404 undefined, but C<property> is provided and the combination of
9405 C<property> and C<refines> matches an existing element, that element
9406 will be deleted.
9407  
9408 =item C<lang>
9409  
9410 The xml:lang attribute to set. This is valid on both OPF 2 and OPF 3
9411 <meta> elements.
9412  
9413 =back
9414  
9415 =cut
9416  
9417 sub set_meta :method {
9418 my ($self, %args) = @_;
9419 my $subname = ( caller(0) )[3];
9420 croak($subname . "() called as a procedure") unless(ref $self);
9421 debug(3,"DEBUG[",$subname,"]");
9422 my %valid_args = (
9423 'name' => 1,
9424 'content' => 1,
9425 'property' => 1,
9426 'refines' => 1,
9427 'scheme' => 1,
9428 'text' => 1,
9429 'lang' => 1,
9430 );
9431 foreach my $arg (keys %args) {
9432 croak($subname,"(): invalid argument '",$arg,"'")
9433 if (!$valid_args{$arg});
9434 }
9435  
9436 my $name = $args{name};
9437 my $content = $args{content};
9438 my $property = $args{property};
9439 my $refines = $args{refines};
9440 my $scheme = $args{scheme};
9441 my $text = $args{text};
9442 my $lang = $args{lang};
9443 my $standard;
9444  
9445 if ($name) {
9446 if ($property) {
9447 $self->add_error($subname,"(): both name (OPF2) and property (OPF3) attributes specified for a meta tag");
9448 return;
9449 }
9450 $standard = 'OPF2';
9451 }
9452 else {
9453 if ($property) {
9454 $standard = 'OPF3';
9455 }
9456 else {
9457 $self->add_error($subname,"(): neither name (OPF2) nor property (OPF3) attributes specified for a meta tag");
9458 return;
9459 }
9460 }
9461  
9462 $self->fix_metastructure_basic();
9463 my $metadata = $self->{twigroot}->first_child('metadata');
9464 my $element;
9465  
9466 if ($standard eq 'OPF2') {
9467 $element = $metadata->first_descendant('meta[@name="' . $name . '"]');
9468  
9469 if ($element) {
9470 if (! $content) {
9471 debug(2,"DEBUG: deleting <meta name='",$name,"'>");
9472 $element->delete;
9473 }
9474 else {
9475 debug(2,"DEBUG: updating <meta name='",$name,"'>");
9476 $element->set_att('content',$content);
9477 if ($lang) {
9478 $element->set_att('xml:lang',$lang);
9479 }
9480 }
9481 }
9482 else {
9483 if ($content) {
9484 debug(2,"DEBUG: creating <meta name='",$name,"'>");
9485 $element = $metadata->insert_new_elt('last_child','meta');
9486 $element->set_att('name',$name);
9487 $element->set_att('content',$content);
9488 }
9489 }
9490 }
9491 elsif ($standard eq 'OPF3') {
9492 if ($refines) {
9493 $element = $metadata->first_descendant(
9494 'meta[@property="' . $property . '" and @refines="' . $refines . '"]');
9495 }
9496 else {
9497 $element = $metadata->first_descendant(
9498 'meta[@property="' . $property . '"]');
9499 }
9500 if ($element) {
9501 if (! $text) {
9502 debug(2,"DEBUG: deleting meta property='",$property,"'>");
9503 $element->delete;
9504 }
9505 else {
9506 debug(2,"DEBUG: updating <meta property='",$property,"'>");
9507 $element->set_text($text);
9508 }
9509 if ($scheme) {
9510 $element->set_att('scheme',$scheme);
9511 }
9512 if ($lang) {
9513 $element->set_att('xml:lang',$lang);
9514 }
9515 }
9516 else {
9517 if ($text) {
9518 debug(2,"DEBUG: creating <meta property='",$property,"'>");
9519 $element = $metadata->insert_new_elt('last_child','meta');
9520 $element->set_att('property',$property);
9521 if ($refines) {
9522 $element->set_att('refines',$refines);
9523 }
9524 if ($scheme) {
9525 $element->set_att('scheme',$scheme);
9526 }
9527 if ($lang) {
9528 $element->set_att('xml:lang',$lang);
9529 }
9530 $element->set_text($text);
9531 }
9532 }
9533 }
9534 else {
9535 croak($subname,"(): unknown standard '${standard}'! (This should be impossible!)");
9536 }
9537  
9538 return;
9539 }
9540  
9541  
9542 =head2 set_metadata(%args)
9543  
9544 Sets the text and optionally the ID of the first specified element
9545 type found (case-insensitive). Creates the element if one did not
9546 exist (with the exact capitalization specified).
9547  
9548 If a <dc-metadata> element exists underneath <metadata>, the language
9549 element will be created underneath the <dc-metadata> and any standard
9550 attributes will be created in OEB 1.2 format, otherwise the element is
9551 created underneath <metadata> in OPF 2.0 format.
9552  
9553 Returns 1 on success, returns undef if no gi or if no text was specified.
9554  
9555 =cut
9556  
9557 =head3 Arguments
9558  
9559 =over
9560  
9561 =item C<gi>
9562  
9563 The generic identifier (tag) of the metadata element to alter or
9564 create. If not specified, the method sets an error and returns undef.
9565  
9566 =item C<parent>
9567  
9568 The generic identifier (tag) of the parent to use for any newly
9569 created element. If not specified, defaults to 'dc-metadata' if
9570 'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.
9571  
9572 A newly created element will be created under the first element found
9573 with this gi. A modified element will be moved under the first
9574 element found with this gi.
9575  
9576 Newly created elements will use OPF 2.0 attribute names if the parent
9577 is 'metadata' and OEB 1.2 attribute names otherwise.
9578  
9579 =item C<text>
9580  
9581 This specifies the element text to set. If not specified, the method
9582 sets an error and returns undef.
9583  
9584 =item C<id> (optional)
9585  
9586 This specifies the ID to set on the element. If set and the ID is
9587 already in use, a warning is logged and the ID is removed from the
9588 other location and assigned to the element.
9589  
9590 =item C<fileas> (optional)
9591  
9592 This specifies the file-as attribute to set on the element.
9593  
9594 =item C<role> (optional)
9595  
9596 This specifies the role attribute to set on the element.
9597  
9598 =item C<scheme> (optional)
9599  
9600 This specifies the scheme attribute to set on the element.
9601  
9602 =back
9603  
9604 =head3 Example
9605  
9606 $retval = $ebook->set_metadata(gi => 'AuthorNonstandard',
9607 text => 'Element Text',
9608 id => 'customid',
9609 fileas => 'Text, Element',
9610 role => 'xxx',
9611 scheme => 'code');
9612  
9613 =cut
9614  
9615 sub set_metadata :method {
9616 my ($self,%args) = @_;
9617 my $subname = ( caller(0) )[3];
9618 croak($subname . "() called as a procedure") unless(ref $self);
9619 debug(3,"DEBUG[",$subname,"]");
9620 my %valid_args = (
9621 'gi' => 1,
9622 'parent' => 1,
9623 'text' => 1,
9624 'id' => 1,
9625 'fileas' => 1,
9626 'role' => 1,
9627 'scheme' => 1,
9628 );
9629 foreach my $arg (keys %args) {
9630 croak($subname,"(): invalid argument '",$arg,"'")
9631 if(!$valid_args{$arg});
9632 }
9633  
9634 my $gi = $args{gi};
9635 unless($gi) {
9636 $self->add_error($subname,"(): no gi specified");
9637 return;
9638 }
9639  
9640 my $text = $args{text};
9641 unless($text) {
9642 $self->add_error($subname,"(): no text specified");
9643 return;
9644 }
9645  
9646 my $newid = $args{id};
9647 my $idelem;
9648 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
9649  
9650 my $element = $self->{twigroot}->first_descendant(qr/^ $gi $/ix);
9651 my $meta;
9652 my $dcmeta;
9653 my $parent;
9654 my %dcatts;
9655  
9656 $self->fix_metastructure_basic();
9657 $parent = $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
9658 if($args{parent});
9659 $meta = $self->{twigroot}->first_child('metadata');
9660 $dcmeta = $meta->first_child('dc-metadata');
9661 $parent = $parent || $dcmeta || $meta;
9662 if($parent->gi eq 'metadata') {
9663 %dcatts = (
9664 'file-as' => 'opf:file-as',
9665 'role' => 'opf:role',
9666 'scheme' => 'opf:scheme',
9667 );
9668 }
9669 else {
9670 %dcatts = (
9671 'file-as' => 'file-as',
9672 'role' => 'role',
9673 'scheme' => 'scheme'
9674 );
9675 }
9676  
9677  
9678 if($element) {
9679 debug(2,"DEBUG: updating '",$gi,"'");
9680 if($element->att('opf:file-as') && $args{fileas}) {
9681 debug(3,"DEBUG: setting opf:file-as '",$args{fileas},"'");
9682 $element->set_att('opf:file-as',$args{fileas});
9683 }
9684 elsif($args{fileas}) {
9685 debug(3,"DEBUG: setting file-as '",$args{fileas},"'");
9686 $element->set_att('file-as',$args{fileas});
9687 }
9688 if($element->att('opf:role') && $args{role}) {
9689 debug(3,"DEBUG: setting opf:role '",$args{role},"'");
9690 $element->set_att('opf:role',$args{role});
9691 }
9692 elsif($args{role}) {
9693 debug(3,"DEBUG: setting role '",$args{role},"'");
9694 $element->set_att('role',$args{role});
9695 }
9696 if($element->att('opf:scheme') && $args{scheme}) {
9697 debug(3,"DEBUG: setting opf:scheme '",$args{scheme},"'");
9698 $element->set_att('opf:scheme',$args{scheme});
9699 }
9700 elsif($args{scheme}) {
9701 debug(3,"DEBUG: setting scheme '",$args{scheme},"'");
9702 $element->set_att('scheme',$args{scheme});
9703 }
9704 debug(3,"DEBUG: setting text");
9705 $element->set_text($text);
9706  
9707 unless($element->parent->gi eq $parent->gi) {
9708 debug(2,"DEBUG: moving <",$element->gi,"> under <",
9709 $parent->gi,">");
9710 $element->move('last_child',$parent);
9711 }
9712 }
9713 else {
9714 debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
9715 $element = $parent->insert_new_elt('last_child',$gi);
9716 $element->set_att($dcatts{'file-as'},$args{fileas})
9717 if($args{fileas});
9718 $element->set_att($dcatts{'role'},$args{role})
9719 if($args{role});
9720 $element->set_att($dcatts{'scheme'},$args{scheme})
9721 if($args{scheme});
9722 $element->set_text($text);
9723 }
9724  
9725 if($idelem && $idelem->cmp($element) ) {
9726 $self->add_warning(
9727 $subname,"(): reassigning id '",$newid,
9728 "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
9729 );
9730 $idelem->del_att('id');
9731 }
9732 $element->set_att('id' => $newid) if($newid);
9733 return 1;
9734 }
9735  
9736  
9737 =head2 set_opffile($filename)
9738  
9739 Sets the filename used to store the OPF metadata.
9740  
9741 Returns 1 on success; sets an error message and returns undef if no
9742 filename was specified.
9743  
9744 =cut
9745  
9746 sub set_opffile :method {
9747 my ($self,$filename) = @_;
9748 my $subname = ( caller(0) )[3];
9749 croak($subname . "() called as a procedure") unless(ref $self);
9750 debug(2,"DEBUG[",$subname,"]");
9751  
9752 unless($filename) {
9753 debug(1,$subname,"(): no filename specified!");
9754 $self->add_warning($subname,"(): no filename specified!");
9755 return;
9756 }
9757 $self->{opffile} = $filename;
9758 return 1;
9759 }
9760  
9761  
9762 =head2 set_retailprice(%args)
9763  
9764 Sets the Mobipocket-specific <SRP> element (Suggested Retail Price),
9765 creating or deleting it as necessary.
9766  
9767 If a new element has to be created, L</fix_metastructure_oeb12> is
9768 called to ensure that <x-metadata> exists and the element is created
9769 under <x-metadata>, as Mobipocket elements are not recognized by
9770 Mobipocket's software when placed directly under <metadata>
9771  
9772 =head3 Arguments
9773  
9774 =over
9775  
9776 =item * C<text>
9777  
9778 The price to set as the text of the element. If this is undefined,
9779 the method sets an error and returns undef. If it is set but false,
9780 any existing <SRP> element is deleted.
9781  
9782 =item * C<currency> (optional)
9783  
9784 The value to set on the 'Currency' attribute. If not provided,
9785 defaults to 'USD' (US Dollars)
9786  
9787 =back
9788  
9789 =cut
9790  
9791 sub set_retailprice :method {
9792 my ($self,%args) = @_;
9793 my $subname = ( caller(0) )[3];
9794 croak($subname . "() called as a procedure") unless(ref $self);
9795 debug(2,"DEBUG[",$subname,"]");
9796 $self->twigcheck;
9797  
9798 my %valid_args = (
9799 'text' => 1,
9800 'currency' => 1,
9801 );
9802  
9803 foreach my $arg (keys %args) {
9804 croak($subname,"(): invalid argument '",$arg,"'")
9805 if(!$valid_args{$arg});
9806 }
9807 unless(defined $args{text}) {
9808 $self->add_error($subname,"(): text not defined");
9809 return;
9810 }
9811  
9812 my $xmeta;
9813 my $element;
9814 my @elements;
9815  
9816 if($args{text}) {
9817 $element = $self->{twigroot}->first_descendant(qr/^ SRP $/ix);
9818 unless($element) {
9819 $self->fix_metastructure_oeb12();
9820 $xmeta = $self->{twigroot}->first_descendant('x-metadata');
9821 $element = $xmeta->insert_new_elt('last_child','SRP');
9822 }
9823 $element->set_text($args{text});
9824 $element->set_att('Currency',$args{currency}) if($args{currency});
9825 }
9826 else {
9827 @elements = $self->{twigroot}->descendants(qr/^ SRP $/ix);
9828 foreach my $el (@elements) {
9829 debug(2,"DEBUG: deleting <SRP>");
9830 $el->delete;
9831 }
9832 }
9833 return 1;
9834 }
9835  
9836  
9837 =head2 set_primary_author(%args)
9838  
9839 Sets the text, id, file-as, and role attributes of the primary author
9840 element (see L</primary_author()> for details on how this is found),
9841 or if no primary author exists, creates a new element containing the
9842 information.
9843  
9844 This method calls L</fix_metastructure_basic()> to enforce the
9845 presence of the <metadata> element. When creating a new element, the
9846 method will use the OEB 1.2 element name and create the element
9847 underneath <dc-metadata> if an existing <dc-metadata> element is found
9848 underneath <metadata>. If no existing <dc-metadata> element is found,
9849 the new element will be created with the OPF 2.0 element name directly
9850 underneath <metadata>. Regardless, it is probably a good idea to call
9851 L</fix_oeb12()> or L</fix_opf20()> after calling this method to ensure
9852 a consistent scheme.
9853  
9854 =head3 Arguments
9855  
9856 Three optional named arguments can be passed:
9857  
9858 =over
9859  
9860 =item * C<text>
9861  
9862 Specifies the author text to set. If omitted and a primary author
9863 element exists, the text will be left as is; if omitted and a primary
9864 author element cannot be found, an error message will be generated and
9865 the method will return undef.
9866  
9867 =item * C<fileas>
9868  
9869 Specifies the 'file-as' attribute to set. If omitted and a primary
9870 author element exists, any existing attribute will be left untouched;
9871 if omitted and a primary author element cannot be found, the newly
9872 created element will not have this attribute.
9873  
9874 =item * C<id>
9875  
9876 Specifies the 'id' attribute to set. If this is specified, and the id
9877 is already in use, a warning will be added but the method will
9878 continue, removing the id attribute from the element that previously
9879 contained it.
9880  
9881 If this is omitted and a primary author element exists, any existing
9882 id will be left untouched; if omitted and a primary author element
9883 cannot be found, the newly created element will not have an id set.
9884  
9885 =back
9886  
9887 If called with no arguments, the only effect this method has is to
9888 enforce that either an 'opf:role' or 'role' attribute is set to 'aut'
9889 on the primary author element.
9890  
9891 =head3 Return values
9892  
9893 Returns 1 if successful, returns undef and sets an error message if
9894 the author argument is missing and no primary author element was
9895 found.
9896  
9897 =cut
9898  
9899 sub set_primary_author :method {
9900 my ($self,%args) = @_;
9901 my $subname = ( caller(0) )[3];
9902 croak($subname . "() called as a procedure") unless(ref $self);
9903 debug(2,"DEBUG[",$subname,"]");
9904 my %valid_args = (
9905 'text' => 1,
9906 'fileas' => 1,
9907 'id' => 1,
9908 );
9909 foreach my $arg (keys %args) {
9910 croak($subname,"(): invalid argument '",$arg,"'")
9911 if(!$valid_args{$arg});
9912 }
9913  
9914 my $twigroot = $self->{twigroot};
9915 $self->fix_metastructure_basic();
9916 my $meta = $twigroot->first_child('metadata');
9917 my $dcmeta = $meta->first_child('dc-metadata');
9918 my $element;
9919 my $newauthor = $args{text};
9920 my $newfileas = $args{fileas};
9921 my $newid = $args{id};
9922 my $idelem;
9923 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
9924  
9925 $element = $twigroot->first_descendant(\&twigelt_is_author);
9926 $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
9927  
9928 unless($element) {
9929 unless($newauthor) {
9930 add_error(
9931 $subname,
9932 "(): cannot create a new author element when the author is not specified");
9933 return;
9934 }
9935 if($dcmeta) {
9936 $element = $dcmeta->insert_new_elt('last_child','dc:Creator');
9937 $element->set_att('role' => 'aut');
9938 $element->set_att('file-as' => $newfileas) if($newfileas);
9939 }
9940 else {
9941 $element = $meta->insert_new_elt('last_child','dc:creator');
9942 $element->set_att('opf:role' => 'aut');
9943 $element->set_att('opf:file-as' => $newfileas) if($newfileas);
9944 }
9945 } # unless($element)
9946 $element->set_text($newauthor);
9947  
9948 if($idelem && $idelem->cmp($element) ) {
9949 $self->add_warning(
9950 $subname,"(): reassigning id '",$newid,
9951 "' from a '",$idelem->gi,"' element!"
9952 );
9953 $idelem->del_att('id');
9954 }
9955 $element->set_att('id' => $newid) if($newid);
9956 return 1;
9957 }
9958  
9959  
9960 =head2 C<set_publisher(%args)>
9961  
9962 Sets the text and optionally the ID of the first dc:publisher element
9963 found (case-insensitive). Creates the element if one did not exist.
9964 If a <dc-metadata> element exists underneath <metadata>, the publisher
9965 element will be created underneath the <dc-metadata> in OEB 1.2
9966 format, otherwise the title element is created underneath <metadata>
9967 in OPF 2.0 format.
9968  
9969 Returns 1 on success, returns undef if no publisher was specified.
9970  
9971 =head3 Arguments
9972  
9973 C<set_publisher()> takes one required and one optional named argument
9974  
9975 =over
9976  
9977 =item C<text>
9978  
9979 This specifies the publisher name to set as the text of the element.
9980 If not specified, the method returns undef.
9981  
9982 =item C<id> (optional)
9983  
9984 This specifies the ID to set on the element. If set and the ID is
9985 already in use, a warning is logged and the ID is removed from the
9986 other location and assigned to the element.
9987  
9988 =back
9989  
9990 =head3 Example
9991  
9992 $retval = $ebook->set_publisher('text' => 'My Publishing House',
9993 'id' => 'mypubid');
9994  
9995 =cut
9996  
9997 sub set_publisher :method {
9998 my ($self,%args) = @_;
9999 my $subname = ( caller(0) )[3];
10000 croak($subname . "() called as a procedure") unless(ref $self);
10001 debug(2,"DEBUG[",$subname,"]");
10002 my %valid_args = (
10003 'text' => 1,
10004 'id' => 1,
10005 );
10006 foreach my $arg (keys %args) {
10007 croak($subname,"(): invalid argument '",$arg,"'")
10008 if(!$valid_args{$arg});
10009 }
10010  
10011 my $publisher = $args{text};
10012 return unless($publisher);
10013  
10014 my $newid = $args{id};
10015 my $idelem;
10016 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10017  
10018 $self->fix_metastructure_basic();
10019 my $element = $self->{twigroot}->first_descendant(qr/^dc:publisher$/ix);
10020 my $meta = $self->{twigroot}->first_child('metadata');
10021 my $dcmeta = $meta->first_child('dc-metadata');
10022  
10023 if(!$element && $dcmeta) {
10024 $element = $dcmeta->insert_new_elt('last_child','dc:Publisher');
10025 }
10026 elsif(!$element) {
10027 $element = $meta->insert_new_elt('last_child','dc:publisher');
10028 }
10029 $element->set_text($publisher);
10030 if($idelem && $idelem->cmp($element) ) {
10031 $self->add_warning(
10032 $subname,"(): reassigning id '",$newid,
10033 "' from a '",$idelem->gi,"' element!"
10034 );
10035 $idelem->del_att('id');
10036 }
10037 $element->set_att('id' => $newid) if($newid);
10038 return 1;
10039 }
10040  
10041  
10042 =head2 set_review(%args)
10043  
10044 Sets the text and optionally ID of the first <Review> element found
10045 (case-insensitive), creating the element if one did not exist.
10046  
10047 This is a Mobipocket-specific element and if it needs to be created it
10048 will always be created under <x-metadata> with
10049 L</fix_metastructure_oeb12()> called to ensure that <x-metadata>
10050 exists.
10051  
10052 Returns 1 on success, returns undef if no review text was specified
10053  
10054 =head3 Arguments
10055  
10056 =over
10057  
10058 =item C<text>
10059  
10060 This specifies the description to use as the text of the element. If
10061 not specified, the method returns undef.
10062  
10063 =item C<id> (optional)
10064  
10065 This specifies the ID to set on the element. If set and the ID is
10066 already in use, a warning is logged and the ID is removed from the
10067 other location and assigned to the element.
10068  
10069 =back
10070  
10071 =head3 Example
10072  
10073 $retval = $ebook->set_review('text' => 'This book is perfect!',
10074 'id' => 'revid');
10075  
10076 =cut
10077  
10078 sub set_review :method {
10079 my ($self,%args) = @_;
10080 my $subname = ( caller(0) )[3];
10081 croak($subname . "() called as a procedure") unless(ref $self);
10082 debug(2,"DEBUG[",$subname,"]");
10083 my %valid_args = (
10084 'text' => 1,
10085 'id' => 1,
10086 );
10087 foreach my $arg (keys %args) {
10088 croak($subname,"(): invalid argument '",$arg,"'")
10089 if(!$valid_args{$arg});
10090 }
10091  
10092 my $text = $args{text};
10093 unless($text) {
10094 $self->add_error($subname,"(): no text specified");
10095 return;
10096 }
10097  
10098 $self->fix_metastructure_oeb12();
10099 $self->set_metadata(gi => 'Review',
10100 parent => 'x-metadata',
10101 text => $args{text},
10102 id => $args{id});
10103  
10104 return 1;
10105 }
10106  
10107  
10108 =head2 C<set_rights(%args)>
10109  
10110 Sets the text of the first dc:rights or dc:copyrights element found
10111 (case-insensitive). If the element found has the gi of dc:copyrights,
10112 it will be changed to dc:rights. This is to correct certain
10113 noncompliant Mobipocket files.
10114  
10115 Creates the element if one did not exist. If a <dc-metadata> element
10116 exists underneath <metadata>, the title element will be created
10117 underneath the <dc-metadata> in OEB 1.2 format, otherwise the title
10118 element is created underneath <metadata> in OPF 2.0 format.
10119  
10120 Returns 1 on success, returns undef if no rights string was specified.
10121  
10122 =head3 Arguments
10123  
10124 =over
10125  
10126 =item * C<text>
10127  
10128 This specifies the text of the element. If not specified, the method
10129 returns undef.
10130  
10131 =item * C<id> (optional)
10132  
10133 This specifies the ID to set on the element. If set and the ID is
10134 already in use, a warning is logged but the method continues anyway.
10135  
10136 =back
10137  
10138 =cut
10139  
10140 sub set_rights :method {
10141 my ($self,%args) = @_;
10142 my $subname = ( caller(0) )[3];
10143 croak($subname . "() called as a procedure") unless(ref $self);
10144 debug(2,"DEBUG[",$subname,"]");
10145 my %valid_args = (
10146 'text' => 1,
10147 'id' => 1,
10148 );
10149 foreach my $arg (keys %args) {
10150 croak($subname,"(): invalid argument '",$arg,"'")
10151 if(!$valid_args{$arg});
10152 }
10153 my $rights = $args{text};
10154 return unless($rights);
10155 my $newid = $args{id};
10156 my $idelem;
10157 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10158  
10159 $self->fix_metastructure_basic();
10160 my $element = $self->{twigroot}->first_descendant(qr/^dc:(copy)?rights$/ix);
10161 my $meta = $self->{twigroot}->first_child('metadata');
10162 my $dcmeta = $meta->first_child('dc-metadata');
10163 my $parent = $dcmeta || $meta;
10164  
10165 $element ||= $parent->insert_new_elt('last_child','dc:rights');
10166 $element->set_text($rights);
10167 $element->set_gi('dc:Rights') if($element->gi eq 'dc:Copyrights');
10168 $element->set_gi('dc:rights') if($element->gi eq 'dc:copyrights');
10169 if($idelem && $idelem->cmp($element) ) {
10170 $self->add_warning(
10171 $subname,"(): reassigning id '",$newid,
10172 "' from a '",$idelem->gi,"' element!"
10173 );
10174 $idelem->del_att('id');
10175 }
10176 $element->set_att('id' => $newid) if($newid);
10177 return 1;
10178 }
10179  
10180  
10181 =head2 C<set_spec($spec)>
10182  
10183 Sets the OEB specification to match when modifying OPF data.
10184 Allowable values are 'OEB12', 'OPF20', and 'MOBI12'.
10185  
10186 Returns 1 if successful; returns undef and sets an error message if an
10187 unknown specification was set.
10188  
10189 =cut
10190  
10191 sub set_spec :method {
10192 my ($self,$spec) = @_;
10193 my $subname = ( caller(0) )[3];
10194 croak($subname . "() called as a procedure") unless(ref $self);
10195 debug(2,"DEBUG[",$subname,"]");
10196  
10197 unless($validspecs{$spec}) {
10198 $self->add_error($subname,"(): invalid specification '",$spec,"'");
10199 return;
10200 }
10201 $self->{spec} = $validspecs{$spec};
10202 return 1;
10203 }
10204  
10205  
10206 =head2 C<set_timestamp()>
10207  
10208 Sets the <meta property="dcterms:modified"> element to the current
10209 timestamp and removes duplicate or nonstandard timestamps.
10210  
10211 =cut
10212  
10213 sub set_timestamp :method {
10214 my ($self) = @_;
10215 my $subname = ( caller(0) )[3];
10216 croak($subname . "() called as a procedure") unless(ref $self);
10217 debug(2,"DEBUG[",$subname,"]");
10218  
10219 my @timestamps;
10220 my $twigroot = $self->{twigroot};
10221 my $time = Date::Manip::Date->new();
10222  
10223 @timestamps = $twigroot->descendants(
10224 'meta[@property="dcterms:modified" or @name="calibre:timestamp"]');
10225 foreach my $timestamp (@timestamps) {
10226 $timestamp->delete;
10227 }
10228 @timestamps = $twigroot->descendants(
10229 'dc:date[@opf:event="modification" or @event="modification"]');
10230 foreach my $timestamp (@timestamps) {
10231 $timestamp->delete;
10232 }
10233 $time->parse('now');
10234 $self->set_meta('property' => 'dcterms:modified',
10235 'text' => $time->printf('%O') );
10236 return;
10237 }
10238  
10239  
10240 =head2 C<set_title(%args)>
10241  
10242 Sets the text or id of the first dc:title element found
10243 (case-insensitive). Creates the element if one did not exist. If a
10244 <dc-metadata> element exists underneath <metadata>, the title element
10245 will be created underneath the <dc-metadata> in OEB 1.2 format,
10246 otherwise the title element is created underneath <metadata> in OPF
10247 2.0 format.
10248  
10249 =head3 Arguments
10250  
10251 set_title() takes two optional named arguments. If neither is
10252 specified, the method will do nothing.
10253  
10254 =over
10255  
10256 =item * C<text>
10257  
10258 This specifies the text of the element. If not specified, and no
10259 title element is found, an error will be set and the method will
10260 return undef -- set_title() will refuse to create a dc:title element
10261 with no text.
10262  
10263 =item * C<id>
10264  
10265 This specifies the ID to set on the element. If set and the ID is
10266 already in use, a warning is logged but the method continues anyway.
10267  
10268 =back
10269  
10270 =cut
10271  
10272 sub set_title :method {
10273 my ($self,%args) = @_;
10274 my $subname = ( caller(0) )[3];
10275 croak($subname . "() called as a procedure") unless(ref $self);
10276 debug(2,"DEBUG[",$subname,"]");
10277  
10278 my %valid_args = (
10279 'text' => 1,
10280 'id' => 1,
10281 );
10282 foreach my $arg (keys %args) {
10283 croak($subname,"(): invalid argument '",$arg,"'")
10284 if(!$valid_args{$arg});
10285 }
10286 my $title = $args{text};
10287 my $newid = $args{id};
10288 my $idelem;
10289 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10290  
10291 $self->fix_metastructure_basic();
10292 my $element = $self->{twigroot}->first_descendant(qr/^dc:title$/ix);
10293 my $meta = $self->{twigroot}->first_child('metadata');
10294 my $dcmeta = $meta->first_child('dc-metadata');
10295 my $parent = $dcmeta || $meta;
10296 unless($element) {
10297 unless($title) {
10298 add_error($subname,
10299 "(): no title specified, but no existing title found");
10300 return;
10301 }
10302 $element = $parent->insert_new_elt('last_child','dc:title');
10303 }
10304 $element->set_text($title) if($title);
10305  
10306 if($idelem && $idelem->cmp($element) ) {
10307 $self->add_warning(
10308 $subname,"(): reassigning id '",$newid,
10309 "' from a '",$idelem->gi,"' element!"
10310 );
10311 $idelem->del_att('id');
10312 }
10313 $element->set_att('id' => $newid) if($newid);
10314 return 1;
10315 }
10316  
10317  
10318 =head2 C<set_type(%args)>
10319  
10320 Sets the text and optionally the ID of the first dc:type element
10321 found (case-insensitive). Creates the element if one did not exist.
10322 If a <dc-metadata> element exists underneath <metadata>, the publisher
10323 element will be created underneath the <dc-metadata> in OEB 1.2
10324 format, otherwise the title element is created underneath <metadata>
10325 in OPF 2.0 format.
10326  
10327 Returns 1 on success, returns undef if no publisher was specified.
10328  
10329 =head3 Arguments
10330  
10331 C<set_type()> takes one required and one optional named argument
10332  
10333 =over
10334  
10335 =item C<text>
10336  
10337 This specifies the publisher name to set as the text of the element.
10338 If not specified, the method returns undef.
10339  
10340 =item C<id> (optional)
10341  
10342 This specifies the ID to set on the element. If set and the ID is
10343 already in use, a warning is logged and the ID is removed from the
10344 other location and assigned to the element.
10345  
10346 =back
10347  
10348 =head3 Example
10349  
10350 $retval = $ebook->set_type('text' => 'Short Story',
10351 'id' => 'mytypeid');
10352  
10353 =cut
10354  
10355 sub set_type :method {
10356 my ($self,%args) = @_;
10357 my $subname = ( caller(0) )[3];
10358 croak($subname . "() called as a procedure") unless(ref $self);
10359 debug(2,"DEBUG[",$subname,"]");
10360 my %valid_args = (
10361 'text' => 1,
10362 'id' => 1,
10363 );
10364 foreach my $arg (keys %args) {
10365 croak($subname,"(): invalid argument '",$arg,"'")
10366 if(!$valid_args{$arg});
10367 }
10368  
10369 my $text = $args{text};
10370 return unless($text);
10371  
10372 my $newid = $args{id};
10373 my $idelem;
10374 $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
10375  
10376 $self->fix_metastructure_basic();
10377 my $element = $self->{twigroot}->first_descendant(qr/^dc:type$/ix);
10378 my $meta = $self->{twigroot}->first_child('metadata');
10379 my $dcmeta = $meta->first_child('dc-metadata');
10380  
10381 if(!$element && $dcmeta) {
10382 $element = $dcmeta->insert_new_elt('last_child','dc:Type');
10383 }
10384 elsif(!$element) {
10385 $element = $meta->insert_new_elt('last_child','dc:type');
10386 }
10387 $element->set_text($text);
10388 if($idelem && $idelem->cmp($element) ) {
10389 $self->add_warning(
10390 $subname,"(): reassigning id '",$newid,
10391 "' from a '",$idelem->gi,"' element!"
10392 );
10393 $idelem->del_att('id');
10394 }
10395 $element->set_att('id' => $newid) if($newid);
10396 return 1;
10397 }
10398  
10399  
10400 ################################
10401 ########## PROCEDURES ##########
10402 ################################
10403  
10404 =head1 PROCEDURES
10405  
10406 All procedures are exportable, but none are exported by default. All
10407 procedures can be exported by using the ":all" tag.
10408  
10409  
10410 =head2 C<_lc>
10411  
10412 Wrapper for CORE::lc to get around the fact that builtins can't be
10413 used in dispatch tables prior to Perl 5.16.
10414  
10415 WARNING: this procedure may disappear once Perl 5.16 is standard on
10416 all systems in common use! For that reason, this is not exportable.
10417  
10418 =cut
10419  
10420 sub _lc {
10421 my ($string) = @_;
10422 return lc $string;
10423 }
10424  
10425  
10426 =head2 C<_uc>
10427  
10428 Wrapper for CORE::uc to get around the fact that builtins can't be
10429 used in dispatch tables prior to Perl 5.16.
10430  
10431 WARNING: this procedure may disappear once Perl 5.16 is standard on
10432 all systems in common use! For that reason, this is not exportable.
10433  
10434 =cut
10435  
10436 sub _uc {
10437 my ($string) = @_;
10438 return uc $string;
10439 }
10440  
10441  
10442 =head2 C<capitalize($string)>
10443  
10444 Capitalizes the first letter of each word in $string.
10445  
10446 Returns the corrected string.
10447  
10448 =cut
10449  
10450 sub capitalize {
10451 my ($string) = @_;
10452 $string =~ s/(?<=\w)(.)/\l$1/gx;
10453 return $string;
10454 }
10455  
10456  
10457 =head2 C<clean_filename($string)>
10458  
10459 Takes an input string and cleans out any characters that would not be
10460 valid in a filename.
10461  
10462 Returns the cleaned string.
10463  
10464 =cut
10465  
10466 sub clean_filename {
10467 my ($string) = @_;
10468 $string =~ s/[^A-Za-z0-9_ \-\.]//g;
10469 return $string;
10470 }
10471  
10472  
10473 =head2 C<create_epub_container($opffile)>
10474  
10475 Creates the XML file META-INF/container.xml pointing to the
10476 specified OPF file.
10477  
10478 Creates the META-INF directory if necessary. Will destroy any
10479 non-directory file named 'META-INF' in the current directory. If
10480 META-INF/container.xml already exists, it will rename that file to
10481 META-INF/container.xml.backup.
10482  
10483 =head3 Arguments
10484  
10485 =over
10486  
10487 =item $opffile
10488  
10489 The OPF filename (and path, if necessary) to use in the container. If
10490 not specified, looks for a sole OPF file in the current working
10491 directory. Fails if more than one is found.
10492  
10493 =back
10494  
10495 =head3 Return values
10496  
10497 =over
10498  
10499 =item Returns a twig representing the container data if successful, undef
10500 otherwise
10501  
10502 =back
10503  
10504 =cut
10505  
10506 sub create_epub_container {
10507 my ($opffile) = @_;
10508 my $subname = ( caller(0) )[3];
10509 debug(2,"DEBUG[",$subname,"]");
10510  
10511 my $twig;
10512 my $twigroot;
10513 my $rootfiles;
10514 my $element;
10515 my $fh_container;
10516  
10517 if($opffile eq '') { return; }
10518  
10519 if(-e 'META-INF') {
10520 if(! -d 'META-INF') {
10521 unlink('META-INF') or return;
10522 mkdir('META-INF') or return;
10523 }
10524 }
10525 else { mkdir('META-INF') or return; }
10526  
10527 $twig = XML::Twig->new(
10528 output_encoding => 'utf-8',
10529 pretty_print => 'record'
10530 );
10531  
10532 $element = XML::Twig::Elt->new('container');
10533 $element->set_att('version' => '1.0',
10534 'xmlns' => 'urn:oasis:names:tc:opendocument:xmlns:container');
10535 $twig->set_root($element);
10536 $twigroot = $twig->root;
10537  
10538 $rootfiles = $twigroot->insert_new_elt('first_child','rootfiles');
10539 $element = $rootfiles->insert_new_elt('first_child','rootfile');
10540 $element->set_att('full-path',$opffile);
10541 $element->set_att('media-type','application/oebps-package+xml');
10542  
10543  
10544 # Backup existing file
10545 if(-e 'META-INF/container.xml') {
10546 rename('META-INF/container.xml','META-INF/container.xml.backup')
10547 or croak($subname,"(): could not backup container.xml!");
10548 }
10549  
10550 open($fh_container,'>:encoding(UTF-8)','META-INF/container.xml')
10551 or croak($subname,"(): could not write to 'META-INF/container.xml'\n");
10552 $twig->print(\*$fh_container);
10553 close($fh_container)
10554 or croak($subname,"(): could not close 'META-INF/container.xml'\n");
10555 return $twig;
10556 }
10557  
10558  
10559 =head2 C<create_epub_mimetype()>
10560  
10561 Creates a file named 'mimetype' in the current working directory
10562 containing 'application/epub+zip' (no trailing newline)
10563  
10564 Destroys and overwrites that file if it exists.
10565  
10566 Returns the mimetype string if successful, undef otherwise.
10567  
10568 =cut
10569  
10570 sub create_epub_mimetype {
10571 my $subname = ( caller(0) )[3];
10572 debug(2,"DEBUG[",$subname,"]");
10573  
10574 my $mimetype = "application/epub+zip";
10575 my $fh_mimetype;
10576  
10577 open($fh_mimetype,">",'mimetype') or return;
10578 print {*$fh_mimetype} $mimetype;
10579 close($fh_mimetype) or croak($subname,"(): failed to close filehandle [$!]");
10580  
10581 return $mimetype;
10582 }
10583  
10584  
10585 =head2 C<debug($level,@message)>
10586  
10587 Prints a debugging message to C<STDERR> if package variable C<$debug>
10588 is greater than or equal to C<$level>. A trailing newline is
10589 appended, and should not be part of @message.
10590  
10591 Returns true or dies.
10592  
10593 =cut
10594  
10595 sub debug {
10596 my ($level,@message) = @_;
10597 my $subname = ( caller(0) )[3];
10598 croak($subname,"(): no debugging level specified") unless($level);
10599 croak($subname,"(): invalid debugging level '",$level,"'")
10600 unless( $level =~ /^\d$/ );
10601 croak($subname,"(): no message specified") unless(@message);
10602 print {*STDERR} @message,"\n" if($debug >= $level);
10603 return 1;
10604 }
10605  
10606  
10607 =head2 C<excerpt_line($text)>
10608  
10609 Takes as an argument a list of text pieces that will be joined. If
10610 the joined length is less than 70, all of the joined text is returned.
10611  
10612 If the joined length is greater than 70, the return string is the
10613 first 30 characters followed by C<' [...] '> followed by the last 30
10614 characters.
10615  
10616 =cut
10617  
10618 sub excerpt_line {
10619 my @parts = @_;
10620 my $subname = ( caller(0) )[3];
10621 my $text = join('',@parts);
10622 if(length($text) > 70)
10623 {
10624 $text =~ /^ (.{30}) .*? (.{30}) $/sx;
10625 return ($1 . ' [...] ' . $2);
10626 }
10627 else { return $text; }
10628 }
10629  
10630  
10631 =head2 C<find_in_path($pattern,@extradirs)>
10632  
10633 Searches through C<$ENV{PATH}> (and optionally any additional
10634 directories specified in C<@extradirs>) for the first regular file
10635 matching C<$pattern>. C<$pattern> itself can take two forms: if
10636 passed a C<qr//> regular expression, that expression is used directly.
10637 If passed any other string, that string will be used for a
10638 case-insensitive exact match where the extension '.bat', '.com', or
10639 '.exe' is optional (i.e. the final pattern will be
10640 C<qr/^ $pattern (\.bat|\.com|\.exe)? $/ix>).
10641  
10642 Returns the first match found, or undef if there were no matches or if
10643 no pattern was specified.
10644  
10645 =cut
10646  
10647 sub find_in_path {
10648 my ($pattern,@extradirs) = @_;
10649 return unless($pattern);
10650 my $subname = ( caller(0) )[3];
10651 debug(3,"DEBUG[",$subname,"]");
10652  
10653 my $regexp;
10654 my @dirs;
10655 my $fh_dir;
10656 my @filelist;
10657 my $envsep = ':';
10658 my $filesep = '/';
10659 if($OSNAME eq 'MSWin32') {
10660 $envsep = ';';
10661 $filesep = "\\";
10662 }
10663  
10664 if(ref($pattern) eq 'Regexp') { $regexp = $pattern; }
10665 else { $regexp = qr/^ $pattern (\.bat|\.com|\.exe)? $/ix; }
10666  
10667 @dirs = split(/$envsep/,$ENV{PATH});
10668 unshift(@dirs,@extradirs) if(@extradirs);
10669 foreach my $dir (@dirs) {
10670 if(-d $dir) {
10671 if(opendir($fh_dir,$dir)) {
10672 @filelist = grep { /$regexp/ } readdir($fh_dir);
10673 @filelist = grep { -f "$dir/$_" } @filelist;
10674 closedir($fh_dir);
10675  
10676 if(@filelist) { return $dir . $filesep . $filelist[0]; }
10677 }
10678 }
10679 }
10680 return;
10681 }
10682  
10683 =head2 C<find_links($filename)>
10684  
10685 Searches through a file for href and src attributes, and returns a
10686 list of unique links with any named anchors removed
10687 (e.g. 'myfile.html#part7' returns as just 'myfile.html'). If no links
10688 are found, or the file does not exist, returns undef.
10689  
10690 Does not check to see if the links are local. Requires that links be
10691 surrounded by double quotes, not single or left bare. Assumes that
10692 any link will not be broken across multiple lines, so it will (for
10693 example) fail to find:
10694  
10695 <img src=
10696 "myfile.jpg">
10697  
10698 though it can find:
10699  
10700 <img
10701 src="myfile.jpg">
10702  
10703 This also does not distinguish between local files and remote links.
10704  
10705 =cut
10706  
10707 sub find_links {
10708 my ($filename) = @_;
10709 return unless(-f $filename);
10710 my $subname = ( caller(0) )[3];
10711 debug(3,"DEBUG[",$subname,"]");
10712  
10713 my $fh;
10714 my %linkhash;
10715 my @links;
10716  
10717 my $subdir = dirname($filename);
10718 if($subdir eq '.') {
10719 $subdir = '';
10720 }
10721 else {
10722 $subdir = $subdir . '/';
10723 }
10724  
10725 open($fh,'<:raw',$filename)
10726 or croak($subname,"(): unable to open '",$filename,"'\n");
10727  
10728 while(<$fh>) {
10729 @links = /(?:href|src) \s* = \s* "
10730 ([^">]+)/gix;
10731 foreach my $link (@links) {
10732 # Perform URI decoding
10733 $link = uri_unescape($link);
10734  
10735 # Strip off any named anchors
10736 $link =~ s/#.*$//;
10737 next unless $link;
10738  
10739 # Skip links that begin with backwards directory traversal
10740 next if $link =~ m#^\.\./.*$#;
10741  
10742 # Strip javascript: hrefs
10743 next if $link =~ m#javascript:#;
10744  
10745 # Baen HTML sources in particular may contain javascript
10746 # href generators
10747 next if $link =~ /\+ /;
10748  
10749 # If the link is not a URI and we are in a subdirectory
10750 # relative to the OPF, ensure that subdirectory is placed
10751 # as a prefix.
10752 if($subdir and $link !~ m#^ \w+://#ix) {
10753 $link = $subdir . $link;
10754 }
10755 debug(2, "DEBUG: found link '",$link,"'");
10756 $linkhash{$link}++;
10757 }
10758 }
10759 if(%linkhash) { return keys(%linkhash); }
10760 else { return; }
10761 }
10762  
10763  
10764 =head2 C<find_opffile()>
10765  
10766 Attempts to locate an OPF file, first by calling
10767 L</get_container_rootfile()> to check the contents of
10768 C<META-INF/container.xml>, and then by looking for a single file with
10769 the extension C<.opf> in the current working directory.
10770  
10771 Returns the filename of the OPF file, or undef if nothing was found.
10772  
10773 =cut
10774  
10775 sub find_opffile {
10776 my $subname = ( caller(0) )[3];
10777 my $opffile = get_container_rootfile();
10778  
10779 if(!$opffile) {
10780 my @candidates = glob("*.opf");
10781 if(scalar(@candidates) > 1) {
10782 debug(1,"DEBUG: Multiple OPF files found, but no container",
10783 " to specify which one to choose!");
10784 return;
10785 }
10786 if(scalar(@candidates) < 1) {
10787 debug(1,"DEBUG: No OPF files found!");
10788 return;
10789 }
10790 $opffile = $candidates[0];
10791 }
10792 return $opffile;
10793 }
10794  
10795  
10796 =head2 C<fix_datestring($datestring)>
10797  
10798 Takes a date string and attempts to convert it to the limited subset
10799 of ISO8601 allowed by the OPF standard (YYYY, YYYY-MM, or YYYY-MM-DD).
10800  
10801 In the special case of finding MM/DD/YYYY, it assumes that it was a
10802 Mobipocket-mangled date, and not only converts it, but will strip the
10803 day information if the day is '01', and both the month and day
10804 information if both month and day are '01'. This is because
10805 Mobipocket Creator enforces a complete MM/DD/YYYY even if the month
10806 and day aren't known, and it is common practice to use 01 for an
10807 unknown value.
10808  
10809 =head3 Arguments
10810  
10811 =over
10812  
10813 =item $datestring
10814  
10815 A date string in a format recognizable by Date::Manip
10816  
10817 =back
10818  
10819 =head3 Returns $fixeddate
10820  
10821 =over
10822  
10823 =item $fixeddate : the corrected string, or undef on failure
10824  
10825 =back
10826  
10827 =cut
10828  
10829 sub fix_datestring {
10830 my ($datestring) = @_;
10831 return unless($datestring);
10832 my $subname = ( caller(0) )[3];
10833 debug(2,"DEBUG[",$subname,"]");
10834  
10835 my $date;
10836 my ($year,$month,$day);
10837 my $fixeddate;
10838  
10839 $_ = $datestring;
10840  
10841 debug(3,"DEBUG: checking M(M)/D(D)/YYYY");
10842 if(( ($month,$day,$year) = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/x ) == 3) {
10843 # We have a XX/XX/XXXX datestring
10844 debug(3,"DEBUG: found '",$month,"/",$day,"/",$year,"'");
10845 ($year,$month,$day) = ymd_validate($year,$month,$day);
10846 if($year) {
10847 $fixeddate = $year;
10848 $fixeddate .= sprintf("-%02u",$month)
10849 unless( ($month == 1) && ($day == 1) );
10850 $fixeddate .= sprintf("-%02u",$day) unless($day == 1);
10851 debug(3,"DEBUG: returning '",$fixeddate,"'");
10852 return $fixeddate;
10853 }
10854 }
10855  
10856 debug(3,"DEBUG: checking M(M)/YYYY");
10857 if(( ($month,$year) = /^(\d{1,2})\/(\d{4})$/x ) == 2) {
10858 # We have a XX/XXXX datestring
10859 debug(3,"DEBUG: found '",$month,"/",$year,"'");
10860 if($month <= 12) {
10861 # We probably have MM/YYYY
10862 $fixeddate = sprintf("%04u-%02u",$year,$month);
10863 debug(3,"DEBUG: returning '",$fixeddate,"'");
10864 return $fixeddate;
10865 }
10866 }
10867  
10868 # These regexps will reduce '2009-xx-01' to just 2009
10869 # We don't want this, so don't use them.
10870 # ($year,$month,$day) = /(\d{4})-?(\d{2})?-?(\d{2})?/;
10871 # ($year,$month,$day) = /(\d{4})(?:-?(\d{2})-?(\d{2}))?/;
10872  
10873 # Force exact match)
10874 debug(3,"DEBUG: checking YYYY-MM-DD");
10875 ($year,$month,$day) = /^(\d{4})-(\d{2})-(\d{2})$/x;
10876 ($year,$month,$day) = ymd_validate($year,$month,$day);
10877  
10878 if(!$year) {
10879 debug(3,"DEBUG: checking YYYYMMDD");
10880 ($year,$month,$day) = /^(\d{4})(\d{2})(\d{2})$/x;
10881 ($year,$month,$day) = ymd_validate($year,$month,$day);
10882 }
10883  
10884 if(!$year) {
10885 debug(3,"DEBUG: checking YYYY-M(M)");
10886 ($year,$month) = /^(\d{4})-(\d{1,2})$/x;
10887 ($year,$month) = ymd_validate($year,$month,undef);
10888 }
10889  
10890 if(!$year) {
10891 debug(3,"DEBUG: checking YYYY");
10892 ($year) = /^(\d{4})$/x;
10893 }
10894  
10895 # At this point, we've exhausted all of the common cases. We use
10896 # Date::Manip to hit all of the unlikely ones as well. This comes
10897 # with a drawback: Date::Manip doesn't distinguish between 2008
10898 # and 2008-01-01, but we should have covered that above.
10899 #
10900 # Note that Date::Manip will die on MS Windows system unless the
10901 # TZ environment variable is set in a specific manner.
10902 # See:
10903 # http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES
10904  
10905 if(!$year) {
10906 $date = ParseDate($datestring);
10907 $year = UnixDate($date,"%Y");
10908 $month = UnixDate($date,"%m");
10909 $day = UnixDate($date,"%d");
10910 debug(2,"DEBUG: Date::Manip found '",UnixDate($date,"%Y-%m-%d"),"'");
10911 }
10912  
10913 if($year) {
10914 # If we still have a $year, $month and $day either don't exist
10915 # or are plausibly valid.
10916 print {*STDERR} "DEBUG: found year=",$year," " if($debug >= 2);
10917 $fixeddate = sprintf("%04u",$year);
10918 if($month) {
10919 print {*STDERR} "month=",$month," " if($debug >= 2);
10920 $fixeddate .= sprintf("-%02u",$month);
10921 if($day) {
10922 print {*STDERR} "day=",$day if($debug >= 2);
10923 $fixeddate .= sprintf("-%02u",$day);
10924 }
10925 }
10926 print {*STDERR} "\n" if($debug >= 2);
10927 debug(2,"DEBUG: returning '",$fixeddate,"'");
10928 return $fixeddate if($fixeddate);
10929 }
10930  
10931 if(!$year) {
10932 debug(3,"fix_date: didn't find a valid date in '",$datestring,"'!");
10933 return;
10934 }
10935 elsif($debug) {
10936 print {*STDERR} "DEBUG: found ",sprintf("04u",$year);
10937 print {*STDERR} sprintf("-02u",$month) if($month);
10938 print {*STDERR} sprintf("-02u",$day),"\n" if($day);
10939 }
10940  
10941 $fixeddate = sprintf("%04u",$year);
10942 $fixeddate .= sprintf("-%02u-%02u",$month,$day);
10943 return $fixeddate;
10944 }
10945  
10946  
10947 =head2 C<get_container_rootfile($container)>
10948  
10949 Opens and parses an OPS/epub container, extracting the 'full-path'
10950 attribute of element 'rootfile'
10951  
10952 =head3 Arguments
10953  
10954 =over
10955  
10956 =item $container
10957  
10958 The OPS container to parse. Defaults to 'META-INF/container.xml'
10959  
10960 =back
10961  
10962 =head3 Return values
10963  
10964 =over
10965  
10966 =item Returns a string containing the rootfile on success, undef on failure.
10967  
10968 =back
10969  
10970 =cut
10971  
10972 sub get_container_rootfile {
10973 my ($container) = @_;
10974 my $subname = ( caller(0) )[3];
10975 debug(2,"DEBUG[",$subname,"]");
10976  
10977 my $twig = XML::Twig->new();
10978 my $rootfile;
10979 my $retval = undef;
10980  
10981 $container = 'META-INF/container.xml' if(! $container);
10982  
10983 if(-f $container) {
10984 $twig->parsefile($container) or return;
10985 $rootfile = $twig->root->first_descendant('rootfile');
10986 return unless($rootfile);
10987 $retval = $rootfile->att('full-path');
10988 }
10989 return $retval;
10990 }
10991  
10992  
10993 =head2 C<hashvalue_key_self(\%hash, $modifier)>
10994  
10995 Takes as an argument a hash reference and an optional modifier and
10996 inserts a new key for every value in that hash if no such key already
10997 exists.
10998  
10999 If the modifer is set to 'lc' or 'uc', the value is either lowercased
11000 or uppercased respectively before it is used as a key.
11001  
11002 Croaks if the first argument is not a hashref, or if an invalid
11003 modifier string is used.
11004  
11005 =cut
11006  
11007 sub hashvalue_key_self {
11008 my ($hashref, $modifier) = @_;
11009 my $subname = ( caller(0) )[3];
11010 debug(4,"DEBUG[",$subname,"]");
11011  
11012 if (not $hashref or not ref($hashref)) {
11013 croak($subname,"(): first argument is not a reference");
11014 }
11015 elsif (!UNIVERSAL::isa($hashref,'HASH')) {
11016 croak($subname,"(): first argument is not a hashref");
11017 }
11018  
11019 my %modifier_dispatch = (
11020 'lc' => \&_lc,
11021 'uc' => \&_uc,
11022 );
11023  
11024 if ($modifier and not $modifier_dispatch{$modifier}) {
11025 croak($subname,"(): ",$modifier," is not a valid modifier string");
11026 }
11027  
11028 foreach my $value (values %{$hashref}) {
11029 my $key;
11030 if($modifier) {
11031 $key = $modifier_dispatch{$modifier}($value);
11032 }
11033 else {
11034 $key = $value;
11035 }
11036 if (! $hashref->{$key}) {
11037 $hashref->{$key} = $value;
11038 }
11039 }
11040 return;
11041 }
11042  
11043  
11044 =head2 C<hexstring($bindata)>
11045  
11046 Takes as an argument a scalar containing a sequence of binary bytes.
11047 Returns a string converting each octet of the data to its two-digit
11048 hexadecimal equivalent. There is no leading "0x" on the string.
11049  
11050 =cut
11051  
11052 sub hexstring {
11053 my $data = shift;
11054 my $subname = ( caller(0) )[3];
11055 debug(4,"DEBUG[",$subname,"]");
11056  
11057 croak($subname,"(): no data provided")
11058 unless($data);
11059  
11060 my $byte;
11061 my $retval = '';
11062 my $pos = 0;
11063  
11064 while($pos < length($data)) {
11065 $byte = unpack("C",substr($data,$pos,1));
11066 $retval .= sprintf("%02x",$byte);
11067 $pos++;
11068 }
11069 return $retval;
11070 }
11071  
11072  
11073 =head2 C<print_memory($label)>
11074  
11075 Checks /proc/$PID/statm and prints out a line to STDERR showing the
11076 current memory usage. This is a debugging tool that will likely fail
11077 to do anything useful on a system without a /proc system compatible
11078 with Linux.
11079  
11080 =head3 Arguments
11081  
11082 =over
11083  
11084 =item $label
11085  
11086 If defined, will be output along with the memory usage.
11087  
11088 =back
11089  
11090 Returns 1 on success, undef otherwise.
11091  
11092 =cut
11093  
11094 sub print_memory {
11095 my ($label) = @_;
11096 my $subname = ( caller(0) )[3];
11097 debug(2,"DEBUG[",$subname,"]");
11098  
11099 my @mem;
11100 my $fh_procstatm;
11101  
11102 if(!open($fh_procstatm,"<","/proc/$$/statm")) {
11103 print "[",$label,"]: " if(defined $label);
11104 print "Couldn't open /proc/$$/statm [$!]\n";
11105 return;
11106 }
11107  
11108 @mem = split(/\s+/,<$fh_procstatm>);
11109 close($fh_procstatm);
11110  
11111 # @mem[0]*4 = size (kb)
11112 # @mem[1]*4 = resident (kb)
11113 # @mem[2]*4 = shared (kb)
11114 # @mem[3] = trs
11115 # @mem[4] = lrs
11116 # @mem[5] = drs
11117 # @mem[6] = dt
11118  
11119 print "Current memory usage";
11120 print " [".$label."]" if(defined $label);
11121 print ": size=",$mem[0]*4,"k";
11122 print " resident=",$mem[1]*4,"k";
11123 print " shared=",$mem[2]*4,"k\n";
11124 return 1;
11125 }
11126  
11127  
11128  
11129 =head2 C<split_metadata($metahtmlfile, $metafile)>
11130  
11131 Takes a psuedo-HTML containing one or more <metadata>...</metadata>
11132 blocks and splits out the metadata blocks into an XML file ready to be
11133 used as an OPF document. The input HTML file is rewritten without the
11134 metadata.
11135  
11136 If $metafile (or the temporary HTML-only file created during the
11137 split) already exists, it will be moved to filename.backup.
11138  
11139 =head3 Arguments
11140  
11141 =over
11142  
11143 =item C<$metahtmlfile>
11144  
11145 The filename of the pseudo-HTML file
11146  
11147 =item C<$metafile> (optional)
11148  
11149 The filename to write out any extracted metadata. If not specified,
11150 will default to the basename of $metahtmlfile with '.opf' appended.
11151  
11152 =back
11153  
11154 Returns the filename the metadata was written to, or undef if no
11155 metadata was found.
11156  
11157 =cut
11158  
11159 sub split_metadata {
11160 my ($metahtmlfile,$metafile) = @_;
11161 my $subname = ( caller(0) )[3];
11162 debug(2,"DEBUG[",$subname,"]");
11163  
11164 croak($subname,"(): no input file specified")
11165 if(!$metahtmlfile);
11166  
11167 croak($subname,"(): input file has zero size")
11168 if(-z $metahtmlfile);
11169  
11170 my @metablocks;
11171 my @guideblocks;
11172 my $htmlfile;
11173  
11174 my ($filebase,$filedir,$fileext);
11175 my ($fh_metahtml,$fh_meta,$fh_html);
11176  
11177 ($filebase,$filedir,$fileext) = fileparse($metahtmlfile,'\.\w+$');
11178 $metafile = $filedir . $filebase . ".opf" if(!$metafile);
11179 $htmlfile = $filedir . $filebase . "-html.html";
11180  
11181 debug(2,"DEBUG: metahtml='",$metahtmlfile,"' meta='",$metafile,
11182 " html='",$htmlfile,"'");
11183  
11184 # Move existing output files to avoid overwriting them
11185 if(-f $metafile) {
11186 debug(3, "DEBUG: moving metafile '",$metafile,"'");
11187 croak ($subname,"(): output file '",$metafile,
11188 "' exists and could not be moved!")
11189 if(! rename($metafile,"$metafile.backup") );
11190 }
11191 if(-f $htmlfile) {
11192 debug(3, "DEBUG: moving htmlfile '",$htmlfile,"'");
11193 croak ($subname,"(): output file '",$htmlfile,
11194 "' exists and could not be moved!")
11195 if(! rename($htmlfile,"$metafile.backup") );
11196 }
11197  
11198 debug(2," splitting '",$metahtmlfile,"'");
11199 open($fh_metahtml,"<:raw",$metahtmlfile)
11200 or croak($subname,"(): Failed to open '",$metahtmlfile,"' for reading!");
11201 open($fh_meta,">:raw",$metafile)
11202 or croak($subname,"(): Failed to open '",$metafile,"' for writing!");
11203 open($fh_html,">:raw",$htmlfile)
11204 or croak($subname,"(): Failed to open '",$htmlfile,"' for writing!");
11205  
11206  
11207 # Preload the return value with the OPF headers
11208 print $fh_meta $utf8xmldec,$oeb12doctype,"<package>\n";
11209 #print $fh_meta $utf8xmldec,$opf20package;
11210  
11211 # Finding and removing all of the metadata requires that the
11212 # entire thing be handled as one slurped string, so temporarily
11213 # undefine the perl delimiter
11214 #
11215 # Since multiple <metadata> sections may be present, cannot use
11216 # </metadata> as a delimiter.
11217 local $/;
11218 while(<$fh_metahtml>) {
11219 s/\sfilepos=\d+//gix;
11220 (@metablocks) = m#(<metadata>.*</metadata>)#gisx;
11221 (@guideblocks) = m#(<guide>.*</guide>)#gisx;
11222 last unless(@metablocks || @guideblocks);
11223 print {*$fh_meta} @metablocks,"\n" if(@metablocks);
11224 print {*$fh_meta} @guideblocks,"\n" if(@guideblocks);
11225 s#<metadata>.*</metadata>##gisx;
11226 s#<guide>.*</guide>##gisx;
11227 print {*$fh_html} $_,"\n";
11228 }
11229 print $fh_meta "</package>\n";
11230  
11231 close($fh_html)
11232 or croak($subname,"(): Failed to close '",$htmlfile,"'!");
11233 close($fh_meta)
11234 or croak($subname,"(): Failed to close '",$metafile,"'!");
11235 close($fh_metahtml)
11236 or croak($subname,"(): Failed to close '",$metahtmlfile,"'!");
11237  
11238 if( (-z $htmlfile) && (-z $metafile) ) {
11239 croak($subname,"(): ended up with no text in any output file",
11240 " -- bailing out!");
11241 }
11242  
11243 # It is very unlikely that split_metadata will be called twice
11244 # from the same program, so undef all capture variables reclaim
11245 # the memory. Just going out of scope will not necessarily do
11246 # this.
11247 undef(@metablocks);
11248 undef(@guideblocks);
11249 undef($_);
11250  
11251 if(-z $htmlfile) {
11252 debug(1,"split_metadata(): HTML has zero size.",
11253 " Not replacing original.");
11254 unlink($htmlfile);
11255 }
11256 else {
11257 rename($htmlfile,$metahtmlfile)
11258 or croak("split_metadata(): Failed to rename ",$htmlfile,
11259 " to ",$metahtmlfile,"!\n");
11260 }
11261  
11262 if(-z $metafile) {
11263 croak($subname,
11264 "(): unable to remove empty output file '",$metafile,"'!")
11265 if(! unlink($metafile) );
11266 return;
11267 }
11268 return $metafile;
11269 }
11270  
11271  
11272 =head2 C<split_pre($htmlfile,$outfilebase)>
11273  
11274 Splits <pre>...</pre> blocks out of a source HTML file into their own
11275 separate HTML files including required headers. Each block will be
11276 written to its own file following the naming format
11277 C<$outfilebase-###.html>, where ### is a three-digit number beginning
11278 at 001 and incrementing for each block found. If C<$outfilebase> is
11279 not specified, it defaults to the basename of C<$htmlfile> with
11280 "-pre-###.html" appended. The
11281  
11282 Returns a list containing all filenames created.
11283  
11284 =cut
11285  
11286 sub split_pre {
11287 my ($htmlfile,$outfilebase) = @_;
11288 my $subname = ( caller(0) )[3];
11289 debug(2,"DEBUG[",$subname,"]");
11290  
11291 croak($subname,"(): no input file specified")
11292 if(!$htmlfile);
11293  
11294 my ($filebase,$filedir,$fileext);
11295 my ($fh_html,$fh_htmlout,$fh_pre);
11296 my $htmloutfile;
11297 my @preblocks;
11298 my @prefiles = ();
11299 my $prefile;
11300 my $count = 0;
11301  
11302 my $htmlheader = <<'END';
11303 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
11304 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
11305 <html>
11306 <head>
11307 <title></title>
11308 </head>
11309 <body>
11310 END
11311  
11312 ($filebase,$filedir,$fileext) = fileparse($htmlfile,'\.\w+$');
11313 $outfilebase = "$filebase-pre" if(!$outfilebase);
11314 $htmloutfile = "$filebase-nopre.html";
11315  
11316 open($fh_html,"<:raw",$htmlfile)
11317 or croak($subname,"(): Failed to open '",$htmlfile,"' for reading!");
11318 open($fh_htmlout,">:raw",$htmloutfile)
11319 or croak($subname,"(): Failed to open '",$htmloutfile,"' for writing!");
11320  
11321 local $/;
11322 while(<$fh_html>)
11323 {
11324 (@preblocks) = /(<pre>.*?<\/pre>)/gisx;
11325 last unless(@preblocks);
11326  
11327 foreach my $pre (@preblocks)
11328 {
11329 $count++;
11330 debug(1,"DEBUG: split_pre() splitting block ",
11331 sprintf("%03d",$count));
11332 $prefile = sprintf("%s-%03d.html",$outfilebase,$count);
11333 if(-f $prefile)
11334 {
11335 rename($prefile,"$prefile.backup")
11336 or croak("Unable to rename '",$prefile,
11337 "' to '",$prefile,".backup'");
11338 }
11339 open($fh_pre,">:raw",$prefile)
11340 or croak("Unable to open '",$prefile,"' for writing!");
11341 print {*$fh_pre} $utf8xmldec;
11342 print {*$fh_pre} $htmlheader,"\n";
11343 print {*$fh_pre} $pre,"\n";
11344 print {*$fh_pre} "</body>\n</html>\n";
11345 close($fh_pre) or croak("Unable to close '",$prefile,"'!");
11346 push @prefiles,$prefile;
11347 }
11348 s/(<pre>.*?<\/pre>)//gisx;
11349 print {*$fh_htmlout} $_,"\n";
11350 close($fh_htmlout)
11351 or croak($subname,"(): Failed to close '",$htmloutfile,"'!");
11352 rename($htmloutfile,$htmlfile)
11353 or croak($subname,"(): Failed to rename '",$htmloutfile,"' to '",
11354 $htmlfile,"'!");
11355 }
11356 return @prefiles;
11357 }
11358  
11359  
11360 =head2 C<strip_script(%args)>
11361  
11362 Strips any <script>...</script> blocks out of a HTML file.
11363  
11364 =head3 Arguments
11365  
11366 =over
11367  
11368 =item C<infile>
11369  
11370 Specifies the input file. If not specified, the sub croaks.
11371  
11372 =item C<outfile>
11373  
11374 Specifies the output file. If not specified, it defaults to C<infile>
11375 (i.e. the input file is overwritten).
11376  
11377 =item C<noscript>
11378  
11379 If set to true, the sub will strip <noscript>...</noscript> blocks as
11380 well.
11381  
11382 =back
11383  
11384 =cut
11385  
11386 sub strip_script {
11387 my %args = @_;
11388 my $subname = ( caller(0) )[3];
11389 debug(2,"DEBUG[",$subname,"]");
11390  
11391 croak($subname,"(): no input file specified")
11392 if(!$args{infile});
11393  
11394 my %valid_args = (
11395 'infile' => 1,
11396 'outfile' => 1,
11397 'noscript' => 1,
11398 );
11399 foreach my $arg (keys %args) {
11400 croak($subname,"(): invalid argument '",$arg,"'")
11401 if(!$valid_args{$arg});
11402 }
11403  
11404 my $infile = $args{infile};
11405 my $outfile = $args{outfile};
11406 $outfile = $infile unless($outfile);
11407  
11408 my ($fh_in,$fh_out);
11409 my $html;
11410 local $/;
11411  
11412 open($fh_in,"<:raw",$infile)
11413 or croak($subname,"(): Failed to open '",$infile,"' for reading!\n");
11414 $html = <$fh_in>;
11415 close($fh_in)
11416 or croak($subname,"(): Failed to close '",$infile,"'!\n");
11417  
11418 $html =~ s#<script>.*?</script>\n?##gix;
11419 $html =~ s#<noscript>.*?</noscript>\n?##gix
11420 if($args{noscript});
11421  
11422 open($fh_out,">:raw",$outfile)
11423 or croak($subname,"(): Failed to open '",$outfile,"' for writing!\n");
11424 print {*$fh_out} $html;
11425 close($fh_out)
11426 or croak($subname,"(): Failed to close '",$outfile,"'!\n");
11427  
11428 return 1;
11429 }
11430  
11431  
11432 =head2 C<system_result($caller,$retval,@syscmd)>
11433  
11434 Checks the result of a system call and croak on failure with an
11435 appropriate message. For this to work, it MUST be used as the line
11436 immediately following the system command.
11437  
11438 =head3 Arguments
11439  
11440 =over
11441  
11442 =item $caller
11443  
11444 The calling function (used in output message)
11445  
11446 =item $retval
11447  
11448 The return value of the system command
11449  
11450 =item @syscmd
11451  
11452 The array passed to the system call
11453  
11454 =back
11455  
11456 =head3 Return Values
11457  
11458 Returns 0 on success
11459  
11460 Croaks on failure.
11461  
11462 =cut
11463  
11464 sub system_result {
11465 my ($caller,$retval,@syscmd) = @_;
11466  
11467 if ( ($CHILD_ERROR >> 8) == 0 ) {
11468 return 0;
11469 }
11470 elsif ($CHILD_ERROR == -1) {
11471 croak($caller," child failed to execute (ERRNO=",$ERRNO,"):\n ",
11472 join(' ',@syscmd),"\n")
11473 }
11474 elsif ($CHILD_ERROR & 127) {
11475 my $withcoredump = ($CHILD_ERROR & 128) ? 'with' : 'without';
11476 croak($caller," child died with signal ",($CHILD_ERROR & 127)," ",
11477 $withcoredump," coredump:\n ",join(' ',@syscmd),"\n");
11478 }
11479 else {
11480 croak($caller," child exited with value ",$CHILD_ERROR >> 8,":\n ",
11481 join(' ',@syscmd),"\n")
11482 }
11483 }
11484  
11485  
11486 =head2 C<system_tidy_xhtml($infile,$outfile)>
11487  
11488 Runs tidy on a XHTML file semi-safely (using a secondary file)
11489  
11490 Converts HTML to XHTML if necessary
11491  
11492 =head3 Arguments
11493  
11494 =over
11495  
11496 =item $infile
11497  
11498 The filename to tidy
11499  
11500 =item $outfile
11501  
11502 The filename to use for tidy output if the safety condition to
11503 overwrite the input file isn't met.
11504  
11505 Defaults to C<infile-tidy.ext> if not specified.
11506  
11507 =back
11508  
11509 =head3 Global variables used
11510  
11511 =over
11512  
11513 =item $tidycmd
11514  
11515 the location of the tidy executable
11516  
11517 =item $tidyxhtmlerrors
11518  
11519 the filename to use to output errors
11520  
11521 =item $tidysafety
11522  
11523 the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)
11524  
11525 =back
11526  
11527 =head3 Return Values
11528  
11529 Returns the return value from tidy
11530  
11531 =over
11532  
11533 =item 0 - no errors
11534  
11535 =item 1 - warnings only
11536  
11537 =item 2 - errors
11538  
11539 =item Dies horribly if the return value is unexpected
11540  
11541 =back
11542  
11543 =cut
11544  
11545 sub system_tidy_xhtml {
11546 my ($infile,$outfile) = @_;
11547 my $retval;
11548  
11549 croak("system_tidy_xhtml called with no input file") if(!$infile);
11550 if(!$outfile)
11551 {
11552 my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
11553 $outfile = $filebase . "-tidy" . $fileext;
11554 }
11555 croak("system_tidy_xhtml called with no output file") if(!$outfile);
11556  
11557 $retval = system($tidycmd,
11558 '-q','-utf8','--tidy-mark','no',
11559 '--wrap','0',
11560 '--clean','yes',
11561 '-asxhtml',
11562 '--output-xhtml','yes',
11563 '--add-xml-decl','yes',
11564 '--doctype','auto',
11565 '-f',$tidyxhtmlerrors,
11566 '-o',$outfile,
11567 $infile);
11568  
11569 # Some systems may return a two-byte code, so deal with that first
11570 if($retval >= 256) { $retval = $retval >> 8 };
11571 if($retval == 0)
11572 {
11573 rename($outfile,$infile) if($tidysafety < 4);
11574 unlink($tidyxhtmlerrors);
11575 }
11576 elsif($retval == 1)
11577 {
11578 rename($outfile,$infile) if($tidysafety < 3);
11579 unlink($tidyxhtmlerrors) if($tidysafety < 2);
11580 }
11581 elsif($retval == 2)
11582 {
11583 print {*STDERR} "WARNING: Tidy errors encountered. Check ",$tidyxhtmlerrors,"\n"
11584 if($tidysafety > 0);
11585 unlink($tidyxhtmlerrors) if($tidysafety < 1);
11586 }
11587 else
11588 {
11589 # Something unexpected happened (program crash, sigint, other)
11590 croak("Tidy did something unexpected (return value=",$retval,
11591 "). Check all output.");
11592 }
11593 return $retval;
11594 }
11595  
11596  
11597 =head2 C<system_tidy_xml($infile,$outfile)>
11598  
11599 Runs tidy on an XML file semi-safely (using a secondary file)
11600  
11601 =head3 Arguments
11602  
11603 =over
11604  
11605 =item C<$infile>
11606  
11607 The filename to tidy
11608  
11609 =item C<$outfile> (optional)
11610  
11611 The filename to use for tidy output if the safety condition to
11612 overwrite the input file isn't met.
11613  
11614 Defaults to C<infile-tidy.ext> if not specified.
11615  
11616 =back
11617  
11618 =head3 Global variables used
11619  
11620 =over
11621  
11622 =item C<$tidycmd>
11623  
11624 the name of the tidy executable
11625  
11626 =item C<$tidyxmlerrors>
11627  
11628 the filename to use to output errors
11629  
11630 =item C<$tidysafety>
11631  
11632 the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)
11633  
11634 =back
11635  
11636 =head3 Return values
11637  
11638 Returns the return value from tidy
11639  
11640 =over
11641  
11642 =item 0 - no errors
11643  
11644 =item 1 - warnings only
11645  
11646 =item 2 - errors
11647  
11648 =item Dies horribly if the return value is unexpected
11649  
11650 =back
11651  
11652 =cut
11653  
11654 sub system_tidy_xml {
11655 my ($infile,$outfile) = @_;
11656 my $retval;
11657  
11658 croak("system_tidy_xml called with no input file") if(!$infile);
11659  
11660 if (!$outfile) {
11661 my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
11662 $outfile = $filebase . "-tidy" . $fileext;
11663 }
11664 croak("system_tidy_xml called with no output file") if(!$outfile);
11665  
11666 $retval = system($tidycmd,
11667 '-q','-utf8','--tidy-mark','no',
11668 '--wrap','0',
11669 '-xml',
11670 '--add-xml-decl','yes',
11671 '-f',$tidyxmlerrors,
11672 '-o',$outfile,
11673 $infile);
11674  
11675 # Some systems may return a two-byte code, so deal with that first
11676 if ($retval >= 256) {
11677 $retval = $retval >> 8;
11678 }
11679 ;
11680 if ($retval == 0) {
11681 rename($outfile,$infile) if($tidysafety < 4);
11682 unlink($tidyxmlerrors);
11683 }
11684 elsif ($retval == 1) {
11685 rename($outfile,$infile) if($tidysafety < 3);
11686 unlink($tidyxmlerrors) if($tidysafety < 2);
11687 }
11688 elsif ($retval == 2) {
11689 print STDERR "WARNING: Tidy errors encountered. Check ",$tidyxmlerrors,"\n"
11690 if ($tidysafety > 0);
11691 unlink($tidyxmlerrors) if($tidysafety < 1);
11692 }
11693 else {
11694 # Something unexpected happened (program crash, sigint, other)
11695 croak("Tidy did something unexpected (return value=",$retval,
11696 "). Check all output.");
11697 }
11698 return $retval;
11699 }
11700  
11701  
11702 =head2 C<trim>
11703  
11704 Removes any whitespace characters from the beginning or end of every
11705 string in @list (also works on scalars).
11706  
11707 trim; # trims $_ inplace
11708 $new = trim; # trims (and returns) a copy of $_
11709 trim $str; # trims $str inplace
11710 $new = trim $str; # trims (and returns) a copy of $str
11711 trim @list; # trims @list inplace
11712 @new = trim @list; # trims (and returns) a copy of @list
11713  
11714 This was shamelessly copied from japhy's example at perlmonks.org:
11715  
11716 http://www.perlmonks.org/?node_id=36684
11717  
11718 If needed for large lists, it would probably be better to use
11719 String::Strip.
11720  
11721 =cut
11722  
11723 sub trim { ## no critic
11724 ## no critic
11725 # PerlCritic is turned off here, as this is unusual code
11726 # deliberately bending rules.
11727 @_ = $_ if not @_ and defined wantarray;
11728 @_ = @_ if defined wantarray;
11729 for ( @_ ? @_ : $_ ) { s/^\s+//, s/\s+$// }
11730 return wantarray ? @_ : $_[ 0 ] if defined wantarray;
11731 }
11732  
11733  
11734 =head2 C<twigelt_create_uuid($gi)>
11735  
11736 Creates an unlinked element with the specified gi (tag), and then
11737 assigns it the id and scheme attributes 'UUID'.
11738  
11739 =head3 Arguments
11740  
11741 =over
11742  
11743 =item $gi : The gi (tag) to use for the element
11744  
11745 Default: 'dc:identifier'
11746  
11747 =back
11748  
11749 Returns the element.
11750  
11751 =cut
11752  
11753 sub twigelt_create_uuid {
11754 my ($gi) = @_;
11755 my $subname = ( caller(0) )[3];
11756 debug(2,"DEBUG[",$subname,"]");
11757 my $element;
11758  
11759 if(!$gi) { $gi = 'dc:identifier'; }
11760  
11761 my $uuidgen = Data::UUID->new();
11762 $element = XML::Twig::Elt->new($gi);
11763 $element->set_id('UUID');
11764 $element->set_att('scheme' => 'UUID');
11765 $element->set_text($uuidgen->create_str());
11766 return $element;
11767 }
11768  
11769  
11770 =head2 C<twigelt_detect_duplicate($element1, $element2)>
11771  
11772 Takes two twig elements and returns 1 if they have the same GI (tag),
11773 text, and attributes, but are not actually the same element. The GI
11774 comparison is case-insensitive. The others are case-sensitive.
11775  
11776 Returns 0 otherwise.
11777  
11778 Croaks if passed anything but twig elements.
11779  
11780 =cut
11781  
11782 sub twigelt_detect_duplicate {
11783 my ($element1,$element2) = @_;
11784 my $subname = ( caller(0) )[3];
11785 debug(3,"DEBUG[",$subname,"]");
11786  
11787 croak($subname,"(): arguments must be XML::Twig::Elt objects")
11788 unless( $element1->isa('XML::Twig::Elt')
11789 && $element2->isa('XML::Twig::Elt') );
11790  
11791 my (%atts1, %atts2);
11792  
11793 unless($element1->cmp($element2)) {
11794 debug(3," both elements have the same position");
11795 return 0;
11796 }
11797  
11798 unless( lc($element1->gi) eq lc($element2->gi) ) {
11799 debug(3," elements have different GIs");
11800 return 0;
11801 }
11802  
11803 unless($element1->text eq $element2->text) {
11804 debug(3," elements have different text");
11805 return 0;
11806 }
11807  
11808 %atts1 = %{$element1->atts};
11809 %atts2 = %{$element2->atts};
11810  
11811 my $attkeys1 = join('',sort keys %atts1);
11812 my $attkeys2 = join('',sort keys %atts2);
11813  
11814 unless($attkeys1 eq $attkeys2) {
11815 debug(3," elements have different attributes");
11816 return 0;
11817 }
11818  
11819 foreach my $att (keys %atts1) {
11820 unless($element1->att($att) eq $element2->att($att)) {
11821 debug(3," elements have different values for attribute '",
11822 $att,"'");
11823 return 0;
11824 }
11825 }
11826 debug(3," elements are duplicates of each other!");
11827 return 1;
11828 }
11829  
11830 =head2 C<twigelt_fix_oeb12_atts($element)>
11831  
11832 Checks the attributes in a twig element to see if they match OPF names
11833 with an opf: namespace, and if so, removes the namespace. Used by the
11834 fix_oeb12() method.
11835  
11836 Takes as a sole argument a twig element.
11837  
11838 Returns that element with the modified attributes, or undef if the
11839 element didn't exist. Returns an unmodified element if both att and
11840 opf:att exist.
11841  
11842 =cut
11843  
11844 sub twigelt_fix_oeb12_atts {
11845 my ($element) = @_;
11846 return unless($element);
11847 my $subname = ( caller(0) )[3];
11848 debug(3,"DEBUG[",$subname,"]");
11849  
11850 my %opfatts_no_ns = (
11851 "opf:role" => "role",
11852 "opf:file-as" => "file-as",
11853 "opf:scheme" => "scheme",
11854 "opf:event" => "event"
11855 );
11856  
11857 foreach my $att ($element->att_names)
11858 {
11859 debug(3,"DEBUG: checking attribute '",$att,"'");
11860 if($opfatts_no_ns{$att})
11861 {
11862 # If the opf:att attribute properly exists already, do nothing.
11863 if($element->att($opfatts_no_ns{$att}))
11864 {
11865 debug(1,"DEBUG: found both '",$att,"' and '",
11866 $opfatts_no_ns{$att},"' -- skipping.");
11867 next;
11868 }
11869 debug(1,"DEBUG: changing attribute '",$att,"' => '",
11870 $opfatts_no_ns{$att},"'");
11871 $element->change_att_name($att,$opfatts_no_ns{$att});
11872 }
11873 }
11874 return $element;
11875 }
11876  
11877  
11878 =head2 C<twigelt_fix_opf20_atts($element)>
11879  
11880 Checks the attributes in a twig element to see if they match OPF
11881 names, and if so, prepends the OPF namespace. Used by the fix_opf20()
11882 method.
11883  
11884 Takes as a sole argument a twig element.
11885  
11886 Returns that element with the modified attributes, or undef if the
11887 element didn't exist.
11888  
11889 =cut
11890  
11891 sub twigelt_fix_opf20_atts {
11892 my ($element) = @_;
11893 return unless($element);
11894 my $subname = ( caller(0) )[3];
11895 debug(3,"DEBUG[",$subname,"]");
11896  
11897 my %opfatts_ns = (
11898 "role" => "opf:role",
11899 "file-as" => "opf:file-as",
11900 "scheme" => "opf:scheme",
11901 "event" => "opf:event"
11902 );
11903  
11904 foreach my $att ($element->att_names)
11905 {
11906 debug(2,"DEBUG: checking attribute '",$att,"'");
11907 if($opfatts_ns{$att})
11908 {
11909 # If the opf:att attribute properly exists already, do nothing.
11910 if($element->att($opfatts_ns{$att}))
11911 {
11912 debug(1,"DEBUG: found both '",$att,"' and '",
11913 $opfatts_ns{$att},"' -- skipping.");
11914 next;
11915 }
11916 debug(1,"DEBUG: changing attribute '",$att,"' => '",
11917 $opfatts_ns{$att},"'");
11918 $element->change_att_name($att,$opfatts_ns{$att});
11919 }
11920 }
11921 return $element;
11922 }
11923  
11924  
11925 =head2 C<twigelt_is_author($element)>
11926  
11927 Takes as an argument a twig element. Returns true if the element is a
11928 dc:creator (case-insensitive) with either a opf:role="aut" or
11929 role="aut" attribute defined. Returns undef otherwise, and also if
11930 the element has no text.
11931  
11932 Croaks if fed no argument, or fed an argument that isn't a twig
11933 element.
11934  
11935 Intended to be used as a twig search condition.
11936  
11937 =head3 Example
11938  
11939 my @elements = $ebook->twigroot->descendants(\&twigelt_is_author);
11940  
11941 =cut
11942  
11943 sub twigelt_is_author {
11944 my ($element) = @_;
11945 my $subname = ( caller(0) )[3];
11946 debug(3,"DEBUG[",$subname,"]");
11947  
11948 croak($subname,"(): no element provided") unless($element);
11949  
11950 my $ref = ref($element) || '';
11951  
11952 croak($subname,"(): argument was of type '",$ref,
11953 "', needs to be 'XML::Twig::Elt' or a subclass")
11954 unless($element->isa('XML::Twig::Elt'));
11955  
11956 return if( (lc $element->gi) ne 'dc:creator');
11957 return unless($element->text);
11958  
11959 my $role = $element->att('opf:role') || $element->att('role');
11960 return unless($role);
11961  
11962 return 1 if($role eq 'aut');
11963 return;
11964 }
11965  
11966  
11967 =head2 C<twigelt_is_isbn($element)>
11968  
11969 Takes as an argument a twig element. Returns true if the element is a
11970 dc:identifier (case-insensitive) where any of the id, opf:scheme, or
11971 scheme attributes start with 'isbn', '-isbn', 'eisbn', or 'e-isbn'
11972 (again case-insensitive).
11973  
11974 Returns undef otherwise, and also if the element has no text.
11975  
11976 Croaks if fed no argument, or fed an argument that isn't a twig
11977 element.
11978  
11979 Intended to be used as a twig search condition.
11980  
11981 =head3 Example
11982  
11983 my @elements = $ebook->twigroot->descendants(\&twigelt_is_isbn);
11984  
11985 =cut
11986  
11987 sub twigelt_is_isbn {
11988 my ($element) = @_;
11989 my $subname = ( caller(0) )[3];
11990 debug(3,"DEBUG[",$subname,"]");
11991  
11992 croak($subname,"(): no element provided") unless($element);
11993  
11994 my $ref = ref($element) || '';
11995 my $id;
11996 my $scheme;
11997  
11998 croak($subname,"(): argument was of type '",$ref,
11999 "', needs to be 'XML::Twig::Elt' or a subclass")
12000 unless($element->isa('XML::Twig::Elt'));
12001  
12002 return if( (lc $element->gi) ne 'dc:identifier');
12003 return unless($element->text);
12004  
12005 $id = $element->id || '';
12006 return 1 if($id =~ /^e?-?isbn/ix);
12007  
12008 $scheme = $element->att('opf:scheme') || '';
12009 return 1 if($scheme =~ /^e?-?isbn/ix);
12010 $scheme = $element->att('scheme') || '';
12011 return 1 if($scheme =~ /^e?-?isbn/ix);
12012 return;
12013 }
12014  
12015  
12016 =head2 C<twigelt_is_knownuid($element)>
12017  
12018 Takes as an argument a twig element. Returns true if the element is a
12019 dc:identifier (case-insensitive) element with an C<id> attribute
12020 matching the known IDs of proper unique identifiers suitable for a
12021 package-id (also case-insensitive). Returns undef otherwise.
12022  
12023 Croaks if fed no argument, or fed an argument that isn't a twig element.
12024  
12025 Intended to be used as a twig search condition.
12026  
12027 =head3 Example
12028  
12029 my @elements = $ebook->twigroot->descendants(\&twigelt_is_knownuid);
12030  
12031 =cut
12032  
12033 sub twigelt_is_knownuid {
12034 my ($element) = @_;
12035 my $subname = ( caller(0) )[3];
12036 debug(3,"DEBUG[",$subname,"]");
12037  
12038 croak($subname,"(): no element provided") unless($element);
12039  
12040 my $ref = ref($element) || '';
12041  
12042 croak($subname,"(): argument was of type '",$ref,
12043 "', needs to be 'XML::Twig::Elt' or a subclass")
12044 unless($element->isa('XML::Twig::Elt'));
12045  
12046 return if( (lc $element->gi) ne 'dc:identifier');
12047 my $id = $element->id;
12048 return unless($id);
12049  
12050 my %knownuids = (
12051 'package-id' => 56,
12052 'overdriveguid' => 48,
12053 'guid' => 40,
12054 'uuid' => 32,
12055 'uid' => 24,
12056 'calibre_id' => 16,
12057 'fwid' => 8,
12058 );
12059  
12060 if($knownuids{lc $id})
12061 {
12062 # debug(2,"DEBUG: '",$element->gi,"' has known UID '",$id,"'");
12063 return 1;
12064 }
12065 return;
12066 }
12067  
12068  
12069 =head2 C<usedir($dir)>
12070  
12071 Changes the current working directory to the one specified, creating
12072 it if necessary.
12073  
12074 Returns the current working directory before the change. If no
12075 directory is specified, returns the current working directory without
12076 changing anything.
12077  
12078 Croaks on any failure.
12079  
12080 =cut
12081  
12082 sub usedir {
12083 my ($dir) = @_;
12084 my $subname = ( caller(0) )[3];
12085 debug(2,"DEBUG[",$subname,"]: $dir");
12086  
12087 my $cwd = getcwd();
12088 return $cwd unless($dir);
12089  
12090 unless(-d $dir) {
12091 debug(2," Creating directory '",$dir,"'");
12092 mkpath($dir)
12093 or croak("Unable to create output directory '",$dir,"'!\n");
12094 }
12095 chdir($dir)
12096 or croak("Unable to change working directory to '",$dir,"'!\n");
12097 return $cwd;
12098 }
12099  
12100  
12101 =head2 C<userconfigdir()>
12102  
12103 Returns the directory in which user configuration files and helper
12104 programs are expected to be found, creating that directory if it does
12105 not exist. Typically, this directory is C<"$ENV{HOME}/.ebooktools">,
12106 but on MSWin32 systems if that directory does not already exist,
12107 C<"$ENV{USERPROFILE}/ApplicationData/EBook-Tools"> is returned (and
12108 potentially created) instead.
12109  
12110 If C<$ENV{HOME}> (and C<$ENV{USERPROFILE}> on MSWin32) are not set, the
12111 sub returns undef.
12112  
12113 =cut
12114  
12115 sub userconfigdir {
12116 my $subname = ( caller(0) )[3];
12117 debug(3,"DEBUG[",$subname,"]");
12118  
12119 my $dir;
12120 $dir = $ENV{HOME} . '/.ebooktools' if($ENV{HOME});
12121 if($OSNAME eq 'MSWin32') {
12122 if(! -d $dir) {
12123 $dir = $ENV{USERPROFILE} . '\Application Data\EBook-Tools'
12124 if($ENV{USERPROFILE});
12125 }
12126 }
12127 if($dir) {
12128 if(! -d $dir) {
12129 mkpath($dir)
12130 or croak($subname,
12131 "(): unable to create configuration directory '",
12132 $dir,"'!\n");
12133 }
12134 return $dir;
12135 }
12136 else { return; }
12137 }
12138  
12139  
12140 =head2 C<ymd_validate($year,$month,$day)>
12141  
12142 Make sure month and day have valid values. Return the passed values
12143 if they are, return 3 undefs if not. Testing of month or day can be
12144 skipped by passing undef in that spot.
12145  
12146 =cut
12147  
12148 sub ymd_validate {
12149 my ($year,$month,$day) = @_;
12150  
12151 return (undef,undef,undef) unless($year);
12152  
12153 if($month) {
12154 return (undef,undef,undef) if($month > 12);
12155 if($day) {
12156 if(!eval { timelocal(0,0,0,$day,$month-1,$year); }) {
12157 debug(1,"DEBUG: timelocal validation failed for year=",
12158 $year," month=",$month," day=",$day);
12159 return (undef,undef,undef);
12160 }
12161 }
12162 return ($year,$month,$day);
12163 }
12164  
12165 # We don't have a month. If we *do* have a day, the result is
12166 # broken, so send back the undefs.
12167 return (undef,undef,undef) if($day);
12168 return ($year,undef,undef);
12169 }
12170  
12171  
12172 ########## END CODE ##########
12173  
12174 =head1 BUGS AND LIMITATIONS
12175  
12176 =over
12177  
12178 =item * fix_links() could be improved to download remote URIs instead
12179 of ignoring them.
12180  
12181 =item * fix_links() needs to check the <reference> links under <guide>
12182  
12183 =item * fix_links() needs to be redone with HTML::TreeBuilder or
12184 Mojo::DOM to avoid the weakness with newlines between attribute names
12185 and values
12186  
12187 =item * Need to implement fix_tours() that should collect the related
12188 elements and delete the parent if none are found. Empty <tours>
12189 elements aren't allowed.
12190  
12191 =item * fix_languages() needs to convert language names into IANA
12192 language codes.
12193  
12194 =item * set_language() should add a warning if the text isn't a valid
12195 IANA language code.
12196  
12197 =item * NCX generation only generates from the spine. It should be
12198 possible to use a TOC html file for generation instead. In the long
12199 term, it should be possible to generate one from the headers and
12200 anchors in arbitrary HTML files.
12201  
12202 =item * It might be better to use sysread / index / substr / syswrite in
12203 &split_metadata to handle the split in 10k chunks, to avoid massive
12204 memory usage on large files.
12205  
12206 This may not be worth the effort, since the average size for most
12207 books is less than 500k, and the largest books are rarely over 10M.
12208  
12209 =item * The only generator is currently for .epub books. PDF,
12210 PalmDoc, Mobipocket, Plucker, and iSiloX are eventually planned.
12211  
12212 =item * Although I like keeping warnings associated with the ebook
12213 object, it may be better to throw exceptions on errors and catch them
12214 later. This probably won't be implemented until it bites someone who
12215 complains, though.
12216  
12217 =item * Unit tests are incomplete
12218  
12219 =back
12220  
12221 =head1 AUTHOR
12222  
12223 Zed Pobre <zed@debian.org>
12224  
12225 =head1 LICENSE AND COPYRIGHT
12226  
12227 Copyright 2008-2013 Zed Pobre
12228  
12229 Licensed to the public under the terms of the GNU GPL, version 2
12230  
12231 =cut
12232  
12233 1;
« blib/lib/EBook/Tools/Unpack.pm ↑ Summary