#!/usr/bin/perl -w
#
# 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;

use File::Basename;
use File::Spec::Functions;
use File::Copy;

BEGIN {
    die "REALISTIC_BOOKS_HOME not set. Have you sourced setup.bash?\n" 
	unless defined $ENV{'REALISTIC_BOOKS_HOME'};
    die "RBOS not set. Have you sourced setup.bash?\n" 
	unless defined $ENV{'RBOS'};
}


sub print_usage
{
    my ($full_progname) = @_;

    my $progname = basename($full_progname);

    print STDERR "\nUsage: $progname pdf_filename\n";
    print STDERR "or     perl -S $progname pdf_filename\n\n";

    exit(-1);
}

sub check_pdf2swf
{
    my $output = `pdf2swf --version`;

    if (!defined $output || ($output !~ m/swftools/i)) {
	print STDERR "Unable to find pdf2swf: $!\n";
	print STDERR "Have you sourced setup.bash (Linux/MacOS)?\n";
	print STDERR "Have you run     setup.bat  (Windows)?\n";
	exit(-1);
    }
}

sub check_file
{
    my ($filename) = @_;

    if (-d $filename) {
	print STDERR "Error: $filename is a directory.\n";
	print STDERR "       Please specify the PDF file as input.\n";
	exit(-1);
    }

    if (!-e $filename) {
	print STDERR "Error: Unable to find $filename\n";
	exit(-1);
    }
}

sub copy_model_col
{
    my ($folder_name) = @_;

    #--
    # Copy modelcol content to new book folder
    # --

    mkdir($folder_name);
    my $modelcol_dir = catfile($ENV{'REALISTIC_BOOKS_HOME'},"books","modelcol");
    opendir(DIR, $modelcol_dir) 
	|| die "Cannot open directory $modelcol_dir: $!";

    my @model_files = grep { -f catfile($modelcol_dir,$_) } readdir(DIR);
    closedir DIR;

    foreach my $f ( @model_files) {
	my $src_filename = catfile($modelcol_dir,$f);
	my $dst_filename = catfile($folder_name,$f);
	copy($src_filename,$dst_filename);
    }
}

sub pdf2swf_info
{
    my ($filename) = @_;

    my $cmd = "pdf2swf --info $filename";
    if ($ENV{'RBOS'} =~ /^windows$/i) {
	$cmd .= " 2>null";
    }
    else {
	$cmd .= " 2>/dev/null";
    }
    
    my @output_lines = split(/\n/,`$cmd`);

    my $last_line = pop(@output_lines);

    # Watch out for trailing \n
    $last_line = pop(@output_lines) if ($last_line =~ m/^$/);

    my ($num_pages) = ($last_line =~ m/^page=(\d+)/);

    return $num_pages;
}

    
sub generate_html
{
    my ($full_folder_name,$folder_root,$filename) = @_;

    my $num_pages = pdf2swf_info($filename);
    print STDOUT "Total page: $num_pages\n";

    my $html_input = "<HTML>\n<title>$folder_root</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_root</Metadata>\n";
    $html_input = "$html_input<Metadata name=\"PageFolder\">.</Metadata>\n";
    $html_input = "$html_input<Metadata name=\"StartNumbering\">1</Metadata>\n";
    $html_input = "$html_input</Description>\n";

    for (my $i=1; $i<=$num_pages; $i++) {

	my $backFile = "Page_$i.swf";
	my $frontFile = "$full_folder_name";
	my $output_file = catfile($frontFile,$backFile);
	my $imgfile = `pdf2swf -p $i -s insertstop -s zoom=100 $filename -o $output_file`;
	
	print STDOUT "creating page $i\n";
	
	$html_input = "$html_input<newpage filename=\"Page_$i\" />\n";
    }

    $html_input = "$html_input</HTML>\n";

    return $html_input;
}


sub main
{
    my ($argc,@argv) = @_;

    my $full_progname = $0;

    if ($argc < 0) {
	print_usage($full_progname);
    }

    check_pdf2swf();

    my $filename = $argv[0];
    check_file($filename);

    # print STDERR "Ignore the message called RegOpenKeyEx failed\n";

    my($file_root, $fulldir, $file_ext) = fileparse($filename,qr/\.[^.]*/);

    my $full_folder_name = catfile($ENV{'REALISTIC_BOOKS_HOME'},"books",$file_root);

    copy_model_col($full_folder_name);

    my $html_input = generate_html($full_folder_name,$file_root,$filename);

    # Write out HTML file
    my $html_file = catfile($full_folder_name,"pages.htm");
    open (PROD, ">$html_file") || die("Error Writing to File: $html_file $!");
    print STDERR "Creating $html_file\n";

    print PROD $html_input;
    close (PROD) || die("Error Closing File: $html_file $!");


    print STDOUT "Realistic book generated in $full_folder_name\n";

}


&main(scalar(@ARGV),@ARGV);
