use strict;
use warnings;
use PDF::API2 ;
use 5.010;
my $dir = '/data/books01/books/';
    opendir(DIR, $dir) or die $!;
my @files =  readdir(DIR); 
#last 18574
#for (my $i =22149 ; $i <= $#files; $i++) {
for (my $i =499 ; $i <= $#files; $i++) {

if ($files[$i] =~m/.pdf/){
my $file = $files[$i];
my $full = $dir.$file;
my $filesz = -s $full ;
my $prec =  $i / $#files * 100 ;
my $fprec = sprintf("%.1f",$prec); 
#print "$@ Karam ";
print "\% $fprec $i of $#files ";
my $test = eval { convert ($full , $filesz) } ;
#convert($full,filesz);
#warn () if $@;

	}
}


#while (my $file = readdir(DIR)) {
#next unless (-f "$dir/$file");
#next unless ($file =~ m/\.pdf$/);
#my $full = $dir.$file;
#my $filesz = -s $full ;
#print $filesz ;
#eval { convert ($full , $filesz) };
#warn () if $@; 
#}

sub convert {
my $oldfile = $_[0];
my $filename = $_[0];
my $size = $_[1];
#for (my $i = 1 ; $i <=$count; $i++ ){
$filename =~ s/\/data\/books01\/books\///g; 
#my $newdir ="/data/books01/books/2014/newfiles2/"."P1_".$filename;  
my $newdir;
if ($size <= 10485760 ) {
#print "proccesing $filename , its size : $size \n";
#my    $pdf = PDF::API2->new();
 my   $old = PDF::API2->open($oldfile) or die "Couldn't process  " ;
my $count = $old->pages();
# my   $page = $pdf->page();
# my   $gfx = $page->gfx();
print "proccesing $filename , its size : $size; total pages number $count \n";

    # Import Page all pages from the old PDF
for (my $i = 1 ; $i <= $count; $i++  ){
$newdir ="/data/books01/books/2014/newfiles2/P".$i."_".$filename;
my    $pdf = PDF::API2->new();
 my   $page = $pdf->page();
 my   $gfx = $page->gfx();
my    $xo = $pdf->importPageIntoForm($old,$i);
    # Add it to the new PDF's first page at 1/2 scale
    $gfx->formimage($xo, 0, 0, 1); 
    $pdf->saveas($newdir);
print "\t Page $i of $count was saved to $newdir \n";
	}
}else  {
print "skipped proccesing $filename \n";
}

}
