// Cette classe est maintenant obsolete: generaldata <==> ntuple pour le dessin

#include <stdio.h>
#include "sopnamsp.h"
#include "pigfd1.h"
 
/* --Methode-- */
PIGenFitDat::PIGenFitDat(GeneralFitData* gfd, bool ad)
: PIDrawer(), mGFD(gfd), mAdDO(ad), VarX(0), ErrX(false), ErrY(false)
{
SelectX(0);
SelectErrBar(false,false);
NptDraw = 0;
}

PIGenFitDat::~PIGenFitDat()
{
if(mAdDO && mGFD)  delete mGFD;
}

/* --Methode-- */
void  PIGenFitDat::SelectX(int varx)
{
VarX = -1;
if(mGFD == NULL) return;
if(varx<0 || varx>=mGFD->NVar()) return;
VarX = varx;
}

/* --Methode-- */
void  PIGenFitDat::SelectErrBar(bool erbx,bool erby)
{
ErrX = erbx; ErrY = erby;
if(mGFD == NULL) {ErrX = ErrY = false; return;}
if(!mGFD->HasXErrors()) ErrX = false;
}

/* --Methode-- */
void PIGenFitDat::UpdateLimits()
{
if(!mGFD) return;
if(mGFD->NData()<=0) return;
if(VarX<0) return;
double xmin=9.e19, xmax=-9.e19, ymin=9.e19, ymax=-9.e19;
mGFD->GetMnMx(10*VarX+2,xmin,xmax);
mGFD->GetMnMx(0,ymin, ymax);
if(xmax<=xmin) xmax = xmin+1.;
if(ymax<=ymin) ymax = ymin+1.;
PIAxes::ReSizeMinMax(isLogScaleX(),xmin,xmax);
PIAxes::ReSizeMinMax(isLogScaleY(),ymin,ymax);
SetLimits(xmin,xmax,ymin,ymax);
SetAxesFlags(kBoxAxes | kExtTicks | kLabels);
}

/* --Methode-- */
void PIGenFitDat::Draw(PIGraphicUC* g, double xmin, double ymin, double xmax, double ymax)
{
if (!mGFD) return;
if(mGFD->NData()<=0) return;
if(VarX<0) return;
// On plotte les barre d'erreurs ligne demandee explicitement
if(GetGraphicAtt().GetLineAtt()!=PI_NotDefLineAtt) SelectErrBar(true,true);
double xp,yp,er;
NptDraw = 0;
for (int i=0; i<mGFD->NData(); i++) {
  xp = mGFD->Absc(VarX,i);
  yp = mGFD->Val(i);
  if(xp<xmin || xp>xmax || yp<ymin || yp>ymax)  continue;
  NptDraw++;
  if(ErrX) {
    er = mGFD->EAbsc(VarX,i);
    if(er>0.) g->DrawLine(xp-er,yp,xp+er,yp);
  }
  if(ErrY) {
    er = mGFD->EVal(i);
    if(er>0.) g->DrawLine(xp,yp-er,xp,yp+er);
  }
  g->DrawMarker(xp, yp); 
}
return;
}

/* --Methode-- */
double PIGenFitDat::GetDistanceToPoint(double x, double y)
{
 if(!mGFD) return 1.e+9;
 if(mGFD->NData()<=0) return 1.e+9;
 if(VarX<0) return 1.e+9;

 const int nessai = 100;
 long inc = (NptDraw>nessai) ? (long)(NptDraw/nessai)+1 : 1;

 double dist = -1.e+18;
 long n = 0;
 for(long i=0; i<mGFD->NData(); i++) {
   double xp=mGFD->Absc(VarX,i);
   if(xp<XMin() || xp>XMax()) continue;
   double yp=mGFD->Val(i);
   if(yp<YMin() || yp>YMax()) continue;
   if(n%inc==0) {
     xp = (xp-x)/(XMax()-XMin())/0.5;
     yp = (yp-y)/(YMax()-YMin())/0.5;
     xp = xp*xp+yp*yp;
     if(dist<0. || xp<dist) dist = xp;
   }
   n++;
 }
 dist=sqrt(fabs(dist));
 //cout<<"PIGenFitDat: xlim="<<XMin()<<","<<XMax()<<" ylim="<<YMin()<<","<<YMax()
 //    <<" NData="<<mGFD->NData()<<" inc="<<inc<<endl;
 //cout<<"....d="<<dist<<" x="<<x<<" y="<<y<<" NptDraw="<<NptDraw<<endl;

 return dist;
}
