Auto mechanical rig script help...

I am working on a script that would do a mechanical rig. When i say mechanical rig i mean, like a robot arm, where you would parent an object to the armatures bone. So in theory i would have a chain of objects that i would want to add an armature to like this:

Arm 3 is parented to Arm 2 and that is parented to Arm 1, so i would select Arm 3 and run my script, it would keep traveling up the parent chain and then go back through it and create the armature and align the objects origins with the bone origins so that everything should line up like this:

but i am having trouble with my script. Somewhere it is getting messed up and the armature and objects dont align, so that it turns out as follows:

All my code seems to work except for when i parent the object to the bone, the axises dont point where they should…what should i do to have everthing align, should i clear all parents and then parent them to the bones…

So i guess my main question is…What steps do i have to do in my code to parent the object to the bone and keep the object in the EXACT position it was in previous???


EDIT: The final bone in the chain is supposed to be like that, i wanted a tail to stick out so that it was easier to for IK.