#!/usr/bin/perl
# requires festival text to speech and cepstral swift voices
# 2008-05-23 modifications by kanzure for use with festival speech synth software (swift = LARGE download)
# 2008-05-25 uhh, logging.
# 2008-05-25 I stole this from Superkuh.
use Parallel::ForkManager;
my $manager = new Parallel::ForkManager( 2 );

unless ($manglefilename = getnautliuspath()) {
	$manglefilename = $ARGV[0];
	foreach $num (0 .. $#ARGV) { 		
		print "\n$num: $ARGV[$num]\n";
		if ($num != 0) {
			$mostargs .= $ARGV[$num] . " "; #arguments for regex
			print "MOSTARGS: $mostargs\n";
		}
	}
}

unless ($ARGV1) { # if they have a page-page transition set, don't don't execute twice.
	`pdftotext \"$manglefilename\"`; 
}

if ($ARGV[1]) {
	if ( $mostargs =~ /(\d+)\s(\d+)/i ) { # to specify pages
		my ($start, $stop) = ($1, $2);
		print "start: $start || stop: $stop\n";
		`pdftotext -nopgbrk -f $start -l $stop $manglefilename`;	
	} else {
		print "\nNormal: \"perl $0 pdf_file.pdf\"\n";
		print "\nPage to Page: \"perl $0 pdf_file.pdf 3 40\" (an example)\n";
	}
}


if ($manglefilename =~ /(.+)\.\w+/) {
	$filename = $1;
	print "\nFilename: $filename\n";
	$realfileext = "$filename" . '.txt'; 
	print "RealExt: $realfileext\n";	
}

open (PDFTEXT, "$realfileext") or die "Can't open $realfileext.\n";
	while (<PDFTEXT>) {
		$pdftotal .= $_;
	}
close(PDFTEXT);

print "\n";
print "\_" x 40;  
#print "\n$pdftotal\n";
print "\_" x 40; 
print "\nReading...slowly, with lag.\n";

@commands = ("evince \"$manglefilename\"", "echo \" " . qq($pdftotal) . " \" | festival --tts"); #"swift -f \"$realfileext\"");
foreach my $command (@commands) {
	my $pid = $manager->start and next;
	exec( $command );
	push (@procid,$pid);
	$manager->finish;	
};

sub getnautliuspath {
	if ($ENV{'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'}) {
		return $ENV{'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'};
	} else {
		 return 0;
	}
}

sub getnautiluspath2 {
	# debug
	while (($key, $value) = each(%ENV)){
		if ($key =~ /NAUTILUS/) {
			print $key.", ".$value."\n";
		}
	}
	# path
	$_ = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'};
	if ($_ and m#^file:///#) {
		s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
		s#^file://##;
		$nautiluspath = $_;
	}
	return;
}

print "Don't press enter until finished.\n";
$meh = <STDIN>;
open(HELLO,">>/home/bryan/cache/hearpdflogs.txt");
printf HELLO "%4d-%02d-%02d %02d:%02d:%02d\n",
$year+1900,$mon+1,$mday,$hour,$min,$sec;
print HELLO "\t\t$manglefilename";
($sec,$min,$hour,$mday,$mon,$year,$wday,
$yday,$isdst)=localtime(time);
close HELLO;

`killall swift.bin`;

