/*
 * OrderSegments.c: 
 * reorder segments so that their normals point outside the domain outline.
 */
#include "./trimesh.h"

int OrderSegments(double** psegments,int nseg, double* index,int nel){

	/*Error management: */
	int i;
	int noerr=1;

	/*Input: */
	double* segments=NULL;

	/*vertex indices: */
	double A,B;
	/*element indices: */
	int el;

	/*Recover segments: */
	segments=*psegments;

	for (i=0;i<nseg;i++){
		A=segments[3*i+0];
		B=segments[3*i+1];
		el=(int)segments[3*i+2]-1; //after AssociateSegmentToElement, el was a matlab index, we need the c index now.

		if (index[3*el+0]==A){
			if (index[3*el+2]==B){
				segments[3*i+0]=B;
				segments[3*i+1]=A;
			}
		}
		else if (index[3*el+1]==A){
			if (index[3*el+0]==B){
				segments[3*i+0]=B;
				segments[3*i+1]=A;
			}
		}
		else{
			if (index[3*el+1]==B){
				segments[3*i+0]=B;
				segments[3*i+1]=A;
			}
		}
	}

	/*Assign output pointers: */
	*psegments=segments;
	return noerr;
}
