#!/usr/bin/perl
#PDF_extract by VxP
#Creates a HTML file from a PDF file - tries to preserve paragraphs and formatting
#Run context is $ perl PDF_extract.pl [PDF file]

use strict;
use warnings;

my @data = `pdftohtml $ARGV[0] -i -c -stdout`;
my $name = substr($ARGV[0], 0, -4);
my @textfile;
my $i=0;

for (my $n=0; $n<=$#data; $n++)
{
	my $filenumber = $n+1;
	my $filename = $name."-".$filenumber.".html";
	open DATA, $filename;
	while (my $line = <DATA>)
	{
		if ($line =~ m/^<DIV/)
		{
			if ($line !~ m/>(\d+<|paizo.com|TM|®|™)/)
			{
				chomp $line;
				$line =~ s/^<DIV.*?>/<DIV>/;
				$line =~ s/<nobr><span.*?>//;
				$line =~ s/<\/span><\/nobr>//;
				$textfile[$i] = $line;
				$i++;
			}
		}
	}
	close DATA;
	unlink $filename;
}

for (my $m=0; $m<=$#textfile; $m++)
{
	$textfile[$m] =~ s/(<i>|<\/i>)//g;
	if ($textfile[$m] =~ m/(&nbsp;<\/DIV>|>\w<)/) 
	{
		$textfile[$m] =~ s/<\/DIV>//;
		$textfile[$m+1] =~ s/<DIV>//;
	}
	if ($textfile[$m] =~ m/<DIV>([a-z]|&nbsp;|[,.;-]|’)/) 
	{
		$textfile[$m-1] =~ s/<\/DIV>//;
		$textfile[$m] =~ s/<DIV>//;
	}
	$textfile[$m] =~ s/&nbsp;<br>/ /g;
	$textfile[$m] =~ s/-<br>/-/g;
	$textfile[$m] =~ s/—<br>/—/g;
	$textfile[$m] =~ s/<br>/<\/DIV><DIV>/g;
	$textfile[$m] =~ s/<\/DIV>/<\/DIV>\n/g;
}

my $outfile1 = $name.".tmp";
my $handle1 = ">".$outfile1;
open OUTPUT, $handle1;
print OUTPUT '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>'.$name.'</TITLE><META http-equiv="Content-Type"content="text/html; charset=UTF-8"></HEAD>';
print OUTPUT @textfile;
print OUTPUT "</DIV></BODY></HTML>";
close OUTPUT;

my $outfile2 = $name.".html";
my $handle2 = ">".$outfile2;
open EDITINPUT, $outfile1;
open EDITOUTPUT, $handle2;
while (my $line = <EDITINPUT>)
{
	$line =~ s/&nbsp;&nbsp;/&nbsp;/g;
	$line =~ s/&nbsp;/ /g;
#	my $count = ()= $line =~ m/\w+/g;
	print EDITOUTPUT $line;
}
close EDITINPUT;
close EDITOUTPUT;
unlink $outfile1;

my $filename2 = $name."-outline.html";
unlink $filename2;
my $filename3 = $name."_ind.html";
unlink $filename3;
