# Parse command line arguments
if(ARGV.size != 2)
	print "Converts a DragonSpeak Binary file back into text.\n"
	print "Revision 2, 2004-09-13, by Tafyrn\n\n"
	print "Usage: ruby dsbconverter dslist.ini default.dsb > default.ds\n"
	print "       Where the dslist.ini file can be found in your furcadia folder.\n"
	exit
else
	dsdFileName = ARGV[0]
	dsbFileName = ARGV[1]
end

# Create a new method to convert
# the numeric values.
class String
	def as_UINT16
		lsbNum = self[0]
		msbNum = self[1]
		
		value = msbNum * 256 + lsbNum
		
		return value
	end
end

# Parse the DS Dictionary
dsDict = File.open(dsdFileName, "rb")
dictionaryHash = Hash.new

while(dsDict.eof? == false)
	print "Loading DS Dictionary file '", dsdFileName, "'...\n"
	
	# Parse lines
	dsDict.each do |line|
		if(line[3] == ?:)
			line = line.slice(2, line.length)
			trigger = line.slice!(0, line.index(" "))
			line.squeeze!(" \t")
			line = line.slice(2, line.length - 4)
			line = line.slice(0, line.index("\""))
			
			# Add to hash
			dictionaryHash[trigger] = line
		end
	end
end

dsDict.close


# Open the file
dsbFile = File.open(dsbFileName, "rb")
magicNum = dsbFile.read(4)

if(magicNum == 'DSB1')
	print "Analyzing Furcadia DSB file '", dsbFileName, "'...\n"
	print "--------------------------------------------\n"

	# Skip the ignore section
	dsbFile.read(17)
	
	while(dsbFile.eof? == false)
		dsMajor = dsbFile.read(2)
		dsMinor = dsbFile.read(2)
		
		# Put a line between causes
		if(dsMajor.as_UINT16 == 0)
			print "\n"
		end
		
		# Print the DS command
		trigger = dsMajor.as_UINT16, ":", dsMinor.as_UINT16
		trigger = trigger.join
		dsline = " " * dsMajor.as_UINT16, "(", trigger, ") ", dictionaryHash[trigger], "\n"
		dsline = dsline.join.sub("...", "#")
		dsarray = dsline.split("#")
		finalarray = Array.new
		
		# Insert the parameters into the array.
		for i in 1..8
			param = dsbFile.read(2)
			
			if(dsarray.length > 1)
				finalarray = finalarray << dsarray.delete_at(0)
				finalarray = finalarray << param.as_UINT16
			end
		end
		
		finalarray = finalarray << dsarray.delete_at(0)
		
		print finalarray.join("")
	end
	print "--------------------------------------------\n"
	print "End of DSB.\n"
	
	dsbFile.close
else
	print "The file '", dsbFileName, "' does not appear to be a valid Furcadia DSB File.\n"
end