#!/usr/bin/perl
#
# Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
# Creation Date: Mon Feb 12 22:24:00 PST 2007
# Last Modified: Mon Feb 12 22:24:00 PST 2007
# Filename:      /project/mazurka/website/info/dyn/dynbeat100/extractbeatdynamics100
# Syntax:        perl 5
#
# Description:   Extract global dynamics at 100 ms after beat onsets.
#


use strict;

my $onsetfile    = $ARGV[0];
my $loudnessfile = $ARGV[1];
my $offset       = $ARGV[2];
my $idstring     = "Global Beat Dynamics (0.2x2 smoothing; 100 ms delay)";
my $date         = `date`;
chomp $date;


if (@ARGV < 2) {
   die "Usage: $0 onsetfile loudnessfile offset\n";
}

if ($offset == 0) {
   $offset = 10;    # 100 milliseconds delay in measurement by default
}

my @LOUDNESS = getLoudnesses($loudnessfile);

my $line;
my $time;
my $tag;
my $dyn;
my $found = 0;

open (FILE, $onsetfile) or die "Cannot open $onsetfile for reading";
while ($line = <FILE>) {
   chomp $line;
   $line =~ s/\s*$//;
   if ($line =~ /^\s*([0-9\+\.\-]+)\s+(.*)/) {
      $time = $1;
      $tag = $2;
      $dyn = getDynamic($time, $offset);
      if ($found == 0) {
         $found = 1;
         print "###data-type:\t\t$idstring\n";
         print "###extraction-date:\t$date\n";
      }
      $time = int($time * 1000.0 + 0.5) / 1000.0;
      print "$time\t$dyn\t($tag)\n";
   } else {
      print "$line\n";
   }
}




exit(0);

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


##############################
##
## getLoudnesses --
##

sub getLoudnesses {
   my ($file) = @_;
   
   my $time;
   my $loudness;

   open(FILE, $file) or die "Cannot open $file";
   my @output;
   my $line;
   while ($line = <FILE>) {
      chomp $line;
      if ($line =~ /^\s*([0-9\.\+eE\-]+)\s*:?\s+([0-9\.\+eE-]+)/) {
         $time = $1;
         $loudness = $2;
      }
      $output[@output] = $loudness;
   }
   close FILE;
   return @output;
}



##############################
##
## getDynamic --
##

sub getDynamic {
   my ($time, $offset) = @_;
   
   my $index = int($time / 0.010);
   $index = $index + $offset;
   my $value = int($LOUDNESS[$index] * 10 + 0.5) / 10.0;
   $value = 100 + $value;
   $value .= ".0" if $value !~ /\./;
   return $value;
}





