set sharename to getShareName()
if sharename ­ "" then
	set pids to getPIDs()
	
	log pids
	
	if (pids is not equal to {}) then
		set XMLpath to getTemporaryFilePath()
		
		writePIDs(pids, XMLpath)
		addPlaylist(sharename, XMLpath)
	end if
end if

-- get iTunes source name, if it's a share only
-- otherwise return empty string
on getShareName()
	set sharename to ""
	tell application "iTunes"
		try -- avoid errors from iTMS windows, etc
			if kind of container of view of front window is shared library then
				set sharename to name of container of view of front window as Unicode text
			end if
		on error
			log "error with kind of container of front window"
		end try
	end tell
	return sharename
end getShareName

-- get persistent IDs
-- otherwise return empty list
on getPIDs()
	set pids to {}
	
	tell application "iTunes"
		set sel to selection
		repeat with tra in sel
			set end of pids to persistent ID of tra
		end repeat
	end tell
	return pids
end getPIDs

-- write PIDs to XML playlist format
on writePIDs(pids, XMLpath)
	-- write XML file
	set ret to ASCII character 10
	
	try
		set handle to open for access file XMLpath with write permission
	on error e
		log "Can't open file for writing: "
		log e
		return false
	end try
	
	write XMLHeader() to handle as Çclass utf8È
	repeat with pid in pids
		
		write "				<dict>" & ret to handle as Çclass utf8È
		write "					<key>Persistent ID</key>" & ret to handle as Çclass utf8È
		write "					<string>" & pid & "</string>" & ret to handle as Çclass utf8È
		write "				</dict>" & ret to handle as Çclass utf8È
		
	end repeat
	write XMLFooter() to handle as Çclass utf8È
	close access handle
end writePIDs

-- add playlist to specified iTunes share
on addPlaylist(sharename, XMLpath)
	tell application "iTunes"
		-- activate
		set shares to every source where kind is shared library
		repeat with share in shares
			get name of share
			if name of share is sharename then
				set playlist_path to XMLpath as alias
				log class of playlist_path
				log playlist_path
				(add playlist_path to share)
				-- todo break
			end if
		end repeat
	end tell
end addPlaylist

-- get path for XML playlist
on getTemporaryFilePath()
	return (path to "temp" from system domain as Unicode text) & ("FrontRowExportPlaylist.xml")
end getTemporaryFilePath

-- XML content
on XMLHeader()
	return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
  <key>Playlists</key>
  <array>
    <dict>
      <key>Name</key>
      <string>Remote Playlist</string>
      <key>Playlist Items</key>
      <array>
"
end XMLHeader

on XMLFooter()
	return "      </array>
    </dict>
  </array>
  <key>Tracks</key>
  <dict/>
</dict>
</plist>
"
end XMLFooter