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

extern  Scalar criter(R2,R2,R2,Metrica);


Boolean busca_criterio(Triangulo_T1_dlist* Ltriangle) {

  Triangulo_T1_dlink* lt_lk;
  Triangulo_T1* t0;
  Metrica mm;
  R2 cor[3];
  Scalar a0,b0,pr;
  Scalar crit;
  Scalar crit_min=1e+30;
  Scalar crit_max=0;
  int nt[11];
  int i,num=0,err0;
  int i_crit;
  Boolean filt=FALSE;

  for (i=0; i<11; i++) nt[i]=0;
 
  lt_lk=Ltriangle->principio();
  while (lt_lk) {
    t0=lt_lk->t;
    mm.set(0,0,0);
    for (i=0; i<3; i++) {
      cor[i]=t0->s[i]->c;
      mm=mm+(t0->s[i]->mtr.inv(err0))/3.0;
    }
    mm=mm.inv(err0);
    crit=criter(cor[0],cor[1],cor[2],mm);
    t0->krit=crit;
    if (crit>crit_max) crit_max=crit;
    if (crit<crit_min) crit_min=crit;
    i_crit=int(crit*10);
    nt[i_crit]++;
    num++;
    lt_lk=lt_lk->sig();
  }
#ifdef DEBUG
  cout<<"Maximal quality:"<<crit_max<<endl;
  cout<<"Minimal quality:"<<crit_min<<endl;
  for (i=0;i<11; i++) {
    a0=Scalar(i)/10;
    b0=Scalar(i+1)/10;
    pr=Scalar(nt[i])*100.0/Scalar(num);
    if (i<3 && pr>3 || crit_min<0.1) filt=TRUE;
    cout<<"N. of Triangles with quality ["
	<<setw(3)
	<<a0 << ","
	<<setw(3)
	<<b0 << ")="
	<<setw(6)
	<<nt[i]	<<"  ........... Percent:"<<pr
	<<endl;
  }
#endif /* DEBUG */
  return filt;
}
