#!/usr/bin/perl
print("Euro-Police ringtone generator\nby Dale Heatherington Feb 10, 2004\n");
@midi_header = (0x4d,0x54,0x68,0x64,0,0,0,6,0,0,0,1,0,0x40);
@midi_trackhdr = (0x4d,0x54,0x72,0x6b,0,0,0,0);
$low_note = 0x50 ; # low note  G#4 = 830
$high_note = 0x53 ; # high note B4 = 987
@time = (0x7f); #note dwell time (1 sec)
$instr = 20;   #Church Organ is default inst
if($ARGV[0]){
	$instr = $ARGV[0];   #sets midi instrument from command line if present
	}
print ("Instrument=",$instr,"\n");
@name = (0,0xff,0x01,7,ord("E"),ord("u"),ord("r"),ord("o"),ord("C"),ord("o"),ord("p"));
@patch = (0x00,0xc0,$instr); #Program Change channel 1
@volume = (0,0xb0,7,0x7f);
@attack = (0,0xb0,0x49,0x3f);
@release = (0,0xb0,0x48,0x3f);
@PB = (0,0xe0,0,0x30);  #PitchBlend down 1/2 semitone for 969/800 hz aprox
@end_track = (0,0xff,0x2f,00);
@low_note_on = (0,0x90,$low_note,0x7f);
@low_note_off = (@time,0x80,$low_note,0);
@high_note_on = (0,0x90,$high_note,0x7f);
@high_note_off = (@time,$high_note,0);
#
@track_setup = (@patch,@volume,@release,@attack,@PB);
@ring_cycle = (@high_note_on,@high_note_off,@low_note_on,@low_note_off);
@data = @track_setup;


$i = 0;
while($i < 15){  # 30seconds of Euro Police sound
	@data = (@data,@ring_cycle);
	$i = $i+1;
	}


#
@data = (@name,@data,@end_track); #Append end of track message
#
$tracksize = @data ;   #get size of track data
$midi_trackhdr[7] = $tracksize & 255; #Insert size into track header
$midi_trackhdr[6] = $tracksize / 256;

#print size to console for reference
print ("tracksize=",$tracksize,"\n");
@packet =  (@midi_header,@midi_trackhdr,@data);
#create a binary packet
$bin_str = $bin_str . pack("C*",@packet);
open( OUTFILE, ">EuroCop.mid");
binmode(OUTFILE);
print OUTFILE ( $bin_str);  #write .mid file to disk
close(OUTFILE);
print "EuroCop.mid file written. \n";




