#include "TMMainFrame.h"
#include "TMConfig.h"
#include "TMControlSPD.h"
#include "TMMsgBox.h"
#include "TMAbout.h"
#include "TMConfigureUpdateTime.h"
#include "TMConfigureEqActive.h"
#include "TMConfigureSuppressErrors.h"
#include "TMConfigureAdvEvCntDumpAll.h"
#include "TMConfigureDateSimple.h"
#include "TMConfigureDumpN.h"
#include "TMConfigureDump2.h"
#include "TMDeadNoisy.h"
#include "TMScreenShotAll.h"
#include "TMMovie.h"
#include "TMSetMask.h"
#include "TMIOMask.h"
#include "TMTrigMask.h"
#include "TMInterDialog.h"
#include "TMHistogrammingList.h"
#include "TMDisplayingList.h"
#include "TMDisplaying.h"
#include "SPDMood.h"
#include <TSystem.h>
#include <TStyle.h>
#include <TGFileDialog.h>
#include <TApplication.h>
#include <fstream>

ClassImp(TMMainFrame)

class TMHistogramming;

extern TString gVERSION;
Bool_t TMMainFrame::instanceFlag = kFALSE;
TMMainFrame* TMMainFrame::single = NULL;
//__________________________________________________________________________
TMMainFrame* TMMainFrame::Instance() {
  if(!instanceFlag) {
    instanceFlag = kTRUE;
    single = new TMMainFrame(gClient->GetRoot(), 850, 130);
    return single;
  }
  else {
    return single;
  }
}
//___________________________________________________________________________________
TMMainFrame::TMMainFrame(const TGWindow *p, UInt_t w, UInt_t h) : 
  TGMainFrame(p, w, h),
  fHeight(h),fWidth(w),
  fLoggedIn(kFALSE)
{
  gStyle->SetPalette(1);

  TMConfig::Instance()->LoadConfig();

  //  printf("Main thread: %ld\n",pthread_self());
}
//___________________________________________________________________________________
TMMainFrame::~TMMainFrame() {
  // Destructor.
  instanceFlag=kFALSE;
  delete   fMenuBar;
  delete[] fL;
  delete   fMenu;
  delete   fPicturePool;
  delete   fStatusBar;
  delete   fStatusMask;
}
//___________________________________________________________________________________
void TMMainFrame::CreateFrame() {
  fL[0] = new TGLayoutHints(kLHintsExpandX  | kLHintsExpandY,0,0,0,0);
  fL[1] = new TGLayoutHints(kLHintsBottom | kLHintsLeft,0,0,0,0);
  fL[2] = new TGLayoutHints(kLHintsBottom | kLHintsLeft | kLHintsExpandX,0,0,0,0);
  fL[3] = new TGLayoutHints(kLHintsBottom | kLHintsLeft | kFixedSize,0,0,0,0);
  fL[4] = new TGLayoutHints(kLHintsBottom | kLHintsRight | kLHintsExpandX,0,0,0,0);
  fL[5] = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 0,0,0,0);
  fL[6] = new TGLayoutHints(kLHintsExpandX | kLHintsTop, 0,0,0,0);
  fL[7] = new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX,0,0,0,0);
  fL[8] = new TGLayoutHints(kLHintsTop | kLHintsRight | kLHintsExpandY, 0,0,0,0);
  fL[9] = new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 0, 0, 0, 0);
  fL[10] = new TGLayoutHints(kLHintsTop | kLHintsRight,0,0,0,0);

  // button colors
  gClient->GetColorByName("brown", brown);
  gClient->GetColorByName("yellow", yellow);
  gClient->GetColorByName("green", green);
  gClient->GetColorByName("red", red);
  gClient->GetColorByName("gray", gray);

  //  TGCompositeFrame *tf; // temporary pointer

  // menu
  fMenu = new TGCompositeFrame(this,fWidth,27,kHorizontalFrame);
  AddFrame(fMenu, fL[7]);
  fMenuBar = new TMMenuBar(fMenu, this);
  fMenu->AddFrame(fMenuBar, fL[0]);

  // mask status bar
  Int_t partsMask[] = {33,33,33};
  fStatusMask = new TGStatusBar(this, 400, 27, kHorizontalFrame | kFixedSize);
  fStatusMask->Draw3DCorner(kFALSE);
  fStatusMask->SetParts(partsMask, 3);
  fMenu->AddFrame(fStatusMask, fL[0]);

  // check pixel mask
  if (TMControlSPD::Instance()->GetNrNoisy()>0) {
    TGText *text = new TGText();
    text->InsLine(text->RowCount(),"Be aware that you have masked pixels.");
    new TMMsgBox(gClient->GetRoot(), this, text);
    delete text;
  }

  // check equipment activation
  UInt_t nrEqActive=0;
  for (UInt_t eq=0; eq<20; eq++) {
    if (TMConfig::Instance()->GETeqActive(eq)==kTRUE) nrEqActive++;
  }
  fStatusMask->SetText(Form("%d equipments active",nrEqActive), 0);
  if (nrEqActive<20) {
    TGText *text = new TGText();
    text->InsLine(text->RowCount(),"Be aware that you do not have all equipments active.");
    new TMMsgBox(gClient->GetRoot(), this, text);
    delete text;
  }

  // suppressed error messages
  UInt_t nrSuppr=0;
  for (UInt_t i=0; i<AliITSRawStreamSPDErrorLog::GetNrErrorCodes(); i++) {
    if (((TMConfig::Instance()->GETerrorSuppr()) >> i) & 0x1 == 0x1) nrSuppr++;
  }
  fStatusMask->SetText(Form("%d error messages suppressed",nrSuppr), 2);

  // top buttons
  fTopButtons1 = new TGCompositeFrame(this, 10, 22, kHorizontalFrame | kFixedSize);
  AddFrame(fTopButtons1, fL[6]);
  fB[B_LOGIN-B_LOGIN] = new TGTextButton(fTopButtons1, "LOGIN ", B_LOGIN);
  fB[B_LOGIN-B_LOGIN]->SetToolTipText("Declare monitoring session to DATE system.", 1000);
  fB[B_LOGIN-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_LOGIN-B_LOGIN]->SetTextColor(yellow);
  fTopButtons1->AddFrame(fB[B_LOGIN-B_LOGIN], fL[2]);
  fB[B_LOGIN-B_LOGIN]->Associate(this);
  fB[B_DUMPC-B_LOGIN] = new TGTextButton(fTopButtons1, "RUN", B_DUMPC);
  fB[B_DUMPC-B_LOGIN]->SetToolTipText("Begin getting events from the stream continuously.", 1000);
  fB[B_DUMPC-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMPC-B_LOGIN]->SetTextColor(yellow);
  fTopButtons1->AddFrame(fB[B_DUMPC-B_LOGIN], fL[2]);
  fB[B_DUMPC-B_LOGIN]->Associate(this);
  fB[B_DUMPC-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMP2-B_LOGIN] = new TGTextButton(fTopButtons1, "RUN UNTIL EVENT", B_DUMP2);
  fB[B_DUMP2-B_LOGIN]->SetToolTipText("Retrieve events from the stream\nuntil specified event number is reached.", 1000);
  fB[B_DUMP2-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMP2-B_LOGIN]->SetTextColor(yellow);
  fTopButtons1->AddFrame(fB[B_DUMP2-B_LOGIN], fL[2]);
  fB[B_DUMP2-B_LOGIN]->Associate(this);
  fB[B_DUMP2-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMPN-B_LOGIN] = new TGTextButton(fTopButtons1, "RUN N EVENTS", B_DUMPN);
  fB[B_DUMPN-B_LOGIN]->SetToolTipText("Retrieve n events from the stream.", 1000);
  fB[B_DUMPN-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMPN-B_LOGIN]->SetTextColor(yellow);
  fTopButtons1->AddFrame(fB[B_DUMPN-B_LOGIN], fL[2]);
  fB[B_DUMPN-B_LOGIN]->Associate(this);
  fB[B_DUMPN-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMP1-B_LOGIN] = new TGTextButton(fTopButtons1, "RUN ONE EVENT", B_DUMP1);
  fB[B_DUMP1-B_LOGIN]->SetToolTipText("Retrieve an event from the stream.", 1000);
  fB[B_DUMP1-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMP1-B_LOGIN]->SetTextColor(yellow);
  fTopButtons1->AddFrame(fB[B_DUMP1-B_LOGIN], fL[2]);
  fB[B_DUMP1-B_LOGIN]->Associate(this);
  fB[B_DUMP1-B_LOGIN]->SetEnabled(kFALSE);


  fTopButtons2 = new TGCompositeFrame(this, 10, 22, kHorizontalFrame | kFixedSize);
  AddFrame(fTopButtons2, fL[6]);
  fB[B_RESET_ERR_FLAG-B_LOGIN] = new TGTextButton(fTopButtons2, "RESET ERROR FLAG", B_RESET_ERR_FLAG);
  fB[B_RESET_ERR_FLAG-B_LOGIN]->SetToolTipText("Acknowledge errors - remove red bar below\n(This is a way to check if errors remain).", 1000);
  fB[B_RESET_ERR_FLAG-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_RESET_ERR_FLAG-B_LOGIN]->SetTextColor(yellow);
  fTopButtons2->AddFrame(fB[B_RESET_ERR_FLAG-B_LOGIN], fL[2]);
  fB[B_RESET_ERR_FLAG-B_LOGIN]->Associate(this);
  //  fB[B_RESET_ERR_FLAG-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_UPDATE-B_LOGIN] = new TGTextButton(fTopButtons2, "UPDATE ALL", B_UPDATE);
  fB[B_UPDATE-B_LOGIN]->SetToolTipText("Update all displays.", 1000);
  fB[B_UPDATE-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_UPDATE-B_LOGIN]->SetTextColor(yellow);
  fTopButtons2->AddFrame(fB[B_UPDATE-B_LOGIN], fL[2]);
  fB[B_UPDATE-B_LOGIN]->Associate(this);
  //  fB[B_UPDATE-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_SCREENSHOT-B_LOGIN] = new TGTextButton(fTopButtons2, "SCREEN-SHOT ALL", B_SCREENSHOT);
  fB[B_SCREENSHOT-B_LOGIN]->SetToolTipText("Make screen-shots of all displays.", 1000);
  fB[B_SCREENSHOT-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_SCREENSHOT-B_LOGIN]->SetTextColor(yellow);
  fTopButtons2->AddFrame(fB[B_SCREENSHOT-B_LOGIN], fL[2]);
  fB[B_SCREENSHOT-B_LOGIN]->Associate(this);
  //  fB[B_SCREENSHOT-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_CLOSEALL-B_LOGIN] = new TGTextButton(fTopButtons2, "CLOSE ALL", B_CLOSEALL);
  fB[B_CLOSEALL-B_LOGIN]->SetToolTipText("Close all displays.", 1000);
  fB[B_CLOSEALL-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_CLOSEALL-B_LOGIN]->SetTextColor(yellow);
  fTopButtons2->AddFrame(fB[B_CLOSEALL-B_LOGIN], fL[2]);
  fB[B_CLOSEALL-B_LOGIN]->Associate(this);
  //  fB[B_CLOSEALL-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_RESET-B_LOGIN] = new TGTextButton(fTopButtons2, "RESET ALL", B_RESET);
  fB[B_RESET-B_LOGIN]->SetToolTipText("Reset all histograms.", 1000);
  fB[B_RESET-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_RESET-B_LOGIN]->SetTextColor(yellow);
  fTopButtons2->AddFrame(fB[B_RESET-B_LOGIN], fL[2]);
  fB[B_RESET-B_LOGIN]->Associate(this);
  //  fB[B_RESET-B_LOGIN]->SetEnabled(kFALSE);

  // status bar
  Int_t parts[] = {15,35,25,25};
  fStatusBar = new TGStatusBar(this, fWidth, 14, kHorizontalFrame);
  fStatusBar->SetParts(parts, 4);
  fStatusBar->Draw3DCorner(kFALSE);
  AddFrame(fStatusBar, fL[6]);

  // tool bar
  fToolBar = new TMToolBar(this, this, 100, 100);
  AddFrame(fToolBar, fL[6]);

  // main tab
//!!!  fMainTab = new TGTab(this, fWidth, fHeight);
//!!!  AddFrame(fMainTab, fL[0]);
  // hit display tab
  //  tf = fMainTab->AddTab("Hit Display");

  // setup displays frame
  fSetupDisplays = new TMSetupDisplays(gClient->GetRoot(), 400, 500);
  //  AddFrame(fSetupDisplays,fL[0]);
  

///  fTestButton = new TGTextButton(tf, "TEST", TESTTEST);
///  tf->AddFrame(fTestButton,fL[0]);
///  fTestButton->Associate(this);
///  fTestButton2 = new TGTextButton(tf, "TEST2", TESTTEST2);
///  tf->AddFrame(fTestButton2,fL[0]);
///  fTestButton2->Associate(this);
  



  // window name
  Char_t hostName[50];
  gethostname(hostName, sizeof(hostName));
  //  fWindowNamePartOne = Form("SPD-MOOD %s (User:%s, Host:%s)", gVERSION.Data(), getlogin(), hostName);
  fWindowNamePartOne = Form("SPD-MOOD %s",gVERSION.Data());
  SetWindowName(fWindowNamePartOne.Data());

  // window attributes
  SetWMSize(fWidth, fHeight);
  SetWMSizeHints(300, fHeight, 2000, 1000, 0, 0);
  MapSubwindows();
  Resize();
  MapWindow();

  fSetupDisplays->LoadDefaultSetup();

}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsAutoUpdate() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_AUTOUPDATE)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsAutoReset() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_AUTORESET)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsSkipPixel() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_SKIPPIXEL)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsSkipCluster() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_SKIPCLUSTER)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsSkipEventCountCheck() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_SKIP_ADV_EVC_CHECK)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsShowErrorEvents() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_TRYDISPERR)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
Bool_t TMMainFrame::IsStopOnError() {
  if (fToolBar->IsToggledDown(TOOL_BAR_BUTTON_STOPONERR)) {
    return kTRUE;
  }
  else {
    return kFALSE;
  }
}
//___________________________________________________________________________________
void TMMainFrame::UpdateStatusBar(const Char_t *msg, UInt_t view) {
  fStatusBar->SetText(msg,view);
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::UpdateStatusBarBG(const Char_t *msg, UInt_t col, UInt_t view) {
  fStatusBar->SetText(msg,view);
  if (col==0) {
    fStatusBar->GetBarPart(view)->SetBackgroundColor(gray);
  }
  else if (col==1) {
    fStatusBar->GetBarPart(view)->SetBackgroundColor(green);
  }
  else if (col==2) {
    fStatusBar->GetBarPart(view)->SetBackgroundColor(red);
  }
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::UpdateStatusMask(const Char_t *msg, UInt_t view) {
  fStatusMask->SetText(msg,view);
}
//___________________________________________________________________________________
void TMMainFrame::LoadConfigAs() {
  TGFileInfo file_info;
  new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &file_info);
  TString fileName = Form("%s", file_info.fFilename);
  if (fileName.CompareTo("(null)")!=0) {
    TMConfig::Instance()->LoadConfig(file_info.fFilename);
  }
}
//___________________________________________________________________________________
void TMMainFrame::SaveConfigAs() {
  TGFileInfo file_info;
  new TGFileDialog(gClient->GetRoot(), this, kFDSave, &file_info);
  TString fileName = Form("%s", file_info.fFilename);
  if (fileName.CompareTo("(null)")!=0) {
    TMConfig::Instance()->SaveConfig(file_info.fFilename);
  }
}
//___________________________________________________________________________________
void TMMainFrame::DumpConfig() {
  new TMAbout(gClient->GetRoot(), this, "SHOWGLOBALS");
}
//___________________________________________________________________________________
Bool_t TMMainFrame::RemoveAllViews() {
  return kTRUE;
}
//___________________________________________________________________________________
void TMMainFrame::CloseWindow() {
  ProcessClose();
}
//___________________________________________________________________________________
void TMMainFrame::ChangeWindowName(const Char_t* newName) {
  TString newWindowName = Form("%s         Source: %s",fWindowNamePartOne.Data(),newName);
  SetWindowName(newWindowName.Data());
}
//___________________________________________________________________________________
void TMMainFrame::DisableTopButtons() {
  //  for (UInt_t i=0; i<gNrTopButtons; i++) {
  for (UInt_t i=0; i<5; i++) {
    fTopState[i]=fB[i]->GetState();
    fB[i]->SetEnabled(kFALSE);
  }
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::RestoreTopButtons() {
  fB[B_DUMPC-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMPC-B_LOGIN]->SetTextColor(yellow);
  fB[B_DUMP2-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMP2-B_LOGIN]->SetTextColor(yellow);
  fB[B_DUMPN-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMPN-B_LOGIN]->SetTextColor(yellow);
  fB[B_DUMP1-B_LOGIN]->SetBackgroundColor(brown);
  fB[B_DUMP1-B_LOGIN]->SetTextColor(yellow);

  fB[B_DUMPC-B_LOGIN]->SetText("RUN");
  fB[B_DUMPC-B_LOGIN]->SetToolTipText("Begin getting events from the stream continuously.", 1000);
  fB[B_DUMP2-B_LOGIN]->SetText("RUN UNTIL EVENT");
  fB[B_DUMP2-B_LOGIN]->SetToolTipText("Retrieve events from the stream\nuntil specified event number is reached.", 1000);
  fB[B_DUMPN-B_LOGIN]->SetText("RUN N EVENTS");
  fB[B_DUMPN-B_LOGIN]->SetToolTipText("Retrieve n events from the stream.", 1000);
  fB[B_DUMP1-B_LOGIN]->SetText("RUN ONE EVENT");
  fB[B_DUMP1-B_LOGIN]->SetToolTipText("Retrieve an event from the stream.", 1000);

  EnableTopButtons();
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::FreezeTopButtons() {
  TopButtonsSnap();
  DisableTopButtons();
}
//___________________________________________________________________________________
void TMMainFrame::DeFreezeTopButtons() {
  RestoreTopButtonsSnap();
}
//___________________________________________________________________________________
void TMMainFrame::TopButtonsSnap() {
  for (UInt_t i=0; i<gNrTopButtons; i++) {
    fTopState[i]=fB[i]->GetState();
  }
}
//___________________________________________________________________________________
void TMMainFrame::RestoreTopButtonsSnap() {
  for (UInt_t i=0; i<gNrTopButtons; i++) {
    fB[i]->SetState((EButtonState)fTopState[i]);
  }
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::EnableTopButtons() {
  for (UInt_t i=0; i<gNrTopButtons; i++) {
    fB[i]->SetEnabled(kTRUE);
  }
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::FinishRunning() {
  RestoreTopButtons();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessLogin1() {
  DisableTopButtons();
  new TMConfigureDateSimple(gClient->GetRoot(), this);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessLogin2() {
  TMControlSPD::Instance()->talk2DATElogin();
  if (fLoggedIn) {
    EnableTopButtons();
    TMDisplayingList::Instance()->UpdateDisplays();
  }
  else {
    printf("ERROR: Could not connect to data source\n");
    ProcessLoginInterrupt();
  }
}
//___________________________________________________________________________________
void TMMainFrame::ProcessLoginInterrupt() {
  fB[B_LOGIN-B_LOGIN]->SetEnabled(kTRUE);
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessLogout1() {
  FreezeTopButtons();
  TGText *text = new TGText();
  text->InsLine(text->RowCount(),"Logout from data source. Are you sure?");
  new TMInterDialog(gClient->GetRoot(), this, "PROCEED", "CANCEL", text, B_LOGOUTYES, B_LOGOUTNO);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessLogout2() {
  DisableTopButtons();
  if (TMControlSPD::Instance()->IsRunning()) {
    TMControlSPD::Instance()->StopRunningSafely();
  }
  TMHistogrammingList::Instance()->Reset();
  TMControlSPD::Instance()->Reset();
  TMControlSPD::Instance()->talk2DATElogout();
  if (fLoggedIn) {
    printf("ERROR: Problem disconnecting from data source\n");
    LogoutSuccess(); // if logout not successful, force logged out state...
  }
}
//___________________________________________________________________________________
void TMMainFrame::ProcessResetDisplays() {
  FreezeTopButtons();
  TMControlSPD::Instance()->HoldRunning();
  TMHistogrammingList::Instance()->Reset();
  TMControlSPD::Instance()->Reset();
  TMDisplayingList::Instance()->UpdateDisplays();
  TMControlSPD::Instance()->ContinueRunning();
  DeFreezeTopButtons();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessUpdateDisplays() {
  FreezeTopButtons();
  TMControlSPD::Instance()->HoldRunning();
  TMDisplayingList::Instance()->UpdateDisplays();
  TMControlSPD::Instance()->ContinueRunning();
  DeFreezeTopButtons();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessResetErrorFlag() {
  TMControlSPD::Instance()->ResetErrorFlag();
}
//___________________________________________________________________________________
void TMMainFrame::LoginSuccess() {
  UpdateStatusBar(TMConfig::Instance()->GETdataSourceFullPath().Data(), 1);
  fB[B_LOGIN-B_LOGIN]->SetText("LOGOUT");
  fB[B_LOGIN-B_LOGIN]->SetToolTipText("Disconnect from data source", 1000);
  //  fStatusBar->SetText("Logged in", 0);
  fStatusBar->SetText(" ", 2);
  fStatusBar->SetText(" ", 3);
  fLoggedIn=kTRUE;
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::LogoutSuccess() {
  UpdateStatusBar("Logged out", 1);
  //  ChangeWindowName("Logged Out");
  fB[B_LOGIN-B_LOGIN]->SetEnabled(kTRUE);
  fB[B_LOGIN-B_LOGIN]->SetText("LOGIN");
  fB[B_LOGIN-B_LOGIN]->SetToolTipText("Connect to data source", 1000);
  fStatusBar->SetText(" ", 2);
  fStatusBar->SetText(" ", 3);
  fLoggedIn=kFALSE;
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessStartDumpC() {
  if (TMControlSPD::Instance()->IsStopRunning()) {
    return;
  }
  if (TMControlSPD::Instance()->IsRunning()) {
    fB[B_DUMPC-B_LOGIN]->SetEnabled(kFALSE);
    gSystem->ProcessEvents();
    //    printf("call from thread %ld\n",pthread_self());
    TMControlSPD::Instance()->StopRunningSafely();
  }
  else {
    fB[B_LOGIN-B_LOGIN]->SetEnabled(kFALSE);
    fB[B_DUMP2-B_LOGIN]->SetEnabled(kFALSE);
    fB[B_DUMPN-B_LOGIN]->SetEnabled(kFALSE);
    fB[B_DUMP1-B_LOGIN]->SetEnabled(kFALSE);

    fB[B_DUMPC-B_LOGIN]->SetBackgroundColor(yellow);
    fB[B_DUMPC-B_LOGIN]->SetTextColor(brown);
    fB[B_DUMPC-B_LOGIN]->SetText("STOP");
    fB[B_DUMPC-B_LOGIN]->SetToolTipText("Stop getting events.", 1000);
    TMControlSPD::Instance()->StartDumpC();
    gSystem->ProcessEvents();
  }
}
//___________________________________________________________________________________
void TMMainFrame::ProcessStartDumpN() {
  if (TMControlSPD::Instance()->IsStopRunning()) {
    return;
  }
  if (TMControlSPD::Instance()->IsRunning()) {
    fB[B_DUMPN-B_LOGIN]->SetEnabled(kFALSE);
    TMControlSPD::Instance()->StopRunningSafely();
    gSystem->ProcessEvents();
  }
  else {
    new TMConfigureDumpN(gClient->GetRoot(), this);
  }
}
//___________________________________________________________________________________
void TMMainFrame::ProcessStartDumpN2() {
  fB[B_LOGIN-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMPC-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMP2-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMP1-B_LOGIN]->SetEnabled(kFALSE);

  fB[B_DUMPN-B_LOGIN]->SetBackgroundColor(yellow);
  fB[B_DUMPN-B_LOGIN]->SetTextColor(brown);
  fB[B_DUMPN-B_LOGIN]->SetText("STOP");
  fB[B_DUMPN-B_LOGIN]->SetToolTipText("Stop getting events.", 1000);
  TMControlSPD::Instance()->StartDumpN();
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessStartDump1() {
  if (TMControlSPD::Instance()->IsStopRunning()) {
    return;
  }
  if (TMControlSPD::Instance()->IsRunning()) {
    fB[B_DUMP1-B_LOGIN]->SetEnabled(kFALSE);
    TMControlSPD::Instance()->StopRunningSafely();
  }
  else {
    fB[B_LOGIN-B_LOGIN]->SetEnabled(kFALSE);
    fB[B_DUMPC-B_LOGIN]->SetEnabled(kFALSE);
    fB[B_DUMP2-B_LOGIN]->SetEnabled(kFALSE);
    fB[B_DUMPN-B_LOGIN]->SetEnabled(kFALSE);

    fB[B_DUMP1-B_LOGIN]->SetBackgroundColor(yellow);
    fB[B_DUMP1-B_LOGIN]->SetTextColor(brown);
    fB[B_DUMP1-B_LOGIN]->SetText("STOP");
    fB[B_DUMP1-B_LOGIN]->SetToolTipText("Stop getting event.", 1000);
    TMControlSPD::Instance()->StartDump1();
  }
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessStartDump2() {
  if (TMControlSPD::Instance()->IsStopRunning()) {
    return;
  }
  if (TMControlSPD::Instance()->IsRunning()) {
    fB[B_DUMP2-B_LOGIN]->SetEnabled(kFALSE);
    TMControlSPD::Instance()->StopRunningSafely();
    gSystem->ProcessEvents();
  }
  else {
    new TMConfigureDump2(gClient->GetRoot(), this);
  }
}
//___________________________________________________________________________________
void TMMainFrame::ProcessStartDump22() {
  fB[B_LOGIN-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMPC-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMPN-B_LOGIN]->SetEnabled(kFALSE);
  fB[B_DUMP1-B_LOGIN]->SetEnabled(kFALSE);

  fB[B_DUMP2-B_LOGIN]->SetBackgroundColor(yellow);
  fB[B_DUMP2-B_LOGIN]->SetTextColor(brown);
  fB[B_DUMP2-B_LOGIN]->SetText("STOP");
  fB[B_DUMP2-B_LOGIN]->SetToolTipText("Stop getting events.", 1000);
  TMControlSPD::Instance()->StartDump2();
  gSystem->ProcessEvents();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessClose() {
  if (fLoggedIn) {
    TGText *text = new TGText();
    text->InsLine(text->RowCount(),"You are still logged in. Are you sure you want to quit?");
    new TMInterDialog(gClient->GetRoot(), this, "PROCEED", "CANCEL", text, APP_FORCE_CLOSE, NAN_NAN);
  }
  else {
    TMControlSPD::Instance()->SaveMask();
    TMConfig::Instance()->SaveConfig();
    gApplication->Terminate(0);
  }
}
//___________________________________________________________________________________
void TMMainFrame::ProcessAutoResetDisplay(UInt_t d_id, UInt_t plotNr, Bool_t autoreset) {
  fSetupDisplays->ProcessAutoResetDisplay(d_id,plotNr,autoreset);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessPauseDisplay(UInt_t d_id, UInt_t plotNr, Bool_t pause) {
  fSetupDisplays->ProcessPauseDisplay(d_id,plotNr,pause);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessCloneDisplay(UInt_t d_id, UInt_t plotNr, TMHistogramming *hist) {
  fSetupDisplays->ThreadProcessCloneDisplay(d_id,plotNr,hist);
  //  fSetupDisplays->ProcessCloneDisplay(d_id,plotNr,hist);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessKillDisplay(UInt_t d_id, UInt_t plotNr) {
  fSetupDisplays->ProcessKillDisplay(d_id,plotNr);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessCloseDisplay(UInt_t d_id, UInt_t plotNr, UInt_t cloneId) {
  fSetupDisplays->ThreadProcessCloseDisplay(d_id,plotNr,cloneId);
  //  fSetupDisplays->ProcessCloseDisplay(d_id,plotNr,cloneId);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessCloseDisplay(UInt_t d_id, UInt_t plotNr) {
  fSetupDisplays->ProcessCloseDisplay(d_id,plotNr);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessCloseAllDisplays() {
  fSetupDisplays->ProcessCloseAllDisplays();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessOpenDisplay(UInt_t d_id) {
  fSetupDisplays->ProcessOpenDisplay(d_id);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessOpenDisplay(UInt_t d_id, UInt_t plotNr, UInt_t cloneId, TMHistogramming *hist) {
  fSetupDisplays->ProcessOpenDisplay(d_id,plotNr,cloneId,hist);
}
//___________________________________________________________________________________
void TMMainFrame::ProcessUpdateSupprError() {
  TMControlSPD::Instance()->UpdateSupprError();
}
//___________________________________________________________________________________
void TMMainFrame::ProcessDeadNoisy() {
  fSetupDisplays->ProcessDeadNoisy();
}
//!!!//___________________________________________________________________________________
//!!!Bool_t TMMainFrame::ProcessGridSourceEnv() {
//!!!  return TMControlSPD::Instance()->GridSourceEnv();
//!!!}
//___________________________________________________________________________________
void TMMainFrame::ProcessGridConnect() {
  TMControlSPD::Instance()->GridConnect();
}
//___________________________________________________________________________________
UInt_t TMMainFrame::GetNewCloneId() {
  return fSetupDisplays->GetNewCloneId();
}
//___________________________________________________________________________________
Bool_t TMMainFrame::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) {
  //  printf("%d,%ld,%ld\n",GET_MSG(msg),parm1,parm2);
  switch(GET_MSG(msg)) {
  case kC_COMMAND :
    switch (GET_SUBMSG(msg)) {
      
      
    case kCM_MENU :
      switch (parm1) {

      case FILE_DUMPCONF :
	DumpConfig();
	break;
      case FILE_LOADCONF :
	LoadConfigAs();
	  break;
      case FILE_DEFAULTCONF :
	TMConfig::Instance()->SetDefaultConfig();
	break;
      case FILE_SAVECONF :
	TMConfig::Instance()->SaveConfig();
	break;
      case FILE_SAVECONFAS :
	SaveConfigAs();
	break;
      case FILE_EXIT :
	ProcessClose();
	break;

      case CONF_UPDATETIME :
	new TMConfigureUpdateTime(gClient->GetRoot(), this);
	break;
      case CONF_TRIGMASKALL:
	new TMTrigMask(gClient->GetRoot(), this, NULL, NAN_NAN);
	break;
      case CONF_EQACTIVATE:
	new TMConfigureEqActive(gClient->GetRoot(), this);
	break;
      case CONF_SUPPRERROR:
	new TMConfigureSuppressErrors(gClient->GetRoot(), this);
	break;
      case CONF_ADVEVCNTDUMPALL:
	new TMConfigureAdvEvCntDumpAll(gClient->GetRoot(), this);
	break;
      case CONF_CHANGESOURCE :
	new TMConfigureDateSimple(gClient->GetRoot(), this);
	break;
      case OP_DEADNOISY :
	new TMDeadNoisy(gClient->GetRoot(), this, OP_DEADNOISY2);
	break;
      case OP_DEADNOISY2 :
	ProcessDeadNoisy();
	break;
//!!!      case OP_GRIDCONNECT :
//!!!	if (ProcessGridSourceEnv()) {
//!!!	  ProcessGridConnect();
//!!!	}
//!!!	break;
      case MASK_MASK:
	new TMSetMask(gClient->GetRoot(), this, kTRUE);
	break;
      case MASK_UNMASK:
	new TMSetMask(gClient->GetRoot(), this, kFALSE);
	break;
      case MASK_LOADDIR:
	new TMIOMask(gClient->GetRoot(), this, kTRUE);
	break;
      case MASK_SAVEDIR:
	new TMIOMask(gClient->GetRoot(), this, kFALSE);
	break;
      case MASK_CLEAR:
	TMControlSPD::Instance()->ClearMask();
	break;
      case MASK_PRINTLIST:
	TMControlSPD::Instance()->PrintMaskedPixels();
	break;

      }
      break;

    case kCM_BUTTON :
      switch (parm1) {

      case B_LOGIN :
	if (!fLoggedIn) ProcessLogin1();
	else            ProcessLogout1();
	break;
      case LOGIN_INTERRUPT :
	ProcessLoginInterrupt();
	break;
      case B_LOGIN2 :
	ProcessLogin2();
	break;
      case B_LOGOUTYES :
	DeFreezeTopButtons();
	ProcessLogout2();
	break;
      case B_LOGOUTNO :
	DeFreezeTopButtons();
	break;
      case B_DUMPC :
	//	printf("b_dumpc thread %ld\n",pthread_self());
	if (!TMControlSPD::Instance()->AmIdump()) {
	  ProcessStartDumpC();
	}
	break;
      case B_DUMP2 :
	ProcessStartDump2();
	break;
      case B_DUMP2_START :
	ProcessStartDump22();
	break;
      case B_DUMPN :
	ProcessStartDumpN();
	break;
      case B_DUMPN_START :
	ProcessStartDumpN2();
	break;
      case B_DUMP1 :
	ProcessStartDump1();
	break;
      case B_CLOSEALL :
	ProcessCloseAllDisplays();
	break;
      case B_RESET :
	ProcessResetDisplays();
	break;
      case B_UPDATE :
	ProcessUpdateDisplays();
	break;
      case B_RESET_ERR_FLAG :
	ProcessResetErrorFlag();
	break;
      case B_SCREENSHOT :
	TMControlSPD::Instance()->HoldRunning();
	new TMScreenShotAll(gClient->GetRoot(), this, B_SCREENSHOT2, TMControlSPD::Instance()->GetRunNb());
	break;
      case B_SCREENSHOT2 :
	TMDisplayingList::Instance()->ScreenShotAll(TMConfig::Instance()->GETuploadCommand().Data(),TMConfig::Instance()->GETuploadCommand2().Data());
	TMControlSPD::Instance()->ContinueRunning();
	break;


      case UPDATE_SUPPRERROR :
	ProcessUpdateSupprError();
	break;


      case TESTTEST :
	{
	  break;
	}
      case TESTTEST2 :
	{
	  break;
	}


      case FINISH_RUNNING :
	FinishRunning();
	break;

      case APP_FORCE_CLOSE :
	printf("Forcing exit...\n");
	ProcessLogout2();
	ProcessClose();
	break;

      }
      break;


    }
  }
  return kTRUE;
}

