Splitting polygon in BSP

Hi ,
Following is the source code which I use to split a polygon by a plane. Sometimes the polygons that are split are not correct and I can’t seem to understand why. The source code is a pascal code found on Delphi3d.net web site which I changed to suit my needs. Please help me in fixing this.
If I traverse the polygon list to find the best node (that leads to less splits of polygon) rather than using the first polygon/plane of my list as the split plane, then my BSP works good, but it takes enormous time to calculate.

Recpolygon has following fields

vec4dbl = array[1…4] of double;
Shaderpolyarr = Array[1…MaxPoints] of point;
RecPolygon = RECORD
npnts : Integer;
plane : vec4dbl;
Clr : Integer;
transp : Single;
poly : Shaderpolyarr;
END;

procedure SplitPoly(tri: RecPolygon; plane: vec4dbl; var inpnts, outpnts: RecPolygon);
const
eps = 0.0001;
var
ptA, ptB, v: point;
sideA, sideB, factor: double;
i: Integer;
begin
{ Slice a polygon in half using the supplied partitioning plane. The procedure
creates front and back, two arrays of triangles. }
inpnts := tri;
inpnts.npnts := 0;
outpnts := tri;
outpnts.npnts := 0;
// Acquire the normal/color/transparency properties for the new polygons

ptA := tri.poly[tri.npnts];
sideA := DistToPlane(plane, ptA);
for i := 1 to tri.npnts do
begin
ptB := tri.poly[i];
sideB := DistToPlane(plane, ptB);
if sideB > EPS then
begin
if sideA < -EPS then
begin
v := subpnt(ptB, ptA);
factor := -DistToPlane(plane, ptA) / cgDotProduct(Plane2Pnt(plane), v);
outpnts.npnts := outpnts.npnts + 1;
outpnts.poly[outpnts.npnts] := AddPnt(ptA, mulpnt(v, factor));
inpnts.npnts := inpnts.npnts + 1;
inpnts.poly[inpnts.npnts] := outpnts.poly[outpnts.npnts];
end;
outpnts.npnts := outpnts.npnts + 1;
outpnts.poly[outpnts.npnts] := ptB;
end
else if sideB < -EPS then
begin
if sideA > EPS then
begin
v := subpnt(ptB, ptA);
factor := -DistToPlane(plane, ptA) / cgDotProduct(Plane2Pnt(plane), v);
outpnts.npnts := outpnts.npnts + 1;
outpnts.poly[outpnts.npnts] := AddPnt(ptA, mulpnt(v, factor));
inpnts.npnts := inpnts.npnts + 1;
inpnts.poly[inpnts.npnts] := outpnts.poly[outpnts.npnts];
end;
inpnts.npnts := inpnts.npnts + 1;
inpnts.poly[inpnts.npnts] := ptB;
end
else begin
outpnts.npnts := outpnts.npnts + 1;
outpnts.poly[outpnts.npnts] := ptB;
inpnts.npnts := inpnts.npnts + 1;
inpnts.poly[inpnts.npnts] := ptB;
end;
ptA := ptB;
sideA := sideB;
end;end;

Thanks

DP