/*
 * Author:
 *         Kendy Kutzner <kutzner@ira.uka.de>
 *
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * $Id: utils.cc,v 1.8 2005/12/29 16:21:58 kutzner Exp $
 *
 */

#include <map>
#include <string>
#include <sstream>
using namespace std;

#include <math.h>
#include <sys/time.h>
#include <assert.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>

#include "utils.h"

string
extractfrommap(map<string,string> * m, string s){
	map<string,string>::const_iterator i;
	i = m->find(s);
	if (i == m->end()){
		return "";
	} else {
		return i->second;
	}
}

string
makeavpair(string attr, string val){
	string res;
	res = attr + ": " + val + "\n";
	return res;
}

string
makeavpair(string attr, int val){
	stringstream st;
	st << val;
	return makeavpair(attr, st.str());
}

std::pair<string,string>
splitavpair(string l){
	unsigned int colpos = l.find(':');
	unsigned int spacepos = l.find(' ');
	if((1<colpos) && // there has to be something before the colon
		(spacepos == colpos+1) && // the space should follow the colon
		(spacepos < l.size() + 1)){ // there has to be something after the space
		string a = l.substr(0, colpos);
		string v = l.substr(spacepos+1, l.size());
		return std::pair<string,string>(a,v);
	}
	return std::pair<string,string>("","");
}

string
itos(int i){
	stringstream st;
	st << i;
	return st.str();
}

/**
 * ??
 * XXX not thread safe
 */

char *
itoa(int i){
	static char buf[100];
	snprintf(buf, 100-1, "%i", i);
	buf[100-1] = '\0';
	return buf;
}

double 
tv2double(timeval *tv){
	double t = (double)(tv->tv_sec) + (double)(tv->tv_usec)/1000000;
	return t;
}

void 
double2tv(timeval *tv, double t){
	assert(t>0);
	double tmp = t;
	tv->tv_sec = (long int)trunc(tmp);
	tmp -= tv->tv_sec;
	tmp *= 1000000;
	tv->tv_usec = (long int)trunc(tmp);
	assert(tv->tv_sec>=0);
	assert(tv->tv_usec>=0);
	assert(tv->tv_usec<1000000);
	return ;
}

double
dbltime(){
	struct timeval tv;
	if (0!=gettimeofday(&tv, NULL))
		return -1.0;
	return tv2double(&tv);
}

