#!/usr/bin/perl

use lib '/ww/webwork/development/'; # mainWeBWorKDirectory;
use capa2PG;
use Benchmark;



# Called by
# convert_capa_2_PG.pl indirectory outdirectory

unless (defined($ARGV[0]) ) {
	print qq!
	Useage: 	
	convert_capa_2_PG.pl in_directory_path out_directory_path

and will convert all *.txt files in the in directory from CAPA to PG files,
placing them in *.pg files in the out directory. 
Files named prob1a.txt prob1b.txt will be concatenated
and placed into the file prob1.pg.

For example:

     convert_capa_2.PG.pl type1 type1pg

If out_directory_path is omitted then the out_directory_path is obtained by adding pg to the 
in_directory  
\n\n
!;
exit;
}
	
	
$directory = $ARGV[0];
$indirectory = $directory;         # no final slash
$outdirectory = "${directory}pg"; 
$outdirectory = $ARGV[1] if defined($ARGV[1]);

print "Converting all *.txt files in the directory
$directory 
to the PG language and placing them in
*.pg files in the directory 
$outdirectory. 
Proceed?>";
my $response = <STDIN>;
exit unless $response =~ /y/i ;
  
 

# $outdirectory = "${directory}pg";  # no final slash
opendir(DIRHANDLE, "$indirectory" ) || die "Can't open $indirectory $!";

@allfiles = sort grep /\.txt/, readdir DIRHANDLE;
closedir DIRHANDLE;

$first_file = shift(@allfiles);




my @all_lines = slurp("$indirectory/$first_file");

while (1) {
	my $file = shift @allfiles;

	if (   root($first_file)  eq root($file)  ) {
		#     $out_line .= "$directory/$file ";
		push(@all_lines, slurp("$directory/$file") );
	} else {
		  # we're done time to ship the file
		  my $newName = root($first_file);
		     #$newName =~ s/prob/capa/;
		  
		   print STDERR "Creating $outdirectory/$newName.pg\n";
		   open(FILE_OUT, ">$outdirectory/$newName.pg") || print STDERR "Unable to output to $outdirectory/$newName.pg\n";
		   
		   ## begin Timing code
				my $beginTime = new Benchmark;
		   ## end Timing code
			print FILE_OUT parse_CAPA_file(\@all_lines);
		   ## begin Timing code
			my $endTime = new Benchmark;
			print FILE_OUT "\n#################################################\n## Processing time = ", timestr( timediff($endTime,$beginTime) ), 
			      "\n#################################################\n";
		   ## end Timing code
		   
		   close(FILE_OUT);
		  # print $out_line;
		   #  system( $out_line);
		  # and prepare the next
		   $first_file = $file;
		   #$out_line = "cat $directory/$first_file ";
		   @all_lines = slurp("$directory/$first_file");
		   last unless defined($first_file);
	 }
}

sub slurp {
	my $path = shift;
	my @lines = ();
	if (open(FILE, "<$path") ) {
	    print STDERR "Reading $path\n";
		@lines = <FILE>;
	} else { 
		print STDERR "Can't open $path for reading.  Skipping.";
	}
	@lines;
}




sub root {
	my $in = shift;
	$in =~ s/[abcdefg]*\.txt$//;
	$in;
}
