/*
Copyright (c) 2000                      RIPE NCC


All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of the author not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

/*
-------------------------------------------------------------------------------
Module Header
Filename          : TTMHistograms.C
Author            : Rene Wilhelm
Date              : 13-OCT-2000
Description       : Implementation of TTM TTMHistograms class
Language Version  : C++
OSs Tested        : Solaris 2.6
External Programs : ps2gif (which in turn needs ghostscript and imaging tools)
$Id: TTMHistograms.C,v 1.5 2003/06/02 10:42:18 ruben Exp $
-------------------------------------------------------------------------------
*/

#define PATH "/ncc/ttpro/data/root"   // path to TTM ROOT data storage
#define TYPE 'H'		      // hierarchical (year/month/day) storage

#include <stdlib.h>
#include <time.h>
#include <iostream.h>
#include <TCanvas.h>
#include <TLine.h>
#include <TPaveLabel.h>
#include <TPostScript.h>
#include <TText.h>
#include "Delay.h"
#include "TTMHistograms.h"
#include "utils.h"

static char const rcsid[] = "$Id: TTMHistograms.C,v 1.5 2003/06/02 10:42:18 ruben Exp $";
static char const *rcsid_p = rcsid;   // Prevent g++ from optimizing out rcsid


/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : Initialize TTMHistogram parameters
Input		  : src    - pointer to source TestBox object
		    tgtnum - number of the target in src TB's target list
		    opt	   - program options (TTMOptions object)
Language Version  : C++
OSs Tested        : Linux
-------------------------------------------------------------------------------
*/

void TTMHistograms::SetConfig(TestBox *src, int tgtnum, TTMOptions* opt) {

	DeleteHistos();		// make sure we have a clean start

	source = src;
	targetNum  = tgtnum;

	verbose    = opt->Verbose();
	ipVersion  = opt->IPversion();

	endtime    = opt->EndTime();
        mindelay   = opt->MinDelay();
        maxdelay   = opt->MaxDelay();
        logscale   = opt->Logscale();
        allpackets = opt->AllPackets();
	outputDir  = opt->OutputPath();

	plotFormat = opt->PlotFormat();

	starttime  = endtime - opt->TimePeriod();

	tm *timestruct = gmtime(&endtime);
	strftime(cendtime1, 20, "%Y-%m-%d %H:%M", timestruct);
	strftime(cendtime2, 8, "%b %d", timestruct);

	timestruct = gmtime(&starttime);
	strftime(cstarttime1, 20, "%Y-%m-%d %H:%M", timestruct);
	strftime(cstarttime2, 8, "%b %d", timestruct);

	CreateHistos();  
}


/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : Add new datapoint to Histograms
Input		  : pointer to Delay object with result from TTM measurement
Side Effects	  : various ROOT histograms updated
Language Version  : C++
OSs Tested        : Linux
-------------------------------------------------------------------------------
*/

void TTMHistograms::Fill (Delay* packet) {

	// process one delay measurement: fill histograms and percentiles
	// calling program already selected right TTMHistogram object
	
	int nhops, routeid;
	
	
	Double_t packettime = packet->GetPacketTime(starttime);
	if ((packettime < starttime) || (packettime > endtime)) {
		// outside selected time interval, silently skip
		return;
	}

	// transform UNIX timestamp into ROOT timestamp
	// (i.e. seconds since 1/1/1995 instead of seconds since 1/1/1970)

	packettime -= ROOT_TIMEZERO;

	// Fill histograms

	PacketsSent->Fill(packettime);

	// number of hops
	if ((routeid=packet->GetRouteId()) > 0) {
 		nhops=packet->GetNhops();
		RoutesNHops->Fill(packettime, (Float_t) 10.0 * nhops);
		RoutesInfo->Update(routeid, nhops) ;
	}


	PacketStatus status = packet->Status();
	
	if (status == ClockValid) {
		Float_t packetdelay = packet->GetPacketDelay();
		Delay2D->Fill(packettime, packetdelay);
		Delay1D->Fill(packetdelay);
		ClocksOK->Fill(packettime);

		// in future perhaps: Add(value, interval);
		// where  interval=(packettime mod delta)

		DelayPercentile->Add(packetdelay);

	}
	else if (status == PacketLost) {
		PacketsLost->Fill(packettime);
	}
	else {
		if (allpackets) {
			Float_t packetdelay = packet->GetPacketDelay();
			Delay2D->Fill(packettime, packetdelay);
			Delay1D->Fill(packetdelay);
		}

		if (status == ClockSrcValid) {
			// source ok, target wrong
			BadTargetClock->Fill(packettime);
		}
		else if (status == ClockTrgValid) {
			// target ok, source wrong
			BadSourceClock->Fill(packettime);
		}
		else if (status == ClockInvalid) {
			// both clocks wrong
			BadClocks->Fill(packettime);
		}
		else {
			cerr << "ERROR: unknown packet status " << status
			     << "Source Id "  << packet->GetSourceId()
			     << " Target Id " << packet->GetTargetId() << endl;
		}
	}

}

/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : 
Input		  :
-------------------------------------------------------------------------------
*/

void TTMHistograms::Plot() {

	// plot the (filled) histograms 
	// files are named <outputDir>/tt<src>tt<dst>.<type>
	// <src> = source id, <dst> = target_id, 
	// <type> = ps, eps, gif

	int ntargets;

	char *sourcename = source->GetShortName();
	TestBox **target = source->GetTargets(ntargets);
	char *targetname = target[targetNum]->GetShortName();

	// filename =  <outputDir>/<sourcename>.<targetname>.<extension>
	// possibly preceded by "IPv6."  

	int pathnamelength = strlen(outputDir) + strlen(sourcename)
				+ strlen(targetname) + 16 ;

	char *pathname = new char[pathnamelength];
	char *buffer   = new char[pathnamelength+strlen(PS2GIF)+1]; 

	TPostScript *psout;

	
	gStyle->SetLineScalePS(0.2); // force thin lines in PS output
	gStyle->SetOptStat(0);       // turn off statistics box


	
	TCanvas *canvas = new TCanvas("canvas", "Plots", 0, 0, 1270, 990);


	strcpy(buffer, outputDir);

	if (ipVersion == 6) {
		strcat(buffer, "/IPv6.");
	}
	else {
		strcat(buffer, "/");
	}

	if (plotFormat == eps) {
		sprintf(pathname, "%s%s.%s.eps", buffer, sourcename, targetname);

		// open eps file - type 113 in ROOT
		psout = new TPostScript(pathname, 113);
	}
	else {
		sprintf(pathname, "%s%s.%s.ps", buffer, sourcename, targetname);
		// open ps file  - type 112 = landscape
		psout = new TPostScript(pathname, 112);
		psout->Range(25.5, 18.8);   // centre on A4 size paper
	}
	PlotHistos(sourcename, targetname);

  	// now update canvas (needed to write to PS file?)
  	canvas->Update();

	psout->Close();
	delete psout;
	delete canvas;

	if (plotFormat == gif) {
		// now convert them to gif; create ps2gif command line which
		// specificies all .ps files that need converting.
		//
		// BoundingBox parameters are taken from a manual run of the
		// bbfig tool; will be fine as long as ROOT PostScript prolog
		// does not change. 
		//
		// rotate to get proper orientation
		// scale up a bit to make text more legible
		//

		sprintf(buffer, "%s %s", PS2GIF, pathname);

		if (verbose) {
			cerr << "executing " << buffer << endl;
		}

		if (system(buffer) != 0) {
			cerr << "ERROR converting to gif: " << pathname << endl;
		}
		else {
			// conversion OK -> cleanup ps (they can be real large)
			sprintf(buffer, "%s %s", "/bin/rm ", pathname);
			if (verbose) {
				cerr << "executing " << buffer << endl;
			}

			if (system(buffer) != 0) {
				cerr << "ERROR removing ps file? " <<
				pathname <<endl;
			}
		}
	}
	else if (plotFormat == pdf) {
		// now convert them to pdf; create ROOTps2pdf command line which
	 	// specificies all .ps files that need converting.
	 	//
	 	// BoundingBox parameters are taken from a manual run of the
	 	// bbfig tool; will be fine as long as ROOT PostScript prolog
	 	// does not change. 
	 	//
	 	// rotate to get proper orientation
		// scale up a bit to make text more legible
		//
 
		sprintf(buffer, "%s %s", PS2PDF, pathname);
 
		if (verbose) {
			cerr << "executing " << buffer << endl;
		}
 
		if (system(buffer) != 0) {
			cerr << "ERROR converting to pdf: " << pathname << endl;
		}
		else {
			// conversion OK -> cleanup ps (they can be real large)
			sprintf(buffer, "%s %s", "/bin/rm ", pathname);
			if (verbose) {
				cerr << "executing " << buffer << endl;
			}
 
			if (system(buffer) != 0) {
				cerr << "ERROR removing ps file? " <<
				pathname <<endl;
			}
		}
	}


	// delete dynamically allocated objects (avoid memory leaks)

	delete[] pathname;
	delete[] buffer;
}


/*
-------------------------------------------------------------------------------
Subroutine Header
Purpose           :   Plot the Histograms
Input parameters  :   sourcename - char* for source box
                      targetname - char* for target box
-------------------------------------------------------------------------------
*/

		
void TTMHistograms::PlotHistos(char* sourcename, char* targetname) {
	
	char buf[175];
	Int_t bin;

	// create pads
	TPad *pad1 = new TPad("pad1", "This is pad 1",0.01,0.49,0.43,0.95);
	TPad *pad2 = new TPad("pad2", "This is pad 2",0.44,0.49,0.86,0.95);
	TPad *pad3 = new TPad("pad3", "This is pad 3",0.01,0.02,0.43,0.48);
	TPad *pad4 = new TPad("pad4", "This is pad 4",0.44,0.02,0.86,0.48);
	TPad *pad5 = new TPad("pad5", "This is pad 5",0.87,0.02,0.99,0.95);

	// force them to be visible on the canvas
	pad1->Draw();
	pad2->Draw();
	pad3->Draw();
	pad4->Draw();
	pad5->Draw();

	// Top Centre Label
	sprintf(buf, "               Delays from %s to %s.  Start: %s  End: %s UTC",
		sourcename, targetname, cstarttime1, cendtime1);
	TPaveLabel *pl = new TPaveLabel(0.274,0.956,0.748,0.998,buf,"br");
	pl->SetTextSize(0.45);
	pl->Draw();

	sprintf(buf, "IPv%d", ipVersion);
//
//	Only label as IPv4 if box is v6 enabled; requires more info  
//	from TestBoxConfig --> future extension
//
//	TPaveLabel *ip = new TPaveLabel(0.01,0.956,0.1,0.998,buf,"br");
	if (ipVersion == 6) {
		TPaveLabel *ip = new TPaveLabel(0.01,0.956,0.1,0.998,buf,"br");
		ip->SetTextColor(9);
		ip->SetTextSize(0.8);
		ip->Draw();
	}

//	else if (ipVersion == 4) {
//	          ip->SetTextColor(8);
//	}
//	ip->SetTextSize(0.8);
//	ip->Draw();
	
	// Top left
	pad1->cd();
	pad1->SetGridx();
	pad1->SetGridy();
	if (logscale) {
		pad1->SetLogy();
	}
	RoutesNHops->Draw();
	Delay2D->Draw("SAME");
	
	// Top Right
	pad2->cd();
	pad2->SetGridx();
	pad2->SetGridy();
	if (logscale) {
		pad2->SetLogx();
	}
	Delay1D->Draw();
	
	// Bottom Left
	pad3->cd();
	pad3->SetGridx();
	pad3->SetGridy();

	// capture satistics *before* adding up Histograms!
	int validpackets = (int) ClocksOK->GetEntries();
	int sourceok = (int) BadTargetClock->GetEntries();
	int targetok = (int) BadSourceClock->GetEntries();
	int badclocks = (int) BadClocks->GetEntries();
	int lostpackets = (int) PacketsLost->GetEntries();

	// add histograms to create stacked plots (1 bin = multiple data items)

	BadSourceClock->Add(BadSourceClock, ClocksOK, 1, 1);
	BadTargetClock->Add(BadTargetClock, BadSourceClock, 1, 1);
	BadClocks->Add(BadClocks, BadTargetClock, 1, 1);


	// PacketsSent histo is the background, everything not obscured 
	// by valid/invalid clock histograms indicates packet loss.

	PacketsSent->Draw();
	BadClocks->Draw("SAME");
	BadTargetClock->Draw("SAME");
	BadSourceClock->Draw("SAME");
	ClocksOK->Draw("SAME");

	// Bottom Right
	pad4->cd();
	pad4->SetGridx();
	pad4->SetGridy();

	Arrived->Reset();
	Arrived->Add(PacketsSent, PacketsLost, 1, -1);
	Arrived->Divide(Arrived, PacketsSent, 1, 1);
	Arrived->Draw();

	// Statistics
	pad5->cd();

	// 

	// percentiles for packet loss (using fraction arrived per bin)
	LossPercentile->Reset();
	for(bin=1; bin<=binsX; bin++) {
		LossPercentile->Add(float(1-Arrived->GetBinContent(bin)));
	}

	// write output with TLatex-class in new root-version  
	strcpy(buf, "STATISTICS:");
	Float_t x = 0.5;       // Starting point
	Float_t y = 0.95;
	Int_t align = 22;      // horizontally and vertically centered
	Font_t font = 20;     // Times-Roman-bold-r
	write_stats(pad5, buf, x, y, align, font);

	y -=0.03;
//	write_stats(pad5, "Histogram", x, y, align, font);
//	y -=0.02;
	write_stats(pad5, "Delay @& Hops:", x, y, align, font);

	font = 10;	// Times-Romand-medium-i
	y -=0.025;
	sprintf(buf,     "Entries: %g", Delay1D->GetEntries());
	write_stats(pad5, buf, x, y, align, font);
	y -=0.02;
	sprintf(buf,     "Overflow: %g", Delay1D->GetBinContent(binsY+1) );
	write_stats(pad5, buf, x, y, align, font);
	y -=0.02;
	sprintf(buf,     "Underflow: %g", Delay1D->GetBinContent(0) );
	write_stats(pad5, buf, x, y, align, font);

	align = 32;
	Float_t x1 = 0.52;
	Float_t x2 = 0.95;

	y -=0.025;
	write_stats(pad5, "2.5 Perc:", x1, y, align, font);
	sprintf(buf,     "%8.1fms", DelayPercentile->GetLevel(2.5));
	write_stats(pad5, buf, x2, y, align, font);

	y -=0.02;
	write_stats(pad5, "Median:", x1, y, align, font);
	sprintf(buf,     "%8.1fms", DelayPercentile->GetLevel(50.0));
	write_stats(pad5, buf, x2, y, align, font);

	y -=0.02;
	write_stats(pad5, "97.5 Perc:", x1, y, align, font);
	sprintf(buf,     "%8.1fms", DelayPercentile->GetLevel(97.5));
	write_stats(pad5, buf, x2, y, align, font);

	y -=0.02;
	write_stats(pad5,"Mean:", x1, y, align, font);
	sprintf(buf,     "%8.1fms", Delay1D->GetMean());
	write_stats(pad5, buf, x2, y, align, font);
	y -=0.02;
	write_stats(pad5,"RMS:", x1, y, align, font);
	sprintf(buf,     "%8.1fms", Delay1D->GetRMS());
	write_stats(pad5, buf, x2, y, align, font);

	align=22;
	y -=0.025;
	sprintf(buf,     "Min. hops: %d", RoutesInfo->GetMinHops());
	write_stats(pad5, buf, x, y, align, font);
	y -=0.02;
	sprintf(buf,     "Max. hops: %d", RoutesInfo->GetMaxHops());
	write_stats(pad5, buf, x, y, align, font);
	
	y -=0.03;
	TLine line1(0.0,0.0,0.0,0.0);
	line1.SetLineWidth(2);
	line1.SetLineColor(4);
	line1.DrawLine(0.05, y, 0.95, y); 

	y -=0.04;
	font = 20;     // Times-Roman-bold-r
	write_stats(pad5, "Packets sent/valid:", x, y, align, font);
	y -=0.025;
	
	font = 10;	// Times-Romand-medium-i
	int totalsent = (int) PacketsSent->GetEntries();
	sprintf( buf,     "Total: %i", totalsent);
	write_stats(pad5, buf, x, y, align, font);
	y -=0.02;

	float percent =  validpackets * 100.0 / totalsent;
	sprintf( buf,     "Valid: %i = %.3g %%", validpackets, percent);
	write_stats(pad5, buf, x, y, align, font);

	y -=0.02;
	percent = targetok * 100.0 / totalsent;
	sprintf( buf,     "Send bad: %i = %.2g %%", targetok, percent);
	write_stats(pad5, buf, x, y, align, font);

	y -=0.02;
	percent = sourceok * 100.0 / totalsent;
	sprintf( buf,     "Recv bad: %i = %.2g %%", sourceok, percent);
	write_stats(pad5, buf, x, y, align, font);

	y -=0.02;
	percent = badclocks * 100.0 / totalsent;
	sprintf( buf,     "2 Clocks bad: %i = %.2g %%", badclocks, percent);
	write_stats(pad5, buf, x, y, align, font);

	y -=0.02;
	percent = lostpackets * 100.0 / totalsent;
	sprintf( buf,     "Lost: %i = %.2g %%", lostpackets, percent);
	write_stats(pad5, buf, x, y, align, font);
	
	y -=0.03;
	line1.SetLineColor(2);
	line1.DrawLine(0.05, y, 0.95, y);  
	y -=0.04;
	
	font = 20;     // Times-Roman-bold-r
	write_stats(pad5,"Packets lost:", x, y, align, font);

	font = 10;	// Times-Romand-medium-i
	align = 32;	// right justified
	x1 += 0.03;
	x2 -= 0.03;

	y -=0.025;
	write_stats(pad5, "2.5 Perc:", x1, y, align, font);
	sprintf(buf,     "%5.1f%%", 100 * LossPercentile->GetLevel(2.5));
	write_stats(pad5, buf, x2, y, align, font);
	y -=0.02;
	write_stats(pad5, "Median:", x1, y, align, font);
	sprintf(buf,     "%5.1f%%", 100 * LossPercentile->GetLevel(50.0));
	write_stats(pad5, buf, x2, y, align, font);
	y -=0.02;
	write_stats(pad5, "97.5 Perc:", x1, y, align, font);
  	sprintf(buf,     "%5.1f%%", 100 * LossPercentile->GetLevel(97.5));
	write_stats(pad5, buf, x2, y, align, font);

	
	// estimate of sending process uptime
	int count = 0;

	for (bin = 1; bin <= binsX; bin++) {
		if (PacketsSent->GetBinContent(bin) > 0) {
			count++;
		}
	}
	float uptime = count*100/(float)binsX;

	y -=0.025;
	align = 22;	// centered
	sprintf(buf,     "Uptime: %.3g %%", uptime);
	write_stats(pad5, buf, x, y, align, font);
	
	y -=0.03;
	line1.SetLineColor(3);
	line1.DrawLine(0.05, y, 0.95, y); 
	
	y -=0.04;
	font = 20;     // Times-Roman-bold-r
	write_stats(pad5, "Over-all statistic:", x, y, align, font);

	font = 10;	// Times-Romand-medium-i
	y -=0.01;  
//	y -=0.02;  
//	write_stats(pad5, "Number of measurements", x, y, align, font);
//	y -=0.02;
//	sprintf( buf,     "in period: %i", nMeasurements);
//	write_stats(pad5, buf, x, y, align, font);

	y -=0.02;
	Float_t days = ((endtime-starttime)/86400);
	if (days > 1) {
		sprintf( buf,     "Time period: %.2g days", days);
	}
	else {
		sprintf( buf,     "Time period: %.2g day",  days);
	}
	write_stats(pad5, buf, x, y, align, font);
	y -=0.035;
	write_stats(pad5, "Number of routing", x, y, align, font);
	y -=0.02;
	sprintf( buf,     "vectors: %i", RoutesInfo->GetEntries());
	write_stats(pad5, buf, x, y, align, font);
	y -=0.02;
	sprintf( buf,     "flaps: %i", RoutesInfo->GetNumFlaps());
	write_stats(pad5, buf, x, y, align, font);
	y -=0.035;
	sprintf( buf,     "Number of bins: %d", binsX );
	write_stats(pad5, buf, x, y, align, font);
	y -=0.02;
	sprintf( buf,     "Minutes/bin: %.3g", ((endtime-starttime)/binsX/60.0));
	write_stats(pad5, buf, x, y, align, font);
  
  
  }
  
  
/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : 
Input		  :
-------------------------------------------------------------------------------
*/

void TTMHistograms::CreateHistos() {
	char	buf[100];     // small buffer for character strings
        char    xtitle[100];  // buffer for x-axis title
	char    *timeformat;  // indicates how time on axis is formatted

	
	binsY = 250; 

	// Some initialisation based on time period

	int ndiv = 0;
	int ndays = (endtime - starttime) / 3600 / 24;
	if (ndays>3)  {
		timeformat = "%b %d";      // <month> <day> 
		strcpy(xtitle, "Time [month day]");
		if (ndays>7) {
			ndiv = -506;	  // 6 major divisions
		}
	}
	else {
		timeformat = "%H:%M";	 //  <hour>:<minute>
		sprintf(xtitle, "      %s%26cTime [hour:minute]%26c%s", cstarttime2,
			' ', ' ', cendtime2);
	}

	// transform UNIX timestamps into ROOT timestamps
	// (seconds since 1/1/1995 instead of seconds since 1/1/1970)

	time_t endtime_root = endtime - ROOT_TIMEZERO;
	time_t starttime_root = starttime - ROOT_TIMEZERO;


	RoutesInfo      = new RoutingInfo;
	DelayPercentile = new Percentiles;


	sprintf(buf, "Delay2D[%d]", targetNum);
	Delay2D = new TH2F(buf, "delay vs time", binsX*2, starttime_root, 			endtime_root, binsY*2, mindelay, maxdelay);

	// Histogram of delay values
	// Note the size binsY is also used in Plot() method!
	sprintf(buf, "Delay1D[%d]", targetNum);
	Delay1D = new TH1F(buf, "PacketDelay", binsY, mindelay, maxdelay);

	sprintf(buf, "PacketsSent[%d]", targetNum);
 	PacketsSent = new TH1F(buf, "Packets sent/valid", binsX, 
		starttime_root, endtime_root);

	sprintf(buf, "ClocksOK[%d]", targetNum);
 	ClocksOK = new TH1F(buf, "Clocks OK", binsX,
		starttime_root, endtime_root);

	sprintf(buf, "BadSourceClock[%d]", targetNum);
	BadSourceClock = new TH1F(buf, "Bad Source Clock", binsX,
		starttime_root, endtime_root);

	sprintf(buf, "BadTargetClock[%d]", targetNum);
	BadTargetClock = new TH1F(buf, "Bad Target Clock", binsX,
		starttime_root, endtime_root);

	sprintf(buf, "BadClocks[%d]", targetNum);
	BadClocks = new TH1F(buf, "Bad Clocks", binsX,
		starttime_root, endtime_root);

	// hops
	sprintf(buf, "RoutesNHops[%d]", targetNum);
  	RoutesNHops = new TH2F(buf, "PacketDelay, Number of hops*10",
			binsX*2, starttime_root, endtime_root,
			binsY*2, mindelay, maxdelay);

	// lost
	sprintf(buf, "PacketsLost[%d]", targetNum);
  	PacketsLost = new TH1F(buf, "Packets arrived/lost", binsX,
			starttime_root, endtime_root);   


	// Now Set various histograms attributes (persistent over reset)

	Delay1D->SetFillColor(5); // yellow
	Delay1D->SetXTitle("Delay [msec]");
	Delay1D->SetYTitle("# packets [Entries/bin]");

	// Force division of "delay" scale in 1D and 2D histograms
	// ROOT 3.0 default behaviour is not good

	Delay1D->SetNdivisions(-505, "x");
	RoutesNHops->SetNdivisions(-505, "y");

	RoutesNHops->SetMarkerSize(2);
	RoutesNHops->SetMarkerColor(2);
	RoutesNHops->SetXTitle(xtitle);
	RoutesNHops->SetYTitle("Delay [msec]");
	if (ndiv != 0) {
			RoutesNHops->SetNdivisions(ndiv,"x"); 
	}
	RoutesNHops->GetXaxis()->SetTimeDisplay(1);
	RoutesNHops->GetXaxis()->SetTimeFormat(timeformat);

	PacketsSent->SetFillColor(7); // cyan
	PacketsSent->SetLineColor(1); // black
	PacketsSent->SetXTitle(xtitle);
	PacketsSent->SetYTitle("# packets [Entries/bin]");
	if (ndiv != 0) {
			PacketsSent->SetNdivisions(ndiv,"x"); 
	}
	PacketsSent->GetXaxis()->SetTimeDisplay(1);
	PacketsSent->GetXaxis()->SetTimeFormat(timeformat);

	BadClocks->SetFillColor(2); // red
	BadClocks->SetLineColor(1); // black

	BadTargetClock->SetFillColor(5); // yellow
	BadTargetClock->SetLineColor(1); // black

	BadSourceClock->SetFillColor(6);  // magenta
	BadSourceClock->SetLineColor(1);  // black

	ClocksOK->SetFillColor(3); // green
	ClocksOK->SetLineColor(1); // black


	// finally one auxilary histogram
	sprintf(buf, "Arrived[%d]", targetNum);
	Arrived = new TH1F(buf, "Packets arrived/lost", binsX,
			starttime_root, endtime_root);   

	Arrived->SetXTitle(xtitle);
	Arrived->SetYTitle("fraction arrived");
	Arrived->SetFillColor(3);      // green
	if (ndiv != 0) {
		Arrived->SetNdivisions(ndiv,"x"); 
	}
	Arrived->GetXaxis()->SetTimeDisplay(1);
	Arrived->GetXaxis()->SetTimeFormat(timeformat);
}

/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : 
Input		  :
-------------------------------------------------------------------------------
*/

void TTMHistograms::ClearHistos () {
	// Reset all histograms and percentiles

	Delay2D->Reset();
	Delay1D->Reset();
	PacketsSent->Reset();
	ClocksOK->Reset();
	BadSourceClock->Reset();
	BadTargetClock->Reset();
	BadClocks->Reset();
	RoutesNHops->Reset();
	PacketsLost->Reset();

	RoutesInfo->Reset();
	DelayPercentile->Reset();	
}

/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : 
Input		  :
-------------------------------------------------------------------------------
*/

void TTMHistograms::DeleteHistos () {
	// delete allocated histograms, reset pointers to NULL, scalars to 0

	if (source != NULL) {
		// if source==NULL, no histograms exist
		delete Delay2D;
		delete Delay1D;
		delete PacketsSent;
		delete ClocksOK;
		delete BadSourceClock;
		delete BadTargetClock;
		delete BadClocks;
		delete RoutesNHops;
		delete PacketsLost;
	
		delete RoutesInfo;
		delete DelayPercentile;	
		delete Arrived;
	}
	source = NULL;
}

/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : Constructor for TTMHistogram objects
Input		  :
-------------------------------------------------------------------------------
*/

TTMHistograms::TTMHistograms() {

	// default construtor
	// initialize everything to zero or NULL

	source = NULL;
	verbose = 0;

	Delay2D		= NULL;
	Delay1D		= NULL;
	PacketsSent	= NULL;
	ClocksOK	= NULL;
	BadSourceClock	= NULL;
	BadTargetClock	= NULL;
	BadClocks	= NULL;
	RoutesNHops	= NULL;
	PacketsLost	= NULL;
        Arrived		= NULL;

	DelayPercentile = NULL;

        endtime=0;
	starttime=0;

	cstarttime1=new char[20];
	cstarttime2=new char[8];
	cendtime1=new char[20];
	cendtime2=new char[8];

	// defaults values for histogram parameters
	maxdelay = 250;
	binsX = 168; 	 // week plot: 1 bin per 60 minutes

	LossPercentile = new Percentiles;
}

/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : Destructor for TTMHistogram objects
		    delete all dynamically created data
-------------------------------------------------------------------------------
*/

TTMHistograms::~TTMHistograms() {

	if (verbose && (source != NULL)) {
		cout << "destructing TTMHistograms object " <<
		    source->GetShortName() << "targetNum: " <<
		    targetNum << endl;
	}

	DeleteHistos();
	delete[] cstarttime1;
	delete[] cstarttime2;
	delete[] cendtime1;
	delete[] cendtime2;

}

/*
-------------------------------------------------------------------------------
Subroutine Header
Description	  : 

//  arguments:     *pad        -> pointer to current pad
//                 *ptr_text   -> pointer to string
//                 x           -> x-coordinate NTC
//                 y           -> y-coordinate NTC
//                 align       -> alignment (see ROOT TattText class)
//		   font	       -> font id   (see ROOT TattText class)
//  purpose:       writes 'ptr_text' on 'pad' as TText on
//                 coordinates 'x' and 'y' with alignment
//                 'align'. Use TLatex-class for a better
//                 correspondence between screen and print-out
//                 in newer versions of ROOT (above 2.21/08)
-------------------------------------------------------------------------------
*/

void TTMHistograms::write_stats(TPad* pad, const char* ptr_text, const Float_t x,
		const Float_t y, const Short_t align, Font_t font)
{
  pad->cd();
  TText *xlabel = new TText(x, y, ptr_text);
  xlabel -> SetTextFont(font);
  xlabel -> SetTextColor(1);
  xlabel -> SetTextSize(0.11);
  xlabel -> SetTextAlign(align);
  xlabel->Draw();
  return;
}

