//Deian Stefan
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "util.h"

int get_addr(char *hname,struct sockaddr_in *sock_out) {
	struct hostent *he;
	if(!inet_aton(hname,&sock_out->sin_addr)) {
		if(!(he=gethostbyname(hname))) {
			fprintf(stderr,"Unknown hostname %s: %s\n",
					hname,hstrerror(h_errno));
			return -1;
		}
		memcpy(&sock_out->sin_addr.s_addr,he->h_addr,
				sizeof(sock_out->sin_addr.s_addr));
	}
	return 0;
}

void print_stat(ullong b,ullong usec) {
	fprintf(stderr,"Wrote %llu B at %0.03f MB/s\n",
			b,(double)(b/1048576.0)/(usec/1000000.0));
}

int write_tf(int from,int to,ullong *b_wrote,ullong *tot_time) {	

	int rc=0;
	char buf[8192];
	ullong n,wrote,readno;
	struct timeval x_time[2];
	*tot_time=*b_wrote=readno=0;

	if(gettimeofday(&x_time[0],NULL)) {
		fprintf(stderr,"gettimeofday() failed: %s\n",
				strerror(errno));
		rc=1; //not fatal
	}
	while((readno=read(from,buf,sizeof(buf)))>0) {
		n=wrote=0;
		while(wrote<readno) {
			if((n=write(to,buf+wrote,readno-wrote))<0) {
				fprintf(stderr,"Failed to write to fd %d: %s\n",
						to,strerror(errno));
				return -1;
			}
			wrote+=n;
		}
		*b_wrote+=wrote;
	}
	if(gettimeofday(&x_time[1],NULL)) {
		fprintf(stderr,"gettimeofday() failed: %s\n",
				strerror(errno));
		rc=1;
	} 
	if(!rc) {
		//dont calculate time if gettimeofday failed
		*tot_time+=(x_time[1].tv_sec-x_time[0].tv_sec)*1000000+
			   (x_time[1].tv_usec-x_time[0].tv_usec);
	}
	if(readno<0) {
		fprintf(stderr, "Failed to read from fd %d: %s\n",
				from,strerror(errno)); 
		return -1;
	}
	return rc;
}

