#!/usr/bin/perl
# Converts a frequency (Hz) to a note
# copyright (c) 2003 Emil Mikulic
#
# $Id: hznote.pl,v 1.2 2004/10/09 08:56:09 emikulic Exp $
#

while ($f = <>)
{
   # f = 440 * 2^(c/1200)
   # c = 1200 * log2(f/440)

   chomp $f;
   $c = log($f/440) / log(2) * 1200;
   $c += 900; # relative to C-4 now

   $octave = 4;
   while ($c < 0)
   {
      $octave--;
      $c += 1200;
   }
   while ($c >= 1200)
   {
      $octave++;
      $c -= 1200;
   }

   $semitone = int($c / 100);
   $off_cents = $c - ($semitone * 100);

   if ($off_cents > 50)
   {
      $semitone++;
      $off_cents -= 100;

      if ($semitone == 12)
      {
         $semitone = 0;
         $octave++;
      }
   }

   $c_hz = 440 * 2**($octave-4 + ($semitone-9)/12);
   $off_hz = $f - $c_hz;

   @note = qw(C- C# D- D# E- F- F# G- G# A- A# B-);
   print $note[$semitone].$octave.
      "\t\t# off $off_cents cents or $off_hz Hz\n";
}

# vim:set ts=3 sw=3 tw=78 expandtab:
