#!/usr/bin/perl
#
# Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
# Creation Date: Sat Oct  8 07:31:10 PDT 2005
# Last Modified: Mon Oct 24 22:06:52 PDT 2005 (supress !!!offset: record)
# Filename:      mma2dat
# Syntax:        perl 5
#
# Description:   Convert a Mathematica output file into a Humdrum file
#                with score information added.
#
# Usage:         ./mma2dat output.mma anoriginaltrial.dat > analysis.dat
#

use strict;

my @timedata = getTimeData($ARGV[0]);
my @tf       = getTemplateFile($ARGV[1]);
my @da;

my $beat = 1;
my $counter = 0;
my $i;

for ($i=0; $i<@tf; $i++) {
   if ($tf[$i] =~ /^\!\!\!offset:/) {
      next;
   }
   if ($tf[$i] =~ /^!/) {
      if ($tf[$i] =~ /\!\!\!trial:\s+\d+\/(\d+)/) {
         $tf[$i] = "!!!trials:\t\t$1\n";
      }
      print $tf[$i];
      next;
   }
   if ($tf[$i] =~ /^=/) {
      $tf[$i] =~ /^([^\t]+)\t/;
      print "$1\t$1\t$1\t$1\t$1\t$1\t$1\t$1\t$1\n";
      next;
   }
   if ($tf[$i] =~ /^\*/) {
      if ($tf[$i] =~ /^\*\*/) {
         print "**kern\t**beat\t**time\t**dur\t**min\t**max\t**cmin\t**cmax\t**sd\n";
      } elsif ($tf[$i] =~ /^\*-/) {
         print "==\t==\t==\t==\t==\t==\t==\t==\t==\n";
         print "*-\t*-\t*-\t*-\t*-\t*-\t*-\t*-\t*-\n";
      } else {
         print "$tf[$i]";
      }
      next;
   }
   if ($tf[$i] =~ /^\s*$/) {
      next;
   }

   # fill $tf[$i] data line:
   $tf[$i] =~ /^([^\t]+)\t([^\t]+)/;
   my $tfrhythm = $1;
   my $tfbeat   = $2;

   if ($counter >= @timedata) {
      print "4\t$beat\t.\t.\t.\t.\t.\t.\t.\n";
   } else {
      $timedata[$counter] =~ s/^\s*//;
      $timedata[$counter] =~ s/\s*$//;
      @da = split(/\s+/, $timedata[$counter]);
      $da[6] = int($da[6] * 10 + 0.5)/10.0;
      $da[6] .= ".0" if $da[6] !~ /\./;
      $da[1] =~ s/\.$/.0/;
      $da[1] = "." if $da[1] eq ".0";
      # print "4\t$beat\t$da[0]\t$da[1]\t$da[2]\t$da[3]\t$da[4]\t$da[5]\t$da[6]\n";
      print "$tfrhythm\t$tfbeat\t$da[0]\t$da[1]\t$da[2]\t$da[3]\t$da[4]\t$da[5]\t$da[6]\n";
   }

   $beat++;
   $beat = 1 if $beat > 3;
   $counter++;
}

# print "!! counter = $counter\n";


exit(0);

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

##############################
##
## getTemplateFile --
##

sub getTemplateFile {
   my ($file) = @_;

   open (TFILE, $file) || die;

   my @output = <TFILE>;
   close TFILE;

   return @output;
}



##############################
##
## getTimeData --
##

sub getTimeData {
   my ($file) = @_;

   open (TDFILE, $file) || die "Cannot open $file for reading";

   my @output;
   my $line;
   while ($line = <TDFILE>) {
      chomp $line;
      $output[@output] = $line;
   }

   close TDFILE;
   return @output;
}



