How do I modify a keyframe/curve's tangent in code?

I recently noticed that when i split animations Unity modifies the tangents of some of the keys (usually the first, last and/or second to the last) creating a very noticable pop especially in looped animations.

using UnityEngine; 
using UnityEditor; 
using System; 
using System.Collections.Generic;

public class FixAnimation : ScriptableObject 
    [MenuItem("Animation/Fix Animation")] 
    static void ListChildTransforms() 

	GameObject g = Selection.activeGameObject;

	if (g.animation && g.animation.clip)
		List<string> clips = new List<string>();

		foreach (AnimationState state in g.animation)

		foreach(string clipName in clips)


     public static void FixClip(AnimationClip clip)

	AnimationClipCurveData[] curveData = AnimationUtility.GetAllCurves(clip,true);
	AnimationCurve anim = null;

	for (int i = 0; i < curveData.Length; i++)

		anim = curveData*.curve;*
  •   	anim.SmoothTangents(0,0);*
  •   	anim.SmoothTangents(anim.length-2,0);*
  •   	anim.SmoothTangents(anim.length-1,0);*

_ /*_

  •   	anim.keys[0].outTangent = 0;*
  •   	anim.keys[0].inTangent = 0;*
  •   	anim.keys[length-2].outTangent = 0;*
  •   	anim.keys[length-2].inTangent = 0;*
  •   	anim.keys[length-1].outTangent = 0;*
  •   	anim.keys[length-1].inTangent = 0;*

_ */_

  •   	//replace existing curve*

clip.SetCurve(curveData.path, curveData_.type,curveData*.propertyName,anim);

I attempted to fix this by code but i am not having much success. It seems when i succed in cleaning up the last frame the first frame suffers. Is there an ordering that need to be followed? what does keyfram.tangentMode control? When editing the animation in the animation view all i need to do is right click on the key and set both tangents to linear and the popping is gone. How do i replicate this in code?_

Have you read this:

If you want to use Mathf.Tan keep in mind that it works with radians. If you want to use degrees you have to multiply by Mathf.Deg2Rad

Thanks for the reply. But this makes me wonder how do you specify both tangents as linear? Cos it seems it would be some what relative to the last key. maybe making a triangle with the value of previous key current key and the time between them to calculate the outTangent of the last key and the inTangent of the current key.

It seems the curve editor has the functions i need there has to be a way to reuse that function.