
#include <iostream>
#include <string.h>
#include <map>
#include <vector>

#include "TROOT.h"
#include "TKey.h"
#include "TFile.h"
#include "TCanvas.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TSystem.h"

using std::cout;
using std::cerr;
using std::endl;

namespace RichTB
{

  // sleep time in ms
  const int sleepTime = 5000 ;

  typedef std::map<std::string,TCanvas*> CanvasMap;
  static CanvasMap canvasMap;

  void plotObject( TObject * obj )
  {
    // get canvas for this object
    TCanvas * canvas = canvasMap[ obj->GetName() ];
    if ( NULL == canvas )
    {
      canvasMap[ obj->GetName() ] = canvas = new TCanvas(obj->GetTitle(),obj->GetName());
    }
    canvas->cd();
    TH1 * th1Obj = (TH1*)obj;
    th1Obj->Draw("zcol");
    canvas->Modified();
    canvas->Update();
    gSystem->ProcessEvents();
 
  }

  void dirScan(TDirectory* dir1)
  {

    dir1->cd(); // change searching directory
    TList * olist = dir1->GetListOfKeys();
    for ( int oidx = 0; oidx<olist->GetSize(); ++oidx )
    {
      // get objects in this directory
      TKey* key = (TKey*)olist->At(oidx);

      // read object from key
      TObject* obj = key->ReadObj();
      cout << "Found " << obj->ClassName() << " object, id = " << obj->GetName() << endl;

      // Plot this object on its own canvas
      plotObject( obj );

    }


  }

  void runMoni( const std::string moniFile )
  {
 
    bool OK ( true );
    int maxRuns(100), nRuns(0);
    while ( OK && nRuns < maxRuns )
    {
      ++nRuns;

      // try to open input file
      TFile * fin = new TFile( moniFile.c_str() );
      if ( fin->IsOpen() )
      {
        cout << "Processing input file : " << fin->GetName() << endl;
        dirScan(gDirectory);
      }
      else
      {
        cout << "WARNING : input file " << fin->GetName() << " does not exist yet" << endl;
      }
      delete fin;

      //break;
      cout << "Sleeping for " << sleepTime << " ms" << endl;
      // sleep ( sleepTime );
      gSystem->Sleep ( sleepTime );

    }

    // delete canvas
    for ( CanvasMap::iterator i = canvasMap.begin(); i != canvasMap.end(); ++i )
    {
      delete (*i).second;
    }
    canvasMap.clear();

  }


}


