/*! \file  MeshSegmentsIntersectionx.c
 */

#include "./MeshProfileIntersectionx.h"

void MeshSegmentsIntersection(double** psegments, int* pnumsegs,int* index, double* x, double* y, int nel, int nods, double* xc, double* yc, int numnodes){

	int      i,j;

	/*output: */
	double*  segments=NULL;
	Segment<double>* segment=NULL;
	int     numsegs;

	/*intermediary: */
	DataSet* segments_dataset=NULL;
	double   xnodes[3];
	double   ynodes[3];

	/*We don't know how many segments  we are going to get, so have a dynamic container: */
	segments_dataset=new DataSet();

	/*Go through elements, and call ElementSegmentsIntersection routine: */
	for(i=0;i<nel;i++){
		for(j=0;j<3;j++){
			xnodes[j]=x[*(index+3*i+j)];
			ynodes[j]=y[*(index+3*i+j)];
		}
		ElementSegmentsIntersection(segments_dataset,i,xnodes,ynodes,xc,yc,numnodes);
	}

	/*Using the segments_dataset dataset, create segments: */
	numsegs=segments_dataset->Size();
	segments=xNew<double>(5*numsegs);
	for(i=0;i<numsegs;i++){
		Segment<double>* segment=(Segment<double>*)segments_dataset->GetObjectByOffset(i);

		/*x1,y1,x2,y2 then element_id: */
		*(segments+5*i+0)=segment->x1;
		*(segments+5*i+1)=segment->y1;
		*(segments+5*i+2)=segment->x2;
		*(segments+5*i+3)=segment->y2;
		*(segments+5*i+4)=(double)segment->eid;
	}

	/*Free ressources:*/
	delete segments_dataset;

	/*Assign output pointers:*/
	*psegments=segments;
	*pnumsegs=numsegs;
}
