#!/usr/bin/perl

# script to make the XDR tones for a CrO2 cassette tape
# so I can cause people to have flashbacks to the 80's.
# scottvr@gmail.com

use Audio::Wav;
use constant M_PI => 3.1415926535897932384626433832795029;
my $sampleRate = 44100;
my $bits = 8;
#my $startfreq = 20;
#my $endfreq = 20480;
my $freq = 20;
my $duration = .175;
my $octaves = 11;
my $max =  ( 2 ** $bits ) / 2;

my $wav = new Audio::Wav;

my $details = {
    'bits_sample' => $bits,
    'sample_rate' =>  $sampleRate,
    'channels' =>  1
};

my $wave = $wav->write('./xdrsweep.wav', $details);

print "samplerate: $sampleRate\n", "bits: $bits\n", "freq: $freq\n", "duration: $duration\n", "octaves: $octaves\n", "max: $max\n" if $DEBUG;

#while($startfreq <= $endfreq ) {
for($x = 1; $x <= $octaves; $x++) {
  my $length = $duration * $sampleRate;
  print "x: $x> samplerate: $sampleRate\n", "bits: $bits\n", "freq: $freq\n", "length: $length\n", "octaves: $octaves\n", "max: $max\n" if $DEBUG;
  for $s (0 .. $length) {
    my $t = $s/$sampleRate;
    $t *= $freq;
    my $val = sin M_PI * 2 * $t;
    my $samp = $val * $max;
    $wave->write($samp);
    if ($DEBUG) { print "x:$x> \tlength: $length\n","\tmax_no: $max\n", "\tpos: $s\n", "\ttime: $t\n", "\tval: $val\n", "\tsamp: $samp\n" if !($s % 5120); }
  }
  $freq *= 2;
}

$wave->finish();