/**
 * \file TrkViewer.cpp
 * \author Elena Vannuccini
 */
#include <TrkViewer.h>
// (mechanical) z-coordinate of the tracker planes
#define ZTRK6 -22.23
#define ZTRK5 -13.32
#define ZTRK4 -4.42
#define ZTRK3 4.48
#define ZTRK2 13.38
#define ZTRK1 22.28
// (mechanical) x/y-coordinates of magnet cavity
#define XTRKL -8.1
#define XTRKR  8.1
#define YTRKL -6.6
#define YTRKR  6.6
// (approximate) position of dead area among sensors
#define DX1 -2.7
#define DX2  2.7
#define DY  -0.2

#define VCOL 18//29      // volume color
#define PCOL 1       // plane color
#define CCOL 15       // column color

#define HTCOL 2      // track-hit color
#define HSCOL 11     // singlet-hit color
 
#define TCCOL 40 // color of track-candidates

/**
 * Tracker volume (x/y/top projections) constructor
 */
GTrkVolume::GTrkVolume(){

 cavity_l = new TBox(XTRKL,ZTRK6,XTRKR,ZTRK1);
 cavity_l->SetFillColor(VCOL);
 plane_l[0] = new TLine(XTRKL,ZTRK1,XTRKR,ZTRK1);
 plane_l[1] = new TLine(XTRKL,ZTRK2,XTRKR,ZTRK2);
 plane_l[2] = new TLine(XTRKL,ZTRK3,XTRKR,ZTRK3);
 plane_l[3] = new TLine(XTRKL,ZTRK4,XTRKR,ZTRK4);
 plane_l[4] = new TLine(XTRKL,ZTRK5,XTRKR,ZTRK5);
 plane_l[5] = new TLine(XTRKL,ZTRK6,XTRKR,ZTRK6);
 for(Int_t ip=1; ip<=6;ip++)plane_l[ip-1]->SetLineColor(PCOL);

 cavity_r = new TBox(YTRKL,ZTRK6,YTRKR,ZTRK1);
 cavity_r->SetFillColor(VCOL);
 plane_r[0] = new TLine(YTRKL,ZTRK1,YTRKR,ZTRK1);
 plane_r[1] = new TLine(YTRKL,ZTRK2,YTRKR,ZTRK2);
 plane_r[2] = new TLine(YTRKL,ZTRK3,YTRKR,ZTRK3);
 plane_r[3] = new TLine(YTRKL,ZTRK4,YTRKR,ZTRK4);
 plane_r[4] = new TLine(YTRKL,ZTRK5,YTRKR,ZTRK5);
 plane_r[5] = new TLine(YTRKL,ZTRK6,YTRKR,ZTRK6);
 for(Int_t ip=1; ip<=6;ip++)plane_r[ip-1]->SetLineColor(PCOL);

 cavity_c = new TBox(XTRKL,YTRKL,XTRKR,YTRKR);
 cavity_c->SetFillColor(VCOL);
 
 column_l[0] = new TLine(DX1,ZTRK6,DX1,ZTRK1);
 column_l[1] = new TLine(DX2,ZTRK6,DX2,ZTRK1);
 column_l[0]->SetLineColor(CCOL);
 column_l[1]->SetLineColor(CCOL);
 column_l[0]->SetLineStyle(2);
 column_l[1]->SetLineStyle(2);

 column_r[0] = new TLine(DY,ZTRK6,DY,ZTRK1);
 column_r[0]->SetLineColor(CCOL);
 column_r[0]->SetLineStyle(2);

 column_c[0] = new TLine(DX1,YTRKL,DX1,YTRKR);
 column_c[1] = new TLine(DX2,YTRKL,DX2,YTRKR);
 column_c[2] = new TLine(XTRKL,DY,XTRKR,DY);
 column_c[0]->SetLineColor(CCOL);
 column_c[1]->SetLineColor(CCOL);
 column_c[2]->SetLineColor(CCOL);
 column_c[0]->SetLineStyle(2);
 column_c[1]->SetLineStyle(2);
 column_c[2]->SetLineStyle(2);


}
//
/**
 *Draw x projection
 */
void GTrkVolume::DrawProjectionX(){
	cavity_l->Draw();
	for(Int_t ip=1; ip<=6;ip++)plane_l[ip-1]->Draw();
	column_l[0]->Draw();
	column_l[1]->Draw();
}
//
/**
 *Draw y projection
 */
void GTrkVolume::DrawProjectionY(){
	cavity_r->Draw();
	for(Int_t ip=1; ip<=6;ip++)plane_r[ip-1]->Draw();
	column_r[0]->Draw();
}
//
/**
 *Draw top projection
 */
void GTrkVolume::DrawProjectionT(){
	cavity_c->Draw();
	column_c[0]->Draw();
	column_c[1]->Draw();
	column_c[2]->Draw();
}
//
void GTrkVolume::Delete(){
	cavity_l->Delete();
	cavity_r->Delete();
	cavity_c->Delete();
	for(Int_t ip=1; ip<=6;ip++){
		plane_l[ip-1]->Delete();
		plane_r[ip-1]->Delete();
	};
	column_l[0]->Delete();
	column_l[1]->Delete();
	column_r[0]->Delete();
	column_c[0]->Delete();
	column_c[1]->Delete();
	column_c[2]->Delete();
	

};

//===============================================================
//
//
//===============================================================
GTrkLevel2::GTrkLevel2(){
    Track    = new TClonesArray("GTrkTrack");
    Image    = new TClonesArray("GTrkTrack");
    SingletX = new TClonesArray("GTrkHit");
    SingletY = new TClonesArray("GTrkHit");

    DRAWIMAGE=false;

}
//
//Int_t GTrkLevel2::Set(TrkLevel2* trk_event){	
//	return 0;
//}
//
/**
 * Constructor
 */
GTrkLevel2::GTrkLevel2(TrkLevel2* trk_event){
	
//    cout << "Tracker: view status ";
    for(Int_t iv=0; iv<12; iv++)cout << trk_event->good[iv];
    cout << endl;

//    cout << "Tracker: n.tracks "<<trk_event->GetNTracks()<<endl;
//    cout << "Tracker: n.singlet X "<<trk_event->nclsx()<<endl;
//    cout << "Tracker: n.singlet Y "<<trk_event->nclsy()<<endl;

    Track    = new TClonesArray("GTrkTrack");
    Image    = new TClonesArray("GTrkTrack");
    SingletX = new TClonesArray("GTrkHit");
    SingletY = new TClonesArray("GTrkHit");

    DRAWIMAGE=false;
   
    SetTracks(trk_event);
    SetSinglets(trk_event);

}

/**
 * Constructor
 */
GTrkLevel2::GTrkLevel2(PamLevel2* pam_event){
    
    TrkLevel2* trk_event = pam_event->GetTrkLevel2();

//    cout << "Tracker: view status ";
//    for(Int_t iv=0; iv<12; iv++)cout << trk_event->good[iv];
//    cout << endl;

//     cout << "Tracker: n.tracks "<<trk_event->GetNTracks()<<endl;
//     cout << "Tracker: n.singlet X "<<trk_event->nclsx()<<endl;
//     cout << "Tracker: n.singlet Y "<<trk_event->nclsy()<<endl;

    Track    = new TClonesArray("GTrkTrack");
    Image    = new TClonesArray("GTrkTrack");
    SingletX = new TClonesArray("GTrkHit");
    SingletY = new TClonesArray("GTrkHit");

    DRAWIMAGE=false;
   
    SetTracks(pam_event);
    SetSinglets(trk_event);

}

void GTrkLevel2::SetTracks(TrkLevel2* trk_event){
    TClonesArray &gt = *Track;
    TClonesArray &gi = *Image;
    TClonesArray &gsx = *SingletX;   
    TClonesArray &gsy = *SingletY;
    Int_t isx = SingletX->GetEntries();
    Int_t isy = SingletY->GetEntries();
    for(Int_t it=0; it<trk_event->GetNTracks(); it++){	
	TrkTrack   *tk = trk_event->GetTrack(it);
	new(gt[it]) GTrkTrack(tk);
	for(Int_t i=0; i<6; i++){
	    if(tk->XGood(i)) new(gsx[isx++]) GTrkHit(tk->xm[i],tk->zm[i],tk->dedx_x[i]);
	    if(tk->YGood(i)) new(gsy[isy++]) GTrkHit(tk->ym[i],tk->zm[i],tk->dedx_y[i]);
	}
	
	if( tk->HasImage() ){
	    TrkTrack   *tk = trk_event->GetTrackImage(it);
	    new(gi[it]) GTrkTrack(tk);	    
	}


    }    


}
void GTrkLevel2::SetTracks(PamLevel2* pam_event){
    TClonesArray &gt = *Track;
    TClonesArray &gi = *Image;
    TClonesArray &gsx = *SingletX;   
    TClonesArray &gsy = *SingletY;
    Int_t isx = SingletX->GetEntries();
    Int_t isy = SingletY->GetEntries();

//  ==== NON FUNZIONA ===
//     TClonesArray *sorted = pam_event->GetTracks();
//     cout << "==== "<<sorted->GetEntries()<<endl;
//     for(Int_t it=0; it<pam_event->GetTrkLevel2()->GetNTracks(); it++){	

// 	TrkTrack   *tk = (TrkTrack*)(*sorted)[it];
// 	new(gt[it]) GTrkTrack(tk);
// 	for(Int_t i=0; i<6; i++){
// 	    if(tk->XGood(i)) new(gsx[isx++]) GTrkHit(tk->xm[i],tk->zm[i],tk->dedx_x[i]);
// 	    if(tk->YGood(i)) new(gsy[isy++]) GTrkHit(tk->ym[i],tk->zm[i],tk->dedx_y[i]);
// 	}	
//     }    
    
    for(Int_t it=0; it<pam_event->GetTrkLevel2()->GetNTracks(); it++){	
	TrkTrack   *tk = pam_event->GetTrack(it)->GetTrkTrack();
	new(gt[it]) GTrkTrack(tk);
	for(Int_t i=0; i<6; i++){
	    if(tk->XGood(i)) new(gsx[isx++]) GTrkHit(tk->xm[i],tk->zm[i],tk->dedx_x[i]);
	    if(tk->YGood(i)) new(gsy[isy++]) GTrkHit(tk->ym[i],tk->zm[i],tk->dedx_y[i]);
	}	
	if( tk->HasImage() ){
// 	    cout << "*** HAS IMAGE ***"<<endl;
	    TrkTrack   *tk = pam_event->GetTrackImage(it)->GetTrkTrack();
	    new(gi[it]) GTrkTrack(tk);	    
	}
    }    


}

void GTrkLevel2::SetSinglets(TrkLevel2* trk_event){
    TClonesArray &gsx = *SingletX;
    Int_t isx = SingletX->GetEntries();
    for(Int_t is=0; is<trk_event->nclsx(); is++){
	
	TrkSinglet   *s = trk_event->GetSingletX(is);
	
	GTrkHit h = GTrkHit(s->coord[0],trk_event->GetZTrk(s->plane),s->sgnl);
//	h.SetCluster(s->GetCluster());
	new(gsx[isx++]) GTrkHit(&h);
    }
    TClonesArray &gsy = *SingletY;
    Int_t isy = SingletY->GetEntries();
    Int_t iss=0;
    for(Int_t is=0; is<trk_event->nclsy(); is++){
	
	for(Int_t i=0; i<2; i++){
	    TrkSinglet   *s = trk_event->GetSingletY(is);

	    GTrkHit h = GTrkHit(s->coord[i],trk_event->GetZTrk(s->plane),s->sgnl);
//	    h.SetCluster(s->GetCluster());
	    new(gsy[isy++]) GTrkHit(&h);
	    iss++;
	}
    }
}

//
void GTrkLevel2::DrawProjectionX(){
	
    
    TClonesArray &s = *(SingletX);
    for(Int_t is=0; is<SingletX->GetEntries(); is++){
	((GTrkHit*)s[is])->Draw();
    };

    TClonesArray &t = *(Track);
    for(Int_t it=0; it<Track->GetEntries(); it++){
	((GTrkTrack*)t[it])->DrawProjectionX();
    };
    
};
void GTrkLevel2::DrawProjectionY(){
	    
    TClonesArray &s = *(SingletY);
    for(Int_t is=0; is<SingletY->GetEntries(); is++){
	((GTrkHit*)s[is])->Draw();
    };

    TClonesArray &t = *(Track);
    for(Int_t it=0; it<Track->GetEntries(); it++){
	((GTrkTrack*)t[it])->DrawProjectionY();
    };

    if(DRAWIMAGE){
	TClonesArray &i = *(Image);
	for(Int_t it=0; it<Image->GetEntries(); it++){
	    if( i[it] ){
		((GTrkTrack*)i[it])->GetProjectionY()->SetLineStyle(2);
		((GTrkTrack*)i[it])->DrawProjectionY();
	    }
	};
    }

};
void GTrkLevel2::DrawProjectionT(){
	
    TClonesArray &t = *(Track);
    for(Int_t it=0; it<Track->GetEntries(); it++){
	((GTrkTrack*)t[it])->DrawProjectionT();
    };
    
    if(DRAWIMAGE){
	TClonesArray &i = *(Image);
	for(Int_t it=0; it<Image->GetEntries(); it++){
	    if( i[it] ){
		((GTrkTrack*)i[it])->GetProjectionT()->SetLineStyle(2);
		((GTrkTrack*)i[it])->DrawProjectionT();
	    }
	};
    }

};
//
void GTrkLevel2::Delete(){
    Track->Delete();
    Image->Delete();
    SingletX->Delete();
    SingletY->Delete();
}
void GTrkLevel2::Clear(){
    Track->Clear("C");
    Image->Clear("C");
    SingletX->Clear("C");
    SingletY->Clear("C");
}
//===============================================================
//
//
//===============================================================
GTrkTrack::GTrkTrack(){

    tr_l = new TPolyLine();
    tr_r = new TPolyLine();
    tr_c = new TPolyLine();
    

    for	(Int_t i=0; i<6; i++){
//	m_l[i] = m_r[i] = m_c[i] = NULL;
	mt_l[i] = new TMarker();
	mt_r[i] = new TMarker();
	mt_c[i] = new TMarker();
    }
    
}
GTrkTrack::~GTrkTrack(){
	
//	delete tr_l;
//	delete tr_r;
//	delete tr_c;
		
    tr_l->Delete();
    tr_r->Delete();
    tr_c->Delete();
    

    for	(Int_t i=0; i<6; i++){
//	cout << " GTrkTrack::~GTrkTrack() ==> m_l[i] "<<m_l[i]<<endl;
// 	if( m_l[i] )m_l[i]->Delete();
// 	if( m_r[i] )m_r[i]->Delete();
// 	if( m_c[i] )m_c[i]->Delete();

	if( mt_l[i] )mt_l[i]->Delete();
	if( mt_r[i] )mt_r[i]->Delete();
	if( mt_c[i] )mt_c[i]->Delete();
    }
    
};
//
GTrkTrack::GTrkTrack(TrkTrack* tr){
	
//  --------------------------------------------
    // create trajectory in the tracker

    float pz[100];
    float ztop = 55.;
    float zbot = -27.;
    float dz = (ztop-zbot)/100;
    for(int i=0; i<100; i++)pz[i]=ztop-dz*i;
//    Trajectory *tj = new Trajectory(100);
    Trajectory *tj = new Trajectory(100,pz);
    tr->DoTrack2(tj);
    
//     cout << tr->GetRigidity()<<" GV"<<endl;

//    for (Int_t ii=0;ii<100;ii+=10)cout<<tj->x[ii]<<" - "<<tj->y[ii]<<" - "<<tj->z[ii]<<endl;

    Int_t iwall=100;
//      Int_t iwall=0;
//      for(iwall=0; iwall<tj->npoint; iwall++){	
//  	if(tj->x[iwall] <= XTRKL || tj->x[iwall] >= XTRKR || tj->y[iwall]<= YTRKL || tj->y[iwall]>= YTRKR)break;
//      }    
    // create track  projections
    tr_l = new TPolyLine( iwall, tj->x, tj->z );
    tr_r = new TPolyLine( iwall, tj->y, tj->z );
    tr_c = new TPolyLine( iwall, tj->x, tj->y );	
    tr_l->SetLineColor(HTCOL);
    tr_r->SetLineColor(HTCOL);
    tr_c->SetLineColor(HTCOL);
    tj->Delete();

//  --------------------------------------------
//  create 
    for(Int_t i=0; i<6; i++){
	if(tr->XGood(i)){
	    mt_l[i] = new TMarker(tr->xm[i],tr->zm[i],20);
	    mt_l[i]->SetMarkerSize(0.6);
	    mt_l[i]->SetMarkerColor(HTCOL);
//	    cout << "X-hit "<<i<<" "<<tr->xm[i]<<endl;
	}else{
	    mt_l[i] = NULL;
	};
	if(tr->YGood(i)){
	    mt_r[i] = new TMarker(tr->ym[i],tr->zm[i],20);
	    mt_r[i]->SetMarkerSize(0.6);
	    mt_r[i]->SetMarkerColor(HTCOL);
//	    cout << "Y-hit "<<i<<" "<<tr->ym[i]<<endl;
	}else{
	    mt_r[i] = NULL;
	};
	if(tr->XGood(i) || tr->YGood(i)){
	    mt_c[i] = new TMarker(tr->xm[i],tr->ym[i],20);
	    mt_c[i]->SetMarkerSize(0.9-i*0.1);
	    mt_c[i]->SetMarkerColor(HTCOL);
	}else{
	    mt_c[i] = NULL;
	};
    }	
    

}

//
GTrkTrack::GTrkTrack(GTrkTrack* gt){
	
    tr_l = new TPolyLine( *(gt->tr_l) );
    tr_r = new TPolyLine( *(gt->tr_r) );
    tr_c = new TPolyLine( *(gt->tr_c) );	
    

    for(Int_t i=0; i<6; i++){
//	m_l[i] = m_r[i] = m_c[i] = NULL;
// 	if( gt->m_l[i] ) m_l[i] = new GTrkHit( gt->m_l[i] );
// 	if( gt->m_r[i] ) m_r[i] = new GTrkHit( gt->m_r[i] );
// 	if( gt->m_c[i] ) m_c[i] = new GTrkHit( gt->m_c[i] );

	mt_l[i] = new TMarker( *(gt->mt_l[i]) );
	mt_r[i] = new TMarker( *(gt->mt_r[i]) );
	mt_c[i] = new TMarker( *(gt->mt_c[i]) );
    }
    
}
//
void GTrkTrack::Delete(){
	
    tr_l->Delete();
    tr_r->Delete();
    tr_c->Delete();
    for	(Int_t i=0; i<6; i++){
	if( mt_l[i] )mt_l[i]->Delete();
	if( mt_r[i] )mt_r[i]->Delete();
	if( mt_c[i] )mt_c[i]->Delete();
    }
};

void GTrkTrack::Clear(){
	
	
};

void GTrkTrack::DrawProjectionX(){
//    cout << "draw track x\n";
    for(Int_t i=0; i<6; i++){
	if( mt_l[i] )mt_l[i]->Draw();
    };
    tr_l->Draw();
};
void GTrkTrack::DrawProjectionY(){
//    cout << "draw track y\n";
    for(Int_t i=0; i<6; i++){
	if( mt_r[i] )mt_r[i]->Draw();
    };
    tr_r->Draw();	
};
void GTrkTrack::DrawProjectionT(){
//    cout << "draw track t\n";
     for(Int_t i=0; i<6; i++){
	if( mt_c[i] )mt_c[i]->Draw();
     };
    tr_c->Draw();	
};
//===============================================================
//
//
//===============================================================
GTrkHit::GTrkHit(){
    m1 = new TMarker();
    m2 = new TEllipse();
    cl = 0;
};

GTrkHit::GTrkHit(GTrkHit* h){
    m1 = new TMarker(*(h->m1));
    m2 = new TEllipse(*(h->m2));
    cl = h->cl;
};
//
GTrkHit::GTrkHit(Float_t x, Float_t y, Float_t w){
	
    m1 = new TMarker(x,y,20);
//	m2 = new TMarker(x,y,20);
    m2 = new TEllipse(x,y,0.,0.);
    cl = 0;
    
    
    
    // create a palette	vvvvvvvvvvvvvvvvvvvvvvvvvvv
//     const Int_t colNum = 30;//12;
//     const Int_t colBase = 500;
// //	Int_t palette[colNum];
//     TColor *color;
// //     for (Int_t i=0;i<colNum;i++) {
// // /*		Int_t ii = 255*i/colNum;
// // 		Int_t R=255;
// // 		Int_t G=255;
// // 		Int_t B=255-ii;*/
// // 	Int_t ii = 255*i/colNum;
// // 	Int_t R=255-51*((Int_t)(i/6))%6;
// // 	Int_t G=255;
// // 	Int_t B=255-51*i%6;
// // 	R=R/255;
// // 	G=G/255;
// // 	B=B/255;
// // 	if( !gROOT->GetColor(colBase+i) ){
// // 	    color = new TColor(colBase+i,R,G,B,"");
// // //					,    pow(i/((colNum)*1.0),0.3)
// // //					,    pow(i/((colNum)*1.0),0.3)
// // //							,0.5*(i/((colNum)*1.0)),"");
// // 	}else{
// // 	    color = gROOT->GetColor(colBase+i);
// // 	    color->SetRGB(R,G,B);
// // 	};
// // //		palette[i] = 301+i;
// //     }
// // //	gStyle->SetPalette(colNum,palette);
// // 	// create a palette	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	
// //     Int_t col = colNum*(Int_t)sqrt(w)/8 + colBase;
//	m2->SetMarkerSize(w*0.2+1.1);
//	m2->SetMarkerSize(sqrt(w)*.9);
//	m2->SetMarkerColor(col);
    Int_t colo = 10;
    if ( w > 0.7  ) colo = 38;
    if ( w > 2.   ) colo = 4;    
    if ( w > 10.  ) colo = 3;
    if ( w > 100. ) colo = 2;
    if ( w > 500. ) colo = 6;

    m1->SetMarkerSize(0.7);
//    m1->SetMarkerColor(HTCOL);
    m1->SetMarkerColor(colo);

    m2->SetR1(sqrt(w)*.8);
    m2->SetR2(m2->GetR1());
    m2->SetLineColor(colo);
    m2->SetLineWidth(1);
//    cout << w << " "<< col << endl;
    
//	cout << "creato \n";
};
//
void GTrkHit::Draw(){
	
    m2->Draw();
    m1->Draw();
    
//    gPad->GetCanvas()->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)", "GTrkHit", this, "ExecuteEvent(Int_t,Int_t,Int_t,TObject*)");
    
};
void GTrkHit::Delete(){
    if( m2 )m2->Delete();
    if( m1 )m1->Delete();
//    if( cl )cl->Delete();
};

void GTrkHit::ExecuteEvent(Int_t event, Int_t px, Int_t py, TObject* obj)
{
   // Execute action corresponding to one event.
   //  This member function is called when a marker is clicked with the locator
   //  If Left button is clicked on a marker, the marker is moved to
   //  a new position when the mouse button is released.
	
    if(obj != m1 && obj != m2) return;
	
    if(!cl) return;
	
    TCanvas *tempc = 0;
    TPad    *tempp = 0;
    TCanvas *clc = 0;
    TPad    *clpx = 0;
    TPad    *clpy = 0;
    TPad    *clp = 0;
    TPad    *from = 0;
    TObject *tempo = 0;
    
    TIter nextcanv(gROOT->GetListOfCanvases());
    while ( (tempc = (TCanvas*) nextcanv()) ) {
//		cout << " canvas - "<<tempc->GetName()<<endl;
	TIter nextpad( tempc->GetListOfPrimitives() );
	while( (tempp = (TPad*) nextpad()) ){
//			cout << " pad    - "<<tempp->GetName()<<endl;
	    TString name = tempp->GetName();
//			if( !name.CompareTo("clx") )clpx = tempp;
//			if( !name.CompareTo("cly") )clpy = tempp;
	    if( !name.CompareTo("cl") )clp = tempp;
	    TIter nextobj( tempp->GetListOfPrimitives() );
	    while( (tempo =  nextobj()) ){
//			cout << " pad    - "<<tempp->GetName()<<endl;
		if( tempo == obj ) from = tempp;
	    };
	};
    }
//	if(clp) clp->cd();
//	if( (from->GetName()).Contains("px") && !clpx)
    if(clp){
//		clp->cd();
	clp->Divide(1,2);
	clp->Update();
	TString name = from->GetName();
//		cout << "obj selected from: "<<from->GetName()<<endl;
	if( !name.CompareTo("px") ){cout<< "clp->cd(1)\n";clp->cd(1);}
	if( !name.CompareTo("py") ){cout<< "clp->cd(2)\n";clp->cd(2);}
	
    }else {
	cout << "cl pad not fownd -- create new canvas \n";
	clc = new TCanvas("cl","Cluster");
	clp = (TPad*) clc;
	clp->cd();
    };
    
    cout << "dove siamo: "<<gPad->GetName()<<endl;
    switch (event) {
	
	
    case kButton1Down:
//			gVirtualX->SetTextColor(-1);  // invalidate current text color (use xor mode)
//			TAttMarker::Modify();  //Change marker attributes only if necessary
	// No break !!!
	
	cout << "kButton1Down\n";
	
	break;
	
    case kMouseMotion:
//			pxold = px;  pyold = py;
//			gPad->SetCursor(kMove);
	cout << "kMouseMotion\n";
	
	cl->Draw();
	gPad->Update();
//			clp->Update();
//			cout << clp->GetName() << endl;
	
	break;
	
    case kButton1Motion:
//			p.fX = pxold; p.fY = pyold;
//			gVirtualX->DrawPolyMarker(1, &p);
//			p.fX = px; p.fY = py;
//			gVirtualX->DrawPolyMarker(1, &p);
//			pxold = px;  pyold = py;
	cout << "kButton1Motion\n";
	break;
	
    case kButton1Up:
//			Double_t dpx, dpy, xp1,yp1;
//			if (TestBit(kMarkerNDC)) {
//				dpx  = gPad->GetX2() - gPad->GetX1();
//				dpy  = gPad->GetY2() - gPad->GetY1();
//				xp1  = gPad->GetX1();
//				yp1  = gPad->GetY1();
//				fX = (gPad->AbsPixeltoX(pxold)-xp1)/dpx;
//				fY = (gPad->AbsPixeltoY(pyold)-yp1)/dpy;
//			} else {
//				fX = gPad->PadtoX(gPad->AbsPixeltoX(px));
//				fY = gPad->PadtoY(gPad->AbsPixeltoY(py));
//			}
//			gPad->Modified(kTRUE);
//			gVirtualX->SetTextColor(-1);
	cout << "kButton1Up\n";
	break;
    }
}

//===============================================================
//
//
//===============================================================
GTrkCluster::GTrkCluster(){
    sgnl = new TH1F();
    cut  = new TH1F();
    seed = new TH1F();
    sat  = new TH1F();
    maxs = new TLine();
    zero = new TLine();
}
//
GTrkCluster::~GTrkCluster(){
    if(sgnl) sgnl->Delete();
    if(cut)  cut->Delete();
    if(seed) seed->Delete();
    if(sat)  sat->Delete();
    if(maxs) maxs->Delete();
    if(zero) zero->Delete();
}
//
GTrkCluster::GTrkCluster(GTrkCluster* gcl){
    sgnl = gcl->sgnl;
    cut  = gcl->cut;
    seed = gcl->seed;
    sat  = gcl->sat;
    maxs = gcl->maxs;
    zero = gcl->zero;
}
//
GTrkCluster::GTrkCluster(TrkCluster* cl){
    
    maxs = new TLine(cl->maxs, 0, cl->maxs, cl->clsignal[cl->indmax]);
    
    Float_t min = cl->maxs - cl->indmax - 0.5;
    Float_t max = min + cl->CLlength;

    zero = new TLine(min,0.,max,0.);

    TString title = "";
    title.Form("Cluster - view %i",cl->view);

    TString h = ""; 
    h = ""; h.Form("sgnl-%i",cl->maxs);
    sgnl = new TH1F(h.Data(),title.Data(),cl->CLlength,min,max);
    h = ""; h.Form("cut-%i",cl->maxs);
    cut  = new TH1F(h.Data(),title.Data(),cl->CLlength,min,max);
    h = ""; h.Form("seed-%i",cl->maxs);
    seed  = new TH1F(h.Data(),title.Data(),cl->CLlength,min,max);
    h = ""; h.Form("sat-%i",cl->maxs);
    sat  = new TH1F(h.Data(),title.Data(),cl->CLlength,min,max);
    for (Int_t is = 0; is < cl->CLlength; is++){
	sgnl->Fill( (Float_t)(min+is), cl->clsignal[is] );
	cut->Fill( (Float_t)(min+is), 4*cl->clsigma[is] );
	if(  (cl->view)%2 )seed->Fill( (Float_t)(min+is), 6*cl->clsigma[is] );
	else               seed->Fill( (Float_t)(min+is), 7*cl->clsigma[is] );

//	if(  (cl->view)%2 &&  cl->cladc[is] < 100 ) sat->Fill( (Float_t)(min+is), cl->clsignal[is] );
//	if( !((cl->view)%2) &&  cl->cladc[is] > 3100) sat->Fill( (Float_t)(min+is), cl->clsignal[is] );
	if( (cl->view)%2 )sat->Fill( (Float_t)(min+is), -80+cl->clsignal[is]+cl->cladc[is] );
	else              sat->Fill( (Float_t)(min+is), 2980+cl->clsignal[is]-cl->cladc[is] );
	
//	if( (cl->view)%2 )cout << -100+cl->clsignal[is]+cl->cladc[is] <<endl;
//	else              cout <<  3100+cl->clsignal[is]-cl->cladc[is]<<endl ;

    };
    
    Float_t mi = -5;
    Float_t ma = 1.1*sgnl->GetMaximum(5000);

    sgnl->SetStats(0);
    sgnl->SetLineWidth(2);
    sgnl->SetFillColor(19);
    sgnl->SetMinimum(mi);
    sgnl->SetMaximum(ma);
    
    cut->SetStats(0);
    cut->SetLineStyle(2);
    cut->SetLineWidth(2);
    cut->SetLineColor(9);
    cut->SetMinimum(mi);
    cut->SetMaximum(ma);
    
    
    sat->SetStats(0);
//    sat->SetFillColor(18);
//    sat->SetLineWidth(0);
//    sat->SetLineColor(18);
    sat->SetLineWidth(2);
    sat->SetLineStyle(2);
    sat->SetLineColor(2);
    sat->SetMinimum(mi);
    sat->SetMaximum(ma);
    
    seed->SetStats(0);
//	seed->SetFillColor(19);
    seed->SetLineWidth(2);
    seed->SetLineStyle(2);
    seed->SetLineColor(3);
    seed->SetMinimum(mi);
    seed->SetMaximum(ma);
    
    maxs->SetLineStyle(2);
    maxs->SetLineWidth(2);
    maxs->SetLineColor(2);
    zero->SetLineStyle(0);
    zero->SetLineWidth(1);
    zero->SetLineColor(0);
    
}
//
void GTrkCluster::Draw(){
	
    sgnl->Draw();	
    sat->Draw("same");
    
    cut->Draw("same");
    seed->Draw("same");
    
    maxs->Draw();
	
	
}
//
void GTrkCluster::Delete(){
    if(sgnl) sgnl->Delete();
    if(cut)  cut->Delete();
    if(seed) seed->Delete();
    if(sat)  sat->Delete();
    if(maxs) maxs->Delete();
    if(zero) zero->Delete();
}
//===============================================================
//
//
//===============================================================
GTrkHough::GTrkHough(){

    TrackCandidates    = new TClonesArray("GTrkTrack");

}
/**
 * Constructor
 */
GTrkHough::GTrkHough(TrkHough *lh){


//     cout << "Tracker: n.track-candidates "<<lh->GetNCandidates()<<endl;

    TrackCandidates    = new TClonesArray("GTrkTrack");
    for(int i=0; i<100; i++)gtrip[i]=0;
    for(int i=0; i<100; i++)gdoub[i]=0;

    if(!lh)return;
    SetCandidates(lh);
    SetHough(lh);

}
void GTrkHough::SetCandidates(TrkHough* lh){

    if(!lh)return;
    TClonesArray &gt = *TrackCandidates;
    for(Int_t it=0; it<lh->GetNCandidates(); it++){	
	TrkTrack   *tk = lh->GetCandidate(it);
	new(gt[it]) GTrkTrack(tk);
    }    

}

void GTrkHough::SetHough(TrkHough* lh){

    if(!lh)return;

    trip = new TMultiGraph();
    doub = new TMultiGraph();
    
//     cout << "Tracker: n.doublets "<<lh->ndblt<<endl;
    // ALL --------------------------------------------------
    int ndblt=0;
    gdoub[ndblt] = new TGraph();
    for(int id=0; id<lh->ndblt; id++){
//	cout << "**Y** "<<lh->alfayz1[id]<<" "<<lh->alfayz2[id]<<endl;
// 	cout << "**Y** "<<lh->db_cloud[id]<<endl;
	gdoub[ndblt]->SetPoint(id+1,lh->alfayz1[id],lh->alfayz2[id]);
    }
    doub->Add(gdoub[ndblt],"p");
    ndblt++;
    // CLOUDS --------------------------------------------------


//     cout << "Tracker: n.triplets "<<lh->ntrpt<<endl;
    int ntrpt=0;
    gtrip[ntrpt] = new TGraph();
    for(int id=0; id<lh->ntrpt; id++){
//	cout << "**X** "<<lh->alfaxz1[id]<<" "<<lh->alfaxz2[id]<<endl;
// 	cout << "**X** "<<lh->tr_cloud[id]<<endl;
	gtrip[ntrpt]->SetPoint(id+1,lh->alfaxz1[id],lh->alfaxz2[id]);
    }
    trip->Add(gtrip[ntrpt],"p");
    ntrpt++;
    
//    cout << "done"<<endl;
    
}

void GTrkHough::DrawProjectionX(){
	
    
    if(!TrackCandidates)return;
    TClonesArray &t = *(TrackCandidates);
    for(Int_t it=0; it<TrackCandidates->GetEntries(); it++){
	((GTrkTrack*)t[it])->GetProjectionX()->SetLineStyle(2);
	((GTrkTrack*)t[it])->GetProjectionX()->SetLineColor(TCCOL);
	for(int ip=0; ip<6; ip++) if( ((GTrkTrack*)t[it])->GetProjectionX_Points(ip) ) ((GTrkTrack*)t[it])->GetProjectionX_Points(ip)->SetMarkerColor(TCCOL);
	((GTrkTrack*)t[it])->DrawProjectionX();
    };
    
//     TCanvas *c = new TCanvas();
//     trip->Draw("ap");

};
void GTrkHough::DrawProjectionY(){
	    
    if(!TrackCandidates)return;
    TClonesArray &t = *(TrackCandidates);
    for(Int_t it=0; it<TrackCandidates->GetEntries(); it++){
	((GTrkTrack*)t[it])->GetProjectionY()->SetLineStyle(2);
	((GTrkTrack*)t[it])->GetProjectionY()->SetLineColor(TCCOL);
	for(int ip=0; ip<6; ip++)if(((GTrkTrack*)t[it])->GetProjectionY_Points(ip))((GTrkTrack*)t[it])->GetProjectionY_Points(ip)->SetMarkerColor(TCCOL);
	((GTrkTrack*)t[it])->DrawProjectionY();
    };

//     TCanvas *c = new TCanvas();
//     doub->Draw("ap");

};
void GTrkHough::DrawProjectionT(){
	
    if(!TrackCandidates)return;
    TClonesArray &t = *(TrackCandidates);
    for(Int_t it=0; it<TrackCandidates->GetEntries(); it++){
	((GTrkTrack*)t[it])->GetProjectionT()->SetLineStyle(2);
	((GTrkTrack*)t[it])->GetProjectionT()->SetLineColor(TCCOL);
	for(int ip=0; ip<6; ip++)if(((GTrkTrack*)t[it])->GetProjectionT_Points(ip))((GTrkTrack*)t[it])->GetProjectionT_Points(ip)->SetMarkerColor(TCCOL);
	((GTrkTrack*)t[it])->DrawProjectionT();
    };
    

};
void GTrkHough::Delete(){

//     for(int i=0; i<100; i++)cout << gtrip[i] << endl;
//     for(int i=0; i<100; i++)cout << gdoub[i] << endl;
    
//    for(int i=0; i<100; i++)if(gtrip[i])trip->Delete();
//    if(trip)trip->Delete();

//    for(int i=0; i<100; i++)if(gdoub[i])doub->Delete();
//    if(doub)doub->Delete();

    TrackCandidates->Delete();
    
}
GTrkHough::~GTrkHough(){

//     cout << "distruttore"<<endl;
    
//    for(int i=0; i<100; i++)cout << gtrip[i] << endl;
//    for(int i=0; i<100; i++)cout << gdoub[i] << endl;
    
//    for(int i=0; i<100; i++)if(gtrip[i])trip->Delete();
//    if(trip)trip->Delete();

//    for(int i=0; i<100; i++)if(gdoub[i])doub->Delete();
//    if(doub)doub->Delete();

    TrackCandidates->Delete();
    
}
void GTrkHough::Clear(){

    TrackCandidates->Clear("C");

}



ClassImp(GTrkVolume);
ClassImp(GTrkTrack);
ClassImp(GTrkLevel2);
ClassImp(GTrkHit);
ClassImp(GTrkCluster);
ClassImp(GTrkHough);

