#
# A component of the Realistic Book software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2007 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

#*****************************************************************
#Realistic Book application
#	Converting each PDF page into a SWF file. Also produce
#	the XHTML input file for the Realistic book program
#
#by Veronica Liesaputra --- 1 August 2007
#*****************************************************************/
use warnings; use strict;

   my $err = 0;
   if ($#ARGV < 0) {
     $err = 1;
   }

    my $newIndex = 0;
    my $newStructure = 0;
    my $filename = "";
    my $j = 0;
    while (($j <= $#ARGV) && ($err == 0)) {
			if ($ARGV[$j] =~ m/^\-noindex$/i) {
				$newIndex = 1;
			} else {
				if ($ARGV[$j] =~ m/^\-nostructure$/i) {
					$newStructure = 1;
				} else {
					if ($ARGV[$j] =~ m/^\-swfupdate$/i) {
					   $newIndex = 1;
					   $newStructure = 1;
                                        } else {
					   if ($ARGV[$j] =~ m/^\-/) {
						print STDERR "Unknown option: $ARGV[$j]\n\n";
                                                $err = 1;
					   } else {
						$filename = $ARGV[$j];
					   }
					}
				}
			}
			
			$j = $j + 1;
		}
   
    # exit from the application and show the usage message
    if ($err == 1) {
	print STDERR "USAGE: perl pdf2image.pl [-options] pdf_filename\n\n";
    	print STDERR "Options:\n";
        print STDERR "-swfupdate \t Only convert each page of the pdf file.\n";
	print STDERR "           \t Do not generate new index.html and book structure files.\n";
    	print STDERR "-noindex \t Do not generate new index.html file.\n";
    	print STDERR "-nostructure \t Do not generate new book structure file.\n";
        die("\n");
    }

    # check that file exists
    if (-d $filename) {
      die("$filename is a directory! Please specify the file extension. \n");
    }
    if (-f $filename) {
    } else {
      die("Cannot find $filename! \n");
    }

    # check that pdf2swf exists
    my $progname = `pdf2swf --version`;
    if (defined $progname && $progname =~ m/swftools/i) {
    } else {
      die("\nPlease make sure that pdf2swf is located in the same location as this script.\nIf you are in Linux/Macintosh, please install swftools in SWFToolsPackage.\n");
    }

    # create folder for swf files
    my $folder_name = $filename;
    $folder_name=~ s/.pdf//i;
    mkdir($folder_name);

    # convert each page of pdf into swf and get its page size
    my $width = 0;
    my $height = 0;
    my $page_input = "";
    my @output_lines = split(/\n/,`pdf2swf -I $filename`);# get info of each pages in pdf
    foreach my $line (@output_lines) {
      if ($line =~ m/^page=(\d+)\s+width=(\d+\.?\d*)\s+height=(\d+\.?\d*)$/i) {
         # get the smallest width and height
         if (($width == 0) || ($2 < $width)) {
            $width = $2;
         }
         if (($height == 0) || ($3 < $height)) {
            $height = $3;
         }

         # convert to swf
         my $i = $1;
				 my $backFile = "Page_$i.swf";
				 my $frontFile = "$folder_name/";
				 my $output_file = "$frontFile$backFile";
				 my $imgfile = `pdf2swf -p $i -s insertstop -s zoom=100 -s bboxvars $filename -o $output_file`;
				 
				 print STDOUT "creating page $i\n";
				 
				 $page_input = "$page_input<newpage filename=\"Page_$i\" />\n";
      }
   }

   if ($newStructure == 0) {
     # get page size
     my $page_size = "x$height";
     $page_size = "$width$page_size";


     # create the book structure file
     my $html_input = "<HTML>\n<title>$folder_name</title>\n<Description>\n";
     $html_input = "$html_input<!-- Please do not remove Filename and PageFolder metadata -->\n";
     $html_input = "$html_input<Metadata name=\"Filename\">$folder_name</Metadata>\n";
     $html_input = "$html_input<Metadata name=\"PageFolder\">$folder_name</Metadata>\n";
     $html_input = "$html_input<Metadata name=\"StartNumbering\">1</Metadata>\n";
     $html_input = "$html_input<Metadata name=\"PageSize\">$page_size</Metadata>\n";
     $html_input = "$html_input</Description>\n";
     $html_input = "$html_input$page_input";
     $html_input = "$html_input</HTML>\n";
    
     my $html_file = "$folder_name.htm";
     open (PROD, ">$html_file") || die("Error Writing to File: $html_file $!");
     print PROD $html_input;
     close (PROD) || die("Error Closing File: $html_file $!");
     print STDOUT "creating $html_file\n";
   }

   if ($newIndex == 0) {
     # creating index.html
     my $index_input = "<html>\n<head>\n";
     $index_input = "$index_input<title>$folder_name</title>\n";
     $index_input = "$index_input<script src='RealisticBook.js' language='javascript'></script>\n</head>\n";
     $index_input = "$index_input<body>\n";
     $index_input = "$index_input<!-- You have to have this div tag with id = bookdiv in your HTML file!! This is where the program will be embedded -->\n";
     $index_input = "$index_input<div id='bookdiv'></div>\n";
     $index_input = "$index_input<script type='text/javascript'>\n";
     $index_input = "$index_input<!-- \n";
     $index_input = "$index_input embedBookProgram(new Array('$folder_name.htm'));\n";
     $index_input = "$index_input// -->\n";
     $index_input = "$index_input</script>\n";
     $index_input = "$index_input<noscript>\n";
     $index_input = "$index_input This content requires JavaScript and Adobe Flash Player.\n";
     $index_input = "$index_input <a href='http://www.macromedia.com/go/getflash/'>Get Flash</a>\n";
     $index_input = "$index_input</noscript>\n</body>\n</html>\n";

     my $index_file = "index.html";
     open (PROD, ">$index_file") || die("Error Writing to File: $index_file $!");
     print PROD $index_input;
     close (PROD) || die("Error Closing File: $index_file $!");
     print STDOUT "creating $index_file\n";
   }

   print STDOUT "Done!\n";

