#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $m3u = shift;
die "Missing m3u as first argument\n" unless ($m3u && (-f $m3u));

open (my $fh, "<", $m3u) or die "Cannot open playlist $!\n";

my $counter = 0;
my %out;

while (my $line = <$fh>) {
  chomp $line;
  $line =~ s/\r//g;
  next unless $line;
  if ($line =~ m/^#EXTINF:(-?\d+),(.+)/) {
    $counter++;
    $out{$counter} = {} unless exists $out{$counter};
    warn "Title for $counter exists" if exists $out{$counter}->{Title};
    $out{$counter}->{Title}  = $2;
    warn "Length for $counter exists" if exists $out{$counter}->{Length};
    $out{$counter}->{Length} = $1;
  }
  elsif ($line !~ m/^#/) {
    warn "File for $counter exists" if exists $out{$counter}->{File};
    $out{$counter}->{File} = $line;
  }
}
close $fh;

print "[playlist]\r\n";

for (my $i = 1; $i <= $counter; $i++) {
  foreach my $key (qw/File Title Length/) {
    print $key . $i . "=" . $out{$i}->{$key} . "\r\n";
  }
}

print "NumberOfEntries=$counter\r\n";
print "Version=2\r\n";