/* LICENSE:
  =========================================================================
    CMPack'04 Source Code Release for OPEN-R SDK 1.1.5-r2 for ERS7
    Copyright (C) 2004 Multirobot Lab [Project Head: Manuela Veloso]
    School of Computer Science, Carnegie Mellon University
    All rights reserved.
  ========================================================================= */
#include "BoundedQueue.h"
#include <sstream>
#include <cstdio> // perror()
#include "Util.h"
#include <sys/types.h>
#include <iostream> // FIXME

#ifdef BUILD_LINUX
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif 


using namespace std;

double mean(BoundedQueue<int> *q) {
  double sum = 0.0;
  for (int i = 0; i < q->size(); i++) {
    sum += q->get(i);
  }
  return sum / q->size();
};

unsigned long mean(BoundedQueue<unsigned long> *q) {
  double sum = 0.0;
  for (int i = 0; i < q->size(); i++) {
    sum += q->get(i);
  }
  return (unsigned long) (sum / q->size());
};

#ifdef PLATFORM_APERIOS

/*
string addrtostring(NetTCPConnection c) {
  stringstream s;

  uint32 addr = c->RemoteAddress.Address();
  Port port = c->RemotePort;

  s << (addr >> 24) << ".";
  s << ((addr & 0x00FF0000) >> 16) << ".";
  s << ((addr & 0x0000FF00) >> 8) << ".";
  s << (addr & 0x000000FF) << ":";
  s << port;

  return s.str();
}
*/
#else
string addrtostring(struct sockaddr_in *a) {
  s << inet_ntoa(a->sin_addr) << ":" << ntohs(a->sin_port);
  return s.str();
}
#endif

/*
string addrtostring(int ip[4]) {
  stringstream s;

  s << ip[0] << ".";
  s << ip[1] << ".";
  s << ip[2] << ".";
  s << ip[3];
  return s.str();

}
*/

/*
// FIXME too much alloc ! no free ! bad programmer
char* addrtostring(int ip[4]) {
  char *s = (char*) malloc(24);
  sprintf(s, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
  return s;
}
*/


struct timeval *now() {
  struct timeval *retval = 
    (struct timeval*) malloc(sizeof(struct timeval));
  if (gettimeofday(retval, NULL) == -1) {
    perror("error getting timeval");
  }
  return retval;
}

#ifdef PLATFORM_APERIOS
string timetostring(unsigned long time) {
  stringstream s;
  s << time;
  return s.str();  
}
#else
string timetostring(struct timeval* t) {
  stringstream s;
  s << t->tv_sec << " " << t->tv_usec;
  return s.str();
}
#endif

double timetodouble(struct timeval* t) {
  double retval = t->tv_sec;
  retval += ((double) t->tv_usec) / 1000000.0;
  return retval;
}

struct timeval *stringtotime(string str) {
  stringstream s(str);
  long sec, usec;
  s >> sec;
  s >> usec;
  struct timeval* retval = 
    (struct timeval*) malloc(sizeof(struct timeval));
  retval->tv_sec = sec;
  retval->tv_usec = usec;
  return retval;
}

