##TODO - should use relative paths
use File::Basename;
use Getopt::Long;

sub makeURLID {
  my $url = $_[0];
  $url =~ s/([^A-Za-z0-9])//seg;
  return $url;
}



my $jpegParam = 0;
my $author = "";
my $title = "";
my ($filename, $directories, $suffix);

GetOptions ( "jpeg" => \$jpegParam, "author=s" => \$author, "title=s" => \$title, "cover=s" => \$coverFile);

  ## let's see if the arguments look right
if (-e $ARGV[0]) {
  $inFileName = $ARGV[0];
}
elsif (-e $ARGV[$#ARGV]) {
  $inFileName = $ARGV[$#ARGV];
}
$invalidFile = 0;
if (-e $inFileName) {
  ($filename, $directories, $suffix) = fileparse($inFileName, qr/\.[^.]*/);
}
else {
  $invalidFile = 1;
}

if (($invalidFile == 1) || (lc($suffix) ne ".html0"))  {
    print "usage:\nbd2mobi.exe filename [--jpeg --author=\"author, name\" --title=\"book title\" --cover=\"cover.jpg\"]";
    print "\n\nwhere filename is the name of the html0 book designer file.\nAdd --jpeg to have the -jpeg command sent to mobigen (if required by your version of mobigen).\nYou can control the author, book title if you wish to override the author and book title from the source file, by specifying them as shown.\nIf you do not include the name of a cover jpg file, bd2mobi will search for a file named for the title of the book or for a cover.jpg in the same directory.\nNote that any file names that contain spaces will need to be quoted or escaped properly.";
    exit;
  }


  $outFileName = "$directories/$filename.mobi.html";

 ## Open the file
  
  open (IN, $inFileName) || die $!;
  
  
  $parseHold = $/;
  $/ = undef;
  $contents = <IN>;
  close (IN);
  $/ = $parseHold;

#  if (($contents =~ m/<img.*src=[^\.]*\.png/i) || (($contents =~ m/<img.*src=[^\.]*\.gif/i))) {
#    print "Detected gif or png images in HTML0 document source.\nPlease convert to jpg and try again.";
#    exit;  
#  }
  
  #fix pagebreaks
  $contents =~ s/<hr>/<mbp:pagebreak\/>/sig;
  #now reference the table of contents in front of first pagebreak
  $contents =~ s/<mbp:pagebreak\/>/<p><a href="toc.html">TABLE OF CONTENTS<\/a><\/p>\n<mbp:pagebreak\/>/si;
  #get rid of justification
  $contents =~ s/align=justify//sig;
  #replace chapter titles with toc references
  $contents =~ s/<SPAN id=title>(<[^>]*>)*([^<]*)(<[^>]*>)*\n<\/SPAN>/<h2 id=\"$2\">$2<\/h2>/sig;

# (<h2 id=(?!BookTitle\b)(?!"BookTitle"\b))"*([^">]*)"*(.*)

#  $contents =~ s/<SPAN id=title>(<[^>]*>)*([^<]*)(<[^>]*>)*\n<\/SPAN>/<h2 id=\"$2\">$2<\/h2>/sig;
#  $contents =~ s/(<h2 id=(?!BookTitle\b)(?!"BookTitle"\b))"*([^">]*)"*(.*)/$1$3/sig;
  
  open FOUT, ">$outFileName";
  print FOUT $contents;
  close(FOUT);
  
  # re-open to build TOC, etc
  open (IN, $outFileName) || die $!;
  @contents = <IN>;
  close (IN);
  
  open FOUT, ">$directories/toc.html";

  print FOUT "<html>\n<body>\n<h2 align='center'>TABLE OF CONTENTS</h2>\n";
  
  my @revisedContents;
  foreach my $line (@contents) {
    if ($line =~ /<H2 id=BookTitle align=center>(<[^>]*>)*([^<]*)/i) {
        $discoveredTitle = $2;
    }
    elsif ($line =~ /<H2 id=BookAuthor[^>]*>(<[^>]*>)*([^<]*)/i) {
        $discoveredAuthor = $2;
    }
    elsif ($line =~ /<h2 id=\"[^>]*>([^<]*)<\/h2>/i) {
        my $url = makeURLID($1);
        print FOUT "<a href='$filename.mobi.html#$url'>$1</a>\n<BR>";
        $line = "<h2 id=\"$url\">$1</h2>";
    }
    push @revisedContents, $line;
  }
  
  print FOUT "</body>\n\</html>";
  close(FOUT);

  open (FOUT, ">$outFileName") || die $!;
  print FOUT @revisedContents;
  close (FOUT);

  if (!$coverFile){
    $coverFile = "$title.jpg";
    }
  #verify that there is a cover.jpg
  if (!-e "$directories/$coverFile") {
      $coverFile = "cover.jpg";
  }
  
  if (-e "$directories/\"$coverFile\"") {
      print "please verify that there is a cover.jpg or $title.jpg image of the book cover\n";
      exit;
    }
  if (!$author) {
    $author = $discoveredAuthor;
  }
  if (!$title) {
    $title = $discoveredTitle;
  }
    
  open FOUT, ">$directories/$filename.opf";
  print FOUT "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
  print FOUT "<package unique-identifier=\"uid\">\n<metadata>\n<dc-metadata xmlns:dc=\"http://purl.org/metadata/dublin_core\" xmlns:oebpackage=\"http://openebook.org/namespaces/oeb-package/1.0/\">\n<dc:Title>$title</dc:Title>\n<dc:Language>en-us</dc:Language>\n<dc:Identifier id=\"uid\">C8C88F49DA</dc:Identifier>\n<dc:Creator>$author</dc:Creator>\n<dc:Subject BASICCode=\"FIC004000\">\n</dc:Subject>\n</dc-metadata>\n<x-metadata>\n<output encoding=\"Windows-1252\">\n</output>\n<EmbeddedCover>$coverFile</EmbeddedCover>\n</x-metadata>\n</metadata>\n<manifest>\n<item id=\"item1\" media-type=\"text/x-oeb1-document\" href=\"$filename.mobi.html\">\n</item>\n<item id=\"item2\" media-type=\"text/x-oeb1-document\" href=\"toc.html\">\n</item>\n</manifest>\n<spine>\n<itemref idref=\"item1\"/>\n<itemref idref=\"item2\"/>\n</spine>\n<tours>\n</tours>\n<guide>\n<reference type=\"toc\" title=\"Table of Contents\" href=\"toc.html\">\n</reference>\n</guide>\n</package>";
  close(FOUT);
  
$jpegParam = 0;  
for (@ARGV) {
  if (lc($_) eq lc("jpeg")) {
    $jepgParam = 1; 
  }
  elsif (lc($_) eq lc("-jpeg")) {
    $jepgParam = 1; 
  }
  elsif (lc($_) eq lc("/jpeg")) {
    $jepgParam = 1; 
  }
}

if ($jpegParam eq 1) {
  system "mobigen.exe", "$directories/$filename.opf", "-c1", "-s0", "-jpeg";
}
else {
  system "mobigen.exe", "$directories/$filename.opf", "-c1", "-s0";
}

unlink "$directories/toc.html";  
unlink "$directories/$filename.opf";
unlink "$directories/$filename.mobi.html";

  print "done processing $title by $author \n";

  