#!/usr/bin/perl -w
use strict;
undef $/;
die "usage: makeaiffhead <samp/sec> <#chan> <bits/samp/chan> <file1> [<file2> [..]]\n" unless(4<=@ARGV);
my $samplerate=1.0*shift @ARGV;
die "weird sample rate: $samplerate Hz\n" unless(100<$samplerate and $samplerate<100000);
$samplerate=pack_ieee80bit($samplerate);
my $numchannels=1*shift @ARGV;
my $bitspersamp=1*shift @ARGV;
die "weird #bits/sample/channel: $bitspersamp\n" unless(0<$bitspersamp and $bitspersamp<=32 and not($bitspersamp%8));
my $framesize=$numchannels*int($bitspersamp/8);
my ($file,$header,$size);
foreach $file (@ARGV) {
	print "$file\n";
	$size=-s $file or die "stat: $!";
	die "$file has length $size which isn't a multiple of $framesize\n" if($size % $framesize);
	$header="FORM".pack("N",50+$size)."AIFF";
	$header.="COMM".pack("NnNn",18,$numchannels,$size/$framesize,$bitspersamp).$samplerate;
	$header.="SSND".pack("NNN",8+$size,0,0);
	open(FILE,">new/$file.aiff") or die "open: $!";
	binmode FILE;
	print FILE $header or die "print: $!";
	close(FILE) or die "close: $!";
}

sub pack_ieee80bit {
	my $float=shift;
	my ($exp,$i);
	$exp=int($float)>>1;
	for($i=0;$i<32;$i++) {
		$exp=$exp>>1;
		last unless($exp);
	}
	my $buf=pack("CC",0x40,$i);
	for($i=32;$i;$i--) {
		last if($float>=0x80000000);
		$float*=2;
	}
	$buf.=pack("NN",$float,0);
	return $buf;
}
