import bpy

class LoadVisemesOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.load_visemes_moho"
    bl_label = "Load and apply visemes from file"
    filepath = bpy.props.StringProperty(subtype="FILE_PATH")

    @classmethod
    def poll(cls, context):
        return context.active_object is not None and context.active_object.type == 'MESH'

    def invoke(self, context, event):
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}
        
    def execute(self, context):
        obj = context.active_object
        start_frame = context.scene.frame_current
        f = open(self.filepath, 'r')        
        last = -1;
        old_factor = obj.muscle_animation_factor
        for line in f:
            words = line.split()
            if len(words) < 2:
                continue
            offset = int(words[0])
            viseme = words[1]
            if viseme == "rest":
                anim_name = "Neutral"
            else:
                anim_name = "Viseme." + viseme
            if last > 0 and (offset - last) < 5:                
                obj.muscle_animation_factor = 1/(5 - (offset-last))
            else:
                obj.muscle_animation_factor = 1
            context.scene.frame_current = start_frame + offset
            old_index = obj.muscle_animation_index
            obj.muscle_animation_index = obj.muscle_animations.keys().index(anim_name)
            bpy.ops.object.insert_muscles_animation()
            obj.muscle_animation_index = old_index
            last = offset
        context.scene.frame_current = start_frame        
        obj.muscle_animation_factor = old_factor
        f.close()
        return {'FINISHED'}