#include "NpotModule.h"
#include "StripHist.h"

#include <JobControl/JobCModuleRegistry.h>
#include <JobControl/JobCResult.h>
#include <MessageService/MsgService.h>

#include <RawData/RawRecord.h>
#include <RawData/RawBeamMonBlock.h>
#include <RawData/RawBeamData.h>

#include <DataUtil/GetRecords.h>
#include <HistMan/HistMan.h>

#include <Conventions/Munits.h>

#include <TGraph.h>
#include <TCanvas.h>
#include <TStyle.h>

#include <vector>

//ClassImp(NpotModule)

using namespace std;

CVSID("$Id: NpotModule.cxx,v 1.9 2005/06/01 17:01:47 thosieck Exp $");
JOBMODULE(NpotModule,"MonNpot","Generate PoT related for Monitoring");

NpotModule::NpotModule()
{

  fStripHist = new StripHist("Protons Delivered Per Spill",
			     "Number of Protons Delivered to NuMI per Spill",
			       250,0,25);
    fStripHist->SetStripRange(1*Munits::day);
}

NpotModule::~NpotModule()
{
}


void NpotModule::BeginJob()
{
    TCanvas* canvas = new TCanvas("Protons Delivered Per Spill",
                                  "Number of Protons Delivered to NuMI",
				  500,400);

    TH1D& hist = fStripHist->GetHist();
    hist.SetXTitle("Protons Delivered per Spill (1E12)");

    canvas->cd();
    fStripHist->Draw("AB");

    HistMan hm = this->GetHistMan();
    hm.Adopt("Protons",canvas);
}


void NpotModule::Fill(const RawBeamMonHeaderBlock& /*head*/, const RawBeamMonBlock& block)
{
    const RawBeamData* tortgt = block["E:TORTGT"];
    if (!tortgt) {
	MSG("BD",Msg::kWarning)
	    << "No TORTGT in the data\n";
	return;
    }
    if (! tortgt->GetDataLength()) {
	MSG("BD",Msg::kWarning)
	    << "TORTGT exists but w/out data\n";
	return;
    }

    double npot = tortgt->GetData()[0];
    double dae = 1.0*tortgt->GetSeconds() + tortgt->GetMsecs()*0.001;
    MSG("BD",Msg::kDebug)
	<< "npot = " << npot << ", dae = " << Form("%12u",dae) << endl;
    
    fStripHist->Fill(dae,npot);
}

