/*
 * ADAPT2D : a software for automatic mesh adaptation in 2D
 *
 * AUTHOR : Manuel J. Castro Diaz(e-mail:castro@gamba.cie.uma.es)
 * ADAPTED FOR FREEFEM : Prud'homme Christophe (e-mail:prudhomm@ann.jussieu.fr) 
 *
 * this code is public domain
 * 
 * You may copy freely these files and use it for    
 * teaching or research. These or part of these may   
 * not be sold or used for a commercial purpose without
 * our consent
 * 
 * Any problems should be reported to the AUTHOR
 * at the following address : castro@gamba.cie.uma.es
 */


#include <header.hxx>
#include <r2.hxx>

void orienta2D(int* somtr, R2* coor,int nbt) {

  R2 coor0,coor1;
  Scalar area;
  int pos0,pos1,pos2;
  int i,cont=0;
  
  for (i=0; i<nbt; i++) {
    pos0=somtr[i*3]-1;
    pos1=somtr[i*3+1]-1;
    pos2=somtr[i*3+2]-1;
    coor0=coor[pos1]-coor[pos0];
    coor1=coor[pos2]-coor[pos0];
    area=(coor0.x*coor1.y-coor0.y*coor1.x)/2.0;
    if (fabs(area)<1e-14) {
      cerr<<"Mesh with degenerated triangles. "<<endl;
      cerr<<"Triangle n."<<i+1<<"area:"<<area<<endl;
      cerr<<"Error in subroutine orienta2D."<<endl;
      exit(1);
    }
    else {
      if (area<0) {
        cont++;
        somtr[i*3]=pos1+1;
        somtr[i*3+1]=pos0+1;
      }
    }
  }
  if (cont>0) {
#ifdef DEBUG
    cout<<"Number of triangles with negative orientation:"\
        <<cont<<endl<<endl;
#endif /* DEBUG */
  }
}
