
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/time.h>
#include <strings.h>

#define SERIALPORT "/dev/ttySP1"
#define BAUDRATE B115200

/* Return 1 if the difference is negative, otherwise 0.  */
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
{
    long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
    result->tv_sec = diff / 1000000;
    result->tv_usec = diff % 1000000;

    return (diff<0);
}

int main(void)
{
	int sp;
	long count, res;
	struct termios mytio;
	char buf[200*1024];
	struct timeval tvBegin, tvEnd, tvDiff;
	
	sp = open(SERIALPORT, O_RDWR | O_NOCTTY);
	if(sp < 0)
	{
		printf("Error while openinig port.\n");
		return -1;
	}
	
	/* fill struct with zeroes */
	bzero(&mytio, sizeof(mytio));
	/* set speed, datasize, enable reciever, ignore modem ctrl lines */
	mytio.c_cflag = BAUDRATE | CS8 | CREAD | CLOCAL;
	/* ignore framing errors */
	mytio.c_iflag = IGNPAR;
	/* define standart output behaviour */
	mytio.c_oflag = 0;
	/* non-canonical , no echo */
	mytio.c_lflag = 0;
	
	/* we don't use timeout timer*/
	mytio.c_cc[VTIME] = 0;
	/* get all available */
	mytio.c_cc[VMIN] = 0;
	
	/* set new settings */
	tcflush(sp, TCIFLUSH);
	tcsetattr(sp, TCSANOW, &mytio);
	
	//wait to recieve 1st byte
	do
	{
		res = read(sp, buf, 1);
	}while(res == 0);	
	
	//get timestamp
	gettimeofday(&tvBegin, NULL);
	//read the remaining characters 200k
	count = res;
	while(count < (200*1024))
	{
		res = read(sp, (buf+count), (200*1024-count));
		count += res;
		printf("count is  %ld\n", count);
	};
	//get timestamp
	gettimeofday(&tvEnd, NULL);
	//print elapsed time
	timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
    printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);
	
	close(sp);
	
    return 0;
}
