'change these 3 lines to reflect what is correct in your system, they will
'be the default values used when no command line args are passed.

const defMP3Dir = "d:\mp3\"
const defDSN = "cdj"
const defID3 = 0

'usage of defID3 -> 0 = use file names for track name derivation, and directory for artist info
'		 -> 1 = use ID3 information for track name and track artist information
'
'usage of defMP3Dir -> set this to your default mp3 directory (ie "m:\mp3s")
'
'usage of defDSN -> set this to the name of the dsn you create that points to
'		    the cdj .mdb file for your library.
'
'CDJ MP3 file import script (mp3Process.vbs)
'---------------------------
'      Rich Boykin
'      June 9, 2001
'      boykster@jetcity.com
'---------------------------
'Feel free to modify/distribute this file
'as you feel necessary.
'---------------------------
'You can run this file in two ways:
'1) edit the constants above and set them to your relevant values,
'   then run the script with no arguments.  
'
'2) edit the constants above and set them to your most used values,
'   but when you want to use a different value, use a command line option.
'
' -----COMMAND LINE USAGE (WITH SWITCHES)--------
'
'  c:\mp3Process.vbs id3(0 or 1) mp3Dir cdjDSN
'
' Where **id3 = either 0 or 1 (yes/no) to using ID3 info for
'   	  track/artist naming.
' 	**mp3Dir is your root mp3 directory
'	**cdjDSN is the name of your dsn for you cdj database
'
' The command line switches are optional, and can only be used
' incrementally;
'	ie: to specify a different mp3Dir from default, you must also
'	    specify the id3 value.  Same for cdjDSN, you would have to
'	    specify all 3 values.
'
'------REVISION LOG-------
'----------------
'rev 1.1 06/12/01
'----------------
'Added support for ID3 tags, just change useID3 to 1 to use ID3 info rather
'than dir/file name info. 
'
'Fixed an issue with track numbering
'-if you have an album with 10 tracks, but are missing a file,
' an album entry with only 9 tracks was created, but the track numbering
' matched the files and there was a hole (cdj would complain).  Now the 
' album is created with either the # of tracks, or the highest 
' track # - leaving an uncreated track for the missing track.
'
'Added support for command line switching of id3, mp3Dir, and cdjDSN
'
'----------------
'rev 1.0 06/09/01
'----------------
'First release...what do you expect?
'
'**********Directory Formatting*******************************************
'
'This import script works with a specific
'directory/file formatting.  It could be
'modified to work with other schemes, but
'that is currently not supported.
'
'Also, a system DSN needs to be created that points
'to the database that is used by CDJ.  You can specify
'the name of the DSN above, as the constant cdjDSN
'
'The format is as follows
'
'x:\Artist (directory)
'     |
'      ---Album (directory)
'            |
'	      - "01 - Track Name.mp3"
'	      - "02 - Track Name1.mp3"
'	      ...
'Where x:\ is your Mp3dir (above or command line).  MP3 file names must be formatted
'as above, and CAN now contain the character ' (that's a single quote, or
'apostrophe. (fixed rev 1.1) 
'
'NOTE: This script doesn't have ANY error code, so if it dies with an error,
'just open your mdb file and delete the necessary entries in the Albums and Tracks
'tables.
'
'****************start code*********************

dim db, rst
dim oTracks, oTrack, baseFolder, oArtist, fso, artistFolders, albumFolders, oAlbum
Dim analyzer
Set analyzer = WScript.CreateObject( "MP3Info.Control" )
analyzer.max_frames = 100

set db = createobject("adodb.connection")
set rst = createobject("adodb.recordset")
set fso = createobject("scripting.filesystemobject")

intCase = cint(wscript.arguments.length)

select case intCase
	case 0	
		useID3 = defID3	
		mp3Dir = defMP3Dir
		cdjDSN = defDSN
		processMP3s
	case 1
		useID3 = wscript.arguments(0)
		mp3Dir = defMP3Dir
		cdjDSN = defDSN
		processMP3s
	case 2
		useID3 = wscript.arguments(0)
		mp3Dir = wscript.arguments(1)
		cdjDSN = defDSN
		processMP3s
	case 3
		useID3 = wscript.arguments(0)
		mp3Dir = wscript.arguments(1)
		cdjDSN = wscript.arguments(2)
		processMP3s
end select

db.close
set analyzer = nothing
set rst = nothing
set db = nothing

sub processMP3s

	db.open "dsn=" & cdjDSN & ";uid=pwd="

	set baseFolder = fso.getfolder(mp3Dir)
	set artistFolders = baseFolder.subfolders

	for each oArtist in artistFolders
	
		if left(oArtist.name, 2) <> "__" then 'I use directories prefaced with __ to denote dirs NOT to be processed
						      'ie I store my cdj db there, and some other stuff
			set albumFolders = oArtist.subfolders
			for each oAlbum in albumFolders
				intExists=checkAlbumExists(oArtist.name, oAlbum.name)
				if intExists > 0 then
				    'add code to show progress if you want
				else
				    addAlbumToCDJ oArtist.name, oAlbum
				end if
			next
		end if
	next

	msgbox "Done!"

end sub

'misc functions

sub addAlbumToCDJ(strArtist, objAlbum)
	
	dim trackHandler
	dim varTracks()	

	set trackHandler = createObject("scripting.dictionary")
	
	strCDJID = generateCDJID
	set oTracks = objAlbum.files
	
	intPlayer = 1001
	intDurationTot = 0	
	strAlbum = objAlbum.name
	intI = 0		


	for each oTrack in oTracks
		intTrack = cint(left(oTrack.name,2))
		redim preserve varTracks(intI)
		varTracks(intI) = intTrack 
		intI = intI + 1
		analyzer.OpenFile(oTrack.path)
		intDuration = analyzer.Duration
		if useID3 = 0 then
			strTrackTitle = mid(oTrack.name, 6)
			strTrackTitle = left(strTrackTitle, instr(strTrackTitle, ".mp3") -1)
			strArtistTrack = strArtist
		else
			strTrackTitle = analyzer.Title
			strArtistTrack = analyzer.Artist
		end if

		strSoundFile = oTrack.path
		intDurationTot = intDurationTot + intDuration
		intMins = intDuration \ 60
		intSecs = cint(intDuration mod 60)
		
		db.execute("Insert into tracks (CDJID, Track, Title, Artist, Soundfile, minutes, seconds, frames, dateAdded, dateReleased) values ('" & strCDJID & "', " & intTrack & ",'" & replace(strTrackTitle, "'", "''") & "', '" & replace(strArtistTrack, "'", "''") & "','" & replace(strSoundFile, "'", "''") & "', " & intMins & ", " & intSecs & ", 0, '" & date & "', '" & date & "')")
	next
	

	for i = 0 to ubound(varTracks) - 1
    		for j= 0 to i
        		if varTracks(j)>varTracks(j+1) then
            			temp=varTracks(j+1)
            			varTracks(j+1)=varTracks(j)
            			varTracks(j)=temp
        		end if
   		 next
	next 
	
	if varTracks(ubound(varTracks)) > oTracks.count then
		intTracks = varTracks(ubound(varTracks))
	else
		intTracks = oTracks.count	
	end if

	intMinsTot = intDurationTot \ 60
	intSecsTot = cint(intDuration mod 60)
	
	db.execute ("Insert into albums (CDJID, Title, Artist, Tracks, Player, Position, frames, Minutes, Seconds, dateAdded, dateReleased) values ('" & strCDJID & "', '" & replace(strAlbum, "'", "''") & "', '" & replace(strArtist, "'", "''") & "', " & intTracks & "," & intPlayer & ", 0, 0, " & intMinsTot & ", " & intSecsTot & ", '" & date & "', '" & date & "')")

end sub



function checkAlbumExists(strArtist, strAlbum1)
	set rst = db.execute("select count(cdjid) from albums where artist = '" & replace(strArtist, "'", "''") & "' and title = '" & replace(strAlbum1, "'", "''") & "'")
	rst.movefirst
	checkAlbumExists = rst(0)
	rst.close
end function

function generateCDJID
	intOK = 1
	do until intOK = 0
		randomize
		strCDJID = ""
		varArray = array(0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F")
		for i = 0 to 15
			intA = cint(rnd*15)
			strCDJID = strCDJID & varArray(intA)
		next
		intOK = checkCDJID(strCDJID)
	loop
	generateCDJID = strCDJID

end function

function checkCDJID(strCDJID1)
	set rst = db.execute("select count(cdjid) from albums where cdjid = '" & strCDJID1 & "'")
	rst.movefirst
	checkCDJID = cint(rst(0))
	rst.close
end function	