#!/usr/bin/perl -w

use Math::FFT;

$pi = 3.1415926;
$t = 0;
$size = 1024;

my $time;
my $input;
my $freq;
my $count = 0;

while (<>) {
	chomp;
	if (/^(.*)/) {
		$time->[$t++] = $1;
	} elsif (/^([^\s]+)\s+(.*)/) {
		$time->[$t++] = $2;
	}
	if ($t == 1024) {
		&sum;
		$t = 0;
	}
}

for ($i=0; $i<$size/2; $i++) {
	print(($i*44100/$size)."\t".(20.0 * log($freq->[$i]/$count)/log(10)-40)."\n");
}

sub sum {
	$count++;
	for ($i=0; $i<$size; $i++) {
		$time->[$i] *= 0.5 + 0.5 * sin(2.0 * $pi / $size);
	}
	my $fft = new Math::FFT($time);
	my $coeff = $fft->rdft();
	my $thisfreq = $fft->spctrm;

	for ($i=0; $i<$size/2; $i++) {
		#$freq->[$i] += $thisfreq->[$i] * $size;
		$freq->[$i] += sqrt($coeff->[$i*2] * $coeff->[$i*2] + $coeff->[$i*2+1] * $coeff->[$i*2+1]);
	}
}
