VEX- Find 2 Closest Points

//Find the 2 closest points for each point

i@closestPoint = -1;
i@secondClosestPoint = -1;

float dist1 = 1000000;
float dist2 = 1000000;

for(int i = 0; i < @numpt; i++){
    if(i != @ptnum) {      
        float newDist = distance(@P, point(0, "P", i));
        if(newDist < dist1) {
            dist1 = newDist;
            i@secondClosestPoint = i@closestPoint;
            i@closestPoint = i;
        } else {
            if(newDist < dist2) {
                dist2 = newDist;
                i@secondClosestPoint = i;
            }
        }
    }
}

int newPrimID = addprim(0, "polyline");
addvertex(0, newPrimID, i@closestPoint);
addvertex(0, newPrimID, @ptnum);
addvertex(0, newPrimID, i@secondClosestPoint);