Exporting Bones With Custom Exporter

I’ve been attempting to export animation from Blender (2.63) for about 3 weeks now, and I simply cannot get it to work. I think the problem is to do with the bone offset matrices, but may possibly be the exported rotations. The problem is that rotations are not correct, they are either around the wrong axis, or the output-ed Z value is minus.

Currently (using the DirectX exporter as a guide) my code is as follows:


#for each bone etc.

RestBone = aObject.data.bones[Bone.name]


OffsetMatrix = RestBone.matrix_local.inverted()
OffsetMatrix *= armatureObject.matrix_world.inverted()

I have tried then multiplying this by the object the armature is attached to’s world matrix, but this gives incorrect results as well (as I translate all my vertices by this matrix when exporting). Is there anything wrong with this? Am I going about it the wrong way?

I thought I may as well post my code for exporting the scale, translation and rotation as well (again based on the DirectX exporter):


#For each bone etc.

if Bone.parent:
                PoseMatrix = Bone.parent.matrix.inverted()
            else:
                PoseMatrix = Matrix()
              
PoseMatrix *= Bone.matrix
                    
Position = PoseMatrix.to_translation()
Scale = PoseMatrix.to_scale()
Rotation = Bone.rotation_quaternion

#I have tried: Rotation = armatureObject.data.bones[Bone.name].matrix.to_quaternion() * Bone.rotation_quaternion
#But that doesn't work either

What am I doing wrong?! Why isn’t it working?! I’ll add more details of the specific incorrect calculations if required!

Thank you very much for your time!