/*
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          : main.C
Author            : Rene Wilhelm
Date              : 17-NOV-2000
Revised for Linux : 15-JUN-2001
Revised 	  : 08-AUG-2002 add format CSV, comma seperated ascii table
Description       : Main program for creating TTM delay plots
Language Version  : C++
OSs Tested        : Solaris 2.6 , Debian Linux 2.2
Command line 
    required args : -p <timeperiod>	iso8601 format time period for plots
    optional args : -o <outputdir>	output directory for plots/data files
		    -s source_id	numeric id of source box
		    -t target_id	numeric id of target box
		    -f format		plot format (default gif)
		    -m maxdelay		maximum value of delay histograms
		    -z mindelay		minimum value of delay histograms
		    -l			use logarithmic scale for delay plots

$Id: main.C,v 1.8 2002/08/09 14:32:41 ttraffic Exp $
-------------------------------------------------------------------------------
*/

#define TTCONFIG_COMMAND  	"/ncc/ttpro/bin/ttconfig"
#define TTCONFIG_COMMAND_ARGS	"-v active"
#define DEFAULT_OUTPUTDIR	"/ncc/ttpro/spool/plots"

#include <TROOT.h>
#include <TApplication.h>
#include <TFile.h>
#include <iostream.h>
#include "TestBoxConfig.h"
#include "Delay.h"
#include "DelayPlots.h"
#include "getargs.h"
#include "iso8601.h"

char *progname;
int  verbose = 0;

int main (int argc, char **argv) {
	int nsources, ntargets;
	uint source_id, target_id;
	TestBox *srclist, **targetlist;
	TestBox *source, *target;
	TestBoxConfig *config;

	plotformat format=gif;
	char *output=DEFAULT_OUTPUTDIR;	// directory for output file(s)
	char srcname[256];
	char tgtname[256];

	srcname[0]='\0';
	tgtname[0]='\0';

	time_t endtime, period;
	short   logscale=0;		// no logarithmic Y-axes
	short   allpackets=0;		// exclude Bad clock state packets
	double  mindelay=0;		// minimum value for Y-axes
	double  maxdelay=250;		// maximum value for Y-axes
	
	// ensure correct timezone for date<->time_t conversions
	putenv("TZ=GMT+0");

	// ROOT initialisation
	TROOT simple ("TTM", "Plots");
	gROOT->SetBatch();		// no graphics windows

	TApplication* app = new TApplication("delayPlots", NULL, NULL, NULL, 0);

	getargs(argc, argv, srcname, tgtname, endtime, period, mindelay,
		maxdelay, logscale, &output, format, allpackets);

#ifdef DEBUG
	cout << "source, target:\t" << srcname << " " << tgtname <<endl;
	cout << "endtime, period:\t" << endtime << " " << period <<endl;
	cout << "output, format: \t"	<< output << " " << format <<endl;
        cout << "mindelay: " << mindelay << " maxdelay: " << maxdelay << endl;
	cout << "  logscale: " << logscale <<endl;
	if (format == gif) {
		cout << "gif" << endl;
	}
	if (format == ps) {
		cout << "ps" << endl;
	}
	if (format == eps) {
		cout << "eps" << endl;
	}
	cout <<endl;
#endif

//
//      Get TestBox config at end date (yyyymmdd)
//
	char command[512] = TTCONFIG_COMMAND ;
	char *p = strchr(command, '\0');

	strcpy(p, " -d ");
	p = p + 4;

        if (strftime(p, 32, "'%Y-%m-%d %H:%M:%S'", localtime(&endtime)) == 0) {
		fprintf(stderr, "%s: strftime(): ERROR converting time %d\n",
			progname, (int) endtime);
	}
	strcat(command, " ");
	strcat(command, TTCONFIG_COMMAND_ARGS);

	config = new TestBoxConfig(command);
#ifdef DEBUG
	cout  << "TestBoxConfig " << config->NumEntries() << " entries " << endl;
#endif

//  NOTE:
//	no srcname     -> all sources to specified targets
//	no tgtname     -> specified source to all targets
// 	no src, no dst -> all sources to all targets

	if (srcname[0] != '\0') {
		// source name specified  
		source_id = atoi(srcname);

		source = config->GetBoxById(source_id);
		if (source == NULL) {
			fprintf(stderr, "%s: ERROR: couldn't find box %s in config for date %s\n", progname, srcname, p);
			exit (1);
		}
		srclist = source;
		nsources = 1;
	}
	else {
		// get all active sources
		
		srclist = config->TBList();
		nsources = config->NumEntries();
	}

	if (tgtname[0] != '\0') {
		// target name specified
		target_id = atoi(tgtname);
		target = config->GetBoxById(target_id);
		if (target == NULL) {
			fprintf(stderr, "%s: ERROR: couldn't find box %s in config for date %s\n", progname, tgtname, p);
			exit (1);
		}
		targetlist = &target;
		ntargets = 1;
	}
	else {
		target_id = 0;	     // existing ID is always >0 
	}

//
// Now for the real work: Plots!
//
	DelayPlots *plots = new DelayPlots;
 
	for (int i=0; i < nsources; i++) {
		source = &srclist[i];
		
		if (target_id == 0) {
			// all targets
			targetlist = config->GetTargets(source);
			ntargets = source->number_of_targets;
		}

                if (format != csv) {
			// fill plot histograms with data
		   	plots->Fill (*source, targetlist, ntargets, period, 
                                endtime, mindelay, maxdelay, allpackets);

		   	// create output files in requested format
		   	plots->Plot(format, output, logscale);
                 } 
                 else {
		   	plots->CSV(*source, targetlist, ntargets, period,
                                 endtime, output);
                 }
	}
	return(0);
}
