5b5d572fc0e273333b4e548007b6b66e6f854423
[project-aon.git] / common / scripts / gbtoepub.pl
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use File::Path qw(mkpath);
7
8 my $PROGRAM_NAME    = 'gbtoepub';
9 my $USAGE           = "$PROGRAM_NAME [options] book-code\n\t--meta=[metadata file]\n\t--xml=[book XML]\n\t--epub-xsl=[XSL transformation]\n\t--language=[language area of input data (output determined by meta file)]\n\t--font-files=[font-files]\n\t--no-validate\n\t--verbose\n";
10
11 my $FILENAME_SEPARATOR = '/';
12
13 my $RXP        = '/usr/bin/rxp';
14 my $CP         = '/bin/cp';
15 my $MV         = '/bin/mv';
16 my $TAR        = '/bin/tar';
17 my $ZIP        = '/usr/bin/zip';
18 my $BZIP2      = '/bin/bzip2';
19 my $JAVA       = '/usr/bin/java';
20 my $XALAN_JAR  = '/usr/share/java/xalan2.jar';
21 my $RM         = '/bin/rm';
22 my $CHMOD      = '/bin/chmod';
23
24 ###
25
26 my $EPUB_MIMETYPE  = 'application/epub+zip';
27 my $MIMETYPE_FILE  = 'mimetype';
28 my $CONTAINER_FILE = 'container.xml';
29 my $OEBPS_DIR      = 'OEBPS';
30 my $META_INF_DIR   = 'META-INF';
31 my $NCX_FILE       = 'toc.ncx';
32 my $XHTML_EXT      = 'html';
33
34 my $PROJECT_AON_URI = 'http://www.projectaon.org';
35
36
37 ###
38
39 my $bookCode     = '';
40 my $metaFile     = '';
41 my $bookXML      = '';
42 my $ncxXSL       = 'common/xsl/epub-ncx.xsl';
43 my $epubXSL      = 'common/xsl/epub-xhtml.xsl';
44 my $metadataXSL  = 'common/xsl/epub-opf-metadata.xsl';
45 my $spineXSL     = 'common/xsl/epub-opf-spine.xsl';
46 my $coverXSL     = 'common/xsl/epub-coverpage.xsl';
47 my $fontFiles    = "$ENV{'HOME'}${FILENAME_SEPARATOR}souvenir";
48 my $language     = 'en';
49
50 my $verbose = 0;
51 my $noValidate = 0;
52
53 ### read command line options
54
55 while( $#ARGV > -1 ) {
56     my $cmdLineItem = shift @ARGV;
57     if( $cmdLineItem =~ /^--meta=(.+)$/ ) {
58         $metaFile = $1;
59     }
60     elsif( $cmdLineItem =~ /^--xml=(.+)$/ ) {
61         $bookXML = $1;
62     }
63     elsif( $cmdLineItem =~ /^--epub-xsl=(.+)$/ ) {
64         $epubXSL = $1;
65     }
66     elsif( $cmdLineItem =~ /^--language=(.+)$/ ) {
67         $language = $1;
68     }
69     elsif( $cmdLineItem =~ /^--verbose/ ) {
70         $verbose = 1;
71     }
72     elsif( $cmdLineItem =~ /^--no-validate/ ) {
73         $noValidate = 1;
74     }
75     elsif( $cmdLineItem =~ /^--font-files=(.+)$/ ) {
76         $fontFiles = $1;
77     }
78     else { 
79         $bookCode = $cmdLineItem;
80     }
81 }
82
83 if( $bookCode eq '' ) { 
84     die "$PROGRAM_NAME: Unspecified book code\n$USAGE";
85 }
86 if( $metaFile eq '' ) { $metaFile = "$language/.publisher/rules/epub"; }
87 if( $bookXML eq '' ) { $bookXML = "$language/xml/$bookCode.xml"; }
88 if( $epubXSL eq '' ) {
89     die "$PROGRAM_NAME: Unspecified XSL transformation file\n$USAGE";
90 }
91
92 ### validate book XML
93
94 if( (not $noValidate) && -e $RXP ) {
95     system( $RXP, '-Vs', $bookXML ) == 0
96         or die "$PROGRAM_NAME: XML validation failed\n";
97 }
98 elsif( $noValidate ) {
99     warn "$PROGRAM_NAME: XML validation skipped - validate before publication\n";
100 }
101 else {
102     warn "$PROGRAM_NAME: XML validator not installed - validate before publication\n";
103 }
104
105 ### read in metadata file
106
107 unless( -e $metaFile && -f $metaFile && -r $metaFile ) {
108     die qq{$PROGRAM_NAME: Improper metadata file "$metaFile"\n};
109 }
110
111 open( META, '<', $metaFile ) or 
112     die qq{$PROGRAM_NAME: Unable to open metadata file "$metaFile": $!\n};
113
114 my $meta = '';
115 while( my $line = <META> ) {
116     $meta .= $line if $line !~ /^[[:space:]]*#/;
117 }
118 close META;
119
120 ### interpret rules from metadata
121 my $rulesString = '';
122 if( $meta =~ /^[[:space:]]*$bookCode[[:space:]]*{([^}]*)}/sm ) {
123     $rulesString = $1;
124 }
125 else {
126     die "$PROGRAM_NAME: Book code ($bookCode) not found in metadata file or invalid file syntax\n";
127 }
128
129 my @rules = split( /[[:space:]\n]*;[[:space:]\n]*/, $rulesString );
130 my %rulesHash;
131 foreach my $rule (@rules) {
132     if( $rule =~ /[[:space:]]*([^:]+)[[:space:]]*:[[:space:]]*(.+)$/s ) {
133         $rulesHash{ $1 } = $2;
134     }
135     else {
136         die "$PROGRAM_NAME: Unrecognized rule syntax:\n$rule\n";
137     }
138 }
139
140 unless( defined $rulesHash{'book-series'} ) {
141     die "$PROGRAM_NAME: no book series set\n";
142 }
143 unless( defined $rulesHash{'csst'} ) {
144     die "$PROGRAM_NAME: metadata file leaves CSS templates unspecified\n";
145 }
146
147 my $SERIES = get_series($rulesHash{'book-series'}) ;
148 my $SERIES_NUMBER = get_series_number($bookCode);
149
150
151 ### create output directories
152
153 my %outPath;
154 $outPath{'top'} = $rulesHash{'language'} . $FILENAME_SEPARATOR .
155                      'epub' . $FILENAME_SEPARATOR .
156                      $rulesHash{'book-series'} . $FILENAME_SEPARATOR .
157                      $bookCode;
158 # clear old files
159 if( -e "$outPath{'top'}$FILENAME_SEPARATOR$MIMETYPE_FILE" ) {
160     print qx{$RM -r $outPath{'top'}$FILENAME_SEPARATOR*};
161 }
162
163 $outPath{'meta-inf'} = $outPath{'top'} . $FILENAME_SEPARATOR . $META_INF_DIR;
164 $outPath{'oebps'} = $outPath{'top'} . $FILENAME_SEPARATOR . $OEBPS_DIR;
165
166 foreach my $directory (keys(%outPath)) {
167     unless( -e $outPath{$directory} && -d $outPath{$directory} ) {
168         mkpath $outPath{$directory}
169             or die "$PROGRAM_NAME: Unknown error creating output directory " .
170                    "\"$outPath{$directory}\"\n";
171     }
172 }
173
174 ### create content files
175
176 # the location of this tempfile also controls where the xhtml will go
177 my $tempFile = "$outPath{'oebps'}${FILENAME_SEPARATOR}foo.xml";
178 print qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$epubXSL" -OUT "$tempFile" -PARAM xhtml-ext ".$XHTML_EXT" -PARAM use-illustrators "$rulesHash{'use-illustrators'}" -PARAM language "$rulesHash{'language'}"}; #" <- comment to unconfuse VIM syntax hilighting (ugh)
179 print qx{$RM $tempFile};
180
181 foreach my $imagePath (split( /:/, $rulesHash{'images'} )) {
182     unless( -e $imagePath && -d $imagePath ) {
183     die "$PROGRAM_NAME: Image path ($imagePath) does not exist or is not a directory\n";
184 }
185     print qx{$CP $imagePath${FILENAME_SEPARATOR}* $outPath{'oebps'}};
186 }
187
188 ### create the CSS stylsheet
189
190 foreach my $cssTemplate (split( /:/, $rulesHash{'csst'} )) {
191     $cssTemplate =~ m/([^${FILENAME_SEPARATOR}]+)t$/;
192     my $templateFile = $1;
193     open( TEMPLATE, '<', $cssTemplate ) 
194         or die "$PROGRAM_NAME: Unable to open CSS template file ($cssTemplate): $!\n";
195
196     my $stylesFile = "$outPath{'oebps'}$FILENAME_SEPARATOR$templateFile";
197     open( STYLESHEET, '>', $stylesFile ) 
198         or die "$PROGRAM_NAME: Unable to open stylesheet file ($stylesFile) for writing: $!\n";
199
200     while( my $templateLine = <TEMPLATE> ) {
201         while( $templateLine =~ /%%([^%[:space:]]+)%%/ ) {
202             my $name = $1;
203             $templateLine =~ s/%%${name}%%/$rulesHash{$name}/g;
204         }
205         print STYLESHEET $templateLine;
206     }
207     close STYLESHEET;
208     close TEMPLATE;
209 }
210
211 ### copy the font files
212
213 unless( -e $fontFiles && -d $fontFiles ) {
214     die "$PROGRAM_NAME: font files directory does not exist or is not a directory \"$fontFiles\": $!\n";
215 }
216 print qx{$CP $fontFiles${FILENAME_SEPARATOR}*.otf $outPath{'oebps'}};
217
218 ### write NCX file
219
220 my $uniqueID = "opf-$bookCode";
221 my $bookUniqueURI = "$PROJECT_AON_URI/$language/epub/" .
222                     "$rulesHash{'book-series'}/$bookCode/";
223
224 my $ncxFile = $outPath{'oebps'} . $FILENAME_SEPARATOR . $NCX_FILE;
225 open( NCXFILE, '>', $ncxFile ) or
226     die "$PROGRAM_NAME: unable to open NCX file for writing " .
227         "\"$ncxFile\"\n";
228 print NCXFILE qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$ncxXSL" -PARAM xhtml-ext ".$XHTML_EXT" -PARAM unique-identifier "$bookUniqueURI" -PARAM language "$rulesHash{'language'}"}; #" comment to unconfuse VIM syntax highlighting
229 close NCXFILE;
230
231 ### write mimetype file
232
233 my $mimeFile = $outPath{'top'} . $FILENAME_SEPARATOR . $MIMETYPE_FILE;
234 open( MIMETYPE, '>', $mimeFile ) or
235     die "$PROGRAM_NAME: unable to open mimetype file for writing " .
236         "\"$mimeFile\"\n";
237 print MIMETYPE $EPUB_MIMETYPE;
238 close MIMETYPE;
239
240
241 ## write coverpage 
242
243 # Generate the cover image. This can be done in two ways:
244 # 1.- A file is available under the directory of JPEG files for the book
245 # 2.- A file is generated using imagemagick
246
247 # Cover filename
248 my $coverImage = $outPath{'oebps'} . $FILENAME_SEPARATOR . "cover.jpg"; 
249 # Cover filename generated by Project Aon
250 my $pa_coverImage = $rulesHash{'language'} . $FILENAME_SEPARATOR . "jpeg" . $FILENAME_SEPARATOR .$rulesHash{'book-series'}. $FILENAME_SEPARATOR .$bookCode . $FILENAME_SEPARATOR . "cover.jpg";
251
252 if ( -e  "$pa_coverImage") {
253     # Copy the file here
254     print STDERR "DEBUG: Using cover from $pa_coverImage\n" if $verbose;
255     system "cp $pa_coverImage $coverImage";
256 } else {
257
258 # Use Imagemagick if available
259     if ( -x "/usr/bin/convert" ) {
260
261         print STDERR "DEBUG: Will generate cover with ImageMagick\n" if $verbose;
262         my $TITLE = quote_shell(find_title($bookXML));
263         my $AUTHOR = quote_shell(find_author($bookXML));
264         my $ILLUSTRATOR = quote_shell(find_illustrator($bookXML));
265         my $convert_cmd = "";
266
267         if ( -e "$fontFiles/SouvenirStd-Demi.otf" && -e "$fontFiles/SouvenirStd-Light.otf" ) { 
268             $convert_cmd="convert -size 600x800 -background white  -font $fontFiles/SouvenirStd-Demi.otf -pointsize 32 -fill '#006633' -gravity north caption:\"\" -annotate +0+218 \"$TITLE\"  -font $fontFiles/SouvenirStd-Light.otf -pointsize 22 -fill black -annotate +0+304 '$AUTHOR' -annotate +0+333 '$ILLUSTRATOR' $coverImage"
269         } else {
270             print STDERR "WARN: Fontfiles not found, using standard font\n";
271             $convert_cmd="convert -size 600x800 -background white -pointsize 32 -fill '#006633' -gravity north caption:\"\" -annotate +0+218 \"$TITLE\"  -pointsize 22 -fill black -annotate +0+304 '$AUTHOR' -annotate +0+333 '$ILLUSTRATOR' $coverImage";
272         }
273
274         print STDERR "DEBUG: Will run '$convert_cmd'\n" if $verbose;
275         system $convert_cmd;
276     }
277 }
278
279 # If there is no coverImage then we will change the XSL output
280 my $addCover = "yes"; 
281 $addCover = "no" if ! -e $coverImage;
282
283
284 #
285 #  TODO: The coverpage seems to be stripped by Calibre since it 
286 #  expects an image file for the coverpage. Alternatively, create
287 #  a jpeg file based on the HTML (using html2ps for example) 
288 #  and use that for the OPF description of the book
289
290 my $coverFileName = "coverpage.html";
291 my $coverFile = "$outPath{'oebps'}$FILENAME_SEPARATOR$coverFileName";
292 open( COVER, '>', $coverFile ) or
293     die "$PROGRAM_NAME: unable to open OPF file for writing " .
294         "\"$coverFile\"\n";
295
296 my $cover  = qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$coverXSL" -PARAM opf-id "$uniqueID" -PARAM unique-identifier "$bookUniqueURI" -PARAM language "$rulesHash{'language'}" -PARAM book_series "$SERIES" -PARAM book_series_index "$SERIES_NUMBER" -PARAM addcover "$addCover"}; #" comment to unconfuse VIM syntax hilighting
297
298
299 print COVER "$cover";
300
301 close COVER;
302
303 check_file($coverFileName);
304
305 ### write OPF Root file
306 # All content files must be created prior to creating the OPF root file
307 # with its manifest of content files.
308
309 my $opfFileName = "$bookCode.opf";
310 my $opfFile = "$outPath{'oebps'}$FILENAME_SEPARATOR$opfFileName";
311 open( OPF, '>', $opfFile ) or
312     die "$PROGRAM_NAME: unable to open OPF file for writing " .
313         "\"$opfFile\"\n";
314
315 print OPF <<END_OPF_HEADER;
316 <?xml version="1.0"?>
317 <package version="2.0" 
318          xmlns="http://www.idpf.org/2007/opf" 
319          unique-identifier="$uniqueID">
320
321 END_OPF_HEADER
322
323 ## write metadata
324
325 my $metadata = qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$metadataXSL" -PARAM opf-id "$uniqueID" -PARAM unique-identifier "$bookUniqueURI" -PARAM language "$rulesHash{'language'}" -PARAM book_series "$SERIES" -PARAM book_series_index "$SERIES_NUMBER" -PARAM addcover "$addCover"}; #" comment to unconfuse VIM syntax hilighting
326 $metadata = " $metadata";
327 $metadata =~ s|(<dc:)|\n  $1|g;
328 $metadata =~ s|(</metadata>)|\n $1|g;
329
330 print OPF "$metadata\n\n";
331
332 ## write manifest data
333 # assuming a flat directory structure within the OEBPS directory
334
335 print OPF " <manifest>\n";
336
337 opendir( my $content_dir, $outPath{'oebps'} )
338     or die "$PROGRAM_NAME: unable to read OEBPS directory " .
339            "\"$outPath{'oebps'}\": $!\n";
340
341 while( my $content_file = readdir $content_dir ) {
342     next if $content_file eq '.';
343     next if $content_file eq '..';
344     next if $content_file =~ m/\.opf$/i;
345     print OPF qq{  <item id="};
346     print OPF make_id( $content_file );
347     print OPF qq{" href="$content_file" media-type="};
348     print OPF get_mime_type( $content_file );
349     print OPF qq{"/>\n};
350 }
351
352 closedir $content_dir;
353
354 print OPF " </manifest>\n\n";
355
356 ## write spine data
357
358 my $ncxID = make_id( $NCX_FILE );
359 #print OPF qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$spineXSL" -PARAM toc-id "$ncxID"};
360 my $spine = qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$spineXSL" -PARAM toc-id "$ncxID" -PARAM addcover "$addCover"};
361
362 $spine =~ s/idref="([^"]*)"/idref="$1.$XHTML_EXT"/g;
363 $spine = " $spine";
364 $spine =~ s|(<itemref)|\n  $1|g;
365 $spine =~ s|(</spine>)|\n $1|g;
366
367 print OPF "$spine\n\n";
368
369 # TODO: write (optional) guide data here
370 #print OPF " <guide>\n";
371 #print OPF " </guide>\n</package>";
372
373 print OPF "</package>";
374 close OPF;
375
376
377 ### write container.xml
378
379 my $containerFile = "$outPath{'meta-inf'}$FILENAME_SEPARATOR$CONTAINER_FILE";
380 open( CONTAINER, '>', $containerFile ) or
381     die "$PROGRAM_NAME: unable to open container file for writing " .
382         "\"$containerFile\"\n";
383 print CONTAINER <<END_CONTAINER;
384 <?xml version="1.0"?>
385 <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
386   <rootfiles>
387     <rootfile full-path="$OEBPS_DIR/$opfFileName"
388      media-type="application/oebps-package+xml" />
389   </rootfiles>
390 </container>
391 END_CONTAINER
392 close CONTAINER;
393
394 ### compress epub contents
395 # complies with Open Container Format 2.0.1
396 # http://idpf.org/epub/20/spec/OCF_2.0.1_draft.doc
397
398 chdir $outPath{'top'};
399
400 system( $ZIP, '-0Xq', "$bookCode.epub", $MIMETYPE_FILE );
401 system( $ZIP, '-rq', "$bookCode.epub", $META_INF_DIR );
402 system( $ZIP, '-rq', "$bookCode.epub", $OEBPS_DIR );
403
404 exit 0;
405
406 ################################################################################
407 # Subroutines
408 ################################################################################
409
410 sub make_id {
411     my ( $name ) = ( @_ );
412     $name = "_$name" if( $name =~ m/^[-.0-9]/ );
413     $name =~ tr/\x80-\xff/_/;
414     return $name
415 }
416
417 sub get_mime_type {
418     # relies on valid file name extensions
419
420     my ( $file ) = ( @_ );
421     if( $file =~ m/\.x?html?$/i ) {
422         return 'application/xhtml+xml';
423     }
424     elsif( $file =~ m/\.css$/i ) {
425         return 'text/css';
426     }
427     elsif( $file =~ m/\.png$/i ) {
428         return 'image/png';
429     }
430     elsif( $file =~ m/\.jpe?g$/i ) {
431         return 'image/jpeg';
432     }
433     elsif( $file =~ m/\.svg$/i ) {
434         return 'image/svg+xml';
435     }
436     elsif( $file =~ m/\.gif$/i ) {
437         return 'image/gif';
438     }
439     elsif( $file =~ m/\.ncx$/i ) {
440         return 'application/x-dtbncx+xml';
441     }
442     elsif( $file =~ m/\.otf$/i ) {
443         return 'application/x-font-opentype';
444     }
445     else {
446         return 'application/x-unrecognized-mime';
447     }
448 }
449
450 sub check_file {
451 # Check if a file is empty, if it is, abort as this is an indication
452 # that the previous processing step went wrong
453     my ($file) = @_;
454
455     if ( -z $file ) {
456         print  STDERR "There was an error generating $file (empty file produced)";
457         exit 1;
458     }
459
460     return 0;
461 }
462
463 #unless( $bookXML =~ m{^([-\w\@./]+)$} ) {
464 #    die "$PROGRAM_NAME: bad book XML filename \"$bookXML\"\n";
465 #}
466 #$bookXML = $1;
467 #
468 #unless( -e $bookXML && -f $bookXML && -r $bookXML ) {
469 #    die "$PROGRAM_NAME: XML does not exist or is not readable \"$bookXML\"\n";
470 #}
471 #
472 #if( -e $RXP ) {
473 #    system( $RXP, '-Vs', $bookXML ) == 0
474 #        or die "$PROGRAM_NAME: XML validation failed\n";
475 #}
476 #else {
477 #    warn "$PROGRAM_NAME: XML Validator not installed - validate before publication\n";
478 #}
479 #
480 #unless( defined $rulesHash{'language'} ) { die "$PROGRAM_NAME: Metadata file leaves language unspecified\n"; }
481 #unless( defined $rulesHash{'book-series'} ) { die "$PROGRAM_NAME: Metadata file leaves book series unspecified\n"; }
482 #unless( defined $rulesHash{'images'} ) { die "$PROGRAM_NAME: Metadata file leaves image directories unspecified\n"; }
483 #unless( defined $rulesHash{'csst'} ) { die "$PROGRAM_NAME: Metadata file leaves CSS templates unspecified\n"; }
484 #
485 #
486 #my $bookPath = "$outPath${FILENAME_SEPARATOR}";
487 #print qx{$RM ${bookPath}*} if -e $bookPath."/toc.htm";
488 #print qx{$JAVA -classpath "$XALAN_JAR" org.apache.xalan.xslt.Process -IN "$bookXML" -XSL "$xhtmlXSL" -OUT "${bookPath}foo.xml" -PARAM background-color "$rulesHash{'background-color'}" -PARAM text-color "$rulesHash{'text-color'}" -PARAM link-color "$rulesHash{'link-color'}" -PARAM use-illustrators "$rulesHash{'use-illustrators'}" -PARAM language "$rulesHash{'language'}"};
489 #print qx{$RM ${bookPath}foo.xml};
490 #
491 #
492 #
493 #print qx{$ZIP -8 -q ${bookCode}.zip ${bookPath}*};
494 #print qx{$MV ${bookCode}* $bookPath};
495 #
496 #print "Success\n" if $verbose;
497
498 # Determine series long name by the series acronym
499 sub get_series {
500     my ($series) = @_;
501     my $series_name = "";
502     if ($series eq "lw" ) {
503         $series_name = "Lone Wolf";
504     } elsif ($series eq "ls" ) {
505         $series_name = "Lobo Solitario";
506     } elsif ($series eq "gs" ) {
507         $series_name = "Grey Star the Wizard";
508     } elsif ($series eq "fw" ) {
509         $series_name = "Freeway Warrior";
510     } else {
511         print STDERR "WARN: Undefined series. Short name given: '$series'\n";
512         $series_name = "[undefined]";
513     }
514     return $series_name;
515 }
516
517 # Determine the series number based on book code
518 sub get_series_number {
519     my ($bookCode) = @_;
520     my $series_number = "";
521     if ( $bookCode =~ /^(\d\d)/ ) {
522         $series_number = $1;
523     } else {
524         print STDERR "WARN: Undefined series number. Book code is '$bookCode'.\n";
525         $series_number = "xx";
526     }
527     return $series_number;
528 }
529
530 # Determine the book title by reading the book meta information
531 sub find_title {
532     my ($book) = @_;
533     my $title = ""; my $line = "";
534     open (BOOK, "head -100 $book | ") || die ("Could not read $book: $!");
535     while ($title eq "" && ( $line = <BOOK> ) ) {
536         chomp $line;
537         if ( $line =~ /<title>(.*?)<\/title>/ ) {
538             $title = $1;
539         }
540     }
541     close BOOK;
542
543     if ( $title eq "" ) {
544         print STDERR "WARN: Cannot find title for book '$book'\n";
545         $title = "[Undefined]";
546     }
547
548     return convert_entities($title);
549 }
550
551 # Determine the book author by reading the book meta information
552 sub find_author {
553     my ($book) = @_;
554     my $author = ""; 
555     my $line = "";
556     open (BOOK, "head -100 $book |") || die ("Could not read $book: $!");
557
558     my $find_line = 0;
559     while ($author eq "" && ( $line = <BOOK> ) ) {
560         chomp $line;
561         if ( $find_line == 1 && $line =~ /<line>(.*?)<\/line>/ ) {
562             $author = $1;
563         }
564         $find_line = 1 if ( $line =~ /<creator class="medium">/ );
565         $find_line = 0 if ( $line =~ /<\/creator>/ );
566         if ( $line =~ /<creator class="author">(.*?)<\/title>/ ) {
567             $author = $1;
568         }
569     }
570     close BOOK;
571
572     if ( $author eq "" ) {
573         print STDERR "WARN: Cannot find author for book '$book'\n";
574         $author = "[Undefined]";
575     }
576
577
578     return $author;
579 }
580
581 # Determine the book illustrator by reading the book meta information
582 sub find_illustrator {
583     my ($book) = @_;
584     my $illustrator = "";
585     my $line = "";
586     open (BOOK, "head -100 $book | ") || die ("Could not read $book: $!");
587
588     my $find_line = 0;
589     while ($illustrator eq "" && ( $line = <BOOK> ) ) {
590         chomp $line;
591         if ( $find_line == 1 && $line =~ /<line>Illustrated by (.*?)<\/line>/ ) {
592             $illustrator = $1;
593         }
594         $find_line = 1 if ( $line =~ /<creator class="medium">/ );
595         $find_line = 0 if ( $line =~ /<\/creator>/ );
596         if ( $line =~ /<creator class="illustrator">(.*?)<\/title>/ ) {
597             $illustrator = $1;
598         }
599     }
600     close BOOK;
601
602     if ( $illustrator eq "" ) {
603         print STDERR "WARN: Cannot find illustrator for book '$book'\n";
604         $illustrator = "[Undefined]";
605     }
606     if ( $language eq "en" ) {
607         $illustrator = "Illustrated by ".$illustrator;
608     } elsif ( $language eq "es" ) {
609         $illustrator = "Illustrado por ".$illustrator;
610     }
611
612     return $illustrator;
613 }
614
615 sub convert_entities {
616 # Convert character entities to their correspondent values
617     my ($text) = @_;
618
619     $text =~ s/\<ch.apos\/\>/'/g; 
620     $text =~ s/\<ch.nbsp\/\>/ /g;
621     $text =~ s/\<ch.plusmn\/\>/+-/g;
622     $text =~ s/\<ch.aacute\/\>/á/g;
623     $text =~ s/\<ch.eacute\/\>/é/g;
624     $text =~ s/\<ch.iacute\/\>/í/g;
625     $text =~ s/\<ch.oacute\/\>/ó/g;
626     $text =~ s/\<ch.uacute\/\>/ú/g;
627     $text =~ s/\<ch.ntilde\/\>/ñ/g;
628     $text =~ s/\<ch.Aacute\/\>/Á/g;
629     $text =~ s/\<ch.Eacute\/\>/É/g;
630     $text =~ s/\<ch.Iacute\/\>/Í/g;
631     $text =~ s/\<ch.Oacute\/\>/Ó/g;
632     $text =~ s/\<ch.Uacute\/\>/Ú/g;
633     $text =~ s/\<ch.auml\/\>/ä/g;
634     $text =~ s/\<ch.euml\/\>/ë/g;
635     $text =~ s/\<ch.iuml\/\>/ï/g;
636     $text =~ s/\<ch.ouml\/\>/ö/g;
637     $text =~ s/\<ch.uuml\/\>/ü/g;
638     $text =~ s/\<ch.Ntilde\/\>/Ñ/g;
639     $text =~ s/\<ch.acute\/\>/´/g;
640     $text =~ s/\<ch.iexcl\/\>/¡/g;
641     $text =~ s/\<ch.iquest\/\>/¿/g;
642     $text =~ s/\<ch.laquo\/\>/«/g;
643     $text =~ s/\<ch.raquo\/\>/»/g;
644     $text =~ s/\<ch.ampersand\/\>/&/g;
645
646     return $text;
647 }
648
649 # Quote metacaracters for shell use
650 sub quote_shell {
651     my ($text) = @_;
652     $text =~ s/'/\\'/g; 
653     return $text;
654 }