#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 <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;
  //
  TGCompositeFrame *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);
  TGGroupFrame *gf = new TGGroupFrame(cframe1, "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,400,800);
  TGHorizontalFrame *htextsl = new TGHorizontalFrame(cframe4,400,800);
  TGHorizontalFrame *htext = new TGHorizontalFrame(inputf,400,800);
  TGHorizontalFrame *htext2 = new TGHorizontalFrame(inputf,400,800);
  TGHorizontalFrame *htext3 = new TGHorizontalFrame(jumpf,400,800);
  TGHorizontalFrame *htext4 = new TGHorizontalFrame(jumpf,400,80);
  TGHorizontalFrame *hframe = new TGHorizontalFrame(this,400,800);
  TGHorizontalFrame *hframe1 = new TGHorizontalFrame(gf, 280, 50);
  TGHorizontalFrame *hframe2 = new TGHorizontalFrame(gf, 280, 40);
  TGHorizontalFrame *hframe3 = new TGHorizontalFrame(gf, 280, 40);
  TGHorizontalFrame *hframe4 = new TGHorizontalFrame(gf,280,10);
  TGVerticalFrame *hframe5 = new TGVerticalFrame(hframe4, 280, 40);
  TGHorizontalFrame *hfrprog = new TGHorizontalFrame(this,400,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 | kLHintsExpandX,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()");
  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 | kLHintsExpandX,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));
  //
  TGCheckButton *fchktof = new TGCheckButton(hframe1, "TOF");   
  fchktof->Connect("Clicked()","PAMevcontrol", this,"chktof()"); 
  if ( cvar->TOF ) fchktof->SetState(kButtonDown);
  hframe1->AddFrame(fchktof, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,0,5,5,5));
  //
  TGCheckButton *fchkac = new TGCheckButton(hframe1, "AC");   
  fchkac->Connect("Clicked()","PAMevcontrol", this,"chkac()");   
  if ( cvar->AC ) fchkac->SetState(kButtonDown);
  hframe1->AddFrame(fchkac, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,5,25,5,5));
  //
  TGCheckButton *fchktrk = new TGCheckButton(hframe1, "Tracker");   
  fchktrk->Connect("Clicked()","PAMevcontrol",this,"chktrk()");   
  if ( cvar->TRK ) fchktrk->SetState(kButtonDown);
  hframe1->AddFrame(fchktrk, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,10,5,5,5));
  //
  gf->AddFrame(hframe1, new TGLayoutHints(kLHintsExpandX));
  //
  TGCheckButton *fchks4 = new TGCheckButton(hframe2, "S4");   
  fchks4->Connect("Clicked()","PAMevcontrol",this,"chks4()");   
  if ( cvar->S4 ) fchks4->SetState(kButtonDown);
  hframe2->AddFrame(fchks4, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,0,15,5,5));
  //
  TGCheckButton *fchknd = new TGCheckButton(hframe2, "ND");   
  fchknd->Connect("Clicked()","PAMevcontrol",this,"chknd()");   
  if ( cvar->ND ) fchknd->SetState(kButtonDown);
  hframe2->AddFrame(fchknd, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,5,25,5,5));
  //
  TGCheckButton *fchkcalo = new TGCheckButton(hframe2, "Calorimeter");   
  fchkcalo->Connect("Clicked()","PAMevcontrol",this,"chkcalo()");   
  if ( cvar->CALO ) fchkcalo->SetState(kButtonDown);
  hframe2->AddFrame(fchkcalo, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,10,2,5,5));
  //
  gf->AddFrame(hframe2, new TGLayoutHints(kLHintsExpandX));
  //
  TGCheckButton *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,0,5,5,5));
  //
  TGCheckButton *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,5,5,5,5));
  TGCheckButton *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,10,5,5,5));
  gf->AddFrame(hframe3, new TGLayoutHints(kLHintsExpandX));
  //
  TGVButtonGroup *group = new TGVButtonGroup(hframe4);
  TGRadioButton *bwc0;
  TGRadioButton *bwc1;
  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,1,5,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,5,2,5,5));
  ffl0 = new TGCheckButton(hframe5, "Force LEVEL0");
  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,5,2,5,5));
  //
  hframe4->AddFrame(hframe5, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterY,10,5,5,5));
  gf->AddFrame(hframe4, new TGLayoutHints(kLHintsExpandX));
  //
  cframe1->AddFrame(gf, new TGLayoutHints(kLHintsExpandX));
  //
  TGHButtonGroup *jgroup = new TGHButtonGroup(htext4);
  TGRadioButton *jbwc0;
  TGRadioButton *jbwc1;
  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 | 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(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 | kLHintsExpandY,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();
}

void PAMevcontrol::DIALOG(Int_t ty, TString warn){    
    //
    // ty = 0 -> INFO, ty = 1 -> WARNING, ty = 3 -> ERROR
    //
    Int_t retval;
    TString title;
    EMsgBoxIcon mb_icon = kMBIconStop;
    if ( ty == 0 ){
	title="INFO";
	mb_icon = kMBIconAsterisk;
    };
    if ( ty == 1 ){
	title="WARNING!";
	mb_icon = kMBIconExclamation;
    };
    if ( ty == 2 ){
	title="ERROR!!";
	mb_icon = kMBIconStop;
    };
    new TGMsgBox(gClient->GetRoot(), this, title.Data(), warn.Data(), mb_icon, kMBOk, &retval);
}


void PAMevcontrol::SetFilename() {
    TGTextEntry *entry = (TGTextEntry*)gTQSender;
    TString text = entry->GetText();
    cvar->thefilename=text.Data();
    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::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);    
    };
  };
}

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

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

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() {
    if ( cvar->fl0 ) {
	cvar->fl0 = false;
    } else {
	cvar->fl0 = true;
    };
    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::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;
}
