Create building pads from poligons

I have a list of lines and arcs. 4 lines/arcs make up on building pad entity. The list is disorganized and so I want to create a polygon based on the lines/arcs startpoint and endpoints. When I run my code, it shows Run Started… for a really long time and I have no choice but to force exit the program. Here is my code:

def SortList(BP:var[])
{
Lots = {};
return = [Imperative]
{
while (List.Count(BP) > 0)
{
Lot = {};
StartPt = BP[0].StartPoint;
List.AddItemToEnd(StartPt,Lot);
OccupiedPt = StartPt;
List.RemoveItemAtIndex(BP, 0);
while (StartPt != OccupiedPt || List.Count(Lot) == 1)
{
cnt = List.Count(BP);
i = 0;
while (i < cnt)
{
if (BP[i].StartPoint == OccupiedPt)
{
List.AddItemToEnd(BP[i].StartPoint, Lot);
OccupiedPt = BP[i].EndPoint;
List.RemoveItemAtIndex(BP,i);
i = cnt;
}
elseif (BP[i].EndPoint == OccupiedPt)
{
List.AddItemToEnd(BP[i].EndPoint, Lot);
OccupiedPt = BP[i].StartPoint;
List.RemoveItemAtIndex(BP,i);
i = cnt;
}
}
}
pg = Polygon.ByPoints(Lot);
List.AddItemToEnd(pg, Lots);
}
return = Lots;
}
};
SortList(curves);