import random

doc = MQSystem.getDocument()
objnum = doc.numObject
matnum = doc.numMaterial

for oi in range(0,objnum):
	obj = doc.object[oi]
	if obj is None: continue

	# Find a material that has the same name.
	newmi = -1
	for mi in range(0,matnum):
		mat = doc.material[mi]
		if mat is not None and mat.name == obj.name:
			newmi = mi
			break
	
	# Create a new material if necessary.
	if newmi == -1:
		mat = MQSystem.newMaterial()
		mat.name = obj.name
		mat.color = MQSystem.newColor(random.random(),random.random(),random.random())
		newmi = doc.addMaterial(mat)
	
	# Assign the material.
	numFace = obj.numFace
	for x in range(0,numFace):
		if obj.face[x].numVertex > 0:
			obj.face[x].material = newmi
