iTunes Script For Missing Tracks on Album

I’m new to AppleScript, but learning fast…

I’m trying to write a script that will find albums in my iTunes library that do not have all of their tracks. For example, if I ripped a cd from my collection and it was scratched, I might not have been able to import track 5, but 1-4 and 6-12 imported fine. With thousands of songs in my library, it’s pretty much impossible to spot these missing tracks until I’m listening to an album and the song I expect to hear next is not there.

My first attempt is a script that matches the Track Count property of a track against the count of tracks with the same album name.

Here’s the code I came up with:

tell application "iTunes"
	
	set SourcePlaylist to "Sample Playlist"
	set TargetPlaylist to "Albums with Missing Tracks"
	
	if (playlist TargetPlaylist exists) then delete playlist TargetPlaylist
	
	make new playlist with properties {name:TargetPlaylist}
	
	set alltracks to every track of playlist SourcePlaylist
	
	repeat with i from 1 to count (every track of playlist SourcePlaylist)
		
		set albummatch to album of item i of alltracks
		set TrackMatchCount to track count of item i of alltracks
		set albummatchcount to count (every track of Sample Playlist where album = albummatch)
		if TrackMatchCount is not equal to albummatchcount then
			duplicate item i of alltracks to playlist TargetPlaylist
		end if
		
	end repeat
	
end tell

This works, but it’s really slow… the library is around 8000 songs and it takes over 10 minutes to run.

Any hints on speeding up the code, especially when it comes to looping through the entire library?

Also, two other problems I’ve considered but haven’t attempted to handle yet are…
-What if the track has no track count?
-What if two albums have the same name? The matching will return both these albums, even if complete.

I suppose a secondary goal might be to export the missing track number and album to a text file, but I’m only ready for scripting one app at a time.

Thanks in advance for any help,
eed
imac intel 183/512
os x 10.4.8
itunes 7.0.2

The problem may be (every track of Sample Playlist where album = albummatch). That’s slow. And aren’t you repeating the check for every track, even if there is more than on track from the same album?

Maybe you could create a running list of albums that have already been checked, and then skip any track that belongs to an album in this list?

Or, you might get rid of the whole “where album =” bit by creating three lists… album name, expected track count, actual track count. Then just loop tracks, if album not in list, add album to names, track count to expected, and a new element to actual, initially set to 1. If the track’s album is in the list, just add one to its actual counter. When you’re done, you can just run through the list and export any album where actual <> expected.