#!/usr/bin/perl
#
# Programmer:    Craig Stuart Sapp <craig.stanford.edu>
# Creation Date: Thu Dec  9 16:13:55 PST 2010
# Last Modified: Thu Dec  9 16:13:55 PST 2010
# Filename:      /tmp/corellipages/concerto/op6n01/editions/temp10/score/mpg2ps
# Syntax:        perl 5
#
# Description:   Convert MPG (MuseData Music PaGe Files) into PostScript
# 		 files using muse2ps.
#

use strict;

use FileHandle;
use IPC::Open2;
use IPC::Open3;
use IO::File;

my @files = @ARGV;
@files = sort @files;
my $program =  "/project/musedata/bin/muse2ps";
#my $program =  "/usr/bin/muse2ps";
my @content = ();
my $file;

foreach $file (@files) {
   push(@content, getContent($file));
   push(@content, "P\n");
}

my $results;
my $error;
($results, $error) = getResults(join("", @content), "$program =p");
#my $results = join("", @content);

if ($error !~ /^\s*$/) {
   print "ERROR:\n";
   print $error;
} else {
   print $results;
}

exit(0);

###########################################################################

##############################
##
## getContent --
##

sub getContent {
   my ($file) = @_;
   open (FILE, $file) or die "Cannot open file: $file";
   my $line;
   my @output;
   while ($line = <FILE>) {
      chomp $line;
      $line =~ s/\s+$//;
      push(@output, "$line\n");
   }
   close FILE;
   return @output;
}
      


##############################
##
## getResults --
##

sub getResults {
   my ($data, $command) = @_;
   local (*READ, *WRITE);
   local *ERROR = IO::File->new_tmpfile;

   #my $pid = open2(*READ, *WRITE, $command);
   my $pid = open3(*WRITE, *READ, ">&ERROR", "$command");

   binmode(WRITE);
   binmode(READ);

   print WRITE "";  # need to do this because of some bug...
   my $tdata = $data;
   print WRITE $tdata;
   close(WRITE);

   my $output = "";
   my $output2 = "";
   my $udata;
   while (read(READ, $udata, 4096)) {
      $output .= $udata;
   }
   close (READ);

   waitpid($pid, 0);
   seek ERROR, 0, 0;
   while (read(ERROR, $udata, 4096)) {
      $output2 .= $udata;
   }

   return ($output, $output2);
}




