#!/usr/bin/perl -w

# Calculate the normalized pairwise variability index for one time
# series.  In this particular instance, I assume that the time series
# is stored in Praat TextGrid format.  I also assume that the time
# points in the file have been checked by some other routine.

scalar(@ARGV) == 1 or die "Usage: getNPvi.pl infile";

$infile = shift;

open(IN, $infile) or die "Cant open $infile";

# First we parse the infile to get a simple list of interval durations

@intervals = ();
$last = 0.0;

# Skip forward a bit
while($_ = <IN>) {
  next unless $_ =~ /TextTier/;
  last;
}

$_ = <IN>;$_ = <IN>;$_ = <IN>;

chomp($nPoints = <IN>);

$firsttime = 1;

for($i = 0; $i < $nPoints; $i++) {
  chomp($beat = <IN>);
  if(! $firsttime) {
    push(@intervals, $beat - $last);
  } else {
    $firsttime = 0;
  }
  $last = $beat;
  $_ = <IN>;   #skip label without check
}

# Now we calculate the nPVI

$sum = 0.0;

for($i=0; $i<scalar(@intervals)-1; $i++) {
  $numerator = $intervals[$i] - $intervals[$i+1];
  $denominator = ($intervals[$i] + $intervals[$i + 1])/2.0;
  $sum = $sum + abs($numerator / $denominator);
  #print "Adding ",  abs($numerator / $denominator), "\n";
}

$npvi = 100.0 * ($sum / (scalar(@intervals) -1));

print "nPVI: $npvi\n";
