#!/usr/bin/perl -w
print "Content-type: text/plain\n\n";
my $script = q`#!perl -w
use strict;

my $cuefile = $ARGV[0] || die "No Cue file specified";
my $m3ufile = $ARGV[1] || die "No m3u specified";
my $path = $ARGV[2] || die "No path specified";

open(CUE, "$cuefile");
open(M3U, ">$m3ufile");
my %cueentry;
my @cueentries;
my $lastnum;
my $curnum = '00';
while (my $line = <CUE>) {
  $line =~ s/\r?\n$//;
  if ($line =~ /^PERFORMER\s"([^"]+)"/) {
    if (defined $cueentry{$curnum}{offset}) {
      foreach my $num (@cueentries) {
        if ($num eq $cueentries[$#cueentries]) {
          printf M3U ("#%s - %s\r\n%s/%s\t%d\t%d\r\n", $cueentry{$num}{performer}, $cueentry{$num}{track}, $path, $cueentry{filename}, $cueentry{$num}{offset}, -1);
        } else {
          printf M3U ("#%s - %s\r\n%s/%s\t%d\t%d\r\n", $cueentry{$num}{performer}, $cueentry{$num}{track}, $path, $cueentry{filename}, $cueentry{$num}{offset}, $cueentry{$num}{endoffset});
        }
      }
    }
    %cueentry = @cueentries = ();
    $cueentry{performer} = $1;
  } elsif ($line =~ /^\s+PERFORMER\s"([^"]+)"/) {
    $cueentry{$curnum}{performer} = $1;
  } elsif ($line =~ /^TITLE\s"([^"]+)"/) {
    $cueentry{album} = $1;
  } elsif ($line =~ /^\s+TRACK (\d+) AUDIO/) {
    push @cueentries, $1;
    $curnum = $1;
  } elsif ($line =~ /^\s+TITLE\s"([^"]+)"/) {
    $cueentry{$curnum}{track} = $1;
  } elsif ($line =~ /^\s+INDEX\s\d+\s(\d+):(\d+):(\d+)/) {
    if ($#cueentries) {
      $cueentry{$cueentries[$#cueentries-1]}{endoffset} = $1 * 60 + $2;
    }
    $cueentry{$curnum}{offset} = $1 * 60 + $2;
  } elsif ($line =~ /^FILE\s"([^"]+)"/) {
    $cueentry{filename} = $1;
  }
}
close(CUE);
if (defined $cueentry{$curnum}{offset}) {
  foreach my $num (@cueentries) {
    if ($num eq $cueentries[$#cueentries]) {
      printf M3U ("#%s - %s\r\n%s/%s\t%d\t%d\r\n", $cueentry{$num}{performer}, $cueentry{$num}{track}, $path, $cueentry{filename}, $cueentry{$num}{offset}, -1);
    } else {
      printf M3U ("#%s - %s\r\n%s/%s\t%d\t%d\r\n", $cueentry{$num}{performer}, $cueentry{$num}{track}, $path, $cueentry{filename}, $cueentry{$num}{offset}, $cueentry{$num}{endoffset});
    }
  }
}
close(M3U);
`;
$script =~ s/\n/\r\n/g;
print $script;
