#include <stdio.h>
#include "pigfd2.h"

/* --Methode-- */
PIGenFitDat3D::PIGenFitDat3D(GeneralFitData* gfd, bool ad)
: PIDrawer3D(), mGFD(gfd), mAdDO(ad)
, VarX(0), VarY(1), ErrX(false), ErrY(false), ErrZ(false)
{
SelectXY(0,1);
SelectErrBar(false,false,false);
}

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

/* --Methode-- */
void  PIGenFitDat3D::SelectXY(int varx,int vary)
{
VarX = VarY = -1;
if(mGFD == NULL) return;
if(varx<0 || varx>=mGFD->NVar()) return;
if(vary<0 || vary>=mGFD->NVar()) return;
VarX = varx; VarY = vary;
}

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

/* --Methode-- */
void PIGenFitDat3D::UpdateLimits()
{
if(!mGFD) return;
if(mGFD->NData()<=0) return;
if(VarX<0 || VarY<0) return;
double xmin=9.e19, xmax=-9.e19, ymin=9.e19, ymax=-9.e19, zmin=9.e19, zmax=-9.e19;
mGFD->GetMinMax(10*VarX+2,xmin,xmax);
mGFD->GetMinMax(10*VarY+2,ymin,ymax);
mGFD->GetMinMax(0,zmin, zmax);
if(xmax<=xmin) xmax = xmin+1.;
if(ymax<=ymin) ymax = ymin+1.;
if(zmax<=zmin) zmax = zmin+1.;
// Voir commentaires pintuple3d.cc
double D = xmax-xmin;
if (D < (ymax-ymin))  D = ymax-ymin;
D *= 1.4;
Set3DView((xmin+xmax)/2., (ymin+ymax)/2, (zmin+zmax)/2., 
          (xmin+xmax)/2.+D , (ymin+ymax)/2.-2.5*D , zmin+(zmax-zmin)*0.85, 0.25, 0.25);  

x3Min = xmin;    x3Max = xmax;
y3Min = ymin;    y3Max = ymax;
z3Min = zmin;    z3Max = zmax;

}

/* --Methode-- */
void PIGenFitDat3D::Draw(PIGraphicUC* g, double xmin, double ymin, double xmax, double ymax)
{
// On trace les axes - En attendant de faire mieux - Reza 8/12/98
if (axesFlags != kAxesNone)  DrawAxes(g);

if (!mGFD) return;
if(mGFD->NData()<=0) return;
if(VarX<0 || VarY<0) return;

// On plotte les barre d'erreurs ligne demandee explicitement
if(mLAtt!=PI_NotDefLineAtt) SelectErrBar(true,true,true);

#if defined(__DECCXX) || defined(__KCC__)
PIGraphic3D* g3 = dynamic_cast<PIGraphic3D*>(g);
#else
PIGraphic3D* g3 = (PIGraphic3D*)(g);
#endif

if (mLAtt == PI_NotDefLineAtt)  g3->SelLine(PI_ThinLine);

double xp,yp,zp,er;
for (int i=0; i<mGFD->NData(); i++) {
  xp = mGFD->Absc(VarX,i);
  yp = mGFD->Absc(VarY,i);
  zp = mGFD->Val(i);
  if(ErrX) {
    er = mGFD->EAbsc(VarX,i);
    if(er>0.) g3->DrawLine3D(xp-er,yp,zp,xp+er,yp,zp);
  }
  if(ErrY) {
    er = mGFD->EAbsc(VarY,i);
    g3->DrawLine3D(xp,yp-er,zp,xp,yp+er,zp);
  }
  if(ErrZ) {
    er = mGFD->EVal(i);
    g3->DrawLine3D(xp,yp,zp-er,xp,yp,zp+er);
  }
  g3->DrawMarker3D(xp,yp,zp); 
}

return;
}
