Rhinoceros with python script: CurveThroughPoints (rs.AddInterpCurve) after sorting the points

Background

I have a few points with witch I want to make a CurveThroughPoints. This is not a problem when doing it manually but when I tried that with python script using rs.AddInterpCurve, it generated strange looping curve. It's quite obvious the order of the points *1 is used for drawing the curve, instead of using the distance to the next point which is likely to be used in the CurveThroughPoints. Therefore, to my understanding, I have to sort the points by myself. So I did that.

Code

Assuming you have a layer "pts_test1" containing the points, and an empty layer "crv_test1" where your resultant curve will be placed.

def make_curve_through_points(layer_name_pts, layer_name_crv, deg, ktstyle):
    ## Obtain the GID of the points
    rs.CurrentLayer(layer_name_crv)
    id_points = rs.ObjectsByLayer(layer_name_pts, True)

    ## Obtain 3D coordinates of each point
    points_3d = []
    for i in range(0, len(id_points)):
        points_3d.append( rs.PointCoordinates(id_points[i]) )

    ## Sort the points
    points_sorted = rs.SortPointList(points_3d)

    ## Generate the curves
    rs.AddInterpCurve(points_sorted, degree=deg, knotstyle=ktstyle, start_tangent=None, end_tangent=None)


## Sample usage
layer_name_pts = "pts_test1"
layer_name_crv = "crv_test1"
deg = 3
ktstyle = 1
make_curve_through_points(layer_name_pts, layer_name_crv, deg, ktstyle)

Instead of using SortPointList, directly specifying the direction with SortPoints might be necessary depending on the situation.

References

*1:Perhaps the order of generations of the points, which is held internally and cannot be seen...