#!/usr/bin/perl -w
use strict;

# XXX: does this every vary?
# or is the lead-in always 88200 samples (88200 / 588 = 150)?
use constant SECTOR_OFFSET => 150;  # the lead-in, in frames

# conversion factors
use constant FRAMES_PER_SECOND => 75;
use constant SECONDS_PER_MINUTE => 60;

# see also http://flac.sourceforge.net/format.html#cuesheet_track
# 588 samples/frame = 44100 samples/sec / 75 frames/sec
use constant SAMPLES_PER_FRAME => 588;

my @sectors;
my $total_sectors;
while (<>) {
    if (/INDEX 01/) {
        my ($m,$s,$f) = /INDEX 01 (\d\d):(\d\d):(\d\d)/;
        push @sectors, ($m * SECONDS_PER_MINUTE * FRAMES_PER_SECOND) + ($s * FRAMES_PER_SECOND) + $f + SECTOR_OFFSET;
    } elsif (/lead-out/) {
        my ($total_samples) = /lead-out \d+ (\d+)/;
        $total_sectors = ($total_samples / SAMPLES_PER_FRAME) + SECTOR_OFFSET;
    }
}

# this is a CD TOC suitable for submitting to MusicBrainz as a CD Stub
# http://musicbrainz.org/doc/XML_Web_Service#Submitting_a_CDStub
my @toc_data = (
    1,                # first track number
    scalar(@sectors), # last track number
    $total_sectors,   # last frame (sector?)
    @sectors,         # start frame for each track
);

my $url = q{http://musicbrainz.org/bare/cdlookup.html?toc=} . join('+', @toc_data);

print "$url\n";
#print join(' ', @toc_data) . "\n";
#print "$_\n" foreach @toc_data;
