#!/usr/bin/awk -f
#
#   http://code.google.com/media-translate/
#   Copyright (C) 2010  Serge A. Timchenko
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#

function escape(str)
{
  gsub(/&/, "&amp;", str);
  gsub(/>/, "&gt;", str);
  gsub(/</, "&lt;", str);
  return str
}

BEGIN {
  IGNORECASE = 1
  track = 0 
  print "<?xml version='1.0' encoding='UTF-8'?>"
  print "<playlist version='1' xmlns='http://xspf.org/ns/0/'>"
  if( name != "" )
  {
    print "<title><![CDATA[" name "]]></title>"
    fn = (match(name, /(.+)\.[^\.]*$/, arr) != 0) ? arr[1] : name;
    print "<image><![CDATA[" path "/" fn ".jpg]]></image>"
  }
  print "<trackList>"
  counter = 0;
}

/^ref/ { 
  gsub(/\r/, "");
  counter = counter + 1;
  ref[counter]=substr($0, index($0, "=")+1)
}

END {
  for(i=1; i<=counter; i++)
  {
    location = ref[i];
    match(location, /^(.+):\/\//, arr);
    protocol = tolower(arr[1]);
  
    print "<track>"
    print "<meta rel=\"protocol\"><![CDATA[" protocol "]]></meta>"
    print "<location><![CDATA[" location "]]></location>"
    print "</track>"
  }
  
  print "</trackList>"
  print "</playlist>"
}