#include <math.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#if (__GNUC__ == 3) && (__GNUC_MINOR__ == 2)
char* operator+( std::streampos&, char* );
#endif
//
#include <TObjectTable.h>
#include <TGClient.h>
#include <TGButton.h>
#include <TGComboBox.h>
#include <TGLabel.h>
#include <TGTextEntry.h>
#include <TGFrame.h>
#include <TGButtonGroup.h>
#include <TGProgressBar.h>
#include <TGMsgBox.h>
#include <TGComboBox.h>
#include <TTree.h>
#include <TClassEdit.h>
#include <TObject.h>
#include <TList.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TFile.h>
#include <TClass.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TH1F.h>
#include <TH2D.h>
#include <TLatex.h>
#include <TPad.h>
#include <TPaveLabel.h>
#include <TLine.h>
#include <TPolyLine.h>
#include <TChain.h>
#include <TApplication.h>
#include <TVirtualX.h>
#include <TGClient.h>
#include <TGWindow.h>
#include <TEllipse.h>
#include <TArrow.h>
#include <TStyle.h>
//
#include <PamLevel2.h>
//
#include <FEVpamevcontrol.h>
//
ClassImp(PAMevcontrol);
ClassImp(CalorimeterCalibration);
//

using namespace std;

void stringcopy(TString& s1, const TString& s2, Int_t from=0, Int_t to=0){    
    if ( to == 0 ){
	Int_t t2length = s2.Length();
	s1 = "";
	to = t2length;
    };
    for (Int_t i = from; i<to; i++){
	s1.Append(s2[i],1);
    };
}

void stringappend(TString& s1, const TString& s2){    
    Int_t t2length = s2.Length();
    for (Int_t i = 0; i<t2length; i++){
	s1.Append(s2[i],1);
    };
}

CalorimeterCalibration::CalorimeterCalibration() {    
  fname = "dw_000000_000.dat";
  status = 0;
  for (Int_t i=0; i<2;i++){
    for (Int_t j=0; j<22;j++){
      for (Int_t m=0; m<96;m++){
	mip[i][j][m] = 0.;
	ermip[i][j][m] = 0.;
	chi2[i][j][m] = 0.;
	ndf[i][j][m] = 0.;
	mask[i][j][m] = 0.;
	for (Int_t a = 0; a < 4 ; a++){
	  fp[a][i][j][m] = 0.;
	  fpe[a][i][j][m] = 0.;
	};
      };
    };	
  };        
};

PAMevcontrol::PAMevcontrol(const TGWindow *p,UInt_t w,UInt_t h,Variables & var, Levels &level, TCanvas &figure) : TGMainFrame(p, w, h){
  //
  SetCleanup(kDeepCleanup);
  DontCallClose();
  Connect("CloseWindow()","PAMevcontrol",this,"Terminate()");
  //
  clev = &level; 
  cvar = &var; 
  thefigure = &figure;
  //
  cframe1 = new TGCompositeFrame(this, 280, 60, kVerticalFrame);
  TGCompositeFrame *cframe2 = new TGCompositeFrame(this, 280, 60, kVerticalFrame);
  TGCompositeFrame *cframe3 = new TGCompositeFrame(this, 280, 60, kVerticalFrame);
  TGCompositeFrame *cframe4 = new TGCompositeFrame(this, 280, 60, kVerticalFrame);
  TGCompositeFrame *cframe5 = new TGCompositeFrame(this, 280, 60, kVerticalFrame);
  gf = new TGGroupFrame(cframe1, "Detectors");
  TGGroupFrame *gf2 = new TGGroupFrame(cframe5, "Appearance");
  TGGroupFrame *inputf = new TGGroupFrame(cframe2, "Input");
  TGGroupFrame *jumpf = new TGGroupFrame(cframe3, "Jump to");
  TGGroupFrame *savef = new TGGroupFrame(cframe4, "Save figure as");
  //
  TGHorizontalFrame *htexts = new TGHorizontalFrame(savef,300,800);
  TGHorizontalFrame *htextsl = new TGHorizontalFrame(cframe4,300,800);
  TGHorizontalFrame *htext = new TGHorizontalFrame(inputf,300,800);
  TGHorizontalFrame *htext2 = new TGHorizontalFrame(inputf,300,800);
  TGHorizontalFrame *htext3 = new TGHorizontalFrame(jumpf,300,800);
  TGHorizontalFrame *htext4 = new TGHorizontalFrame(jumpf,300,80);
  TGHorizontalFrame *hframe = new TGHorizontalFrame(this,300,800);
  for (Int_t fr=0; fr<12; fr++) hframedec[fr] = new TGHorizontalFrame(gf, 7, 7);
  TGHorizontalFrame *hframe3 = new TGHorizontalFrame(gf2, 280, 60);
  TGHorizontalFrame *hframe4 = new TGHorizontalFrame(gf2,280,10);
  TGVerticalFrame *hframe5 = new TGVerticalFrame(hframe4, 280, 60);
  TGHorizontalFrame *hfrprog = new TGHorizontalFrame(this,300,800);
  //
  TGTextEntry *fText = new TGTextEntry(htext, new TGTextBuffer(20),-1);
  fText->SetText(cvar->thefilename.Data());
  TGTextButton *Load = new TGTextButton(htext,"Load");
  Load->Connect("Pressed()","TGTextEntry",fText,"ReturnPressed()");
  fText->Connect("ReturnPressed()", "PAMevcontrol", this,"SetFilename()");
  fText->Connect("TabPressed()", "PAMevcontrol", this,"CompleteText()");
  htext->AddFrame(fText, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY, 0, 5, 5, 5));
  htext->AddFrame(Load, new TGLayoutHints(kLHintsCenterX,0,5,5,5));
  inputf->AddFrame(new TGLabel(inputf, new TGHotString("Filename:")));
  inputf->AddFrame(htext, new TGLayoutHints(kLHintsExpandX));
  //
  fText2 = new TGTextEntry(htext2, new TGTextBuffer(20),-1);
  fText2->SetText(cvar->thefilter.Data());
  TGTextButton *Load2 = new TGTextButton(htext2,"Load");
  Load2->Connect("Clicked()","TGTextEntry",fText2,"ReturnPressed()");
  Load2->SetToolTipText("Clear box and click to unload file");
  fText2->Connect("ReturnPressed()", "PAMevcontrol", this,"SetFilter()");
  fText2->Connect("TabPressed()", "PAMevcontrol", this,"CompleteText()");
  htext2->AddFrame(fText2, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY, 0, 5, 5, 5));
  htext2->AddFrame(Load2, new TGLayoutHints(kLHintsCenterX,0,5,5,5));
  inputf->AddFrame(new TGLabel(inputf, new TGHotString("Selection file:")));
  inputf->AddFrame(htext2, new TGLayoutHints(kLHintsExpandX));
  //
  cframe2->AddFrame(inputf,new TGLayoutHints(kLHintsExpandX,5,5,5,5));
  //
  //
  //
  fComboDec = new TGComboBox(gf, 98);
  fComboDec->AddEntry(" - Select Detector -", 11);
  fComboDec->AddEntry("PSCU - ORB", 0);
  fComboDec->AddEntry("Run", 1);
  fComboDec->AddEntry("Trigger", 2);
  fComboDec->AddEntry("ToF", 3);
  fComboDec->AddEntry("Tracker", 4);
  fComboDec->AddEntry("Anticounter", 5);
  fComboDec->AddEntry("Calorimeter", 6);
  fComboDec->AddEntry("S4", 7);
  fComboDec->AddEntry("ND", 8);
  fComboDec->AddEntry("Software info", 9);
  fComboDec->AddEntry("ALL", 10);
  fComboDec->Select(11);
  fComboDec->Resize(150,23);
  gf->AddFrame(fComboDec, new TGLayoutHints(kLHintsCenterY | kLHintsExpandX| kLHintsLeft, 5, 7, 7, 7));
  fComboDec->Connect("Selected(Int_t)","PAMevcontrol",this,"refreshdec(Int_t)");
  //
  // PSCU/Orbital
  //
  fshoworb = new TGTextButton(hframedec[0], "Show Data");   
  fshoworb->Connect("Clicked()","PAMevcontrol", this,"showorbdata()"); 
  if ( !cvar->ORB ) fshoworb->SetState(kButtonDisabled);
  hframedec[0]->AddFrame(fshoworb, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,5,5,5));
  //
  // RUN
  //
  fshowrun = new TGTextButton(hframedec[1], "Show Data");   
  fshowrun->Connect("Clicked()","PAMevcontrol", this,"showrundata()"); 
  if ( !cvar->RUN ) fshoworb->SetState(kButtonDisabled);
  hframedec[1]->AddFrame(fshowrun, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,5,5,5));
  //
  // Trigger
  //
  fshowtrg = new TGTextButton(hframedec[2], "Show Data");   
  fshowtrg->Connect("Clicked()","PAMevcontrol", this,"showtrgdata()"); 
  if ( !cvar->TRG ) fshowtrg->SetState(kButtonDisabled);
  hframedec[2]->AddFrame(fshowtrg, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,5,5,5));
  //
  // TOF 
  //
  fchktof = new TGCheckButton(hframedec[3], "Show");   
  fchktof->Connect("Clicked()","PAMevcontrol", this,"chktof()"); 
  if ( cvar->TOF ) fchktof->SetState(kButtonDown);
  hframedec[3]->AddFrame(fchktof, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  fshowtof = new TGTextButton(hframedec[3], "Show Data");   
  fshowtof->Connect("Clicked()","PAMevcontrol", this,"showtofdata()"); 
  if ( !cvar->TOF ) fshowtof->SetState(kButtonDisabled);
  hframedec[3]->AddFrame(fshowtof, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  // Tracker
  //
  fchktrk = new TGCheckButton(hframedec[4], "Show");   
  fchktrk->Connect("Clicked()","PAMevcontrol",this,"chktrk()");   
  if ( cvar->TRK ) fchktrk->SetState(kButtonDown);
  hframedec[4]->AddFrame(fchktrk, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  fshowtrk = new TGTextButton(hframedec[4], "Show Data");   
  fshowtrk->Connect("Clicked()","PAMevcontrol", this,"showtrkdata()"); 
  if ( !cvar->TRK ) fshowtrk->SetState(kButtonDisabled);
  hframedec[4]->AddFrame(fshowtrk, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  // AC
  //
  fchkac = new TGCheckButton(hframedec[5], "Show");   
  fchkac->Connect("Clicked()","PAMevcontrol", this,"chkac()");   
  if ( cvar->AC ) fchkac->SetState(kButtonDown);
  hframedec[5]->AddFrame(fchkac, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  fshowac = new TGTextButton(hframedec[5], "Show Data");   
  fshowac->Connect("Clicked()","PAMevcontrol", this,"showacdata()"); 
  if ( !cvar->AC ) fshowac->SetState(kButtonDisabled);
  hframedec[5]->AddFrame(fshowac, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  // Calorimeter
  //
  fchkcalo = new TGCheckButton(hframedec[6], "Show");   
  fchkcalo->Connect("Clicked()","PAMevcontrol",this,"chkcalo()");   
  if ( cvar->CALO ) fchkcalo->SetState(kButtonDown);
  hframedec[6]->AddFrame(fchkcalo, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  fchkcalost = new TGCheckButton(hframedec[6], "Track");   
  fchkcalost->Connect("Clicked()","PAMevcontrol",this,"chkcalost()");   
  if ( cvar->CALO ) fchkcalost->SetState(kButtonUp);
  hframedec[6]->AddFrame(fchkcalost, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,2,5,5));
  fshowcal = new TGTextButton(hframedec[6], "Show Data");   
  fshowcal->Connect("Clicked()","PAMevcontrol", this,"showcaldata()"); 
  if ( !cvar->CALO ) fshowcal->SetState(kButtonDisabled);
  hframedec[6]->AddFrame(fshowcal, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  // S4
  //
  fchks4 = new TGCheckButton(hframedec[7], "Show");   
  fchks4->Connect("Clicked()","PAMevcontrol",this,"chks4()");   
  if ( cvar->S4 ) fchks4->SetState(kButtonDown);
  hframedec[7]->AddFrame(fchks4, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  fshows4 = new TGTextButton(hframedec[7], "Show Data");   
  fshows4->Connect("Clicked()","PAMevcontrol", this,"shows4data()"); 
  if ( !cvar->S4 ) fshows4->SetState(kButtonDisabled);
  hframedec[7]->AddFrame(fshows4, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  // ND
  //
  fchknd = new TGCheckButton(hframedec[8], "Show");   
  fchknd->Connect("Clicked()","PAMevcontrol",this,"chknd()");   
  if ( cvar->ND ) fchknd->SetState(kButtonDown);
  hframedec[8]->AddFrame(fchknd, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  fshownd = new TGTextButton(hframedec[8], "Show Data");   
  fshownd->Connect("Clicked()","PAMevcontrol", this,"shownddata()"); 
  if ( !cvar->ND ) fshownd->SetState(kButtonDisabled);
  hframedec[8]->AddFrame(fshownd, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  // Software infos
  //
  fshowsi = new TGTextButton(hframedec[9], "Show Data");   
  fshowsi->Connect("Clicked()","PAMevcontrol", this,"showsidata()"); 
  if ( !cvar->RUN ) fshoworb->SetState(kButtonDisabled);
  hframedec[9]->AddFrame(fshoworb, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  //
  // All data
  //
  fshowall = new TGTextButton(hframedec[10], "Show Data");   
  fshowall->Connect("Clicked()","PAMevcontrol", this,"showalldata()"); 
  hframedec[10]->AddFrame(fshowall, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,5,5,5));
  //
  //  for (Int_t fr=0; fr<11; fr++) gf->AddFrame(hframedec[fr], new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,1,1,1,1));
  //
  gf->AddFrame(hframedec[11], new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,5,17,17));  
  //
  //  for (Int_t fr=0; fr<11; fr++) gf->AddFrame(hframedec[fr],new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,0,5,5,5));
  //  gf->GetLayoutManager()->SetPadBottom(5);
  //  gf->MapSubwindows();
  //
  fchkinfo = new TGCheckButton(hframe3, "Infos");   
  fchkinfo->Connect("Clicked()","PAMevcontrol",this,"chkinfo()");   
  if ( cvar->INFOS ) fchkinfo->SetState(kButtonDown);
  hframe3->AddFrame(fchkinfo, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,0,1,5,5));
  //
  fchknames = new TGCheckButton(hframe3, "Names");   
  fchknames->Connect("Clicked()","PAMevcontrol",this,"chknames()");   
  if ( cvar->VINFOS ) fchknames->SetState(kButtonDown);
  hframe3->AddFrame(fchknames, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,0,1,5,5));

  fchkpalette = new TGCheckButton(hframe3, "Palette");   
  fchkpalette->Connect("Clicked()","PAMevcontrol",this,"chkpalette()");   
  if ( cvar->PALETTE) fchkpalette->SetState(kButtonDown);
  hframe3->AddFrame(fchkpalette, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,0,2,5,5));

  fchktrigger = new TGCheckButton(hframe3, "Trigger");   
  fchktrigger->Connect("Clicked()","PAMevcontrol",this,"chktrigger()");   
  if ( cvar->PATTRIG) fchktrigger->SetState(kButtonDown);
  hframe3->AddFrame(fchktrigger, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,1,2,5,5));

  gf2->AddFrame(hframe3, new TGLayoutHints(kLHintsExpandX));
  //
  TGVButtonGroup *group = new TGVButtonGroup(hframe4);
  bwc0 = new TGRadioButton(group, "Colour");
  bwc1 = new TGRadioButton(group, "B/W");
  if ( cvar->bw ){
    bwc1->SetState(kButtonDown);
  } else {
    bwc0->SetState(kButtonDown);
  };
  bwc0->Connect("Pressed()", "PAMevcontrol",this,"radiocolor()");
  bwc1->Connect("Pressed()", "PAMevcontrol",this,"radiobw()");
  hframe4->AddFrame(group,new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));
  //
  //
  //  ftrks4 = new TGCheckButton(hframe5, "Track in S4/ND");   
  //  ftrks4->Connect("Clicked()","PAMevcontrol",this,"radiotrack()");   
  //  if ( cvar->tracknds4) ftrks4->SetState(kButtonDown);
  //  hframe5->AddFrame(ftrks4, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,2,5,5));

  fgetl0 = new TGTextButton(hframe5, "Get L0 file");   
  fgetl0->Connect("Clicked()","PAMevcontrol", this,"getl0file()"); 
  hframe5->AddFrame(fgetl0, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,5,5,5,5));

  ffl0 = new TGCheckButton(hframe5, "Force RAW");
  ffl0->Connect("Clicked()","PAMevcontrol",this,"forcel0()");
  if ( cvar->fl0 ) ffl0->SetState(kButtonDown);
  if ( !cvar->fl0 ) ffl0->SetState(kButtonUp);
  hframe5->AddFrame(ffl0, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,2,5,5,5));
  //
  hframe4->AddFrame(hframe5, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,10,5,5,5));
  gf2->AddFrame(hframe4, new TGLayoutHints(kLHintsExpandX));
  //
  cframe1->AddFrame(gf, new TGLayoutHints(kLHintsExpandX,5,5,5,5));
  //  cframe1->Resize(280,10);
  //  cframe1->GetLayoutManager()->SetDefaultHeight(5);
  //  MapWindow();
  //
  cframe5->AddFrame(gf2, new TGLayoutHints(kLHintsExpandX,5,5,5,5));
  //
  TGHButtonGroup *jgroup = new TGHButtonGroup(htext4);
  jbwc0 = new TGRadioButton(jgroup, "packet     ");
  jbwc1 = new TGRadioButton(jgroup, "progressive");
  jbwc1->SetState(kButtonDown);
  jbwc0->Connect("Pressed()", "PAMevcontrol",this,"radioevent()");
  jbwc1->Connect("Pressed()", "PAMevcontrol",this,"radioprog()");
  htext4->AddFrame(jgroup,new TGLayoutHints(kLHintsExpandX,1,1,0,0));
  //
  TGTextEntry *fText3 = new TGTextEntry(htext3, new TGTextBuffer(6),-1);
  TGTextButton *Jump = new TGTextButton(htext3,"go");
  Jump->Connect("Clicked()","TGTextEntry",fText3,"ReturnPressed()");
  fText3->Connect("ReturnPressed()", "PAMevcontrol", this,"jumpto()");
  htext3->AddFrame(new TGLabel(htext3, new TGHotString("number")), new TGLayoutHints(kLHintsExpandX,0,0,1,1));
  htext3->AddFrame(fText3, new TGLayoutHints(kLHintsExpandX, 0, 8, 0, 0));
  htext3->AddFrame(Jump, new TGLayoutHints(kLHintsExpandX,0,0,0,0));
  jumpf->AddFrame(htext4, new TGLayoutHints(kLHintsExpandX,0,0,1,1)); //
  jumpf->AddFrame(htext3, new TGLayoutHints(kLHintsExpandX,0,0,0,1)); //
  //
  cframe3->AddFrame(jumpf,new TGLayoutHints(kLHintsExpandX,5,5,5,5));
  //
  fText4 = new TGTextEntry(htexts, new TGTextBuffer(18),-1);
  TGTextButton *save = new TGTextButton(htextsl,"save");
  save->Connect("Clicked()","TGTextEntry",fText4,"ReturnPressed()");
  fText4->Connect("ReturnPressed()", "PAMevcontrol", this,"saveas()");
  fText4->Connect("TabPressed()", "PAMevcontrol", this,"CompleteText()");
  htexts->AddFrame(fText4, new TGLayoutHints(kLHintsExpandX, 0, 8, 1, 1));
  //
  fCombo = new TGComboBox(htexts, 98);
  fCombo->AddEntry(".ps", 0);
  fCombo->AddEntry(".eps", 1);
  fCombo->AddEntry(".gif", 2);
  fCombo->AddEntry(".jpg", 3);
  fCombo->AddEntry(".tiff", 4);
  fCombo->AddEntry(".xpm", 5);
  fCombo->AddEntry(".pdf", 6);
  fCombo->AddEntry(".xml", 7);
  fCombo->AddEntry(".png", 8);
  fCombo->AddEntry(".svg", 9);
  fCombo->AddEntry(".root", 10);
  fCombo->AddEntry(".C", 11);
  fCombo->Select(0);
  fCombo->Resize(50,23);
  //  htexts->AddFrame(fCombo, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsLeft | kLHintsCenterY | kLHintsExpandX, 0, 8, 1, 1));
  htexts->AddFrame(fCombo, new TGLayoutHints(kLHintsExpandY | kLHintsExpandY| kLHintsRight, 2, 2, 2, 1));
  //
  htextsl->AddFrame(save, new TGLayoutHints(kLHintsExpandX,0,0,2,1));
  savef->AddFrame(htexts, new TGLayoutHints(kLHintsExpandX,0,0,2,5));
  //  savef->AddFrame(htextsl, new TGLayoutHints(kLHintsExpandX,5,2,5,2));
  savef->AddFrame(htextsl, new TGLayoutHints(kLHintsExpandX,8,0,5,2));
  //
  cframe4->AddFrame(savef,new TGLayoutHints(kLHintsExpandX,5,5,5,5));
  //
  fHProg1 = new TGHProgressBar(hfrprog, TGProgressBar::kFancy, 260);
  fHProg1->SetBarColor("green");
  fHProg1->ShowPosition();
  hfrprog->AddFrame(fHProg1, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY | kLHintsExpandX,5,5,5,5));
  //
  //
  TGTextButton *prev = new TGTextButton(hframe,"< &Back");
  prev->Connect("Clicked()","PAMevcontrol",this,"prev()");
  hframe->AddFrame(prev, new TGLayoutHints(kLHintsCenterX | kLHintsExpandX,5,5,3,4));
  //
  TGTextButton *exit = new TGTextButton(hframe,"E&xit");//,"gApplication->Terminate(0)");
  exit->Connect("Clicked()","PAMevcontrol",this,"Terminate()");
  exit->SetToolTipText("Quit the event viewer");
  hframe->AddFrame(exit, new TGLayoutHints(kLHintsCenterX | kLHintsExpandX,5,5,3,4));
  //
  bstop = new TGTextButton(hframe,"&Stop");
  bstop->Connect("Clicked()","PAMevcontrol",this,"stop()");
  hframe->AddFrame(bstop, new TGLayoutHints(kLHintsCenterX | kLHintsExpandX,5,5,3,4));
  bstop->SetState(kButtonDisabled);
  //
  TGTextButton *next = new TGTextButton(hframe,"&Next >");
  next->Connect("Clicked()","PAMevcontrol",this,"next()");
  hframe->AddFrame(next, new TGLayoutHints(kLHintsCenterX | kLHintsExpandX,5,5,3,4));
  //
  //
  //  AddFrame(htext, new TGLayoutHints(kLHintsExpandX,2,2,15,1));
  AddFrame(cframe2, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  AddFrame(cframe1, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  AddFrame(cframe5, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  AddFrame(cframe3, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  AddFrame(cframe4, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  AddFrame(hfrprog, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  AddFrame(hframe, new TGLayoutHints(kLHintsExpandX,1,1,1,1));
  // Set a name to the main frame
  SetWindowName("PAMELA Event Viewer control panel");
  // Map all subwindows of main frame
  MapSubwindows();
  // Initialize the layout algorithm
  Resize(GetDefaultSize());
  // Map main frame
  MapWindow();
  //
  gf->HideFrame(hframedec[11]);
  for (Int_t fr=0; fr<11; fr++){
    gf->AddFrame(hframedec[fr],new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY|kLHintsExpandX,0,5,5,5));
    gf->HideFrame(hframedec[fr]);
  };
  gf->MapSubwindows();
  //
}

void PAMevcontrol::Refresh(){
  // bah
  return;
  this->Clear();
  MapSubwindows();
  // Initialize the layout algorithm
  Resize(GetDefaultSize());
  // Map main frame
  MapWindow();  
}

void PAMevcontrol::DIALOG(Int_t ty, TString warn){    
    //
    // ty = 0 -> INFO, ty = 1 -> WARNING, ty = 2 -> ERROR
    //
    Int_t retval;
    TString title;
    EMsgBoxIcon mb_icon = kMBIconStop;
    if ( ty == 2 || ty == 3 ){
      if ( ty == 2 ){
	title="ERROR!!";
	mb_icon = kMBIconStop;
	new TGMsgBox(gClient->GetRoot(), this, title.Data(), warn.Data(), mb_icon, kMBOk, &retval);
      } else {
	title="HELP";
	mb_icon = kMBIconQuestion;
	new TGMsgBox(gClient->GetRoot(), this, title.Data(), warn.Data(), mb_icon, kMBOk, &retval);
      };
    } else {
      if ( ty == 0 ){
	title="INFO";
	mb_icon = kMBIconAsterisk;
      };
      if ( ty == 1 ){
	title="WARNING!";
	mb_icon = kMBIconExclamation;
      };      
      if ( ty == 4 ){
	title="DATA";
	mb_icon = kMBIconExclamation;
      };
      const TGPicture *icon_pic;
      switch (mb_icon) {
      case kMBIconStop:
	icon_pic = gClient->GetPicture("mb_stop_s.xpm");
	if (!icon_pic) Error("TGMsgBox", "mb_stop_s.xpm not found");
	break;
	
      case kMBIconQuestion:
	icon_pic = gClient->GetPicture("mb_question_s.xpm");
	if (!icon_pic) Error("TGMsgBox", "mb_question_s.xpm not found");
	break;
	
      case kMBIconExclamation:
	icon_pic = gClient->GetPicture("mb_exclamation_s.xpm");
	if (!icon_pic) Error("TGMsgBox", "mb_exclamation_s.xpm not found");
	break;
	
      case kMBIconAsterisk:
	icon_pic = gClient->GetPicture("mb_asterisk_s.xpm");
	if (!icon_pic) Error("TGMsgBox", "mb_asterisk_s.xpm not found");
	break;
	
      default:
	icon_pic = 0;
	break;
      }
      //
      if ( ty == 4 ){// non funziona il recupero dei puntatori a questi oggetti come e` possibile?
	//	gObjectTable->Print();
	TGLabel *la=dynamic_cast<TGLabel*>(gDirectory->FindObject("la"));
	TGHorizontalFrame *fLabelFrame=dynamic_cast<TGHorizontalFrame*>(gDirectory->FindObject("fLabelFrame"));
	TGTransientFrame *compofra=dynamic_cast<TGTransientFrame*>(gDirectory->FindObject("compofra"));
	if ( la ) la->Delete();
	if ( fLabelFrame ) fLabelFrame->Delete();
	if ( compofra ){
	  compofra->DestroyWindow();
	  compofra->Delete();	
	};
      };
      TGTransientFrame *compofra = new TGTransientFrame(gClient->GetRoot(), 0, 200, 80, kHorizontalFrame);      
      TGHorizontalFrame *fIconFrame = NULL;
      TGIcon *fIcon = NULL;
      if ( ty != 4 ){
	compofra->DontCallClose();      
	fIconFrame = new TGHorizontalFrame(compofra, 98, 78);
	fIcon = new TGIcon(fIconFrame, icon_pic, icon_pic->GetWidth(), icon_pic->GetHeight());
	fIconFrame->AddFrame(fIcon, new TGLayoutHints(kLHintsCenterX|kLHintsCenterY, 1, 1, 1, 1));
	compofra->AddFrame(fIconFrame, new TGLayoutHints(kLHintsCenterX|kLHintsCenterY, 1, 1, 1, 1));
      };
      //
      TGHorizontalFrame *fLabelFrame = new TGHorizontalFrame(compofra, 98, 78);
      TGLabel *la=new TGLabel(fLabelFrame,warn.Data());
      la->SetTextJustify(kLHintsCenterX);
      fLabelFrame->AddFrame(la, new TGLayoutHints(kLHintsCenterX|kLHintsCenterY, 1, 1, 1, 1));
      compofra->AddFrame(fLabelFrame, new TGLayoutHints(kLHintsCenterX|kLHintsCenterY, 1, 1, 1, 1));
      //		 
      compofra->SetWindowName(title.Data());
      compofra->MapSubwindows();
      if ( ty != 4 ){
	compofra->Resize(compofra->GetDefaultWidth(),80);
      } else {
	compofra->Resize(compofra->GetDefaultSize());
      };
      compofra->CenterOnParent();
      compofra->MapWindow();
      //
      if ( ty != 4 ){
	Int_t kkk = 0;
	while ( kkk < 200 ){
	  gSystem->ProcessEvents();
	  gSystem->Sleep(10);
	  kkk++;
	};
      };
      if ( compofra && ty != 4 ){
	la->Delete();
	fLabelFrame->Delete();
	if ( fIcon ) fIcon->Delete();
	if ( fIconFrame ) fIconFrame->Delete();
	compofra->DestroyWindow();
	compofra->Delete();	
      };
    };
    //
}

void PAMevcontrol::refreshdec(Int_t n){
  //
  for (Int_t i=0; i<11; i++){
    gf->HideFrame(hframedec[i]);
  };
  //
  if ( n < 11 ){
    gf->ShowFrame(hframedec[n]);
  };
};


void PAMevcontrol::showorbdata(){
  cvar->showorb = !cvar->showorb;
  if ( !cvar->showorb ) fshoworb->SetText("Show Data");
  if ( cvar->showorb ) fshoworb->SetText("Hide Data");
  //  printf("orb \n");
};

void PAMevcontrol::showtrgdata(){
  cvar->showtrg = !cvar->showtrg;
  if ( !cvar->showtrg ) fshowtrg->SetText("Show Data");
  if ( cvar->showtrg ) fshowtrg->SetText("Hide Data");
  //  printf("trg \n");
};

void PAMevcontrol::showrundata(){
  cvar->showrun = !cvar->showrun;
  if ( !cvar->showrun ) fshowrun->SetText("Show Data");
  if ( cvar->showrun ) fshowrun->SetText("Hide Data");
  //  printf("run \n");
};

void PAMevcontrol::showcaldata(){
  cvar->showcal = !cvar->showcal;
  if ( !cvar->showcal ) fshowcal->SetText("Show Data");
  if ( cvar->showcal ) fshowcal->SetText("Hide Data");
  //  printf("cal \n");
};

void PAMevcontrol::chkcalost(){
  if ( cvar->CALOT ) {
    cvar->CALOT = 0;
  } else {
    cvar->CALOT = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
};

void PAMevcontrol::showtrkdata(){
  cvar->showtrk = !cvar->showtrk;
  if ( !cvar->showtrk ) fshowtrk->SetText("Show Data");
  if ( cvar->showtrk ) fshowtrk->SetText("Hide Data");
  //  printf("trk \n");
};

void PAMevcontrol::showtofdata(){
  cvar->showtof = !cvar->showtof;
  if ( !cvar->showtof ) fshowtof->SetText("Show Data");
  if ( cvar->showtof ) fshowtof->SetText("Hide Data");
  //  printf("tof \n");
};

void PAMevcontrol::showacdata(){
  cvar->showac = !cvar->showac;
  if ( !cvar->showac ) fshowac->SetText("Show Data");
  if ( cvar->showac ) fshowac->SetText("Hide Data");
  //  printf("ac \n");
};

void PAMevcontrol::shownddata(){
  cvar->shownd = !cvar->shownd;
  if ( !cvar->shownd ) fshownd->SetText("Show Data");
  if ( cvar->shownd ) fshownd->SetText("Hide Data");
  //  printf("nd \n");
};

void PAMevcontrol::shows4data(){
  cvar->shows4 = !cvar->shows4;
  if ( !cvar->shows4 ) fshows4->SetText("Show Data");
  if ( cvar->shows4 ) fshows4->SetText("Hide Data");
  //  printf("s4 \n");
};

void PAMevcontrol::showsidata(){
  cvar->showsi = !cvar->showsi;
  if ( !cvar->showsi ) fshowsi->SetText("Show Data");
  if ( cvar->showsi ) fshowsi->SetText("Hide Data");
  //  printf("si \n");
};

void PAMevcontrol::showalldata(){
  cvar->showall = !cvar->showall;
  if ( !cvar->showall ) fshowall->SetText("Show Data");
  if ( cvar->showall ) fshowall->SetText("Hide Data");
  //  printf("all \n");
};

void PAMevcontrol::SetFilename() {
    TGTextEntry *entry = (TGTextEntry*)gTQSender;
    TString text = entry->GetText();
    cvar->thefilename=text.Data();
    cvar->i = 0;
    cvar->nevents = 0;
    cvar->firstevno = 0;
    cvar->lastevno = 0;
    if ( cvar->fl0 ) {
      cvar->fl0 = false;
      ffl0->SetState(kButtonUp);
    };
    cvar->restart = true;
    cvar->waitforever = false;
}

void PAMevcontrol::getl0file() {
  //
  TString host = "mysql://localhost/pamelaprod";
  TString user = "anonymous";
  TString psw = "";
  const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");
  const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");
  const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");
  if ( !pamdbhost ) pamdbhost = "";
  if ( !pamdbuser ) pamdbuser = "";
  if ( !pamdbpsw ) pamdbpsw = "";
  if ( strcmp(pamdbhost,"") ) host = pamdbhost;
  if ( strcmp(pamdbuser,"") ) user = pamdbuser;
  if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;
  cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; 
  cout<<"Connecting to DB"<<endl;
  cout<<"HOST "<<host<<endl;
  cout<<"USER "<<user<<endl;
  cout<<"PSW  "<<psw<<endl;
  cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; 
  TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  //
  TSQLResult *pResult;
  TSQLRow *Row;
  //
  if( dbc && dbc->IsConnected() ){
    // 
    // Retrieve the file
    //
    if ( clev->file == 2 ){
      // 
      // Starting from level2
      //
      GL_ROOT glroot = GL_ROOT();
      if( !glroot.Query_GL_ROOT(cvar->idroot,dbc) ){
	//
	cvar->thefilename= glroot.PATH + glroot.NAME;
	cvar->nevents = 0;
	cvar->firstevno = 0;
	cvar->lastevno = 0;
	if ( cvar->fl0 ) {
	  cvar->fl0 = false;
	  ffl0->SetState(kButtonUp);
	};
	cvar->restart = true;
	cvar->waitforever = false;
	//
	if ( cvar->thefilter != "" ){
	  cvar->thefilter="";
	  cvar->selex = true;
	};
	cvar->i = cvar->EVF + cvar->i ;
	//cvar->refresh = true;
	//	cvar->file = 0;
	//
      } else {	
	stringstream warning;
	warning.str("");
	warning << " Problems getting Level0 file ";
	DIALOG(2,warning.str().c_str());
      };
    } else {      
      //
      // starting from L0
      //
      stringstream query;
      query.str("");
      query << " SELECT ID FROM GL_ROOT WHERE NAME='"<< gSystem->BaseName(cvar->thefilename.Data()) <<"' order by INSERT_TIME desc limit 1;";
      //      printf(" query is %s \n",query.str().c_str());
      pResult = dbc->Query(query.str().c_str());
      Row = pResult->Next();      
      UInt_t idrl0 = 0;
      if ( Row ){
	idrl0 = (UInt_t)atoll(Row->GetField(0));
      };
      //
      query.str("");
      query << " SELECT ID,ID_ROOT_L2,EV_FROM FROM GL_RUN WHERE EV_FROM<="<<cvar->i<<" AND EV_TO>="<< cvar->i<<" AND ID_ROOT_L0="<< idrl0 <<";";
      //      printf(" query is %s \n",query.str().c_str());
      pResult = dbc->Query(query.str().c_str());
      Row = pResult->Next();      
      UInt_t idrl2 = 0;
      UInt_t idrlun = 0;
      UInt_t evfrom = 0;
      if ( Row ){
	idrlun = (UInt_t)atoll(Row->GetField(0));
	idrl2 = (UInt_t)atoll(Row->GetField(1));
	evfrom = (UInt_t)atoll(Row->GetField(2));
      };
      //
      query.str("");
      query << " SELECT ID,NEVENTS FROM GL_RUN WHERE ID_ROOT_L2="<< idrl2 <<" order by RUNHEADER_TIME asc;";
      //      printf(" query is %s \n",query.str().c_str());
      pResult = dbc->Query(query.str().c_str());
      Row = pResult->Next();      
      UInt_t coren = 0;
      while ( Row ){
	if ( (UInt_t)atoll(Row->GetField(0)) == idrlun ) break;
	coren += (UInt_t)atoll(Row->GetField(1));
	Row = pResult->Next();      
      };
      coren += cvar->i - evfrom;
      //
      GL_ROOT glroot = GL_ROOT();
      if( !glroot.Query_GL_ROOT(idrl2,dbc) ){
	//
	cvar->i = coren;
	//
	cvar->thefilename= glroot.PATH + glroot.NAME;
	cvar->nevents = 0;
	cvar->firstevno = 0;
	cvar->lastevno = 0;
	if ( cvar->fl0 ) {
	  cvar->fl0 = false;
	  ffl0->SetState(kButtonUp);
	};
	cvar->restart = true;
	cvar->waitforever = false;
	//
	if ( cvar->thefilter != "" ){
	  cvar->thefilter="";
	  cvar->selex = true;
	};
	//
      } else {	
	stringstream warning;
	warning.str("");
	warning << " Problems getting Level2 file ";
	DIALOG(2,warning.str().c_str());
      };
      //      stringstream warning;
      //      warning.str("");
      //      warning << " Not yet implemented ";
      //      DIALOG(2,warning.str().c_str());
    };
    //
  } else {
    stringstream warning;
    warning.str("");
    warning << " Problems connectiong to DB! ";
    DIALOG(2,warning.str().c_str());
  };
  dbc->Close();
};

void PAMevcontrol::CheckLevel() {
  if ( clev->file == 2 ){
    ffl0->SetState(kButtonDisabled);
//     if ( !cvar->tracknds4 ) {
//       ftrks4->SetState(kButtonUp);
//     } else {
//       ftrks4->SetState(kButtonDown);
//     };
  } else {    
    //ftrks4->SetState(kButtonDisabled);
    if ( !cvar->fl0 ) {
      ffl0->SetState(kButtonUp);
    } else {
      ffl0->SetState(kButtonDown);    
    };
  };
  if ( clev->file == 2 ){
    fgetl0->SetText("Get L0 file");
  } else {
    fgetl0->SetText("Get L2 file");
  };
}

void PAMevcontrol::SetSearching() {
  bstop->SetState(kButtonUp);
};

void PAMevcontrol::StopSearching() {
  bstop->SetState(kButtonDisabled);
};

void PAMevcontrol::RefreshButtons() {
  if ( cvar->jumprog ){
    jbwc1->SetState(kButtonDown);
    jbwc0->SetState(kButtonUp);
  } else {
    jbwc1->SetState(kButtonUp);
    jbwc0->SetState(kButtonDown);
  };
  if ( cvar->fl0 ){
    ffl0->SetState(kButtonDown);
  } else {
    ffl0->SetState(kButtonUp);
  };
  //  if ( cvar->tracknds4) ftrks4->SetState(kButtonDown);
  if ( cvar->bw ){
    bwc1->SetState(kButtonDown);
    bwc0->SetState(kButtonUp);
  } else {
    bwc0->SetState(kButtonDown);
    bwc1->SetState(kButtonUp);
  };
  if ( cvar->PATTRIG) fchktrigger->SetState(kButtonDown); else fchktrigger->SetState(kButtonUp);
  if ( cvar->PALETTE) fchkpalette->SetState(kButtonDown); else fchkpalette->SetState(kButtonUp);
  if ( cvar->VINFOS ) fchknames->SetState(kButtonDown); else fchknames->SetState(kButtonUp);
  if ( cvar->INFOS ) fchkinfo->SetState(kButtonDown); else fchkinfo->SetState(kButtonUp);
  //
  if ( cvar->CALOT ) fchkcalost->SetState(kButtonDown); else fchkcalost->SetState(kButtonUp);
  if ( cvar->CALO ){
    fchkcalo->SetState(kButtonDown);
    fshowcal->SetState(kButtonUp);    
  } else {
    fchkcalo->SetState(kButtonUp);
    fchkcalost->SetState(kButtonDisabled);
    fshowcal->SetState(kButtonDisabled);    
  };
  // 
  if ( cvar->ND ){
    fchknd->SetState(kButtonDown); 
    fshownd->SetState(kButtonUp); 
  } else {
    fchknd->SetState(kButtonUp);
    fshownd->SetState(kButtonDisabled); 
  };
  //
  if ( cvar->S4 ){
    fchks4->SetState(kButtonDown);
    fshows4->SetState(kButtonUp);
  } else {
    fchks4->SetState(kButtonUp);
    fshows4->SetState(kButtonDisabled);
  };
  //
  if ( cvar->TRK ){
    fchktrk->SetState(kButtonDown);
    fshowtrk->SetState(kButtonUp);
  } else {
    fchktrk->SetState(kButtonUp);
    fshowtrk->SetState(kButtonDisabled);
  }
  //
  if ( cvar->AC ){
    fchkac->SetState(kButtonDown);
    fshowac->SetState(kButtonUp);
  } else {
    fchkac->SetState(kButtonUp);
    fshowac->SetState(kButtonDisabled);
  };
  //
  if ( cvar->TOF ){
    fchktof->SetState(kButtonDown);
    fshowtof->SetState(kButtonUp);
  } else {
    fchktof->SetState(kButtonUp);
    fshowtof->SetState(kButtonDisabled);
  };
  //
  CheckLevel();
  //
};

void PAMevcontrol::SetFilter() {
    TGTextEntry *entry = (TGTextEntry*)gTQSender;
    TString text = entry->GetText();
    cvar->thefilter=text.Data();
    cvar->i--;
    cvar->selex = true;
    cvar->nevents = 0;
    cvar->firstevno = 0;
    cvar->lastevno = 0;
    cvar->refresh = true;
}

void PAMevcontrol::CompleteText() {
    TGTextEntry *entry = (TGTextEntry*)gTQSender;
    TString text = entry->GetText();
    Int_t curspos = entry->GetCursorPosition();
    Int_t ncurspos = 0;
    TString textrem;
    stringcopy(textrem,text,curspos,text.Length());
    text.Resize(curspos);
    if ( !strcmp(text.Data(),"") ) {
      stringstream ntext;
      ntext.str("");
      ntext << gSystem->ExpandPathName("$HOME");
      text = ntext.str().c_str();
      curspos=ntext.str().length();	
    };
    char *test = gSystem->ExpandPathName(text.Data());
    const char *dir = gSystem->DirName(test);
    const char *base = gSystem->BaseName(test);
    TString lbase = base;
    Int_t lenbase = lbase.Length();
    TSystemDirectory *tsd = new TSystemDirectory("",dir);
    TSystemFile *file;
    TList *lsmatch = new TList;
    Int_t numf = 0;
    Int_t numgo = 0;
    Int_t charmac = 0;
    TString tbase;
    Int_t k = 0;
    stringstream newtext;
    TSystemFile *mfile;
    TSystemFile nfile;
    TList *lsf = new TList;
    const char *ctbase;
    if ( !tsd->GetListOfFiles() ){
	gVirtualX->Bell(0);
	goto end;
    };
    lsf = tsd->GetListOfFiles();
    file = (TSystemFile*)lsf->First();
    //
    while( (TSystemFile*)lsf->After(file) ){
	numf++;
	file = (TSystemFile*)lsf->After(file);
	if ( !strncmp(file->GetName(),base,lenbase) ){
	    numgo++;
	    lsmatch->AddLast(file);
	    const char *ctbase = file->GetName();
	    tbase = ctbase;
	    charmac = tbase.Length();
	};
    };
    newtext.str("");
    if ( numgo > 0 ){
      mfile = (TSystemFile*)lsmatch->First();
      ctbase = mfile->GetName();    
      while ( (!strcmp(ctbase,"..") || !strcmp(ctbase,".")) && (TSystemFile*)lsmatch->After(mfile) ) {
	mfile = (TSystemFile*)lsmatch->After(mfile); 
	ctbase = mfile->GetName();
      };
      tbase = ctbase;
      base = ctbase;	
      charmac = tbase.Length();;
      while( (TSystemFile*)lsmatch->After(mfile) ){
	mfile = (TSystemFile*)lsmatch->After(mfile); 
	ctbase = mfile->GetName();
	while ( (!strcmp(ctbase,"..") || !strcmp(ctbase,".")) && (TSystemFile*)lsmatch->After(mfile) ) {
	  mfile = (TSystemFile*)lsmatch->After(mfile); 
	  ctbase = mfile->GetName();
	};
	tbase = ctbase;
	k = 0;
	for ( Int_t i=lenbase; i<=tbase.Length(); i++){
	  if ( !strncmp(tbase.Data(),base,i) && strcmp(tbase.Data(),base) ){
	    k = i;
	  };
	};
	if ( k <= charmac){
	  charmac = k;		
	};
      };
      gVirtualX->Bell(0);
    };
    if ( !charmac ) {
	gVirtualX->Bell(0);
	goto end;
    };
    tbase.Resize(charmac);
    if ( !strcmp(dir,"") || !strcmp(dir,"/") ){
	newtext << "/" << tbase.Data();
    } else {
	newtext << dir << "/" << tbase.Data();
    };
    nfile = TSystemFile(tbase.Data(),dir);
    if ( nfile.IsDirectory() && numgo == 1 ) newtext << "/";
    ncurspos = newtext.str().length();
    if ( textrem.Length() ) newtext << textrem.Data();    
    entry->SetText(newtext.str().c_str());
    entry->SetCursorPosition(ncurspos);
 end:
    lsf->Clear();
    lsmatch->Clear();    
}

void PAMevcontrol::saveas() {
    TString text = fText4->GetText();
    Int_t sel=fCombo->GetSelected();
    TString ty;
    switch (sel){
    case (0):
	ty = ".ps";
	break;
    case (1):
	ty = ".eps";
	break;
    case (2):
	ty = ".gif";
	break;
    case (3):
	ty = ".jpg";
	break;
    case (4):
	ty = ".tiff";
	break;
    case (5):
	ty = ".xpm";
	break;
    case (6):
	ty = ".pdf";
	break;
    case (7):
	ty = ".xml";
	break;
    case (8):
	ty = ".png";
	break;
    case (9):
	ty = ".svg";
	break;
    case (10):
	ty = ".root";
	break;
    case (11):
	ty = ".C";
	break;
    };
    if ( sel == 0 ) ty = ".ps";
    stringstream name;
    if ( strcmp(text.Data(),"") ){
	name.str("");
	name << text.Data();
	name << ty.Data();
	thefigure->SaveAs(name.str().c_str());
	name.str("");
	name << " Saved as ";
	name << text.Data();
	name << ty.Data();    
	DIALOG(0,name.str().c_str());
	printf(" Saved as %s%s \n",text.Data(),ty.Data());
    };
}

void PAMevcontrol::increment(float val) {
    fHProg1->Reset();
    fHProg1->SetPosition(val);
    gSystem->ProcessEvents();
}

void PAMevcontrol::forcel0() {
  cvar->fl0 = !cvar->fl0;
  cvar->alrforc = false;
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
}

void PAMevcontrol::clearselfi(){
    fText2->SetText("");   
}

void PAMevcontrol::upgrnamfi(){
    fText4->SetText(cvar->svas.Data());   
    fText4->SetCursorPosition(fText4->GetMaxLength());
}

void PAMevcontrol::jumpto() {
    TGTextEntry *entry = (TGTextEntry*)gTQSender;
    TString text = entry->GetText();
    Int_t j;
    j = atoi(text.Data());
    if ( cvar->jumprog ){
	if ( j < 1 || j > cvar->nevents ) {
	    printf("\n You can choose between 1 and %i \n",(int)cvar->nevents);
	    stringstream warning;
	    warning.str("");
	    warning << "You can choose between 1 and ";
	    warning << (int)cvar->nevents;
	    DIALOG(1,warning.str().c_str());
	} else { 
	    stringstream warning;
	    //	    warning.str("");
	    //	    warning << "Jumping to progressive number ";
	    //	    warning << j;
	    //	    DIALOG(0,warning.str().c_str());
	    printf("\n Jumping to progressive number %i\n\n",j);
	    cvar->i = j-2;
	    cvar->goon = true;
	    SetSearching();
	};	
    } else {
	if ( j < cvar->firstevno || j > cvar->lastevno ) {
	    printf("\n You can choose between %i and %i \n",cvar->firstevno,cvar->lastevno);
	    stringstream warning;
	    warning.str("");
	    warning << "You can choose between ";
	    warning << cvar->firstevno;
	    warning << " and ";
	    warning << cvar->lastevno;
	    DIALOG(1,warning.str().c_str());
	} else { 
// 	    stringstream warning;
// 	    warning.str("");
// 	    warning << "Jumping to event number ";
// 	    warning << j;
// 	    DIALOG(0,warning.str().c_str());
	    printf("\n Jumping to packet number %i\n\n",j);
	    cvar->jumpto = j;
	    cvar->jumpen = true;
	    cvar->goon = true;
	    SetSearching();
	};
    };
    entry->SetText("");    
}

void PAMevcontrol::radioevent() {
    cvar->jumprog = false;    
}

void PAMevcontrol::radioprog() {
    cvar->jumprog = true;    
}

void PAMevcontrol::radiocolor() {
    if ( !cvar->goon ){
	if ( cvar->bw ) {
	    cvar->bw = 0;
	    cvar->i--;
	    cvar->goon = true;
	};
    };
}

void PAMevcontrol::radiobw() {
    if ( !cvar->goon ){
	if ( !cvar->bw ) {
	    cvar->bw = 1;
	    cvar->i--;
	    cvar->goon = true;
	};
    };
}

void PAMevcontrol::radiotrack() {
  if ( cvar->tracknds4 ) {
    cvar->tracknds4 = 0;
  } else {
    cvar->tracknds4 = 1;
  };
    cvar->i--;
    cvar->goon = true;
}

void PAMevcontrol::chktof() {
  if ( cvar->TOF ) {
    cvar->TOF = 0;
  } else {
    cvar->TOF = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
}

void PAMevcontrol::chkac() {
  if ( cvar->AC ) {
    cvar->AC = 0;
  } else {
    cvar->AC = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
}

void PAMevcontrol::chktrk() {
  if ( cvar->TRK ) {
    cvar->TRK = 0;
  } else {
    cvar->TRK = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
}

void PAMevcontrol::chkcalo() {
  if ( cvar->CALO ) {
    cvar->CALO = 0;
  } else {
    cvar->CALO = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
}

void PAMevcontrol::chks4() {
  if ( cvar->S4 ) {
    cvar->S4 = 0;
  } else {
    cvar->S4 = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;  
}

void PAMevcontrol::chknd() {
  if ( cvar->ND ) {
    cvar->ND = 0;
  } else {
    cvar->ND = 1;
  };
  cvar->i--;
  cvar->nevents = 0;
  cvar->firstevno = 0;
  cvar->lastevno = 0;
  cvar->refresh = true;
}

void PAMevcontrol::chkinfo() {
  if ( cvar->INFOS ) {
    cvar->INFOS = 0;
  } else {
    cvar->INFOS = 1;
  };
  cvar->i--;
  cvar->goon = true;
}

void PAMevcontrol::chknames() {
  if ( cvar->VINFOS ) {
    cvar->VINFOS = 0;
  } else {
    cvar->VINFOS = 1;
  };
  cvar->i--;
  cvar->goon = true;
}

void PAMevcontrol::chkpalette() {
  if ( cvar->PALETTE ) {
    cvar->PALETTE = 0;
  } else {
    cvar->PALETTE = 1;
  };
  cvar->i--;
  cvar->goon = true;
}

void PAMevcontrol::chktrigger() {
  if ( cvar->PATTRIG ) {
    cvar->PATTRIG = 0;
  } else {
    cvar->PATTRIG = 1;
  };
  cvar->i--;
  cvar->goon = true;
}

void PAMevcontrol::next() {
  SetSearching();
  if ( cvar->i == cvar->nevents-1  ) {
    printf("This is the last event, you can't go forward! \n");
    DIALOG(1,"This is the last event!");
  } else {
    cvar->goon = true;
    cvar->doflag = 1;
  };    
}

void PAMevcontrol::stop() {
    DIALOG(1,"Stop searching");
    cvar->doflag = 3;
}

void PAMevcontrol::prev() {
  SetSearching();
  if ( cvar->i > 0  ) {
    printf("WARNING: going backward!\n\n");
    cvar->doflag = 2;
    cvar->goon = true;
  } else {
    printf("This is the first event, you can't go backward! \n");
    DIALOG(1,"This is the first event!");
  };
}

void PAMevcontrol::Terminate() {
  gSystem->ProcessEvents();
  gApplication->Terminate(0);
}

PAMevcontrol::~PAMevcontrol() {
  // Clean up used widgets: frames, buttons, layouthints
  Cleanup();
  delete this;
}
