import bpy, sys, os
from bpy.app.handlers import persistent

def main():
    argv = sys.argv
    argv = argv[argv.index("--") + 1:]


    #TODO Mettre separateurs en auto; avec os.sep pour les chemins de fichier
    # Rebuild the correct arguments type
    args_colors =  list()
    for i in range(0, len(argv), 3):
        arg1 = float(argv[i-3].replace("[", "").replace(",", ""))
        arg2 = float(argv[i-2].replace(",", ""))
        arg3 = float(argv[i-1].replace("]", "").replace(",", ""))
        args_colors.append((arg1, arg2, arg3, 500))
    basefile = str(os.path.dirname(os.path.realpath(__file__)) + "/tree.blend")
    section = "\\Object\\"
    _object = "Tree"
    @persistent
    def load_tree(dummy):
        bpy.ops.wm.append(filepath=basefile + section + _object, directory=basefile + section, filename=_object)
    for i in range(len(args_colors)):
        bpy.app.handlers.load_post.append(load_tree)
    bpy.ops.wm.open_mainfile(filepath="plateau.blend")
    for i, color in enumerate(args_colors):
        if i == 0:
            name = "Tree"
        else:
            name = "Tree.00" + str(i)
        tree = bpy.context.scene.objects[name].data
        tree_material = bpy.data.materials.new(name=name + "_texture")
        tree_material.diffuse_color = color
        tree.materials[1] = tree_material
main()
    