/**
* Rate
* author  Nagni
* version 1.0 - 27 April 2006
*
* Description: .
*
*
* 27 April 2006
* First implementation
* 
* 6 July 2006
* Released version adding as an "emergency" Trigger and Anticounter plot. A future release should 
* foreseen a general class called OrbitalRate, to be put into the "Utility" for plotting whatever
* data related to the orbit. Under a preliminary analysis this Class will contain
* 
* OrbitalRate(String TLEFile) - file containing one or more TLE
*
* void    populateHisto(double data, double timeFromTLE) - fill the histogram
* TCanvas getCanvas() - return the populated TCanvas
* 
*/
#include <physics/anticounter/AnticounterEvent.h>
#include <physics/trigger/TriggerEvent.h>
#include <mcmd/McmdEvent.h>
#include <mcmd/McmdRecord.h>
#include <EventHeader.h>
#include <PscuHeader.h>
#include <TTree.h>
#include "cTle.h"
#include "cEci.h"
#include "cOrbit.h"
#include "cJulian.h"
#include "TH2F.h"
#include "TFrame.h"
#include "TGraph.h"
#include "TCanvas.h"
#include "TASImage.h"
#include "TMarker.h"
#include <TDatime.h>

#include "TString.h"
#include "TObjString.h"
#include "TStyle.h"
#include "TPaletteAxis.h"
#include "TROOT.h"
#include <sys/stat.h>
#include <fstream>

#define TRUE  1
#define FALSE 0
/**
 * 
 * @param base 
 * @param outDirectory 
 * @param xslPath 
 */
using namespace std;

void InitStyle() {
  gROOT->SetStyle("Plain");

  TStyle *myStyle[2], *tempo;
  myStyle[0]=new TStyle("StyleWhite", "white");
  myStyle[1]=new TStyle("StyleBlack", "black");

  tempo=gStyle;
  Int_t linecol, bkgndcol, histcol;
 
  for(Int_t style=0; style<2; style++) {

    linecol=kWhite*style+kBlack*(1-style);
    bkgndcol=kBlack*style+kWhite*(1-style);
    histcol=kYellow*style+kBlack*(1-style); // was 95

    myStyle[style]->Copy(*tempo);

    myStyle[style]->SetCanvasBorderMode(0);
    myStyle[style]->SetCanvasBorderSize(1);
    myStyle[style]->SetFrameBorderSize(1);
    myStyle[style]->SetFrameBorderMode(0);
    myStyle[style]->SetPadBorderSize(1);
    myStyle[style]->SetStatBorderSize(1);
    myStyle[style]->SetTitleBorderSize(1);
    myStyle[style]->SetPadBorderMode(0);
    myStyle[style]->SetPalette(1,0);
    myStyle[style]->SetPaperSize(20,27);	
    myStyle[style]->SetFuncColor(kRed);
    myStyle[style]->SetFuncWidth(1);
    myStyle[style]->SetLineScalePS(1); 
    myStyle[style]->SetCanvasColor(bkgndcol);
    myStyle[style]->SetAxisColor(linecol,"XYZ");
    myStyle[style]->SetFrameFillColor(bkgndcol);
    myStyle[style]->SetFrameLineColor(linecol);
    myStyle[style]->SetLabelColor(linecol,"XYZ");
    myStyle[style]->SetPadColor(bkgndcol);
    myStyle[style]->SetStatColor(bkgndcol);
    myStyle[style]->SetStatTextColor(linecol);
    myStyle[style]->SetTitleColor(linecol,"XYZ");
    myStyle[style]->SetTitleFillColor(bkgndcol);
    myStyle[style]->SetTitleTextColor(linecol);
    myStyle[style]->SetLineColor(linecol);
    myStyle[style]->SetMarkerColor(histcol);
    myStyle[style]->SetTextColor(linecol);
    
    myStyle[style]->SetGridColor((style)?13:kBlack);
    myStyle[style]->SetHistFillStyle(1001*(1-style));
    myStyle[style]->SetHistLineColor(histcol);
    myStyle[style]->SetHistFillColor((style)?bkgndcol:kYellow);
  }

  myStyle[1]->cd();

  gROOT->ForceStyle();

}

void Rate(TString base, TString outDirectory = "", TString format = "png", TString mapFile = "", TString tleFile = "", int offDate = 20060614, int offTime = 210000){
	TTree                  *tr         = 0;
	pamela::McmdEvent      *mcmdev     = 0;
	pamela::McmdRecord     *mcmdrc     = 0;
	pamela::EventHeader    *eh         = 0;
  	pamela::PscuHeader     *ph	   = 0;
	TArrayC                *mcmddata;
	ULong64_t        	nevents    = 0;
    	double        		timesync   = 0;
  	stringstream 	oss;
    	double offsetTime = 0;
    	double absTime = 0;
    	UInt_t i = 0;
    	UInt_t j = 0;
    	struct stat buf;
    	
    	i = stat (mapFile.Data(), &buf );
	// If the file does not exists
	if (i != 0){
		printf("The %s file does not exists.", mapFile.Data());
		exit(0);
	}
   	
    	TString filename = ((TObjString*)base.Tokenize('/')->Last())->GetString();
  	filename = ((TObjString*)filename.Tokenize('.')->First())->GetString();

    	string str1 = "RESURS-DK 1";
   	string str2 = "1 29228U 06021A   06170.19643714  .00009962  00000-0  21000-3 0   196";
   	string str3 = "2 29228 069.9363 054.7893 0167576 127.4359 017.0674 15.31839265   604";
    	if (tleFile != ""){
		fstream fileTle(tleFile.Data(),ios::in);
		if (fileTle.is_open()) {
			getline (fileTle,str1);
			getline (fileTle,str2);
			getline (fileTle,str3);
		}
		fileTle.close();
    	}

   	cTle tle1(str1, str2, str3);
   	cOrbit       orbit(tle1);
   	cEci         eci;
   	cCoordGeo    coo;
   	TH2F *rate   	= new TH2F("rate", base, 360, -180, 180, 161, -80.5, 80.5);
	TFile *rootFile = new TFile(base);
	if (rootFile->IsZombie()) {
		printf("The %s file does not exist", base.Data());
		exit(0);
	}
	
	
	/* 
	 * process Mcmd
	 */
	long int recEntries;
	tr = (TTree*)rootFile->Get("Mcmd");
	tr->SetBranchAddress("Mcmd", &mcmdev);
	nevents = tr->GetEntries();
	
	bool timeFound = FALSE;
	while (i < nevents) {
		tr->GetEntry(i);
		recEntries = mcmdev->Records->GetEntries();
		while (j < recEntries){
			mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j);
			//mcmddata = mcmdrc->McmdData;
			//printf(" timesync TimeSync %i \n", (unsigned int)mcmddata->At(0));
			//It is a TimeSync?
			if ((mcmdrc != 0) && (mcmdrc->ID1 == 0xE0)){
				mcmddata = mcmdrc->McmdData;
				timesync = (((unsigned int)mcmddata->At(0)<<24)&0xFF000000) + (((unsigned int)mcmddata->At(1)<<16)&0x00FF0000) + (((unsigned int)mcmddata->At(2)<<8)&0x0000FF00) + (((unsigned int)mcmddata->At(3))&0x000000FF);
				timesync = timesync - (mcmdrc->MCMD_RECORD_OBT)*(1./1000.);
				timeFound = TRUE;
				//printf(" timesync TimeSync %i \n", timesync);
			}
			
			//It is an Inclination Mcmd?
			if ((mcmdrc != 0) && (mcmdrc->ID1 == 0xE2)){
				mcmddata = mcmdrc->McmdData;
				timesync = (((mcmddata->At(0) << 24) & 0xFF000000) + ((mcmddata->At(1) << 16) & 0x00FF0000) + ((mcmddata->At(2) << 8) & 0x0000FF00) + (mcmddata->At(3) & 0x000000FF))/128.0;
				timesync = timesync - (mcmdrc->MCMD_RECORD_OBT)*(1./1000.);
				timeFound = TRUE;
				//printf(" timesync Inclination %16.8f \n", timesync);
			}
			
			if (timeFound) break;
			j++;
		}
	if (timeFound) break;
	i++;
	}
	
	if (!timeFound) {
		printf("No timesync info have been found in the file %s", base.Data());
		exit(0);
	}
	
	//Get the Julian date of the TLE Epoch
	cJulian offTLE = cJulian(((int)tle1.getField(cTle::FLD_EPOCHYEAR) + 2000), tle1.getField(cTle::FLD_EPOCHDAY));
	
	//Get the Julian date of the Resours offset
	TDatime offRes = TDatime(offDate, offTime);
	cJulian offResours = cJulian(offRes.GetYear(), offRes.GetMonth(), offRes.GetDay(), offRes.GetHour(), offRes.GetMinute(), offRes.GetSecond());
	//Add to the Resours Offset the seconds differece beetwen the timesynch from MCMD and the relative OBT
	offResours.addSec(timesync);
	
	//Get the MINUTES past since the TLE Epoch
	offsetTime = (offResours.getDate() - offTLE.getDate()) * 24.0 * 60.0;
	tr = (TTree*)rootFile->Get("Physics");
	TBranch *headBr = tr->GetBranch("Header");
	tr->SetBranchAddress("Header", &eh);
	
	/********** Anticounter **************/
  	pamela::anticounter::AnticounterEvent *antiev   = 0;
	TH2F *antiRate40    = new TH2F("rate40", base, 360, -180, 180, 161, -80.5, 80.5);
	TH2F *antiRate30    = new TH2F("rate30", base, 360, -180, 180, 161, -80.5, 80.5);
	tr->SetBranchAddress("Anticounter", &antiev);
	Int_t oldAntiRate40 = 0;
	Int_t newAntiRate40 = 0;
	Int_t oldAntiRate30 = 0;
	Int_t newAntiRate30 = 0;
	Int_t rateAnti40 = 0;
	Int_t rateAnti30 = 0;
	/********** Anticounter **************/
	
	/********** Trigger **************/
	pamela::trigger::TriggerEvent *trigger   = 0;
	TH2F *trigAnd   = new TH2F("trigAnd", base, 360, -180, 180, 161, -80.5, 80.5); // (S11+S12)*(S21+S22)*(S31+S32)
	TH2F *trigS1    = new TH2F("trigS1", base, 360, -180, 180, 161, -80.5, 80.5); //(S11+S12)
	TH2F *trigS111A = new TH2F("trigS111A", base, 360, -180, 180, 161, -80.5, 80.5); //(S111A)
	tr->SetBranchAddress("Trigger", &trigger);
	/********** Trigger **************/
	
	nevents = tr->GetEntries();
	//Fill variables from root-ple
  	for (i = 0; i < nevents; i++){
  	//for (i = 0; i < 1000; i++){
    		tr->GetEntry(i);
    		ph = eh->GetPscuHeader();
    		absTime = offsetTime + (ph->GetOrbitalTime()*(1./60000.));
    		orbit.getPosition(absTime, &eci);
      		coo = eci.toGeo();
      		/********** Anticounter **************/
      		oldAntiRate40 = newAntiRate40;
  		oldAntiRate30 = newAntiRate30;
  		newAntiRate40 = antiev->counters[0][6];
  		newAntiRate30 = antiev->counters[0][10];
  		if (newAntiRate40 < oldAntiRate40){
  			newAntiRate40 += 0xFFFF;
  		}
  		if (newAntiRate30 < oldAntiRate30){
  			newAntiRate30 += 0xFFFF;
  		}
  		rateAnti40 = newAntiRate40 - oldAntiRate40;
  		rateAnti30 = newAntiRate30 - oldAntiRate30;
		/********** Anticounter **************/
		
      		if (coo.m_Lon > PI) {
      			rate->Fill(rad2deg(coo.m_Lon - 2*PI) , rad2deg(coo.m_Lat));
      			antiRate30->Fill(rad2deg(coo.m_Lon - 2*PI) , rad2deg(coo.m_Lat), rateAnti30);
      			antiRate40->Fill(rad2deg(coo.m_Lon - 2*PI) , rad2deg(coo.m_Lat), rateAnti40);
      			trigAnd->Fill(rad2deg(coo.m_Lon - 2*PI) , rad2deg(coo.m_Lat), (1/4.)*trigger->trigrate[1]);
      			trigS1->Fill(rad2deg(coo.m_Lon - 2*PI) , rad2deg(coo.m_Lat), 1.*trigger->pmtpl[0]);
      			trigS111A->Fill(rad2deg(coo.m_Lon - 2*PI) , rad2deg(coo.m_Lat), 1.*trigger->pmtcount1[0]);
      		} else {
      			rate->Fill(rad2deg(coo.m_Lon) , rad2deg(coo.m_Lat));
      			antiRate30->Fill(rad2deg(coo.m_Lon) , rad2deg(coo.m_Lat), rateAnti30);
      			antiRate40->Fill(rad2deg(coo.m_Lon) , rad2deg(coo.m_Lat), rateAnti40);
      			trigAnd->Fill(rad2deg(coo.m_Lon) , rad2deg(coo.m_Lat), (1/4.)*trigger->trigrate[1]);
      			trigS1->Fill(rad2deg(coo.m_Lon) , rad2deg(coo.m_Lat), 1.*trigger->pmtpl[0]);
      			trigS111A->Fill(rad2deg(coo.m_Lon) , rad2deg(coo.m_Lat), 1.*trigger->pmtcount1[0]);
      			//printf(" Time: %16.8f Lat: %16.8f  Long: %16.8f  Alt: %16.8f\n", absTime, rad2deg(coo.m_Lat), rad2deg(coo.m_Lon), coo.m_Alt);
      		}
    	}
	double posx=-1000,posy=-1000,oldposx=-1000,oldposy=-1000;

	TMarker *tma=NULL;
	TImage *tImage=TImage::Open(mapFile);
	int width=(int)(tImage->GetWidth()*0.80);
	int height=(int)(tImage->GetHeight()*0.80);
	InitStyle();
	TCanvas *c1 = new TCanvas("c1","rate/orbit",-width, height); // - : removes the menu bars
		
	TH1F *hframe=NULL;
	hframe=gPad->DrawFrame(-180,-90,180,90);
	
	oss.str("");
	oss << filename << " - Event Rate (Hz)";
	hframe->SetTitle(oss.str().c_str());
	hframe->SetXTitle("Longitude (deg)");
	hframe->SetYTitle("Latitude (deg)");
	
	/********** Anticounter **************/
	TCanvas *anti30 = new TCanvas("anti30","rate/orbit",-width, height); // - : removes the menu bars
	TH1F *hframe30=NULL;
	hframe30=gPad->DrawFrame(-180,-90,180,90);
	
	oss.str("");
	oss << filename << " - CAS3 rate/degree";
	hframe30->SetTitle(oss.str().c_str());
	hframe30->SetXTitle("Longitude (deg)");
	hframe30->SetYTitle("Latitude (deg)");
	
	TCanvas *anti40 = new TCanvas("anti40","rate/orbit",-width, height); // - : removes the menu bars
	TH1F *hframe40=NULL;
	hframe40=gPad->DrawFrame(-180,-90,180,90);
	
	oss.str("");
	oss << filename << " - CAS4 rate/degree";
	hframe40->SetTitle(oss.str().c_str());
	hframe40->SetXTitle("Longitude (deg)");
	hframe40->SetYTitle("Latitude (deg)");
	/********** Anticounter **************/
		
	/********** Trigger **************/
	TCanvas *trigAndC = new TCanvas("AND","rate/orbit",-width, height); // - : removes the menu bars
	TH1F *trigAndF=NULL;
	trigAndF=gPad->DrawFrame(-180,-90,180,90);
	
	oss.str("");
	oss << filename << " - (S11+S12)*(S21+S22)*(S31+S32) rate/degree";
	trigAndF->SetTitle(oss.str().c_str());
	trigAndF->SetXTitle("Longitude (deg)");
	trigAndF->SetYTitle("Latitude (deg)");
	
	TCanvas *trigS1C = new TCanvas("trigS1","rate/orbit",-width, height); // - : removes the menu bars
	TH1F *trigS1F=NULL;
	trigS1F=gPad->DrawFrame(-180,-90,180,90);
	
	oss.str("");
	oss << filename << " - (S11+S12) rate/degree";
	trigS1F->SetTitle(oss.str().c_str());
	trigS1F->SetXTitle("Longitude (deg)");
	trigS1F->SetYTitle("Latitude (deg)");
	
	TCanvas *trigS111AC = new TCanvas("trigS111A","rate/orbit",-width, height); // - : removes the menu bars
	TH1F *trigS111AF=NULL;
	trigS111AF=gPad->DrawFrame(-180,-90,180,90);
	
	oss.str("");
	oss << filename << " - S111A rate/degree";
	trigS111AF->SetTitle(oss.str().c_str());
	trigS111AF->SetXTitle("Longitude (deg)");
	trigS111AF->SetYTitle("Latitude (deg)");
	/********** Trigger **************/
		
	c1->cd();
	TPad *p2 = new TPad("p2", "p2", 0.10, 0.04, 0.983, 1);

	p2->cd();
	TPaletteAxis *tpa=NULL;
	TH2F *forpal=new TH2F("forpal","",2,0,2,2,0,2);
	forpal->SetAxisColor(kBlack); //Delete the stat box
	forpal->SetStats(0); //Delete the stat box
	forpal->SetMinimum(0.1);
	forpal->SetMaximum(rate->GetMaximum());
	p2->SetLogy();
	forpal->SetBinContent(5,1);    // just to initialize the histo
	forpal->SetContour(50);
	TPaletteAxis *tpp=(TPaletteAxis*)((forpal->GetListOfFunctions())->FindObject("palette"));
	tpa=new TPaletteAxis(184,-90,195,90,forpal);
	tpa->SetLabelColor(kWhite);
	forpal->Draw("colz");
	
	c1->cd();
	p2->DrawClone();
	
	/********** Anticounter **************/
	Double_t stepPP30   = (antiRate30->GetMaximum() / 50.0);
	forpal->SetMaximum(antiRate30->GetMaximum());
	anti30->cd();
	p2->DrawClone();
	
	Double_t stepPP40   = (antiRate40->GetMaximum() / 50.0);	
	forpal->SetMaximum(antiRate40->GetMaximum());
	anti40->cd();
	p2->DrawClone();
	/********** Anticounter **************/
	
	/********** Trigger **************/
	Double_t trigAndPP   = (trigAnd->GetMaximum() / 50.0);
	forpal->SetMaximum(trigAnd->GetMaximum());
	trigAndC->cd();
	p2->DrawClone();
	
	Double_t trigS1PP   = (trigS1->GetMaximum() / 50.0);
	forpal->SetMaximum(trigS1->GetMaximum());
	trigS1C->cd();
	p2->DrawClone();
	
	Double_t trigS111APP   = (trigS111A->GetMaximum() / 50.0);
	forpal->SetMaximum(trigS111A->GetMaximum());
	trigS111AC->cd();
	p2->DrawClone();
	/********** Trigger **************/

	c1->cd();
	TPad *p1 = new TPad("p1", "p1", 0.10,0.10,0.90,0.92);
	p1->Draw();
	
	p1->cd();
	tImage->Draw("X");
	
	/********** Anticounter **************/
	anti30->cd();
	p1->DrawClone();
	anti40->cd();
	p1->DrawClone();
	/********** Anticounter **************/
	
	/********** Trigger **************/
	trigAndC->cd();
	p1->DrawClone();
	trigS1C->cd();
	p1->DrawClone();
	trigS111AC->cd();
	p1->DrawClone();
	/********** Trigger **************/
	
	c1->cd();
	gPad->RedrawAxis();
	c1->Update();
	
	/********** Anticounter **************/
	anti30->cd();
	gPad->RedrawAxis();
	anti30->Update();
	anti40->cd();
	gPad->RedrawAxis();
	anti40->Update();
	/********** Anticounter **************/
	
	/********** Trigger **************/
	trigAndC->cd();
	gPad->RedrawAxis();
	trigAndC->Update();
	
	trigS1C->cd();
	gPad->RedrawAxis();
	trigS1C->Update();
	
	trigS111AC->cd();
	gPad->RedrawAxis();
	trigS111AC->Update();
	/********** Trigger **************/
	
  c1->cd();
  tma=new TMarker();
  tma->SetMarkerStyle(21);
  tma->SetMarkerSize(0.5);
  Double_t color = 0.0;  
  Double_t freq  = 0.0;
  Double_t stepPP = (rate->GetMaximum() / 50.0);
  //Double_t cutoffFreq = stepPP/1000.0;
  //Double_t alpha = log10(cutoffFreq/stepPP) * (-1.0); //Obviously is 3.0
  
  	/********** Anticounter **************/
  	Double_t color30 = 0.0;  
        Double_t freq30  = 0.0;
  	//Double_t cutoffFreq30 = stepPP30/1000.0;
  	//Double_t alpha30 = log10(cutoffFreq30/stepPP30) * (-1.0); //Obviously is 3.0
  	
  	Double_t color40 = 0.0;  
        Double_t freq40  = 0.0;
  	//Double_t cutoffFreq40 = stepPP40/1000.0;
  	//Double_t alpha40 = log10(cutoffFreq40/stepPP40) * (-1.0); //Obviously is 3.0
	/********** Anticounter **************/
  
    	/********** Trigger **************/
  	Double_t trigAndCol = 0.0;  
        Double_t trigAndFreq  = 0.0;
  	
  	Double_t trigS1Col = 0.0;  
        Double_t trigS1Freq  = 0.0;
        
        Double_t trigS111ACol = 0.0;  
        Double_t trigS111AFreq  = 0.0;
	/********** Trigger **************/
  
  for (Int_t kk = 0; kk < 360; kk++){
	for (Int_t jj = 0; jj < 161; jj++){
		freq = rate->GetBinContent(kk, jj);
		
		/********** Anticounter **************/
		freq30 = antiRate30->GetBinContent(kk, jj);
		freq40 = antiRate40->GetBinContent(kk, jj);
		/********** Anticounter **************/
		
		/********** Trigger **************/
		trigAndFreq = trigAnd->GetBinContent(kk, jj);
		trigS1Freq = trigS1->GetBinContent(kk, jj);
		trigS111AFreq = trigS111A->GetBinContent(kk, jj);
		/********** Trigger **************/
		
		//printf(" Freq:  %16.8f \n", freq);
		posx=kk - 180;
		posy= jj - 80.5;
		if (freq > 0) {
			c1->cd();
			// color: palette colors from 51 to 100 ie 50 levels
			//color = ((log10(freq/stepPP))/alpha)*49.0 + 100.0; // step defined by palette
			color = 50.0 + (freq / stepPP); // step defined by palette
			//printf(" Color: %16.8f \n", color);
			//if (freq < stepPP) color = 51;
			//if (color < -100.0) color = 100.0; // just in case if max rate is not max...
			tma->SetMarkerColor((int)color);
			tma->DrawMarker(posx,posy);
		}
		
		/********** Anticounter **************/
		if (freq30 > 0) {
			anti30->cd();
			color30 = 50.0 + (freq30 / stepPP30); // step defined by palette
			//printf(" Color: %16.8f \n", color30);
			//color30 = ((log10(freq30/stepPP30))/alpha30)*49.0 + 100.0; // step defined by palette
			//printf(" Color: %16.8f Step: %16.8f Freq:  %16.8f \n", color, stepPP, freq);
			//if (freq30 < cutoffFreq30) color30 = 51;
			//if (color30 > 100.0) color30 = 100.0; // just in case if max rate is not max...
			tma->SetMarkerColor((int)color30);
			tma->DrawMarker(posx,posy);
		}
		
		if (freq40 > 0) {
			anti40->cd();
			color40 = 50.0 + (freq40 / stepPP40); // step defined by palette
			//color40 = ((log10(freq40/stepPP40))/alpha40)*49.0 + 100.0; // step defined by palette
			//printf(" Color: %16.8f Step: %16.8f Freq:  %16.8f \n", color, stepPP, freq);
			//if (freq40 < cutoffFreq40) color40 = 51;
			//if (color40 > 100.0) color40 = 100.0; // just in case if max rate is not max...
			tma->SetMarkerColor((int)color40);
			tma->DrawMarker(posx,posy);
		}
		/********** Anticounter **************/
		
		/********** Trigger **************/
		if (trigAndFreq > 0) {
			trigAndC->cd();
			trigAndCol = 50.0 + (trigAndFreq / trigAndPP); // step defined by palette
			tma->SetMarkerColor((int)trigAndCol);
			tma->DrawMarker(posx,posy);
		}
		
		if (trigS1Freq > 0) {
			trigS1C->cd();
			trigS1Col = 50.0 + (trigS1Freq / trigS1PP); // step defined by palette
			tma->SetMarkerColor((int)trigS1Col);
			tma->DrawMarker(posx,posy);
		}
		
		if (trigS111AFreq > 0) {
			trigS111AC->cd();
			trigS111ACol = 50.0 + (trigS111AFreq / trigS111APP); // step defined by palette
			tma->SetMarkerColor((int)trigS111ACol);
			tma->DrawMarker(posx,posy);
		}
		/********** Anticounter **************/
	}
 }

  	oss.str("");
  	if (outDirectory == "") {
  		oss << filename.Data() << "_OrbitRate." << format.Data();
  	} else {
  		oss << outDirectory.Data() << filename.Data() << "_OrbitRate." << format.Data();
  	}
  	c1->SaveAs(oss.str().c_str());
  	
  	oss.str("");
  	if (outDirectory == "") {
  		oss << filename.Data() << "_CAS3." << format.Data();
  	} else {
  		oss << outDirectory.Data() << filename.Data() << "_CAS3." << format.Data();
  	}
  	anti30->SaveAs(oss.str().c_str());
  	
  	oss.str("");
  	if (outDirectory == "") {
  		oss << filename.Data() << "_CAS4." << format.Data();
  	} else {
  		oss << outDirectory.Data() << filename.Data() << "_CAS4." << format.Data();
  	}
  	anti40->SaveAs(oss.str().c_str());
  	
	oss.str("");
  	if (outDirectory == "") {
  		oss << filename.Data() << "_TrigAND." << format.Data();
  	} else {
  		oss << outDirectory.Data() << filename.Data() << "_TrigAND." << format.Data();
  	}
  	trigAndC->SaveAs(oss.str().c_str());
	
	oss.str("");
  	if (outDirectory == "") {
  		oss << filename.Data() << "_TrigS1." << format.Data();
  	} else {
  		oss << outDirectory.Data() << filename.Data() << "_TrigS1." << format.Data();
  	}
  	trigS1C->SaveAs(oss.str().c_str());
  		
	oss.str("");
  	if (outDirectory == "") {
  		oss << filename.Data() << "_trigS111A." << format.Data();
  	} else {
  		oss << outDirectory.Data() << filename.Data() << "_trigS111A." << format.Data();
  	}
  	trigS111AC->SaveAs(oss.str().c_str());

        rootFile->Close();
}




int main(int argc, char* argv[]){
    TString outDir  = "./";
    TString mapFile = "";
    TString tleFile = "";
    TString format  = "png";
    int offDate = 20060614;
    int offTime = 210000;
    
 if (argc < 2){
    printf("You have to insert at least the file to analyze and the mapFile \n");
    printf("Try '--help' for more information. \n");
    exit(1);
  }  

  if (!strcmp(argv[1], "--help")){
        printf( "Usage: OrbitRate FILE -map mapFile [OPTION] \n");
        printf( "mapFile have to be a mercator map image [gif|jpg|png] \n");
        printf( "\t --help                 Print this help and exit \n");
        printf( "\t -tleFile[path]         Path where to find the tle infos [default dummyOrbit] \n");
        printf( "\t\tThe tle file have to satisfy a 3-line structure like (this is the included dummyOrbit)\n ");
        printf( "\t\t\tGP4 Test\n");
   	printf( "\t\t\t1 25544U 98067A   06117.32388940  .00009459  00000-0  64427-4 0  8131\n");
   	printf( "\t\t\t2 25544  51.6388  89.2928 0009043 155.3293 354.6512 15.75673697425143\n");
        printf( "\t -outDir[path]          Path where to put the output [default ~/tmp] \n");
        printf( "\t -format[jpg|gif|ps]    Format for output files [default 'png'] \n");
        printf( "\t -offDate               Date of resetting of the Resource counter [format YYMMDD default 20060614] \n");
        printf( "\t -offTime               Time of resetting of the Resource counter [format HHMMSS default 210000] \n");
        exit(1);
  }

  for (int i = 2; i < argc; i++){
    if (!strcmp(argv[i], "-outDir")){
        if (++i >= argc){
            printf( "-outDir needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } else {
            outDir = argv[i];
            continue;
        }
    }

   if (!strcmp(argv[i], "-tle")){
        if (++i >= argc){
            printf( "-tle needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } else {
            tleFile = argv[i];
            continue;
        }
    }

    if (!strcmp(argv[i], "-offTime")){
      if (++i >= argc){
	printf( "-offTime needs arguments. \n");
	printf( "Try '--help' for more information. \n");
	exit(1);
      } 
      else{
	offTime = atol(argv[i]);
	continue;
      }
    }

    if (!strcmp(argv[i], "-offDate")){
      if (++i >= argc){
	printf( "-offDate needs arguments. \n");
	printf( "Try '--help' for more information. \n");
	exit(1);
      } 
      else{
	offDate = atol(argv[i]);
	continue;
      }
    }

    if (!strcmp(argv[i], "-map")){
        if (++i >= argc){
            printf( "-map needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } else {
            mapFile = argv[i];
            continue;
        }
    }

    if (!strcmp(argv[i], "-format")) {
    	if (++i >= argc){
            printf( "-format needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } else {
        	format = argv[i];
        	continue;
        }
    }
}
if (mapFile != ""){
	Rate(argv[1], outDir, format, mapFile, tleFile, offDate, offTime);
} else {
	printf("You have to insert at least the file to analyze and the mapFile \n");
	printf("Try '--help' for more information. \n");
    }
}



   
