#!/usr/bin/perl -W

use strict;
use warnings;

sub t {
	my @ti = gmtime( shift );
	return( "$ti[2]:$ti[1]:$ti[0]" );
}

my %progs = ( "sox" => "/usr/bin/sox", "lame" => "/usr/local/bin/lame",
"rm" => "/bin/rm" );

my @lines;
my $album;
my $track;
my $title;
my $start;
my $file;
my $index;
my $performer;
my @trackdata; # 0 = number, 1 = title, 2 = performer, 3 = index

@lines = <STDIN>;

foreach my $line ( @lines ) {
	if( $line =~ /^\s+(TRACK) ([0-9]+) / ) {
		if( $2 > scalar( @trackdata ) ) {
			for( my $i=0; $i<$2 ; $i++ ) {
				$trackdata[$i][0] = -1;
			}
		}
		$trackdata[$2][0] = $2;
		$track = $2;
	}
	if( $line =~ /^(FILE) (")*(.*)("){1}/ ) {
		$file = $3;
		#$file =~ s/mp3/wav/;
	}
	if( $line =~ /^(TITLE) (.*)$/ ) {
		$album = $2;
	}
	if( $line =~ /^\s+(TITLE) (")*(.*)("){1}/ ) {
		$trackdata[$track][1] = $3;
	}
	if( $line =~ /^\s+(PERFORMER) (")*(.*)("){1}/ ) {
		$trackdata[$track][2] = $3;		
	}
	if( $line =~ /^\s+(INDEX) [0-9]+ ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/ ) {
		$trackdata[$track][3] = ( $2 * 60 ) + ( $3 ) ;
		$trackdata[$track][3] = ( $trackdata[$track][3] * 100 ) + $4;
	}
	
}

my $count = scalar( @trackdata );

for( my $i=0 ; $i<$count ; $i++ ) {
	next if( $trackdata[$i][0] == -1 );
	my $command;
	$command = "sox $file \"$trackdata[$i][0]_-_$trackdata[$i][2]_-_$trackdata[$i][1].wav\" trim " . t( $trackdata[$i][3] / 100 ) . "." . $trackdata[$i][3] % 100 ;
	if( $i < $count-1 ) {
		$command .= " " . t( ( $trackdata[$i+1][3] - $trackdata[$i][3] ) / 100 );
		$command .= "." . ( $trackdata[$i+1][3] - $trackdata[$i][3] ) % 100;
	}
	$command =~ s/\///g;
	print( $command . "\n" );
	`$command`;
	`${progs{"lame"}} -b 192 \"$trackdata[$i][0]_-_$trackdata[$i][2]_-_$trackdata[$i][1].wav\" \"$trackdata[$i][0]_-_$trackdata[$i][2]_-_$trackdata[$i][1].mp3\"`;
	`${progs{"rm"}} \"$trackdata[$i][0]_-_$trackdata[$i][2]_-_$trackdata[$i][1].wav\"`;
}

