#!/usr/bin/perl -w

# convert a frequency to a note name.
# formula came from http://en.wikipedia.org/wiki/Note
# p = 69 + 12 * log2(f/440)
# ...where f is in Hz and p is the MIDI note number

@notenames = (
		'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'
		);

sub log2 {
	return log($_[0])/log(2);
}

sub midi2note {
	my $pitch = int(shift);
	my $class = $notenames[$pitch % 12];
	my $octave = int($pitch / 12) - 1;
	return $class . $octave;
}

for(@ARGV) {
	my $p = 69 + 12 * log2($_ / 440);
	my $pitch = int($p);
	my $cents = int(($p - $pitch) * 1000)/10;
	if($cents > 50) {
		$pitch++;
		$cents = $cents - 100;
	}
	if($cents == 0) {
		$cents = "";
	} elsif($cents > 0) {
		$cents = "+$cents" . "c";
	} else {
		$cents .= "c";
	}
	print $_ . "Hz = MIDI $pitch = " . midi2note($pitch) . " $cents\n";
}
