/*
 * 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 <m_t0.hxx>

Scalar* gradfb(Mallado_T0* malla) {
  Triangulo_T0* t0;
  Vertice_T0* s0,*s1;
  Scalar* gfb;
  Scalar area0;
  int nbt=malla->nbtt();
  int sig[3];
  int i,j;
  int k0,k1;
  sig[0]=1;sig[1]=2;sig[2]=0;
  gfb=new Scalar[6*nbt];
  if (gfb==NIL) ERROR();
  for (i=0; i<nbt; i++) {
    t0=malla->saca_triangle(i);
    area0=t0->area();
    if (area0<1e-30) {
      cerr<<"Sorry. Triangle n."<<i+1<<" is degenerated. Area:"<<area0<<endl;
      cerr<<"Error in subroutine gradbf."<<endl;
      exit(1);
    }
    area0=0.5/area0;
    for (j=0; j<3; j++) {
      k0=sig[j];
      k1=sig[k0];
      s0=t0->s[k0];
      s1=t0->s[k1];
      gfb[i*6+j*2]=area0*(s0->c.y-s1->c.y);
      gfb[i*6+j*2+1]=area0*(s1->c.x-s0->c.x);
    }
  }
  return gfb;
}
